feat(webui): report which dashboard sections a process can serve

The same dashboard is served by the daemon, which holds every runtime handle,
and by the UI process, which holds two remote contracts. A section with
nothing behind it still answers -- an empty list, a "disabled" marker, a 501 --
and the browser cannot tell that from a deployment where nothing has happened
yet. GET /api/capabilities says which sections this process can back, and the
nav drops the rest rather than offering a page that is permanently empty.

It fails open in both directions: an unreported section stays visible, and a
failed read hides nothing, because an entry that silently vanished is worse
than a page that explains itself.

Mappings and bindings move the other way. Both are ratified State Store
contracts carried by the client the UI process already holds, so leaving them
nil degraded two pages that have an owner; compose wires them.

A table test now enumerates every route whose capability is daemon-local and
pins what it answers without one (requirement 4 of archie-core-8cda.5.4):
task logs, the log feed and its stream, version and the update flow, channels
and reload, curators, memory, skills, workflows and work requests. Adding a
route with no owner now fails that test rather than the operator's browser.
This commit is contained in:
sam committed 2026-09-09 23:49:40 +10:00
1 parent 6f34e34adb
commit 54862f9fe6
11 files changed
+371 -20

No files matched your search

+10
View File
@@ -55,6 +55,16 @@ func compose(d deps) *webui.Server {
if snapshots, ok := d.Store.(store.ConfigSnapshotStore); ok {
srv.ConfigSource = webui.RemoteConfigView(snapshots)
}
// Mappings and bindings are ratified State Store contracts, and the same
// client already carries them: withholding them would degrade two pages
// that have an owner, which is a different thing from the intake surfaces
// below.
if mappings, ok := d.Store.(store.MappingStore); ok {
srv.Mappings = mappings
}
if bindings, ok := d.Store.(store.BindingStore); ok {
srv.Bindings = bindings
}
if d.Chat != nil {
srv.Chat = &webui.ChatService{Contract: d.Chat}
}
+6 -2
View File
@@ -91,8 +91,6 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
"LogFeed": srv.LogFeed,
"TaskLogs": srv.TaskLogs,
"WorkRequests": srv.WorkRequests,
"Mappings": srv.Mappings,
"Bindings": srv.Bindings,
"Captures": srv.Captures,
"BindingDispatcher": srv.BindingDispatcher,
"CaptureLimiter": srv.CaptureLimiter,
@@ -105,6 +103,12 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
if srv.Workflows != nil {
t.Error("Workflows is wired; the definition catalog is a filesystem scan on the daemon host")
}
// Mappings and bindings are the other way round: ratified State Store
// contracts, carried by the client this process already holds, so
// leaving them nil would degrade two pages that have an owner.
if srv.Mappings == nil || srv.Bindings == nil {
t.Error("Mappings/Bindings are unwired; both are State Store contracts the composed client implements")
}
if srv.UpdateReportPath != "" {
t.Error("UpdateReportPath is set; host-local update relay stays with the daemon")
}
@@ -0,0 +1,176 @@
package archieui
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"path/filepath"
"strconv"
"strings"
"testing"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/webui"
)
// TestRoutesWithoutAContractDegradeExplicitly enumerates every dashboard
// route whose backing capability lives in the daemon and has no contract the
// UI process can reach (archie-core-8cda.5.4 requirement 4).
//
// The enumeration is the point. Each of these is nil in the UI process, and a
// nil that reaches a handler by accident is a panic, a hang, or an empty
// answer indistinguishable from real emptiness. Pinning the response here
// means adding a route without an owner fails this test rather than the
// operator's browser, and gives the SPA a documented status to hide on.
func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
srv, taskID := composeUIProcess(t)
ts := httptest.NewServer(srv.Handler())
defer ts.Close()
for _, tc := range []struct {
name string
method string
path string
body string
want int
// emptyJSON asserts the response carries a well-formed empty
// answer rather than a fabricated one.
emptyJSON string
}{
{
name: "daemon log feed", method: http.MethodGet, path: "/api/logs",
want: http.StatusOK, emptyJSON: `"disabled":true`,
},
{
name: "daemon log stream", method: http.MethodGet, path: "/api/logs/stream",
want: http.StatusServiceUnavailable,
},
{
// The task exists; its logs do not, because the files live on
// the daemon's host. "disabled" is the same answer the daemon
// gives when task logging is off, and the page already reads it.
name: "per-task logs", method: http.MethodGet, path: "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs",
want: http.StatusOK, emptyJSON: `"disabled":true`,
},
{
name: "release version and update flow", method: http.MethodGet, path: "/api/version",
want: http.StatusNotImplemented,
},
{
name: "chat update check", method: http.MethodGet, path: "/api/chat/update",
want: http.StatusNotImplemented,
},
{
name: "channel lifecycle", method: http.MethodGet, path: "/api/channels",
want: http.StatusOK, emptyJSON: `[]`,
},
{
name: "channel reload", method: http.MethodPost, path: "/api/channels/telegram/reload",
want: http.StatusNotImplemented,
},
{
name: "curator registry", method: http.MethodGet, path: "/api/curators",
want: http.StatusOK, emptyJSON: `[]`,
},
{
name: "memory", method: http.MethodGet, path: "/api/memory",
want: http.StatusOK,
},
{
name: "skills catalog", method: http.MethodGet, path: "/api/skills",
want: http.StatusOK, emptyJSON: `[]`,
},
{
// Statistics come from the State Store, the definition list from
// the daemon's registry: the remote half answers, the local half
// is absent, and both are absent-shaped rather than missing keys.
name: "workflow registry", method: http.MethodGet, path: "/api/workflows",
want: http.StatusOK, emptyJSON: `"definitions":null`,
},
{
name: "dashboard work request", method: http.MethodPost, path: "/api/work-requests",
body: `{"repository":"acme/widget","workflow":"implement","title":"do it"}`,
want: http.StatusServiceUnavailable,
},
{
// The browser reads this to decide which sections to show at
// all, so it is the one route that must answer here.
name: "capabilities", method: http.MethodGet, path: "/api/capabilities",
want: http.StatusOK, emptyJSON: `"logs":false`,
},
} {
t.Run(tc.name, func(t *testing.T) {
var reader *strings.Reader
if tc.body != "" {
reader = strings.NewReader(tc.body)
} else {
reader = strings.NewReader("")
}
req, err := http.NewRequestWithContext(t.Context(), tc.method, ts.URL+tc.path, reader)
if err != nil {
t.Fatalf("request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", "1")
resp, err := ts.Client().Do(req)
if err != nil {
t.Fatalf("%s %s: %v", tc.method, tc.path, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
body := string(raw)
if resp.StatusCode != tc.want {
t.Fatalf("%s %s = %d (%s), want %d", tc.method, tc.path, resp.StatusCode, body, tc.want)
}
if tc.emptyJSON != "" && !strings.Contains(body, tc.emptyJSON) {
t.Fatalf("%s %s body = %s, want it to carry %s", tc.method, tc.path, body, tc.emptyJSON)
}
if resp.StatusCode == http.StatusOK && !json.Valid([]byte(body)) {
t.Fatalf("%s %s returned invalid JSON: %s", tc.method, tc.path, body)
}
})
}
}
// composeUIProcess builds the dashboard exactly as the UI process does, over
// a State Store with nothing published and a Gateway that is not wired at
// all -- the shape every route below has to survive.
func composeUIProcess(t *testing.T) (*webui.Server, int64) {
t.Helper()
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite"))
if err != nil {
t.Fatalf("open store: %v", err)
}
t.Cleanup(func() { _ = st.Close() })
target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) {
staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)})
})
t.Cleanup(stop)
client, closeClient, err := staterpc.Dial(target, "")
if err != nil {
t.Fatalf("dial state store: %v", err)
}
t.Cleanup(closeClient)
task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "")
if err != nil {
t.Fatalf("seed task: %v", err)
}
options := Options{Listen: "127.0.0.1:0", DependencyTimeout: defaultDependencyTimeout}
return compose(deps{
Options: options,
Log: slog.New(slog.DiscardHandler),
Store: client,
Health: newReadinessRegistry(options, client, nil),
}), task.ID
}
+41
View File
@@ -0,0 +1,41 @@
package webui
import "net/http"
// handleCapabilities reports which dashboard sections this process can
// actually serve.
//
// The dashboard is served by two different compositions: the daemon, which
// holds every runtime handle, and the UI process, which holds two remote
// contracts and nothing else. Sections whose capability lives only in the
// daemon still answer -- with an empty list, a "disabled" marker, or a 501 --
// and the page cannot tell that apart from a deployment where nothing has
// happened yet. Rather than have every page guess, the server says which
// sections it can back, and the browser hides the rest.
//
// A section is reported available when the handle behind it is wired, which
// is the same condition its handler already uses to decide between real data
// and its degraded answer. Sections backed by the task store are absent from
// this list: the store is mandatory in both compositions.
func (s *Server) handleCapabilities(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, map[string]any{
"sections": map[string]bool{
"chat": s.Chat != nil && s.Chat.Contract != nil,
"logs": s.LogFeed != nil,
"skills": s.Cfg != nil,
"memory": s.Memory != nil,
"curators": s.Curators != nil,
"channels": s.Channels != nil || s.Cfg != nil,
"captures": s.Captures != nil,
"mappings": s.Mappings != nil,
"bindings": s.Bindings != nil,
// The workflows page draws its statistics from the task store
// and its definition list from the local registry, so it is
// worth showing with only the former.
"workflows": true,
// Configuration renders from whichever source is wired; the
// page reports its own editability (see ConfigView.Editable).
"settings": true,
},
})
}
+53
View File
@@ -11,6 +11,9 @@ import (
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/memory"
"github.com/samcharles93/archie-core/internal/secret"
"github.com/samcharles93/archie-core/internal/store"
)
@@ -685,3 +688,53 @@ func (s stubSnapshots) PutConfigSnapshot(context.Context, store.ConfigSnapshot)
func (s stubSnapshots) ConfigSnapshot(context.Context) (store.ConfigSnapshot, bool, error) {
return s.snapshot, s.found, s.err
}
// TestCapabilitiesReportWhatThisProcessCanServe: the same dashboard is served
// by the daemon, which holds every runtime handle, and by the UI process,
// which holds two remote contracts. A section with nothing behind it answers
// empty rather than failing, which the browser cannot tell from a quiet
// deployment -- so the server says which sections it can back.
func TestCapabilitiesReportWhatThisProcessCanServe(t *testing.T) {
get := func(srv *Server) map[string]bool {
t.Helper()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/capabilities", nil)
res := httptest.NewRecorder()
srv.Handler().ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("GET /api/capabilities = %d, want 200", res.Code)
}
var body struct {
Sections map[string]bool `json:"sections"`
}
if err := json.Unmarshal(res.Body.Bytes(), &body); err != nil {
t.Fatalf("decode capabilities: %v", err)
}
return body.Sections
}
bare := get(newTestServer(t))
for _, section := range []string{"logs", "memory", "curators", "channels", "mappings", "bindings", "skills"} {
if bare[section] {
t.Errorf("section %q reported available with nothing wired behind it", section)
}
}
// The task board and configuration page work from the store and the
// configured source, so they are never hidden.
for _, section := range []string{"workflows", "settings"} {
if !bare[section] {
t.Errorf("section %q reported unavailable; it is served in every composition", section)
}
}
wired := newTestServer(t)
wired.Cfg = config.NewHolder(config.Config{})
wired.LogFeed = logging.NewFeed(10)
wired.Memory = &memory.Manager{}
wired.Curators = &curator.Registry{}
got := get(wired)
for _, section := range []string{"logs", "memory", "curators", "skills", "channels"} {
if !got[section] {
t.Errorf("section %q reported unavailable despite being wired", section)
}
}
}
+1
View File
@@ -276,6 +276,7 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/channels/{id}/reload", s.handleChannelReload)
mux.HandleFunc("GET /api/version", s.handleVersion)
mux.HandleFunc("GET /api/memory", s.handleMemory)
mux.HandleFunc("GET /api/capabilities", s.handleCapabilities)
}
func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
+7 -7
View File
@@ -1,16 +1,16 @@
(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),te(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,re(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=te(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&ie(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=ee(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)),L(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 ee(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 M(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function N(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||M(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||M(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 P(e){return function(n){if(this.l){var rLine truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var B=class extends Error{constructor(e,t){super(e),this.status=t}};function le(e){let t=e instanceof B?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}}var V={summary:()=>R(`/api/summary`),tasks:()=>R(`/api/tasks`),taskMeta:()=>R(`/api/task-meta`),task:e=>R(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},setup:()=>R(`/api/setup`),workflows:()=>R(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},skills:()=>R(`/api/skills`),channels:()=>R(`/api/channels`),curators:()=>R(`/api/curators`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},config:()=>R(`/api/config`),version:()=>R(`/api/version`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},configRepoUpdate:async(e,t,n,r)=>{let i=await fetch(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({field:n,value:r}),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new B(await z(i),i.status);return i.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},logs:e=>R(`/api/logs`+ce(e)),taskLogs:(e,t)=>R(`/api/tasks/${e}/logs`+ce(t)),captures:e=>R(`/api/captures`+ce({limit:e})),mappings:()=>R(`/api/mappings`),mappingCreate:async e=>{let t=await fetch(`/api/mappings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},mappingUpdate:async(e,t)=>{let n=await fetch(`/api/mappings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},mappingDelete:async e=>{let t=await fetch(`/api/mappings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status)},mappingPreview:async(e,t)=>{let n=await fetch(`/api/mappings/preview`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({capture_id:e,fields:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},bindings:()=>R(`/api/bindings`),bindingCreate:async e=>{let t=await fetch(`/api/bindings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},bindingUpdate:async(e,t)=>{let n=await fetch(`/api/bindings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},bindingDelete:async e=>{let t=await fetch(`/api/bindings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status)},bindingApprove:async e=>{let t=await fetch(`/api/bindings/${e}/approve`,{method:`POST`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},memory:()=>R(`/api/memory`),chatSessions:()=>R(`/api/chat/sessions`),chatMessages:e=>R(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>R(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chat Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var B=class extends Error{constructor(e,t){super(e),this.status=t}};function le(e){let t=e instanceof B?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}}var V={summary:()=>R(`/api/summary`),tasks:()=>R(`/api/tasks`),taskMeta:()=>R(`/api/task-meta`),task:e=>R(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},setup:()=>R(`/api/setup`),capabilities:()=>R(`/api/capabilities`),workflows:()=>R(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},skills:()=>R(`/api/skills`),channels:()=>R(`/api/channels`),curators:()=>R(`/api/curators`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},config:()=>R(`/api/config`),version:()=>R(`/api/version`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},configRepoUpdate:async(e,t,n,r)=>{let i=await fetch(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({field:n,value:r}),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new B(await z(i),i.status);return i.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},logs:e=>R(`/api/logs`+ce(e)),taskLogs:(e,t)=>R(`/api/tasks/${e}/logs`+ce(t)),captures:e=>R(`/api/captures`+ce({limit:e})),mappings:()=>R(`/api/mappings`),mappingCreate:async e=>{let t=await fetch(`/api/mappings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},mappingUpdate:async(e,t)=>{let n=await fetch(`/api/mappings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},mappingDelete:async e=>{let t=await fetch(`/api/mappings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status)},mappingPreview:async(e,t)=>{let n=await fetch(`/api/mappings/preview`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({capture_id:e,fields:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},bindings:()=>R(`/api/bindings`),bindingCreate:async e=>{let t=await fetch(`/api/bindings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},bindingUpdate:async(e,t)=>{let n=await fetch(`/api/bindings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new B(await z(n),n.status);return n.json()},bindingDelete:async e=>{let t=await fetch(`/api/bindings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status)},bindingApprove:async e=>{let t=await fetch(`/api/bindings/${e}/approve`,{method:`POST`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new B(await z(t),t.status);return t.json()},memory:()=>R(`/api/memory`),chatSessions:()=>R(`/api/chat/sessions`),chatMessages:e=>R(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>R(`/api/chat/sessioLine truncated
<path d="${c(150,240)}" fill="none" stroke="var(--border)"
stroke-width="12" stroke-linecap="round"/>
<path d="${c(150,240)}" fill="none" stroke="${i}"
stroke-width="12" stroke-linecap="round"
stroke-dasharray="${s}"
stroke-dashoffset="${s*(1-r/100)}"
class="gauge-value"/>`,H(`div.gauge-wrap`,l,H(`div.gauge-center`,H(`div.gauge-pct`,`${Math.round(r)}%`),H(`div.gauge-label`,t)))}function Ze(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return H(`div`,H(`div.segbar`,...e.filter(e=>e.value>0).map(e=>H(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),H(`div.segbar-legend`,...e.map(e=>H(`span.segbar-key`,H(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var Qe=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:--Qe,__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}function Z({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}var $e=`archie.setup-complete.dismissed.v1`;function et(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.($e),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function tt(e=globalThis.localStorage){e?.setItem?.($e,`1`)}var nt=new Set([`waiting_human`,`parked`]);function rt(e=[]){let t=e.filter(e=>nt.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function it({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function at(e){return X(it,{node:Je(e)})}function ot(e){return X(it,{node:Xe(e)})}function st({segments:e}){return X(it,{node:Ze(e)})}function ct({name:e,opts:t}){return X(it,{node:W(e,t)})}function lt({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function ut(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function dt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function ft(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function pt(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,a]=q(`idle`),[o,s]=q(new Map),[c,l]=q(null),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[,v]=q(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([V.summary(),V.setup().catch(()=>null),V.workflows().catch(()=>null),V.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};J(()=>(y(),ue(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{tt(),v(e=>!e)},x=u?.operator?`${dt()}, ${u.operator}`:dt(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(ct,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=rt(m),t=e.attention.count,n=e.running.count;C=X(S,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(ct,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(ct,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(ct,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(ct,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(lt,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=X(S,{children:[X(at,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(at,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(at,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(at,{label:`Tokens used`,value:Te(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:ft(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=et(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children 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(Z,{text:un[e.status]||e.status,kind:dn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({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 pn({origins:e}){return e?.length?X($,{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(on,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function mn(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function hn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{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??ve(e.id),n=e.kind??ye(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Z,{text:t,kind:n})})]},e.id)})}):X(Q,{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=mn(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(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function gn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(!1),[o,s]=q(null),[c,l]=q(!!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 V.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 _n({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!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 V.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 vn({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{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($,{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(gn,{r:e,field:`allow_concuLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(H(`p`,lr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(H(`pre`,H(`code`,a.join(`
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=dr(c),u=e+1<n.length?dr(n[e+1]):null;if(l&&u&&fr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=dr(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=H(`tbody`);for(let e of r)i.append(H(`tr`,...e.map(e=>H(`td`,lr(e)))));t.append(H(`table`,H(`thead`,H(`tr`,...l.map(e=>H(`th`,lr(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(H(`h${d[1].length}`,lr(d[2])));continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tagName.toLowerCase()!==e)&&(s(),i=H(e)),i.append(H(`li`,lr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(H(`blockquote`,lr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(H(`pre`,H(`code`,a.join(`
`)))),t}function dr(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 fr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var pr=`archie.web.chat.channel`;function mr(){let e=localStorage.getItem(pr);return e||(e=se(),localStorage.setItem(pr,e)),e}function hr(e){return{text:e,sourceID:se()}}function gr(e){return{...e}}function _r(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?gr(e.turn):hr(r),isRetry:n}}function vr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function yr(e){return e?.status===501?null:`Could not check for updates.`}function br(){return location.hash.slice(1)||`/`}function xr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(ur(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Sr(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q([]),[o,s]=q(``),[c,l]=q(`Ready`),[u,d]=q(!1),[f,p]=q({}),[m,h]=q(``),[g,_]=q(``),[v,y]=q(``),[b,x]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,ee]=q(null),[M,N]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),ie=Y(null),L=Y(null),ae=Y(null),oe=Y(null),se=Y(null),R=Y(u);R.current=u,J(()=>{ie.current&&(ie.current.scrollTop=ie.current.scrollHeight)},[i,F]),J(()=>{fe().catch(e=>{l(e.message||`Chat unavailable`)}),ce();let e=()=>{ae.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ae.current?.abort()}},[]);async function ce(){try{let e=await V.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=yr(e);A(t?{error:t}:null)}}async function z(){if(j)try{await V.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function B(){if(j)try{l(`Installing…`);let e=await V.chatUpdateInstall(j);ee(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 le(){try{let e=await V.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function ue(e,t){if(t)try{await V.chatDangerousRequest(e,t),l(`Approval requested`),await le()}catch(e){l(e.message||`Could not request action`)}}async function de(e,t){try{await V.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await le()}catch(e){l(e.message||`Approval failed`)}}async function fe(){let e=await V.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 le(),!n&&r[0]&&await pe(r[0].session_id,e,r)}async function pe(e,t,n){let i=t||f;r(e),a([]),I(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await V.chatMessage(mr(),`/resume ${e}`);let[t,n]=await Promise.all([V.chatMessages(e),V.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 me(e){if(n)try{l(`Working…`);let t=await V.chatMessage(mr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await fe(),(t.session_id||n)&&await pe(t.session_id||n),oe.current&&(oe.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function he(e,t){let n=window.prompt(t);n?.trim()&&me(`${e} ${n.trim()}`)}function ge(e){let t=e.target.value;h(t),!(!n||!t)&&V.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 _e(e){let t=e.target.value;if(_(t),t)try{let e=await V.chatMessage(mr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await fe()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ve(e){let t=e.target.value;if(y(t),t)try{let e=await V.chatMessage(mr(),`/model ${t}`);l(e.reply||`Model updated`),await fe()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ye(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),Ce({textOverride:`/restart`}))}function be(){s(`/new`),Ce({textOverride:`/new`})}function xe(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 Se(e){let t=C[e];if(!t||!L.current)return;let n=L.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a= Line truncated
class="gauge-value"/>`,H(`div.gauge-wrap`,l,H(`div.gauge-center`,H(`div.gauge-pct`,`${Math.round(r)}%`),H(`div.gauge-label`,t)))}function Qe(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return H(`div`,H(`div.segbar`,...e.filter(e=>e.value>0).map(e=>H(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),H(`div.segbar-legend`,...e.map(e=>H(`span.segbar-key`,H(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var $e=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:--$e,__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}function Z({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}var et=`archie.setup-complete.dismissed.v1`;function tt(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(et),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function nt(e=globalThis.localStorage){e?.setItem?.(et,`1`)}var rt=new Set([`waiting_human`,`parked`]);function it(e=[]){let t=e.filter(e=>rt.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function at({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function ot(e){return X(at,{node:Ye(e)})}function st(e){return X(at,{node:Ze(e)})}function ct({segments:e}){return X(at,{node:Qe(e)})}function lt({name:e,opts:t}){return X(at,{node:W(e,t)})}function ut({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function dt(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function ft(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function pt(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function mt(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,a]=q(`idle`),[o,s]=q(new Map),[c,l]=q(null),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[,v]=q(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([V.summary(),V.setup().catch(()=>null),V.workflows().catch(()=>null),V.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};J(()=>(y(),ue(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{nt(),v(e=>!e)},x=u?.operator?`${ft()}, ${u.operator}`:ft(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(lt,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=it(m),t=e.attention.count,n=e.running.count;C=X(S,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(lt,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(lt,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(lt,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(lt,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(ut,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=X(S,{children:[X(ot,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(ot,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(ot,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(ot,{label:`Tokens used`,value:Ee(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:pt(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=tt(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children 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(Z,{text:dn[e.status]||e.status,kind:fn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({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 mn({origins:e}){return e?.length?X($,{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(sn,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function hn(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function gn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{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??ye(e.id),n=e.kind??be(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Z,{text:t,kind:n})})]},e.id)})}):X(Q,{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=hn(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(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function _n({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(!1),[o,s]=q(null),[c,l]=q(!!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 V.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 vn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!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 V.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 yn({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{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($,{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(_n,{r:e,field:`allow_concuLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(H(`p`,ur(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(H(`pre`,H(`code`,a.join(`
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=fr(c),u=e+1<n.length?fr(n[e+1]):null;if(l&&u&&pr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=fr(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=H(`tbody`);for(let e of r)i.append(H(`tr`,...e.map(e=>H(`td`,ur(e)))));t.append(H(`table`,H(`thead`,H(`tr`,...l.map(e=>H(`th`,ur(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(H(`h${d[1].length}`,ur(d[2])));continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tagName.toLowerCase()!==e)&&(s(),i=H(e)),i.append(H(`li`,ur((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(H(`blockquote`,ur(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(H(`pre`,H(`code`,a.join(`
`)))),t}function fr(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 pr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var mr=`archie.web.chat.channel`;function hr(){let e=localStorage.getItem(mr);return e||(e=se(),localStorage.setItem(mr,e)),e}function gr(e){return{text:e,sourceID:se()}}function _r(e){return{...e}}function vr(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?_r(e.turn):gr(r),isRetry:n}}function yr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function br(e){return e?.status===501?null:`Could not check for updates.`}function xr(){return location.hash.slice(1)||`/`}function Sr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(dr(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Cr(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q([]),[o,s]=q(``),[c,l]=q(`Ready`),[u,d]=q(!1),[f,p]=q({}),[m,h]=q(``),[g,_]=q(``),[v,y]=q(``),[b,x]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,ee]=q(null),[M,N]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),ie=Y(null),L=Y(null),ae=Y(null),oe=Y(null),se=Y(null),R=Y(u);R.current=u,J(()=>{ie.current&&(ie.current.scrollTop=ie.current.scrollHeight)},[i,F]),J(()=>{fe().catch(e=>{l(e.message||`Chat unavailable`)}),ce();let e=()=>{ae.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ae.current?.abort()}},[]);async function ce(){try{let e=await V.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=br(e);A(t?{error:t}:null)}}async function z(){if(j)try{await V.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function B(){if(j)try{l(`Installing…`);let e=await V.chatUpdateInstall(j);ee(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 le(){try{let e=await V.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function ue(e,t){if(t)try{await V.chatDangerousRequest(e,t),l(`Approval requested`),await le()}catch(e){l(e.message||`Could not request action`)}}async function de(e,t){try{await V.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await le()}catch(e){l(e.message||`Approval failed`)}}async function fe(){let e=await V.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 le(),!n&&r[0]&&await pe(r[0].session_id,e,r)}async function pe(e,t,n){let i=t||f;r(e),a([]),I(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await V.chatMessage(hr(),`/resume ${e}`);let[t,n]=await Promise.all([V.chatMessages(e),V.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 me(e){if(n)try{l(`Working…`);let t=await V.chatMessage(hr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await fe(),(t.session_id||n)&&await pe(t.session_id||n),oe.current&&(oe.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function he(e,t){let n=window.prompt(t);n?.trim()&&me(`${e} ${n.trim()}`)}function ge(e){let t=e.target.value;h(t),!(!n||!t)&&V.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 _e(e){let t=e.target.value;if(_(t),t)try{let e=await V.chatMessage(hr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await fe()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ve(e){let t=e.target.value;if(y(t),t)try{let e=await V.chatMessage(hr(),`/model ${t}`);l(e.reply||`Model updated`),await fe()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ye(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),H({textOverride:`/restart`}))}function be(){s(`/new`),H({textOverride:`/new`})}function xe(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 Se(e){let t=C[e];if(!t||!L.current)return;let n=L.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r. Line truncated
`);s=i.pop()||``;for(let e of i){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,I(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(t)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),I(null),l(`Ready`),await fe()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:u,isError:!0,turn:gr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ae.current=null,d(!1),L.current&&L.current.focus()}}function we(){l(`Stopping…`),n&&V.chatCancel(n).catch(()=>{}),ae.current?.abort()}let U=f.models_by_provider||{},Te=g&&U[g]?U[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:ye,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ce,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:ge,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:_e,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:ve,children:[X(`option`,{value:``,children:`Model`}),Te.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:z,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:B,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&M&&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:P,onChange:e=>te(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(M.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:()=>ue(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ue(`stop`,ne),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(M.pending||[]).length?M.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:()=>de(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>de(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>de(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:be,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:()=>pe(e.session_id),children:[X(`strong`,{children:vr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations willLine 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,I(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(t)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),I(null),l(`Ready`),await fe()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:u,isError:!0,turn:_r(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ae.current=null,d(!1),L.current&&L.current.focus()}}function we(){l(`Stopping…`),n&&V.chatCancel(n).catch(()=>{}),ae.current?.abort()}let Te=f.models_by_provider||{},U=g&&Te[g]?Te[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:ye,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ce,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:ge,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:_e,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:ve,children:[X(`option`,{value:``,children:`Model`}),U.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:z,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:B,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&M&&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:P,onChange:e=>te(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(M.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:()=>ue(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ue(`stop`,ne),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(M.pending||[]).length?M.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:()=>de(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>de(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>de(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:be,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:()=>pe(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 wilLine truncated
+1
View File
@@ -83,6 +83,7 @@ export const api = {
return res.json();
},
setup: () => req("/api/setup"),
capabilities: () => req("/api/capabilities"),
workflows: () => req("/api/workflows"),
workRequest: async (request) => {
const res = await fetch("/api/work-requests", {
+17
View File
@@ -0,0 +1,17 @@
// Which dashboard sections the serving process can actually back.
//
// The dashboard is served by two compositions: the daemon, which holds every
// runtime handle, and the extracted UI service, which holds two remote
// contracts. 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);
}
+28 -11
View File
@@ -1,5 +1,7 @@
import "./css/_main.css";
import { render } from "preact";
import { api } from "./base/api.jsx";
import { hiddenRoutes } from "./capabilities.jsx";
import { el, mount } from "./base/dom.jsx";
import { icon } from "./base/icons.jsx";
import { dashboardPage } from "./dashboard/dashboard.jsx";
@@ -24,20 +26,26 @@ import { chatPage } from "./chat/chat.jsx";
* 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).
const routes = [
{ path: "/", label: "Dashboard", icon: "dashboard", view: dashboardPage },
{ path: "/chat", label: "Chat", icon: "chat", view: chatPage },
{ path: "/chat", label: "Chat", icon: "chat", view: chatPage, section: "chat" },
{ path: "/tasks", label: "Tasks", icon: "tasks", view: tasksPage },
{ path: "/logs", label: "Logs", icon: "logs", view: logsPage },
{ path: "/captures", label: "Event inspector", icon: "captures", view: capturesPage },
{ path: "/mappings", label: "Field mappings", icon: "mappings", view: mappingsPage },
{ path: "/bindings", label: "Playbook bindings", icon: "bindings", view: bindingsPage },
{ path: "/skills", label: "Skills", icon: "skills", view: skillsPage },
{ path: "/workflows", label: "Workflows", icon: "workflows", view: workflowsPage },
{ path: "/memory", label: "Memory", icon: "memory", view: memoryPage },
{ path: "/curators", label: "Curators", icon: "curators", view: curatorsPage },
{ path: "/channels", label: "Channels", icon: "channels", view: channelsPage },
{ path: "/settings", label: "Configuration", icon: "settings", view: settingsPage },
{ 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: "/memory", label: "Memory", icon: "memory", view: memoryPage, section: "memory" },
{ 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";
@@ -168,6 +176,9 @@ function commandBar(onNavigate, onToggleChat) {
else node.removeAttribute("aria-current");
}
},
hide(paths) {
for (const path of paths) items.get(path)?.remove();
},
};
}
@@ -191,6 +202,12 @@ function start() {
chatDrawer.append(el("div.chat-drawer-panel", drawerHead, chatPage()),
el("div.chat-scrim", { onclick: () => toggleChat(false) }));
const bar = commandBar(navigate, () => toggleChat());
// 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.
api.capabilities()
.then((caps) => bar.hide(hiddenRoutes(caps?.sections, routes)))
.catch(() => {});
const shell = el("div.shell", bar.node, outlet, chatDrawer);
mount(document.getElementById("app"), shell);
+31
View File
@@ -0,0 +1,31 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { hiddenRoutes } from "../src/capabilities.jsx";
const routes = [
{ path: "/", label: "Dashboard" },
{ path: "/logs", label: "Logs", section: "logs" },
{ path: "/memory", label: "Memory", section: "memory" },
{ path: "/tasks", label: "Tasks" },
];
// The dashboard is served by two processes with different capabilities. A
// section the serving process cannot back renders as permanently empty, which
// reads as "nothing has happened" rather than "not served here".
test("a section the server cannot serve is hidden", () => {
assert.deepEqual(hiddenRoutes({ logs: false, memory: true }, routes), ["/logs"]);
});
test("sections with no capability entry stay visible", () => {
assert.deepEqual(hiddenRoutes({}, routes), []);
});
// Fail open: an older server, or a failed read, must not blank the nav.
test("no capabilities at all hides nothing", () => {
assert.deepEqual(hiddenRoutes(undefined, routes), []);
assert.deepEqual(hiddenRoutes(null, routes), []);
});
test("routes without a section are never hidden", () => {
assert.deepEqual(hiddenRoutes({ logs: false }, routes), ["/logs"]);
});