fix(ui): unbreak binding approve and the two deletes, and centralise the client

Three dashboard mutations were refused 415 on every use. archied's
authorizeTaskMutation runs before the handler body and answers
"Content-Type must be application/json" unless the request declares a JSON
body -- including when there is no body to send, because that requirement is
what makes a simple cross-origin form post inexpressible. bindingApprove,
mappingDelete and bindingDelete sent Accept and X-Archie-CSRF but no
Content-Type, so approving a binding or deleting a mapping or binding never
worked from the dashboard.

Reproduced against the real handler with the browser's exact headers: 415,
where the same request plus Content-Type returns 200 and arms the binding.
The Go tests missed it because doJSONWithHeaders sets Content-Type
unconditionally, even for a nil body, so no test ever exercised the shape the
client actually sends.

Every api.* method now goes through one request() (and one send()), which
sets Content-Type and the CSRF marker on every mutation rather than only
where a payload happens to exist. The module already claimed to be "the
single place that knows how to talk to archied" while 22 call sites built
their own fetch, headers, timeout and error handling inline and chat.jsx
built a 23rd; that claim is now true, and chat.jsx's stream goes through
api.chatStream so only the URL, headers and failure shape are shared while
chat.jsx keeps its abort/timeout and SSE parsing.

Behaviour deliberately preserved: 204 deletes still parse no body, the
install timeout stays 120s, and 401 still classifies as session-expired. One
intentional change -- a 401 message is now the server's own text ("open the
dashboard URL archied logged at startup") rather than a bare "unauthorised",
since errorMessage already prefers the actionable reason and the classification
is derived from the status either way.

ui/test/api-client.test.js asserts the browser mutation contract for every
method, that reads carry no mutation marker, that a 204 resolves without
parsing, that api.jsx holds exactly one fetch call, and that every api method
is classified by the suite so a new one cannot be added uncovered. ui/dist is
rebuilt, being a committed asset.

I had claimed this work was needed to fix a 401 defect. It was not: all 22 raw
call sites passed res.status to ApiError, so classifyActionError already mapped
401 to session-expired, and chat.jsx never classified at all. The missing
Content-Type was the real defect.
This commit is contained in:
sam committed 2026-09-15 13:49:53 +10:00
1 parent dacec700a6
commit cb69cf1979
4 files changed
+374 -255

No files matched your search

+9 -9
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`),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
(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 de=class extends Error{constructor(e,t){super(e),this.status=t}};function fe(e){let t=e instanceof de?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 pe(e,t){let n=await fetch(e,t);if(!n.ok)throw new de(await ue(n),n.status);return n}async function R(e,{method:t=`GET`,body:n,timeoutMs:r=ce,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 pe(e,o);return i?s.json():void 0}var z={summary:()=>R(`/api/summary`),tasks:()=>R(`/api/tasks`),taskMeta:()=>R(`/api/task-meta`),task:e=>R(`/api/tasks/${e}`),taskAction:(e,t)=>R(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>R(`/api/setup`),capabilities:()=>R(`/api/capabilities`),workflows:()=>R(`/api/workflows`),workRequest:e=>R(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>R(`/api/skills`),channels:()=>R(`/api/channels`),curators:()=>R(`/api/curators`),channelReload:e=>R(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>R(`/api/config`),version:()=>R(`/api/version`),configUpdate:e=>R(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>R(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>R(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>R(`/api/logs`+le(e)),taskLogs:(e,t)=>R(`/api/tasks/${e}/logs`+le(t)),captures:e=>R(`/api/captures`+le({limit:e})),mappings:()=>R(`/api/mappings`),mappingCreate:e=>R(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>R(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>R(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>R(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>R(`/api/bindings`),bindingCreate:e=>R(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>R(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>R(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>R(`/api/bindings/${e}/approve`,{method:`POST`}),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`),chatCancel:e=>R(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>R(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:se(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>R(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>R(`/api/chat/update`),chatUpdateDefer:e=>R(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>R(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>R(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>R(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>R(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>pe(`/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 B(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 he(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var ge=[{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`}],_e=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quLine 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 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
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 et(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 tt=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:--tt,__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 nt=`archie.setup-complete.dismissed.v1`;function rt(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?.(nt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function it(e=globalThis.localStorage){e?.setItem?.(nt,`1`)}var at=new Set([`waiting_human`,`parked`]);function ot(e=[]){let t=e.filter(e=>at.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 st({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function ct(e){return X(st,{node:Ze(e)})}function lt(e){return X(st,{node:$e(e)})}function ut({segments:e}){return X(st,{node:et(e)})}function dt({name:e,opts:t}){return X(st,{node:W(e,t)})}function ft({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pt(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 mt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function ht(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 gt(){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([z.summary(),z.setup().catch(()=>null),z.workflows().catch(()=>null),z.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(),B(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{it(),v(e=>!e)},x=u?.operator?`${mt()}, ${u.operator}`:mt(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=ot(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(dt,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(dt,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(dt,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(ft,{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(ct,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(ct,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(ct,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(ct,{label:`Tokens used`,value:Oe(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:ht(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=rt(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:pn[e.status]||e.status,kind:mn[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 gn({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(ln,{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 _n(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function vn({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??Se(e.id),n=e.kind??Ce(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=_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(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function yn({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 z.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 bn({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 z.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 xn({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(yn,{r:e,field:`allow_concuLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(H(`p`,fr(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=mr(c),u=e+1<n.length?mr(n[e+1]):null;if(l&&u&&hr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=mr(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`,fr(e)))));t.append(H(`table`,H(`thead`,H(`tr`,...l.map(e=>H(`th`,fr(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}`,fr(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`,fr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(H(`blockquote`,fr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(H(`pre`,H(`code`,a.join(`
`)))),t}function mr(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 hr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var gr=`archie.web.chat.channel`;function _r(){let e=localStorage.getItem(gr);return e||(e=se(),localStorage.setItem(gr,e)),e}function vr(e){return{text:e,sourceID:se()}}function yr(e){return{...e}}function br(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?yr(e.turn):vr(r),isRetry:n}}function xr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Sr(e){return e?.status===501?null:`Could not check for updates.`}function Cr(){return location.hash.slice(1)||`/`}function wr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(pr(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Tr(){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),ce=Y(u);ce.current=u,J(()=>{ie.current&&(ie.current.scrollTop=ie.current.scrollHeight)},[i,F]),J(()=>{B().catch(e=>{l(e.message||`Chat unavailable`)}),le();let e=()=>{ae.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ae.current?.abort()}},[]);async function le(){try{let e=await z.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=Sr(e);A(t?{error:t}:null)}}async function ue(){if(j)try{await z.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function de(){if(j)try{l(`Installing…`);let e=await z.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 fe(){try{let e=await z.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function pe(e,t){if(t)try{await z.chatDangerousRequest(e,t),l(`Approval requested`),await fe()}catch(e){l(e.message||`Could not request action`)}}async function R(e,t){try{await z.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await fe()}catch(e){l(e.message||`Approval failed`)}}async function B(){let e=await z.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 fe(),!n&&r[0]&&await me(r[0].session_id,e,r)}async function me(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 z.chatMessage(_r(),`/resume ${e}`);let[t,n]=await Promise.all([z.chatMessages(e),z.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 he(e){if(n)try{l(`Working…`);let t=await z.chatMessage(_r(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await B(),(t.session_id||n)&&await me(t.session_id||n),oe.current&&(oe.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function ge(e,t){let n=window.prompt(t);n?.trim()&&he(`${e} ${n.trim()}`)}function _e(e){let t=e.target.value;h(t),!(!n||!t)&&z.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 ve(e){let t=e.target.value;if(_(t),t)try{let e=await z.chatMessage(_r(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await B()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ye(e){let t=e.target.value;if(y(t),t)try{let e=await z.chatMessage(_r(),`/model ${t}`);l(e.reply||`Model updated`),await B()}catch(e){l(`Model update failed: ${e.message||e}`)}}function be(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),V({textOverride:`/restart`}))}function xe(){s(`/new`),V({textOverride:`/new`})}function Se(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 Ce(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.se 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:_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
`);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,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(i)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 B()}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:yr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ae.current=null,d(!1),L.current&&L.current.focus()}}function Te(){l(`Stopping…`),n&&z.chatCancel(n).catch(()=>{}),ae.current?.abort()}let H=f.models_by_provider||{},Ee=g&&H[g]?H[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:be,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:le,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:_e,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:ve,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:ye,children:[X(`option`,{value:``,children:`Model`}),Ee.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:ue,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:de,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:()=>pe(`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:()=>pe(`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:()=>R(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>R(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>R(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:xe,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:()=>me(e.session_id),children:[X(`strong`,{children:xr(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
+110 -235
View File
@@ -1,23 +1,15 @@
// Single place that knows how to talk to archied. Every feature folder goes
// through this, so auth handling and error shape live in one file.
// through api.* below, and every api.* method goes through send(), so the CSRF
// header, the Content-Type, the request timeout, and the error shape live in
// this one file. ui/test/api-client.test.js asserts that: it fails if a second
// fetch() call appears here, and it fails if any method omits a header the
// server requires.
import { randomUUID } from "./uuid.jsx";
async function req(path) {
// A daemon that accepts the connection but never answers would otherwise
// leave the UI stuck in a loading state with no way back; the retry
// affordances rely on fetch settling, so bound it.
const res = await fetch(path, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(15000),
});
if (res.status === 401) {
throw new ApiError("unauthorised", 401);
}
if (!res.ok) {
throw new ApiError(`${res.status} ${res.statusText}`, res.status);
}
return res.json();
}
// DEFAULT_TIMEOUT_MS bounds a request so a daemon that accepts the connection
// but never answers cannot leave the UI in a loading state with no way back.
// The retry affordances rely on fetch settling, so bound it.
const DEFAULT_TIMEOUT_MS = 15000;
// qs builds a query string, omitting empty values so the server sees an
// absent filter rather than an empty one.
@@ -32,8 +24,9 @@ function qs(params) {
// errorMessage prefers what the server actually said. archied answers these
// with http.Error, i.e. a plain-text reason -- "task is not awaiting
// approval", "max retries reached (3/3)" -- and discarding it in favour of
// "409 Conflict" throws away the only part an operator can act on.
// approval", "max retries reached (3/3)", "Content-Type must be
// application/json" -- and discarding it in favour of "409 Conflict" throws
// away the only part an operator can act on.
async function errorMessage(res) {
try {
const body = (await res.text()).trim();
@@ -53,12 +46,12 @@ export class ApiError extends Error {
// classifyActionError turns a failed operator action into a rendering
// decision. archied's own handlers already return distinguishable status
// codes for a refused mutation (400/403/409 -- bad input, missing CSRF,
// cross-origin, conflicting state) versus a broken one (5xx, or no status at
// all when fetch itself failed -- network drop, timeout); 401 additionally
// means the session -- archied's own token cookie, or an upstream
// forward-auth proxy sitting in front of it -- has expired rather than that
// the action was rejected or the daemon is unwell.
// codes for a refused mutation (400/403/409/415 -- bad input, missing CSRF,
// cross-origin, conflicting state, a body that is not JSON) versus a broken
// one (5xx, or no status at all when fetch itself failed -- network drop,
// timeout); 401 additionally means the session -- archied's own token cookie,
// or an upstream forward-auth proxy sitting in front of it -- has expired
// rather than that the action was rejected or the daemon is unwell.
export function classifyActionError(err) {
const status = err instanceof ApiError ? err.status : undefined;
const message = err?.message || "Action failed";
@@ -67,219 +60,101 @@ export function classifyActionError(err) {
return { kind: "broken", message };
}
// send is the only fetch() in the dashboard. It converts a non-ok response
// into an ApiError carrying the server's own explanation and a usable status,
// and hands the raw Response back so the streaming caller can read the body
// itself.
async function send(path, init) {
const res = await fetch(path, init);
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res;
}
// request performs a JSON request. Every mutating method must declare a JSON
// body: archied's handlers run authorizeTaskMutation first, and it answers 415
// unless Content-Type is application/json -- including for a mutation that has
// no body to send, because that requirement is what makes a simple cross-origin
// form post inexpressible. Sending the header on every mutation, rather than
// only where a payload happens to exist, is what keeps a bodyless DELETE or
// approve from being refused.
async function request(path, { method = "GET", body, timeoutMs = DEFAULT_TIMEOUT_MS, parse = true } = {}) {
const headers = { Accept: "application/json" };
const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
if (method !== "GET") {
headers["Content-Type"] = "application/json";
headers["X-Archie-CSRF"] = "1";
}
if (body !== undefined) init.body = JSON.stringify(body);
const res = await send(path, init);
return parse ? res.json() : undefined;
}
export const api = {
summary: () => req("/api/summary"),
tasks: () => req("/api/tasks"),
taskMeta: () => req("/api/task-meta"),
task: (id) => req(`/api/tasks/${id}`),
taskAction: async (id, action) => {
const res = await fetch(`/api/tasks/${id}/action`, {
summary: () => request("/api/summary"),
tasks: () => request("/api/tasks"),
taskMeta: () => request("/api/task-meta"),
task: (id) => request(`/api/tasks/${id}`),
taskAction: (id, action) => request(`/api/tasks/${id}/action`, { method: "POST", body: { action } }),
setup: () => request("/api/setup"),
capabilities: () => request("/api/capabilities"),
workflows: () => request("/api/workflows"),
workRequest: (workRequest) => request("/api/work-requests", { method: "POST", body: workRequest }),
skills: () => request("/api/skills"),
channels: () => request("/api/channels"),
curators: () => request("/api/curators"),
channelReload: (id) => request(`/api/channels/${encodeURIComponent(id)}/reload`, { method: "POST", body: {} }),
config: () => request("/api/config"),
version: () => request("/api/version"),
configUpdate: (updates) => request("/api/config", { method: "PATCH", body: { updates } }),
configRepoUpdate: (owner, name, field, value) =>
request(`/api/config/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { method: "PATCH", body: { field, value } }),
configReset: (key) => request("/api/config/reset", { method: "POST", body: { key } }),
logs: (params) => request("/api/logs" + qs(params)),
taskLogs: (id, params) => request(`/api/tasks/${id}/logs` + qs(params)),
captures: (limit) => request("/api/captures" + qs({ limit })),
mappings: () => request("/api/mappings"),
mappingCreate: (mapping) => request("/api/mappings", { method: "POST", body: mapping }),
mappingUpdate: (id, mapping) => request(`/api/mappings/${id}`, { method: "PATCH", body: mapping }),
// A delete answers 204, so there is no body to parse.
mappingDelete: (id) => request(`/api/mappings/${id}`, { method: "DELETE", parse: false }),
mappingPreview: (captureId, fields) => request("/api/mappings/preview", { method: "POST", body: { capture_id: captureId, fields } }),
bindings: () => request("/api/bindings"),
bindingCreate: (binding) => request("/api/bindings", { method: "POST", body: binding }),
bindingUpdate: (id, binding) => request(`/api/bindings/${id}`, { method: "PATCH", body: binding }),
bindingDelete: (id) => request(`/api/bindings/${id}`, { method: "DELETE", parse: false }),
bindingApprove: (id) => request(`/api/bindings/${id}/approve`, { method: "POST" }),
memory: () => request("/api/memory"),
chatSessions: () => request("/api/chat/sessions"),
chatMessages: (id) => request(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
chatTurns: (id) => request(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
chatCancel: (sessionID) => request("/api/chat/cancel", { method: "POST", body: { session_id: sessionID } }),
chatMessage: (channelID, text) =>
request("/api/chat/message", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify({ action }),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
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", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(request), signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
skills: () => req("/api/skills"),
channels: () => req("/api/channels"),
curators: () => req("/api/curators"),
channelReload: async (id) => {
const res = await fetch(`/api/channels/${encodeURIComponent(id)}/reload`, {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: "{}", signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
config: () => req("/api/config"),
version: () => req("/api/version"),
configUpdate: async (updates) => {
const res = await fetch("/api/config", {
method: "PATCH",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify({ updates }),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
configRepoUpdate: async (owner, name, field, value) => {
const res = await fetch(`/api/config/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, {
method: "PATCH",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify({ field, value }),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
configReset: async (key) => {
const res = await fetch("/api/config/reset", {
body: { channel_id: channelID, source_id: randomUUID(), text, page: location.hash.slice(1) || "/" },
}),
chatPersona: (sessionID, name) => request("/api/chat/persona", { method: "POST", body: { session_id: sessionID, name } }),
chatUpdate: () => request("/api/chat/update"),
chatUpdateDefer: (snapshot) => request("/api/chat/update/defer", { method: "POST", body: { snapshot } }),
// Installing restarts archied, so it is allowed far longer than a normal
// request before the UI gives up.
chatUpdateInstall: (snapshot) => request("/api/chat/update/install", { method: "POST", body: { snapshot }, timeoutMs: 120000 }),
chatDangerous: () => request("/api/chat/dangerous"),
chatDangerousRequest: (kind, spec) =>
request(`/api/chat/dangerous/${encodeURIComponent(kind)}`, { method: "POST", body: { spec } }),
chatDangerousDecision: (id, decision) =>
request(`/api/chat/dangerous/${encodeURIComponent(id)}/decision`, { method: "POST", body: { decision } }),
// A server-sent event stream cannot be parsed as JSON and outlives a normal
// request, so the caller owns the abort controller and the timeout, and
// reads the body itself. Only the URL, headers, and failure shape are shared.
chatStream: (payload, { signal } = {}) =>
send("/api/chat/stream", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify({ key }),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
logs: (params) => req("/api/logs" + qs(params)),
taskLogs: (id, params) => req(`/api/tasks/${id}/logs` + qs(params)),
captures: (limit) => req("/api/captures" + qs({ limit })),
mappings: () => req("/api/mappings"),
mappingCreate: async (mapping) => {
const res = await fetch("/api/mappings", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(mapping),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
mappingUpdate: async (id, mapping) => {
const res = await fetch(`/api/mappings/${id}`, {
method: "PATCH",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(mapping),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
mappingDelete: async (id) => {
const res = await fetch(`/api/mappings/${id}`, {
method: "DELETE",
headers: { Accept: "application/json", "X-Archie-CSRF": "1" },
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
},
mappingPreview: async (captureId, fields) => {
const res = await fetch("/api/mappings/preview", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify({ capture_id: captureId, fields }),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
bindings: () => req("/api/bindings"),
bindingCreate: async (binding) => {
const res = await fetch("/api/bindings", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(binding),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
bindingUpdate: async (id, binding) => {
const res = await fetch(`/api/bindings/${id}`, {
method: "PATCH",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(binding),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
bindingDelete: async (id) => {
const res = await fetch(`/api/bindings/${id}`, {
method: "DELETE",
headers: { Accept: "application/json", "X-Archie-CSRF": "1" },
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
},
bindingApprove: async (id) => {
const res = await fetch(`/api/bindings/${id}/approve`, {
method: "POST",
headers: { Accept: "application/json", "X-Archie-CSRF": "1" },
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
memory: () => req("/api/memory"),
chatSessions: () => req("/api/chat/sessions"),
chatMessages: (id) => req(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
chatTurns: (id) => req(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
chatCancel: async (sessionID) => {
const res = await fetch("/api/chat/cancel", {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ session_id: sessionID }), signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
chatMessage: async (channelID, text) => {
const res = await fetch("/api/chat/message", {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ channel_id: channelID, source_id: randomUUID(), text, page: location.hash.slice(1) || "/" }),
signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
chatPersona: async (sessionID, name) => {
const res = await fetch("/api/chat/persona", {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ session_id: sessionID, name }), signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
chatUpdate: () => req("/api/chat/update"),
chatUpdateDefer: async (snapshot) => {
const res = await fetch("/api/chat/update/defer", {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ snapshot }), signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
chatUpdateInstall: async (snapshot) => {
const res = await fetch("/api/chat/update/install", {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ snapshot }), signal: AbortSignal.timeout(120000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
chatDangerous: () => req("/api/chat/dangerous"),
chatDangerousRequest: async (kind, spec) => {
const res = await fetch(`/api/chat/dangerous/${encodeURIComponent(kind)}`, {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ spec }), signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
chatDangerousDecision: async (id, decision) => {
const res = await fetch(`/api/chat/dangerous/${encodeURIComponent(id)}/decision`, {
method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ decision }), signal: AbortSignal.timeout(15000),
});
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res.json();
},
headers: { Accept: "text/event-stream", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(payload),
signal,
}),
};
/**
+5 -11
View File
@@ -403,21 +403,15 @@ export function ChatApp() {
controller.abort();
}, 120000);
const response = await fetch("/api/chat/stream", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "text/event-stream" },
body: JSON.stringify({
const response = await api.chatStream(
{
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
}),
signal: controller.signal,
});
if (!response.ok) {
throw new Error((await response.text()) || `${response.status} ${response.statusText}`);
}
},
{ signal: controller.signal },
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
+250
View File
@@ -0,0 +1,250 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import "./shim.js";
import { api, classifyActionError } from "../src/base/api.js";
// archied's mutation handlers run authorizeTaskMutation before doing anything
// else, and it refuses a request that does not declare
// Content-Type: application/json with 415. The dashboard must therefore send
// that header on every mutation -- including the ones with no body. Three
// bodyless mutations (bindingApprove, mappingDelete, bindingDelete) did not,
// and were refused 415 on every click.
const JSON_CONTENT_TYPE = "application/json";
// Every mutating method, with arguments that satisfy its signature. The
// inventories below are checked for completeness, so a new api method cannot
// be added without these contract assertions applying to it.
const MUTATIONS = [
["taskAction", [1, "retry"]],
["workRequest", [{ title: "t" }]],
["channelReload", ["c1"]],
["configUpdate", [{ "a.b": 1 }]],
["configRepoUpdate", ["owner", "name", "field", 1]],
["configReset", ["key"]],
["mappingCreate", [{}]],
["mappingUpdate", [1, {}]],
["mappingDelete", [1]],
["mappingPreview", [1, {}]],
["bindingCreate", [{}]],
["bindingUpdate", [1, {}]],
["bindingDelete", [1]],
["bindingApprove", [1]],
["chatCancel", ["session"]],
["chatMessage", ["channel", "hello"]],
["chatPersona", ["session", "name"]],
["chatUpdateDefer", [{}]],
["chatUpdateInstall", [{}]],
["chatDangerousRequest", ["kind", {}]],
["chatDangerousDecision", ["id", "approve"]],
];
// Reads must not carry a mutation marker, and must ask for JSON.
const READS = [
["summary", []],
["tasks", []],
["taskMeta", []],
["task", [1]],
["setup", []],
["capabilities", []],
["workflows", []],
["skills", []],
["channels", []],
["curators", []],
["config", []],
["version", []],
["logs", [{}]],
["taskLogs", [1, {}]],
["captures", [10]],
["mappings", []],
["bindings", []],
["memory", []],
["chatSessions", []],
["chatMessages", ["s"]],
["chatTurns", ["s"]],
["chatUpdate", []],
["chatDangerous", []],
];
// The one streaming call: it cannot be parsed as JSON, so it is asserted
// separately rather than folded into either inventory above.
const STREAMS = ["chatStream"];
let calls = [];
function stubFetch(respond) {
calls = [];
globalThis.fetch = async (path, init = {}) => {
calls.push({ path, init });
return respond(path, init);
};
}
function okResponse() {
return {
ok: true,
status: 200,
statusText: "OK",
json: async () => ({}),
text: async () => "",
};
}
test.after(() => {
delete globalThis.fetch;
});
test("every mutation satisfies archied's browser mutation contract", async () => {
for (const [name, args] of MUTATIONS) {
stubFetch(okResponse);
await api[name](...args);
assert.equal(calls.length, 1, `${name} made ${calls.length} requests, expected 1`);
const { init } = calls[0];
assert.ok(init.method && init.method !== "GET", `${name} must use a mutating method`);
assert.equal(
init.headers["Content-Type"],
JSON_CONTENT_TYPE,
`${name} must send Content-Type: ${JSON_CONTENT_TYPE}; archied answers 415 without it`,
);
assert.equal(init.headers["X-Archie-CSRF"], "1", `${name} must send X-Archie-CSRF`);
}
});
test("every read asks for JSON and carries no mutation marker", async () => {
for (const [name, args] of READS) {
stubFetch(okResponse);
await api[name](...args);
assert.equal(calls.length, 1, `${name} made ${calls.length} requests, expected 1`);
const { init } = calls[0];
assert.equal(init.headers.Accept, JSON_CONTENT_TYPE, `${name} must accept JSON`);
assert.equal(init.headers["X-Archie-CSRF"], undefined, `${name} must not send a mutation marker`);
}
});
test("the chat stream posts its payload and asks for an event stream", async () => {
stubFetch(okResponse);
await api.chatStream({ text: "hi" }, {});
assert.equal(calls.length, 1);
const { path, init } = calls[0];
assert.equal(path, "/api/chat/stream");
assert.equal(init.method, "POST");
assert.equal(init.headers.Accept, "text/event-stream");
assert.equal(init.headers["Content-Type"], JSON_CONTENT_TYPE);
assert.equal(init.body, JSON.stringify({ text: "hi" }));
});
test("a bodyless DELETE resolves on 204 without parsing a body", async () => {
stubFetch(() => ({
ok: true,
status: 204,
statusText: "No Content",
json: async () => {
throw new Error("a 204 has no body to parse");
},
text: async () => "",
}));
await api.mappingDelete(1);
await api.bindingDelete(1);
});
test("a 415 keeps the server's explanation and reads as refused", async () => {
stubFetch(() => ({
ok: false,
status: 415,
statusText: "Unsupported Media Type",
text: async () => "Content-Type must be application/json\n",
json: async () => ({}),
}));
await assert.rejects(
() => api.bindingApprove(1),
(err) => {
assert.equal(err.status, 415);
assert.equal(err.message, "Content-Type must be application/json");
assert.equal(classifyActionError(err).kind, "refused");
return true;
},
);
});
test("every api method is classified by this suite", () => {
const classified = new Set([
...MUTATIONS.map(([name]) => name),
...READS.map(([name]) => name),
...STREAMS,
]);
const actual = Object.keys(api).filter((key) => typeof api[key] === "function");
const unclassified = actual.filter((name) => !classified.has(name)).sort();
assert.deepEqual(
unclassified,
[],
"add each new api method to MUTATIONS, READS, or STREAMS so the contract assertions cover it",
);
});
// The module comment claims this file is the single place that talks to
// archied. That claim is only true while there is exactly one fetch() call
// here; a second one added later would silently bypass the shared CSRF,
// timeout, and error handling -- which is how the three 415s arose.
//
// stripComments keeps this count measuring code rather than prose about code:
// a comment that mentions fetch() must not be able to fail the gate, and must
// not be able to hide a real call either.
function stripComments(source) {
let out = "";
let quote = null;
for (let i = 0; i < source.length; ) {
const c = source[i];
const next = source[i + 1];
if (quote) {
out += c;
if (c === "\\") {
out += next ?? "";
i += 2;
continue;
}
if (c === quote) quote = null;
i++;
continue;
}
if (c === '"' || c === "'" || c === "`") {
quote = c;
out += c;
i++;
continue;
}
if (c === "/" && next === "/") {
while (i < source.length && source[i] !== "\n") i++;
continue;
}
if (c === "/" && next === "*") {
i += 2;
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i++;
i += 2;
continue;
}
out += c;
i++;
}
return out;
}
test("api.jsx holds exactly one fetch call", () => {
const source = readFileSync(fileURLToPath(new URL("../src/base/api.jsx", import.meta.url)), "utf8");
const count = (stripComments(source).match(/\bfetch\s*\(/g) ?? []).length;
// A count of zero means the stripper ate the call, not that the file is
// clean; this check must never pass vacuously.
assert.ok(count >= 1, "no fetch() call found in api.jsx; the extractor is broken, not the file");
assert.equal(
count,
1,
`api.jsx contains ${count} fetch() calls, expected exactly 1: every call must go through the shared send() so CSRF, timeout, and error shape stay in one place`,
);
});