diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index c5e4ca6e4..2d6744c77 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -1,16 +1,9 @@ -(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;tt&&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;d0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:ic?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a+!!u){for(i=n-1,a=n+1;i>=0||a=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function P(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function F(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[c]==null)n[c]=d++;else if(n[c]0?e:_(e)?e.map(L):e.constructor===void 0?v({},e):null}function R(n,r,i,a,o,s,c,l,u){var d,f,p,h,g,v,b,x=i.props||m,S=r.props,C=r.type;if(C==`svg`?o=`http://www.w3.org/2000/svg`:C==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;de.toString(16).padStart(2,`0`));return`${n.slice(0,4).join(``)}-${n.slice(4,6).join(``)}-${n.slice(6,8).join(``)}-${n.slice(8,10).join(``)}-${n.slice(10).join(``)}`}var ae=15e3;function V(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function oe(e){try{let t=(await e.text()).trim();if(t)return t.split(` -`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var se=class extends Error{constructor(e,t){super(e),this.status=t}};function ce(e){let t=e instanceof se?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 le(e,t){let n=await fetch(e,t);if(!n.ok)throw new se(await oe(n),n.status);return n}async function H(e,{method:t=`GET`,body:n,timeoutMs:r=ae,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 le(e,o);return i?s.json():void 0}var U={summary:()=>H(`/api/summary`),tasks:()=>H(`/api/tasks`),taskMeta:()=>H(`/api/task-meta`),task:e=>H(`/api/tasks/${e}`),taskAttempts:e=>H(`/api/tasks/${e}/attempts`),taskChanges:(e,t)=>H(`/api/tasks/${e}/changes`+V(t)),taskDebug:(e,t)=>H(`/api/tasks/${e}/debug`+V(t)),taskAction:(e,t)=>H(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>H(`/api/setup`),capabilities:()=>H(`/api/capabilities`),workflows:()=>H(`/api/workflows`),workRequest:e=>H(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>H(`/api/skills`),channels:()=>H(`/api/channels`),curators:()=>H(`/api/curators`),channelReload:e=>H(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>H(`/api/config`),version:()=>H(`/api/version`),configUpdate:e=>H(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>H(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>H(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>H(`/api/logs`+V(e)),taskLogs:(e,t)=>H(`/api/tasks/${e}/logs`+V(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>H(`/api/captures`+V({limit:e})),mappings:()=>H(`/api/mappings`),mappingCreate:e=>H(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>H(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>H(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>H(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>H(`/api/bindings`),bindingCreate:e=>H(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>H(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>H(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>H(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>H(`/api/memory`),chatSessions:()=>H(`/api/chat/sessions`),chatMessages:e=>H(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>H(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>H(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>H(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:ie(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>H(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>H(`/api/chat/update`),chatUpdateDefer:e=>H(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>H(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>H(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>H(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>H(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>le(`/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 ue(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 de(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 fe(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var pe=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],me=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quiet`,confirm:`Archive the local record for "{title}"?`},{id:`open_pr`,label:`Open PR`,kind:`link`},{id:`open_issue`,label:`Open issue`,kind:`link`}],he=[...pe],ge=[...me],_e=new Map(he.map(e=>[e.id,e])),ve=new Map(ge.map(e=>[e.id,e]));function ye(e){return _e.get(e)?.label||e||`Unknown`}function be(e){return _e.get(e)?.kind||`idle`}function xe(){return he.map(e=>e.id)}function Se(){return new Set(he.filter(e=>e.needs_you).map(e=>e.id))}function Ce(e){return ve.get(e)||null}function W(e,t,...n){let[r,...i]=e.split(`.`),a=document.createElement(r||`div`);i.length&&(a.className=i.join(` `)),t!==void 0&&(typeof t!=`object`||t instanceof Node)&&(n.unshift(t),t=null);for(let[e,n]of Object.entries(t||{}))n!=null&&n!==!1&&(e.startsWith(`on`)&&typeof n==`function`?a.addEventListener(e.slice(2).toLowerCase(),n):e===`class`?a.className=[a.className,n].filter(Boolean).join(` `):e===`html`?a.innerHTML=n:a.setAttribute(e,n===!0?``:String(n)));return we(a,n),a}function we(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function Te(e,...t){return e.replaceChildren(),we(e,t),e}function Ee(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function De(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}var Oe={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,curators:``,captures:``,mappings:``,bindings:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,close:``,help:``};function G(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=Oe[e]||Oe.dashboard,r}var ke,K,Ae,je,Me=0,Ne=[],q=t,Pe=q.__b,Fe=q.__r,Ie=q.diffed,Le=q.__c,Re=q.unmount,ze=q.__;function Be(e,t){q.__h&&q.__h(K,e,Me||t),Me=0;var n=K.__H||(K.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function J(e){return Me=1,Ve(Ye,e)}function Ve(e,t,n){var r=Be(ke++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ye(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=K,!K.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};K.__f=!0;var a=K.shouldComponentUpdate,o=K.componentWillUpdate;K.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},K.shouldComponentUpdate=i}return r.__N||r.__}function Y(e,t){var n=Be(ke++,3);!q.__s&&Je(n.__H,t)&&(n.__=e,n.u=t,K.__H.__h.push(n))}function X(e){return Me=5,He(function(){return{current:e}},[])}function He(e,t){var n=Be(ke++,7);return Je(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function Ue(){for(var e;e=Ne.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Ke),t.__h.some(qe),t.__h=[]}catch(n){t.__h=[],q.__e(n,e.__v)}}}q.__b=function(e){K=null,Pe&&Pe(e)},q.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ze&&ze(e,t)},q.__r=function(e){Fe&&Fe(e),ke=0;var t=(K=e.__c).__H;t&&(Ae===K?(t.__h=[],K.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(Ke),t.__h.some(qe),t.__h=[],ke=0)),Ae=K},q.diffed=function(e){Ie&&Ie(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ne.push(t)!==1&&je===q.requestAnimationFrame||((je=q.requestAnimationFrame)||Ge)(Ue)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),Ae=K=null},q.__c=function(e,t){t.some(function(e){try{e.__h.some(Ke),e.__h=e.__h.filter(function(e){return!e.__||qe(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],q.__e(n,e.__v)}}),Le&&Le(e,t)},q.unmount=function(e){Re&&Re(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{Ke(e)}catch(e){t=e}}),n.__H=void 0,t&&q.__e(t,n.__v))};var We=typeof requestAnimationFrame==`function`;function Ge(e){var t,n=function(){clearTimeout(r),We&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);We&&(t=requestAnimationFrame(n))}function Ke(e){var t=K,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),K=t}function qe(e){var t=K;e.__c=e.__(),K=t}function Je(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Ye(e,t){return typeof t==`function`?t(e):t}function Xe({label:e,value:t,unit:n,trend:r,compare:i,series:a=[],goodDirection:o=`up`}){let s=r==null?null:r>=0?`up`:`down`,c=s==null?null:s===o;return W(`div.card.stat`,W(`div.stat-head`,W(`span.stat-label`,e),s&&W(`span.stat-trend.${c?`up`:`down`}`,G(s===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(r).toFixed(1)}%`)),W(`div.stat-value`,t,n&&W(`span.stat-unit`,n)),i&&W(`div.stat-compare`,i),a.length>1&&Ze(a,c===!1?`var(--danger)`:`var(--ok)`))}function Ze(e,t=`var(--ok)`,{width:n=220,height:r=34}={}){let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=e.length>1?n/(e.length-1):n,c=e.map((e,t)=>`${(t*s).toFixed(1)},${(r-(e-a)/o*r).toFixed(1)}`).join(` `),l=W(`svg.spark`,{viewBox:`0 0 ${n} ${r}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return l.innerHTML=``,l}function Qe({value:e,label:t,size:n=168}){let r=Math.max(0,Math.min(100,Number(e)||0)),i=r>=90?`var(--ok)`:r>=70?`var(--warn)`:`var(--danger)`,a=n/2,o=n/2,s=2*Math.PI*62*(240/360),c=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${a+62*Math.cos(n)} ${o+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${a+62*Math.cos(r)} ${o+62*Math.sin(r)}`].join(` `)},l=W(`svg.gauge`,{viewBox:`0 0 ${n} ${n*.78}`,role:`img`,"aria-label":`${t}: ${r}%`});return l.innerHTML=` - - `,W(`div.gauge-wrap`,l,W(`div.gauge-center`,W(`div.gauge-pct`,`${Math.round(r)}%`),W(`div.gauge-label`,t)))}function $e(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return W(`div`,W(`div.segbar`,...e.filter(e=>e.value>0).map(e=>W(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),W(`div.segbar-legend`,...e.map(e=>W(`span.segbar-key`,W(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var et=0;Array.isArray;function Z(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:--et,__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 Q({text:e,kind:t=`idle`}){return Z(`span`,{className:`pill pill-${t}`,children:e})}var tt=`archie.setup-complete.dismissed.v1`;function nt(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?.(tt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function rt(e=globalThis.localStorage){e?.setItem?.(tt,`1`)}var it=new Set([`waiting_human`,`parked`]);function at(e=[]){let t=e.filter(e=>it.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 ot({node:e}){let t=X();return Y(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function st(e){return Z(ot,{node:Xe(e)})}function ct(e){return Z(ot,{node:Qe(e)})}function lt({segments:e}){return Z(ot,{node:$e(e)})}function ut({name:e,opts:t}){return Z(ot,{node:G(e,t)})}function dt({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function ft(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 pt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function mt(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 ht(){let[e,t]=J([]),[n,r]=J(`connecting`),[i,a]=J(`idle`),[o,s]=J(new Map),[c,l]=J(null),[u,d]=J(null),[f,p]=J(null),[m,h]=J(null),[g,_]=J(null),[,v]=J(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([U.summary(),U.setup().catch(()=>null),U.workflows().catch(()=>null),U.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))}};Y(()=>(y(),ue(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{rt(),v(e=>!e)},x=u?.operator?`${pt()}, ${u.operator}`:pt(),C=null;if(g)C=Z(`button`,{className:`btn btn-primary`,onClick:y,children:[Z(ut,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=at(m),t=e.attention.count,n=e.running.count;C=Z(S,{children:[t>0&&Z(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[Z(ut,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&Z(`a`,{className:`btn`,href:e.running.href,children:[Z(ut,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),Z(`a`,{className:`btn`,href:`#/logs`,children:[Z(ut,{name:`logs`,opts:{size:15}}),` Logs`]}),Z(`button`,{className:`btn btn-primary`,onClick:y,children:[Z(ut,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=Z(`div`,{className:`card`,children:Z(dt,{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=Z(S,{children:[Z(st,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),Z(st,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),Z(st,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),Z(st,{label:`Tokens used`,value:De(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:mt(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=nt(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=Z(`div`,{className:`card setup`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Finish setting up`}),Z(`p`,{className:`card-sub`,children:`Archie needs these before it can work on its own.`})]}),Z(`span`,{className:`setup-pct`,children:[t,`%`]})]}),Z(`div`,{className:`setup-bar`,children:Z(`div`,{className:`setup-bar-fill`,style:{width:`${t}%`}})}),Z(`ul`,{className:`setup-list`,children:u.steps.map((e,t)=>Z(`li`,{className:`setup-step ${e.done?`done`:``}`,children:[Z(`span`,{className:`setup-check`,children:e.done?Z(ut,{name:`check`,opts:{size:12}}):``}),Z(`div`,{children:[Z(`div`,{className:`setup-step-title`,children:e.title}),e.detail&&Z(`div`,{className:`setup-step-detail`,children:e.detail})]})]},t))})]})}else T=Z(`div`,{className:`card setup setup-done`,children:Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Setup complete`}),Z(`p`,{className:`card-sub`,children:`Archie is configured and ready to work.`})]}),Z(`div`,{className:`setup-complete-actions`,children:[Z(`span`,{className:`setup-pct`,children:Z(ut,{name:`check`,opts:{size:16}})}),Z(`button`,{className:`icon-btn setup-dismiss`,type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onClick:b,children:`×`})]})]})})}let O=null;if(c){let e=f?.workflows||[],t=e.reduce((e,t)=>e+(t.runs||0),0),n=e.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),r=e.reduce((e,t)=>e+(t.parked||0),0);if(!t)O=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`h2`,{className:`card-title`,children:`Gate pulse`})}),Z(dt,{title:`No completed runs yet`,detail:`Once Archie finishes a task, its gate pass rate appears here.`})]});else{let i=n/t*100;O=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Gate pulse`}),Z(`p`,{className:`card-sub`,children:`Work that passed its quality gates`})]})}),Z(ct,{value:i,label:`pass rate`}),Z(`ul`,{className:`pulse-list`,children:[e.slice(0,3).map((e,t)=>Z(`li`,{className:`pulse-item`,children:[Z(`span`,{className:`pulse-name`,children:e.workflow||`workflow`}),Z(Q,{text:`${e.merged||0}/${e.runs||0}`,kind:(e.merged||0)===(e.runs||0)?`ok`:(e.parked||0)>0?`warn`:`info`})]},t)),r>0&&Z(`li`,{className:`pulse-item`,children:[Z(`span`,{className:`pulse-name`,children:`Parked, awaiting you`}),Z(Q,{text:String(r),kind:`warn`})]})]})]})}}let k=null;if(c){let e=c?.tokens_by_day||[],t=e.reduce((e,t)=>e+(t.tokens||0),0);if(!e.length)k=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`h2`,{className:`card-title`,children:`Token outlook`})}),Z(dt,{title:`Nothing spent yet`,detail:`Usage appears here once Archie runs its first task.`})]});else{let n=t/e.length,r=Math.round(n*30),i=e.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);k=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Token outlook`}),Z(`p`,{className:`card-sub`,children:`Next 30 days at the current rate`})]})}),Z(`div`,{className:`forecast-value`,children:De(r)}),Z(`div`,{className:`forecast-note`,children:[`Based on `,De(Math.round(n)),` per day over `,e.length,` days`]}),Z(lt,{segments:[{label:`Last 7 days (${De(i)})`,value:i,kind:`info`},{label:`Earlier (${De(t-i)})`,value:Math.max(t-i,0),kind:`idle`}]})]})}}return Z(S,{children:[Z(`div`,{className:`hero`,children:[Z(`div`,{children:[Z(`h1`,{className:`hero-title`,children:x}),Z(`p`,{className:`hero-sub`,children:`Your agent's control room — what it is working on, what needs you, and what it is spending.`})]}),Z(`div`,{className:`hero-actions`,children:Z(`div`,{className:`hero-actions-inner`,children:C})})]}),Z(`div`,{className:`dash-section`,children:[Z(`div`,{className:`dash-section-head`,children:Z(`h2`,{className:`dash-section-title`,children:`Health`})}),Z(`div`,{className:`dash-top ${D?`dash-top-standalone`:``}`,children:[Z(`div`,{children:T}),Z(`div`,{children:O})]})]}),Z(`div`,{className:`dash-section`,children:[Z(`div`,{className:`dash-section-head`,children:[Z(`h2`,{className:`dash-section-title`,children:`Throughput`}),Z(`span`,{className:`dash-section-note`,children:`Across all repositories`})]}),Z(`div`,{className:`grid grid-4`,children:w})]}),Z(`div`,{className:`dash-section`,children:[Z(`div`,{className:`dash-section-head`,children:Z(`h2`,{className:`dash-section-title`,children:`Right now`})}),Z(`div`,{className:`dash-split`,children:[Z(`div`,{children:k}),Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Live activity`}),Z(`p`,{className:`card-sub`,children:`Last 50, newest first`})]}),Z(Q,{text:n,kind:i})]}),Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Event`}),Z(`th`,{children:`Task`}),Z(`th`,{children:`Detail`}),Z(`th`,{children:`When`})]})}),Z(`tbody`,{children:e.length?e.map((e,t)=>{let n=ft(e,o),r=n>0,i=()=>{r&&(location.hash=`#/tasks?task=${encodeURIComponent(n)}`)};return Z(`tr`,{className:r?`activity-row`:``,role:r?`link`:void 0,tabIndex:r?`0`:void 0,title:r?`Open task details`:void 0,onClick:r?i:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,children:[Z(`td`,{className:`strong`,children:Z(`span`,{children:e.kind||e.type||`event`})}),Z(`td`,{className:`mono`,children:r?`#${n}`:`—`}),Z(`td`,{children:e.detail||e.message||``}),Z(`td`,{children:Ee(e.at||Date.now())})]},t)}):Z(`tr`,{children:Z(`td`,{colSpan:`4`,children:Z(dt,{title:`Waiting for activity`,detail:`Events appear here as Archie works.`})})})})]})})]})]})]})]})}function gt(){return Z(ht,{})}function _t(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var vt=Se(),yt=new Set([`needs_you`,...xe()]);function bt(e){let t=e?.get?.(`status`)||``;return yt.has(t)?t:``}function xt(e,t){return t?t===`needs_you`?vt.has(e.status):e.status===t:!0}function St(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function Ct(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function wt(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function Tt(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=Ct(t.duration_ms),i=[r,e&&`ran for ${e}`].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[i,t.error].filter(Boolean).join(` — `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[t.previous_stage&&`after ${t.previous_stage}`,t.previous_reason].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=wt(t.iterations),i=wt(t.tokens),a=Number(t.cached_tokens)||0,o=wt((Number(t.prompt_tokens)||0)-a),s=wt(t.completion_tokens),c=wt(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,t.model].filter(Boolean);return{title:`Agent ${t.status||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}if(e.kind===`config_captured`)return{title:`Configuration captured`,detail:`The effective task-runtime configuration for this run.`};if(e.kind===`changes_captured`){let e=Number(t.totals?.files);return{title:`Change capture recorded`,detail:[Number.isFinite(e)&&e>0?`${e} file${e===1?``:`s`} changed`:``,t.captured_after?`captured after ${t.captured_after}`:``].filter(Boolean).join(` · `)}}return{title:St(e.kind||e.type),detail:e.detail||``}}var Et=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function Dt(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ot(e){let t=e.fields||{};return W(`div.log-row.log-${Dt(e.level)}`,W(`span.log-time.mono`,At(e.time)),W(`span.log-level`,(e.level||`info`).toUpperCase()),W(`span.log-body`,W(`span.log-msg`,e.message||e.msg||``),...Object.entries(t).map(([e,t])=>W(`span.log-field`,W(`span.log-field-key`,e),String(kt(t))))))}function kt(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function At(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function jt({entry:e}){let t=X(null);return Y(()=>{t.current&&t.current.replaceChildren(Ot(e))},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function Mt(e,t){return`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`)}var Nt={level:``,stage:``};function Pt(e,t,n=Nt){let r=n||Nt;return[e,Number(t)||0,r.level||``,r.stage||``].join(`|`)}function Ft({filters:e,onFilterChange:t,stages:n,attempt:r}){let i=n=>t?.({...e,...n}),a=Number(r)||0;return Z(`div`,{className:`log-filters task-log-filters`,children:[Z(`span`,{className:`task-log-attempt`,children:a>0?`Attempt ${a}`:`Current attempt`}),t?Z(S,{children:[Z(`label`,{className:`task-log-filter`,children:[Z(`span`,{className:`task-log-filter-label`,children:`Level`}),Z(`select`,{className:`task-filter`,value:e.level,"aria-label":`Filter log entries by level`,onChange:e=>i({level:e.target.value}),children:Et.map(e=>Z(`option`,{value:e.value,children:e.label},e.value))})]}),Z(`label`,{className:`task-log-filter`,children:[Z(`span`,{className:`task-log-filter-label`,children:`Stage`}),Z(`select`,{className:`task-filter`,value:e.stage,"aria-label":`Filter log entries by stage`,onChange:e=>i({stage:e.target.value}),children:[Z(`option`,{value:``,children:`All stages`}),(n||[]).map(e=>Z(`option`,{value:e,children:e},e))]})]}),e.stage?Z(`p`,{className:`task-log-filter-note`,children:`A stage filter matches only log lines that record a stage. Agent and tool output carries none, so it is not shown while this filter is set.`}):null,!e.stage&&!(n||[]).length?Z(`p`,{className:`task-log-filter-note`,children:`This attempt recorded no stage names, so the stage filter has nothing to match.`}):null]}):null]})}function It({text:e}){return Z(`p`,{className:`visually-hidden`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:e})}function Lt({state:e,onRetry:t,taskId:n,attempt:r,filters:i=Nt,onFilterChange:a,stages:o=[]}){let s=Number(r)||Number(e?.attempt)||0,c,l;if(e===void 0)c=`Loading this attempt's log`,l=Z(`div`,{className:`task-log-loading`,children:`Loading attempt log…`});else if(e===null)c=`This attempt's log could not be loaded`,l=Z(`div`,{className:`task-log-error`,children:[Z(`div`,{className:`task-timeline-detail`,children:`Could not load this attempt's log.`}),Z(`button`,{className:`btn`,onClick:t,children:`Retry`})]});else if(e.found===!1&&!e.disabled)c=`No log recorded for this attempt`,l=Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`No log recorded for this attempt`}),Z(`div`,{children:`This attempt produced no output, or it has not started writing yet.`})]});else if(e.disabled)c=`This dashboard cannot read task logs`,l=Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`No persisted log for this attempt`}),Z(`div`,{children:`This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.`})]});else{let t=e.entries||[],r=n==null?null:Mt(n,s||null),i=r?Z(`a`,{className:`btn btn-small task-log-download`,href:r,download:!0,children:`Download log`}):null;t.length?(c=`${t.length} log entr${t.length===1?`y`:`ies`} shown`,l=Z(S,{children:[Z(`div`,{className:`log-list task-log-list`,children:t.map((e,t)=>Z(jt,{entry:e},t))}),i]})):(c=`This attempt's log has no entries matching the current filter`,l=Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`Nothing recorded`}),Z(`div`,{children:`This attempt's log file has no entries matching the current filter.`}),i]}))}return Z(S,{children:[Z(Ft,{filters:i,onFilterChange:a,stages:o,attempt:s}),Z(It,{text:c}),l]})}function Rt(){return typeof window<`u`&&window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches===!0}function zt(){return Rt()?`auto`:`smooth`}function Bt(e){let t=X(null);return Y(()=>{t.current&&t.current.replaceChildren(Xe(e))},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function Vt({kind:e,message:t}){return e===`session-expired`?Z(`span`,{className:`task-action-error task-action-error-session`,children:[`Your session has expired.`,` `,Z(`button`,{className:`button btn btn-small`,type:`button`,onClick:()=>window.location.reload(),children:`Reload to sign in`})]}):e===`refused`?Z(`span`,{className:`task-action-error task-action-error-refused`,children:[t,` — you can't do that.`]}):Z(`span`,{className:`task-action-error task-action-error-broken`,children:[t,` — try again, or check the daemon.`]})}function Ht({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Ut({taskId:e,attempt:t,state:n,onLoad:r,onRetry:i}){let a=X(r);return a.current=r,Y(()=>{n===void 0&&a.current()},[n]),Z(Lt,{state:n,taskId:e,attempt:t,onRetry:i})}function Wt({query:e}){let[t,n]=J(null),[r,i]=J(null),[a,o]=J(()=>bt(e)),[s,c]=J(``),l=Number(e.get(`task`)),u=Number.isFinite(l)&&l>0?l:null,[d,f]=J(u),[p,m]=J(u!==null),[h,g]=J(new Map),[_,v]=J(new Map),y=X(new Set),[b,x]=J(new Set),[C,w]=J(new Map),[T,E]=J(new Set),D=async()=>{try{i(null);let e=await U.tasks();return n(e),d&&e.some(e=>String(e.id)===String(d))&&(h.has(d)||O(d)),e}catch(e){return i(String(e.message||e)),n(null),null}};Y(()=>{D()},[]);let O=async e=>{try{let t=await U.task(e);g(n=>new Map(n).set(e,t||[]))}catch{g(t=>new Map(t).set(e,null))}},k=async(e,t,{force:n=!1}={})=>{let r=Pt(e,t);if(!(y.current.has(r)&&!n)){y.current.add(r),n&&v(e=>{let t=new Map(e);return t.delete(r),t});try{let n=await U.taskLogs(e,{attempt:t||void 0,limit:500});v(e=>new Map(e).set(r,n))}catch{v(e=>new Map(e).set(r,null))}}},A=e=>{g(t=>{let n=new Map(t);return n.delete(e),n})},j=async(e,t)=>{w(t=>{let n=new Map(t);return n.delete(e),n}),E(t=>new Set(t).add(e));try{await U.taskAction(e,t),E(t=>{let n=new Set(t);return n.delete(e),n}),t===`archive`&&f(null),A(e);let n=await D();Array.isArray(n)&&n.find(t=>String(t.id)===String(e))&&d===e&&O(e)}catch(t){E(t=>{let n=new Set(t);return n.delete(e),n}),w(n=>new Map(n).set(e,ce(t)))}};Y(()=>{p&&d&&t&&(m(!1),requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${d}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView?.({block:`center`,behavior:zt()}))}))},[p,d,t]);let M=(e,t)=>{t&&t.stopPropagation();let n=d!==e;f(n?e:null),n&&O(e)},N=e=>{x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},P=()=>{if(!t)return null;let e=t.length,n={};for(let e of t)n[e.status]=(n[e.status]||0)+1;let r=n.running||0,i=(n.waiting_human||0)+(n.parked||0),a=(n.merged||0)+(n.pr_open||0);return Z(`div`,{className:`grid grid-4 task-summary`,children:[Z(Bt,{label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),Z(Bt,{label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),Z(Bt,{label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),Z(Bt,{label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`})]})},F=e=>{let t=C.get(e.id),n=t?Vt(t):null,r=T.has(e.id),i=e=>e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``,a=(e.actions||[]).map(t=>{let n=Ce(t);if(!n)return null;let a=e.title||`this task`,o=n.confirm?n.confirm.replaceAll(`{title}`,a):void 0,s=[`button`,`btn`,`btn-small`,i(n.kind)].filter(Boolean).join(` `);if(n.kind===`link`){if(t===`open_pr`)return I(e,`pull_request`,e.pr_number,n.label);if(t===`open_issue`)return I(e,`issue`,e.issue_number,n.label)}return Z(`button`,{className:s,type:`button`,disabled:r,onClick:n=>{n.stopPropagation(),!(o&&!window.confirm(o))&&j(e.id,t)},children:n.label},t)}).filter(Boolean);return!a.length&&!n?`—`:Z(`div`,{className:`task-actions`,children:[n,a]})},I=(e,t,n,r)=>{let i=t===`issue`?e.issue_url:e.pr_url;return!i||!n||t===`issue`&&e.source===`chat`?Z(`button`,{className:`btn btn-small`,type:`button`,disabled:!0,title:`${r} is unavailable`,children:r}):Z(`a`,{className:`btn btn-small`,href:i,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:r})},ee=e=>{let t=e.repo_url;return t?Z(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open ${e.owner}/${e.repo} on the forge`,onClick:e=>e.stopPropagation(),children:[e.owner,`/`,e.repo]}):null},te=e=>{let t=e.issue_url;return e.source===`chat`||!t||!e.issue_number?null:Z(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open issue #${e.issue_number} on the forge`,onClick:e=>e.stopPropagation(),children:[`#`,e.issue_number]})},L=e=>{let t=Pt(e.id,e.attempt),n=h.get(e.id),r=b.has(e.id);return Z(`tr`,{className:`task-timeline-row`,id:`task-timeline-${e.id}`,children:Z(`td`,{colSpan:8,children:[Z(`div`,{className:`task-detail-actions`,children:[Z(`div`,{className:`task-decision-title`,children:`Available actions`}),F(e)]}),e.status===`waiting_human`&&e.plan&&Z(`div`,{className:`task-decision`,children:[Z(`div`,{className:`task-decision-title`,children:`Decision required`}),Z(`div`,{className:`task-decision-plan`,children:e.plan})]}),e.status===`parked`&&e.park_reason&&Z(`div`,{className:`task-decision`,children:[Z(`div`,{className:`task-decision-title`,children:`Park reason`}),Z(`div`,{className:`task-decision-plan`,children:e.park_reason})]}),n===void 0?Z(`div`,{className:`task-timeline-loading`,children:`Loading timeline…`}):n===null?Z(`div`,{className:`task-timeline-error`,children:[Z(`div`,{className:`task-timeline-title`,children:`Could not load timeline`}),Z(`div`,{className:`task-timeline-detail`,children:`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`}),Z(`button`,{className:`btn`,onClick:()=>O(e.id),children:`Retry`})]}):n.length?Z(`ul`,{className:`task-timeline`,children:n.map((e,t)=>{let n=Tt(e);return Z(`li`,{className:`task-timeline-entry`,children:[Z(`span`,{className:`task-timeline-dot`}),Z(`div`,{children:[Z(`div`,{className:`task-timeline-kind`,children:n.title}),n.detail&&Z(`div`,{className:`task-timeline-detail`,children:n.detail}),Z(`div`,{className:`task-timeline-when`,children:Ee(e.at)})]})]},t)})}):Z(Ht,{title:`No events yet`,detail:`This task has not recorded any transitions.`}),Z(`div`,{className:`task-logs-section`,children:[Z(`div`,{className:`task-decision-title`,children:[`Attempt log`,Z(`button`,{className:`btn btn-small`,onClick:()=>N(e.id),style:{marginLeft:`10px`},children:r?`Hide`:`Show`})]}),r&&Z(Ut,{taskId:e.id,attempt:e.attempt,state:_.has(t)?_.get(t):void 0,onLoad:()=>k(e.id,e.attempt),onRetry:()=>k(e.id,e.attempt,{force:!0})})]})]})})};return Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Tasks`}),Z(`p`,{className:`page-sub`,children:`Every issue archied has picked up, and where it stands.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:D,children:`Refresh`})})]}),r?Z(`div`,{className:`grid grid-4 task-summary`,children:Z(`div`,{className:`card`,children:Z(Ht,{title:`Cannot reach archied`,detail:r})})}):P(),Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`All tasks`}),Z(`p`,{className:`card-sub`,children:`Click a row for its timeline`})]}),Z(`div`,{className:`task-filters`,children:[Z(`input`,{className:`task-search`,type:`search`,placeholder:`Search by title or repo…`,value:s,onInput:e=>c(e.target.value.trim().toLowerCase())}),Z(`select`,{className:`task-filter`,value:a,onChange:e=>o(e.target.value),children:[Z(`option`,{value:``,children:`All statuses`}),Z(`option`,{value:`needs_you`,children:`Needs you`}),xe().map(e=>Z(`option`,{value:e,children:ye(e)},e))]})]})]}),Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(e=>Z(`th`,{children:e},e))})}),Z(`tbody`,{children:(()=>{if(r)return Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(Ht,{title:`Cannot reach archied`,detail:r})})});if(!t)return Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(`div`,{className:`task-timeline-loading`,children:`Loading tasks...`})})});if(!t.length)return Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(Ht,{title:`No tasks yet`,detail:`Tasks appear here once archied picks up an issue to work.`})})});let e=t.filter(e=>xt(e,a)?!s||`${e.title} ${e.repo}`.toLowerCase().includes(s):!1);return e.length?e.map(e=>{let t=d===e.id,n=`task-timeline-${e.id}`;return Z(S,{children:[Z(`tr`,{className:`task-row`,id:`task-row-${e.id}`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),M(e.id,t))},onClick:t=>M(e.id,t),..._t(e,t),children:[Z(`td`,{className:`mono`,"data-label":`Repository`,children:[Z(`button`,{className:`task-expand`,type:`button`,"aria-expanded":String(t),"aria-controls":n,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${e.title||`untitled task`}`,onClick:t=>M(e.id,t),children:t?`−`:`+`}),ee(e)??`${e.owner}/${e.repo}`]}),Z(`td`,{className:`mono`,"data-label":`Issue`,children:te(e)??`#${e.issue_number}`}),Z(`td`,{className:`strong`,"data-label":`Title`,children:Z(`a`,{className:`task-detail-link`,href:`#/tasks/${e.id}`,title:`Open the run detail for this task`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:e.title||`(untitled)`})}),Z(`td`,{"data-label":`Status`,children:Z(Q,{text:ye(e.status),kind:be(e.status)})}),Z(`td`,{"data-label":`Workflow`,children:e.workflow||`—`}),Z(`td`,{"data-label":`Stage`,children:e.stage||`—`}),Z(`td`,{"data-label":`Last activity`,title:e.created_at?`Created ${Ee(e.created_at)}`:``,children:Ee(e.updated_at)}),Z(`td`,{"data-label":`Actions`,children:F(e)})]}),t&&L(e)]},e.id)}):Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(Ht,{title:`No matching tasks`,detail:`Try a different search or status filter.`})})})})()})]})})]})]})}function Gt(e){return Z(Wt,{query:e})}function Kt(e,t){return`${e}-tab-${t}`}function qt(e,t){return`${e}-panel-${t}`}function Jt({tabs:e,active:t,onSelect:n,prefix:r=`run`,label:i=`Run detail views`}){let a=X([]),o=t=>{let r=e[t];r&&(n?.(r.id),a.current[t]?.focus?.())};return Z(`div`,{className:`tab-bar`,role:`tablist`,"aria-label":i,onKeyDown:n=>{let r=e.findIndex(e=>e.id===t);if(r<0)return;let i;if(n.key===`ArrowRight`)i=(r+1)%e.length;else if(n.key===`ArrowLeft`)i=(r-1+e.length)%e.length;else if(n.key===`Home`)i=0;else if(n.key===`End`)i=e.length-1;else return;n.preventDefault(),o(i)},children:e.map((e,i)=>{let o=e.id===t;return Z(`button`,{ref:e=>{a.current[i]=e},id:Kt(r,e.id),className:`tab${o?` is-selected`:``}`,type:`button`,role:`tab`,"aria-selected":o,"aria-controls":qt(r,e.id),tabIndex:o?0:-1,onClick:()=>n?.(e.id),children:e.label},e.id)})})}var Yt={ok:{label:`ok`,kind:`ok`},failed:{label:`failed`,kind:`danger`},interrupted:{label:`interrupted`,kind:`warn`},running:{label:`running`,kind:`info`},unknown:{label:`unknown`,kind:`idle`}};function Xt(e){return Yt[e]||{label:e||`unknown`,kind:`idle`}}function Zt(e,t,n){return(e||[]).filter(e=>e&&e.kind===`agent_finish`&&Number(e.attempt)===Number(t)&&(e.stage||``)===(n||``)).map(e=>Tt(e))}function Qt(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`start time not recorded`:`started ${t.toISOString().replace(`T`,` `).slice(0,16)} UTC`}function $t({stage:e,attemptNumber:t,events:n}){let r=Xt(e.status),i=Ct(e.duration_ms),a=Zt(n,t,e.name);return Z(`li`,{className:`run-stage`,"data-status":e.status||`unknown`,children:[Z(`span`,{className:`run-stage-node`,"aria-hidden":`true`}),Z(`div`,{className:`run-stage-body`,children:[Z(`div`,{className:`run-stage-head`,children:[Z(`span`,{className:`run-stage-name mono`,children:e.name||`(unnamed stage)`}),Z(Q,{text:r.label,kind:r.kind}),Z(`span`,{className:`run-stage-duration`,children:i?`ran for ${i}`:`duration not recorded`})]}),e.error?Z(`div`,{className:`run-stage-error`,children:e.error}):null,a.map((e,t)=>Z(`div`,{className:`run-agent-report`,children:[Z(`span`,{className:`run-agent-report-label`,children:`Agent's own report, not verified by archie: `}),[e.title,e.detail].filter(Boolean).join(` · `)]},t))]})]})}function en({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function tn({count:e}){let t=Number(e)||0;return t?Z(`p`,{className:`run-rail-note`,children:[t,` event`,t===1?``:`s`,` on this task predate attempt attribution and cannot be assigned to a run.`]}):null}function nn({state:e,attemptNumber:t,events:n,onRetry:r}){if(e===void 0)return Z(`div`,{className:`run-loading`,children:`Loading this task's attempts…`});if(e===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this task's attempts`}),Z(`div`,{className:`run-error-detail`,children:`archied did not answer for this task's run history. It may be restarting — retry, or check the daemon.`}),r?Z(`button`,{className:`btn`,type:`button`,onClick:r,children:`Retry`}):null]});let i=e?.attempts||[];if(!i.length)return Z(S,{children:[Z(en,{title:`No attempts recorded`,detail:`This task has no recorded run. An attempt is written when a stage event is emitted, and none exist here.`}),Z(tn,{count:e?.unattributed_events})]});let a=i.find(e=>Number(e.attempt)===Number(t));if(!a)return Z(S,{children:[Z(en,{title:`Attempt ${t} is not recorded for this task`,detail:`This task recorded attempt ${i.map(e=>e.attempt).join(`, `)}.`}),Z(tn,{count:e?.unattributed_events})]});let o=a.stages||[],s=Xt(a.status);return Z(`div`,{className:`run-rail`,children:[Z(`div`,{className:`run-rail-head`,children:[Z(`span`,{className:`run-rail-attempt`,children:[`Attempt `,a.attempt]}),Z(Q,{text:s.label,kind:s.kind}),Z(`span`,{className:`run-rail-when`,children:Qt(a.started_at)})]}),o.length?Z(`ol`,{className:`run-stages`,"aria-label":`Stages recorded in attempt ${a.attempt}`,children:o.map((e,t)=>Z($t,{stage:e,attemptNumber:a.attempt,events:n},`${e.seq??t}:${e.name}`))}):Z(en,{title:`No stages recorded for this attempt`,detail:`The attempt exists, but nothing recorded a stage for it.`}),Z(`p`,{className:`run-rail-legend`,children:[Z(`strong`,{children:`ok`}),` means the stage returned without error. Archie records no exit code and does not verify that the work was correct, so this is a progress status, not a check result.`]}),Z(tn,{count:e?.unattributed_events})]})}var rn={added:`Added`,modified:`Modified`,deleted:`Deleted`,renamed:`Renamed`,typechange:`Type changed`};function an(e){return rn[e]||e||`unknown`}function on(e,t){let n=e?.repo_url||t?.repo_url||``,r=t&&String(t.pr_number??``)!==``&&String(t.pr_number)===String(e?.pr_number??``);return{repo:n,pr:e?.pr_url||r&&t.pr_url||``}}function sn(e={}){let t=Number(e.files)||0,n=[`${t} file${t===1?``:`s`}`];return e.additions&&n.push(`+${e.additions}`),e.deletions&&n.push(`−${e.deletions}`),n.join(` · `)}function cn({capture:e}){let t=e.files||[],n=Number(e.totals?.files)||t.length;return t.length?Z(S,{children:[Z(`table`,{className:`table run-changes-table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Path`}),Z(`th`,{children:`Change`}),Z(`th`,{className:`run-changes-count`,children:`Added`}),Z(`th`,{className:`run-changes-count`,children:`Deleted`})]})}),Z(`tbody`,{children:t.map((e,t)=>Z(`tr`,{children:[Z(`td`,{className:`mono run-changes-path`,children:[e.old_path?Z(`span`,{className:`run-changes-old`,children:[e.old_path,` → `]}):null,e.path]}),Z(`td`,{children:[an(e.status),e.binary?Z(`span`,{className:`run-changes-hint`,children:`no textual hunks`}):null]}),Z(`td`,{className:`run-changes-count mono`,children:e.additions?`+${e.additions}`:`—`}),Z(`td`,{className:`run-changes-count mono`,children:e.deletions?`−${e.deletions}`:`—`})]},`${e.path}:${t}`))})]}),e.truncated?Z(`p`,{className:`run-changes-note`,children:[`Showing the first `,t.length,` of `,n,` files. The totals above cover every file in this capture.`]}):null]}):Z(`div`,{className:`run-changes-empty`,children:[`This capture recorded no file entries`,n?`, though its totals cover ${n} file${n===1?``:`s`}`:``,`.`]})}function ln({capture:e,task:t}){let n=on(e,t),r=e.pr_number;return Z(`section`,{className:`run-capture`,children:[Z(`div`,{className:`run-capture-head`,children:[Z(`span`,{className:`run-capture-when`,children:[e.captured_after?`Captured after ${e.captured_after}`:`Captured`,e.stage?` in stage ${e.stage}`:``]}),Z(`span`,{className:`run-capture-at`,children:e.captured_at?Ee(e.captured_at):``})]}),Z(`div`,{className:`run-capture-meta`,children:[Z(`span`,{className:`mono`,children:n.repo?Z(`a`,{className:`run-capture-link`,href:n.repo,target:`_blank`,rel:`noreferrer`,children:[e.owner,`/`,e.repo]}):`${e.owner||``}/${e.repo||``}`}),e.branch?Z(`span`,{className:`mono run-capture-branch`,children:[e.branch,e.base?` → ${e.base}`:``]}):null,e.head_sha?Z(`span`,{className:`mono run-capture-sha`,children:String(e.head_sha).slice(0,8)}):null,r?n.pr?Z(`a`,{className:`run-capture-link`,href:n.pr,target:`_blank`,rel:`noreferrer`,children:[`PR #`,r]}):Z(`span`,{className:`mono`,children:[`PR #`,r]}):null,Z(`span`,{className:`run-capture-totals`,children:sn(e.totals)})]}),Z(cn,{capture:e})]})}function un({state:e,task:t,onRetry:n}){if(e===void 0)return Z(`div`,{className:`run-loading`,children:`Loading changed files…`});if(e===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this attempt's changed files`}),Z(`div`,{className:`run-error-detail`,children:`archied did not answer for this attempt. It may be restarting — retry, or check the daemon.`}),n?Z(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]});let r=e.captures||[];return e.found===!0&&!r.length?Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`A change capture was recorded but could not be read`}),Z(`div`,{children:`This attempt has a change capture event, but this dashboard could not decode its payload. That is a read failure, not a statement about what the attempt changed.`})]}):!e.found||!r.length?Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`No change capture was recorded for this attempt`}),Z(`div`,{children:`Archie records what an attempt changed when it commits or pushes that work. Nothing was recorded here — the attempt may predate capture, or it produced no commit. This is not the same as "no files changed".`})]}):Z(`div`,{className:`run-changes`,children:r.map((e,n)=>Z(ln,{capture:e,task:t},`${e.captured_at||``}:${n}`))})}function dn(e,t){return(e||[]).find(e=>e&&e.kind===`config_captured`&&Number(e.attempt)===Number(t))||null}function fn({events:e,attempt:t,onRetry:n}){if(e===void 0)return Z(`div`,{className:`run-loading`,children:`Loading this task's events…`});if(e===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this task's events`}),Z(`div`,{className:`run-error-detail`,children:`The configuration is recorded as an event on the task, so it cannot be shown while the event stream is unreadable. archied did not answer — retry, or check the daemon.`}),n?Z(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]});let r=dn(e,t);if(!r)return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`Not captured for this run`}),Z(`div`,{children:[`Archie records the effective configuration when it dispatches an attempt. Attempt `,t,` `,`has no such record — it predates the record, or the capture did not run. Nothing here says the run used the defaults.`]})]});let i=r.data||{},a=i.schema||``,o=i.document;return Z(`div`,{className:`run-config`,children:[Z(`p`,{className:`run-config-scope`,children:[`This is attempt `,r.attempt,`'s effective task-runtime configuration: a non-secret subset covering bot identity, models, limits, budgets, dispatch, diff cap, notifications, forge host and tool policy. It is not the dashboard configuration view — providers, repositories, identities, credentials and lock state are not part of it.`]}),Z(`div`,{className:`run-config-when`,children:[`Captured `,r.at||`at an unrecorded time`,r.stage?` in stage ${r.stage}`:``]}),a===`archie/task-config@1`?Z(`pre`,{className:`run-json`,children:JSON.stringify(o??{},null,2)}):Z(S,{children:[Z(`div`,{className:`run-config-unknown`,children:[`Recorded in an unknown schema`,a?` (${a})`:``,`. The raw payload is shown verbatim; nothing here reinterprets it.`]}),Z(`pre`,{className:`run-json`,children:JSON.stringify(i,null,2)})]})]})}function pn({state:e,attempt:t,onRetry:n}){return e===void 0?Z(`div`,{className:`run-loading`,children:`Loading the stored record…`}):e===null?Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load the stored record`}),Z(`div`,{className:`run-error-detail`,children:`archied did not answer for this task's debug view. It may be restarting — retry, or check the daemon.`}),n?Z(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]}):Z(`div`,{className:`run-debug`,children:[Z(`p`,{className:`run-debug-note`,children:[`The stored task record and its events, verbatim. Events are unfiltered on purpose: this is every event the task has, and each one carries the attempt it belongs to. Attempt `,t,` `,`is the one selected above.`]}),Z(`pre`,{className:`run-json`,children:JSON.stringify(e,null,2)})]})}var mn=[{id:`stages`,label:`Stages`},{id:`log`,label:`Log`},{id:`changes`,label:`Changed files`},{id:`config`,label:`Configuration`},{id:`debug`,label:`Debug`}],hn=`run`,gn=new Set(mn.map(e=>e.id));function _n(e){let t=String(e??``).trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:null}function vn(e){let t=e?.get?.(`tab`)||``;return gn.has(t)?t:mn[0].id}function yn(e){let t=e?.get?.(`attempt`);if(t==null||t===``)return null;let n=Number(t);return Number.isInteger(n)&&n>0?n:null}function bn(e,t,n){let r=new URLSearchParams;return r.set(`tab`,t||mn[0].id),n&&r.set(`attempt`,String(n)),`#/tasks/${e}?${r.toString()}`}function xn(e,t,n){try{window.history.replaceState(null,``,`${location.pathname}${location.search}${bn(e,t,n)}`)}catch{}}function Sn(e,t){return`${e}|${Number(t)||0}`}function Cn({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function wn({id:e}){return Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Task not found`}),Z(`p`,{className:`page-sub`,children:[`No task with id `,e,` in this deployment.`]})]}),Z(`div`,{className:`page-actions`,children:Z(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`})})]}),Z(`div`,{className:`card`,children:Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:[`Nothing is recorded for task `,e]}),Z(`div`,{children:`archied answered that this task does not exist, so there is no run history to show.`})]})})]})}function Tn({raw:e}){return Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Not a task id`}),Z(`p`,{className:`page-sub`,children:`The run view addresses one task by its id: #/tasks/42`})]}),Z(`div`,{className:`page-actions`,children:Z(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`})})]}),Z(`div`,{className:`card`,children:Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:[`“`,e,`” is not a task id`]}),Z(`div`,{children:`A task id is a positive whole number. Nothing was requested.`})]})})]})}function En({attempts:e,selected:t,onSelect:n}){let r=e?.attempts||[];return r.length?Z(`div`,{className:`run-attempts`,role:`group`,"aria-label":`Attempts of this task`,children:r.map(e=>{let r=Xt(e.status),i=Number(e.attempt)===Number(t);return Z(`button`,{type:`button`,className:`run-attempt${i?` is-selected`:``}`,"aria-pressed":i,onClick:()=>n(e.attempt),children:[Z(`span`,{className:`run-attempt-id`,children:[`Attempt `,e.attempt]}),Z(Q,{text:r.label,kind:r.kind}),Z(`span`,{className:`run-attempt-meta`,children:[(e.stages||[]).length,` stage`,(e.stages||[]).length===1?``:`s`]})]},e.attempt)})}):null}function Dn({id:e,query:t}){let[n,r]=J(()=>vn(t)),[i,a]=J(()=>yn(t)),[o,s]=J(void 0),[c,l]=J(void 0),[u,d]=J(!1),[f,p]=J(void 0),[m,h]=J(Nt),[g,_]=J(new Map),[v,y]=J(new Map),[b,x]=J(new Map),[S,C]=J(!1),[w,T]=J(null),[E,D]=J(0),O=X(new Set),k=Array.isArray(o)&&o.find(t=>String(t.id)===String(e))||null,A=Number(c?.current_attempt)>0?Number(c.current_attempt):null,j=i??A,M=(c?.attempts||[]).find(e=>Number(e.attempt)===Number(j)),N=[...new Set((M?.stages||[]).map(e=>e.name).filter(Boolean))],P=(e,t,n,{force:r=!1}={})=>{O.current.has(e)&&!r||(O.current.add(e),n(t=>new Map(t).set(e,void 0)),t().then(t=>n(n=>new Map(n).set(e,t))).catch(()=>n(t=>new Map(t).set(e,null))))},F=()=>{s(void 0),U.tasks().then(e=>s(e)).catch(()=>s(null))},I=()=>{l(void 0),d(!1),U.taskAttempts(e).then(e=>l(e)).catch(e=>{e?.status===404&&d(!0),l(null)})},ee=()=>{p(void 0),U.task(e).then(e=>p(e||[])).catch(()=>p(null))},te=(t,n)=>P(Pt(e,t,m),()=>U.taskLogs(e,{attempt:t||void 0,level:m.level,stage:m.stage,limit:500}),_,n),L=(t,n)=>P(Sn(e,t),()=>U.taskChanges(e,{attempt:t}),y,n),R=(t,n)=>P(Sn(e,t),()=>U.taskDebug(e,{attempt:t}),x,n),ne=()=>{O.current=new Set,_(new Map),y(new Map),x(new Map),F(),I(),ee(),D(e=>e+1)};Y(()=>{F(),I(),ee()},[]),Y(()=>{j!=null&&(n===`log`?te(j):n===`changes`?L(j):n===`debug`&&R(j))},[n,j,m,E]),Y(()=>{xn(e,n,j)},[e,n,j]);let z=async()=>{let t=k?.title||`task ${e}`;if(window.confirm(`Start a new run for "${t}"? This is a new attempt, and the previous attempt's commits are discarded.`)){T(null),C(!0);try{await U.taskAction(e,`retry`),O.current=new Set,_(new Map),y(new Map),x(new Map),a(null),F(),I(),ee(),D(e=>e+1)}catch(e){T(ce(e))}finally{C(!1)}}};if(u)return Z(wn,{id:e});let B=j==null?null:Pt(e,j,m),re=Sn(e,j),ie=Sn(e,j),ae=()=>{if(n===`stages`)return Z(nn,{state:c,attemptNumber:j,events:f,onRetry:I});if(c===void 0)return Z(`div`,{className:`run-loading`,children:`Loading this task's attempts…`});if(c===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this task's attempts`}),Z(`div`,{className:`run-error-detail`,children:`This panel reads one attempt, and the task's run history could not be read.`}),Z(`button`,{className:`btn`,type:`button`,onClick:I,children:`Retry`})]});if(j==null)return Z(Cn,{title:`No attempt recorded`,detail:`This task has no recorded run, so there is nothing to read for an attempt.`});switch(n){case`log`:return Z(Lt,{state:B&&g.has(B)?g.get(B):void 0,attempt:j,stages:N,filters:m,onFilterChange:h,taskId:e,onRetry:()=>te(j,{force:!0})});case`changes`:return Z(un,{state:v.has(re)?v.get(re):void 0,task:k,onRetry:()=>L(j,{force:!0})});case`config`:return Z(fn,{events:f,attempt:j,onRetry:ee});case`debug`:return Z(pn,{state:b.has(ie)?b.get(ie):void 0,attempt:j,onRetry:()=>R(j,{force:!0})});default:return Z(nn,{state:c,attemptNumber:j,events:f,onRetry:I})}},V=Ce(`retry`),oe=!!(V&&(k?.actions||[]).includes(`retry`));return Z(`div`,{className:`run-page`,children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:k?.title||`Task #${e}`}),Z(`p`,{className:`page-sub`,children:[`One run of task `,e,k?.workflow?` · ${k.workflow} workflow`:``,k?.repo?` · ${k.owner}/${k.repo}`:``]})]}),Z(`div`,{className:`page-actions`,children:[Z(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`}),Z(`button`,{className:`btn`,type:`button`,onClick:ne,children:`Refresh`})]})]}),Z(`div`,{className:`run-meta`,children:[Z(`span`,{className:`run-meta-item`,children:[Z(`span`,{className:`run-meta-label`,children:`Task status`}),o===void 0?Z(`span`,{className:`run-meta-muted`,children:`loading…`}):k?Z(Q,{text:ye(k.status),kind:be(k.status)}):Z(`span`,{className:`run-meta-muted`,children:`not read`})]}),Z(`span`,{className:`run-meta-item`,children:[Z(`span`,{className:`run-meta-label`,children:`Attempt`}),Z(`span`,{className:`run-meta-value`,children:c===null?`run history unreadable`:c===void 0?`loading…`:j==null?`none recorded`:`attempt ${j} of ${A??j}`})]}),k?.repo_url?Z(`a`,{className:`run-meta-link`,href:k.repo_url,target:`_blank`,rel:`noreferrer`,children:[k.owner,`/`,k.repo]}):null,k?.issue_url&&k.issue_number?Z(`a`,{className:`run-meta-link`,href:k.issue_url,target:`_blank`,rel:`noreferrer`,children:[`Issue #`,k.issue_number]}):null,k?.pr_url&&k.pr_number?Z(`a`,{className:`run-meta-link`,href:k.pr_url,target:`_blank`,rel:`noreferrer`,children:[`PR #`,k.pr_number]}):null]}),o===null?Z(`p`,{className:`run-note`,children:`The task list could not be read, so this page cannot show the task's current status or its operator controls. The run history below comes from the task's own endpoints.`}):null,Array.isArray(o)&&!k?Z(`p`,{className:`run-note`,children:[`Task `,e,` is not among the tasks this dashboard lists (the list covers the 100 most recently updated). Its recorded attempts are shown below; the Debug tab holds the stored record verbatim.`]}):null,Z(`section`,{className:`run-restart`,"aria-label":`Start a new run`,children:[Z(`button`,{className:`btn ${V?.kind===`primary`?`btn-primary`:``}`,type:`button`,disabled:!oe||S,title:`Retry this task as a new run`,onClick:z,children:S?`Starting…`:`Start a new run`}),Z(`p`,{className:`run-restart-copy`,children:`Starts a new attempt for this task: a fresh worktree reset onto the base branch. The previous attempt's commits are discarded — they are not carried into the new run.`}),!oe&&o!==void 0?Z(`p`,{className:`run-restart-unavailable`,children:k?`A new run can only start from a parked task. This task is ${ye(k.status)}.`:`This task's operator controls could not be read, so a new run cannot be started from here.`}):null,w?Z(`p`,{className:`run-restart-error run-restart-error-${w.kind}`,children:w.kind===`session-expired`?`Your session has expired. Reload to sign in.`:w.kind===`refused`?`${w.message} — this run cannot be restarted from here.`:`${w.message} — try again, or check the daemon.`}):null]}),Z(En,{attempts:c,selected:j,onSelect:e=>a(e)}),Z(`div`,{className:`card run-card`,children:[Z(Jt,{tabs:mn,active:n,onSelect:r,prefix:hn}),Z(`div`,{className:`run-panel`,role:`tabpanel`,id:qt(hn,n),"aria-labelledby":Kt(hn,n),tabIndex:0,children:ae()})]})]})}function On(e,t){let n=t?.id,r=_n(n);return r===null?Z(Tn,{raw:n??``}):Z(Dn,{id:r,query:e},r)}function kn({title:e,detail:t}){return Z(`div`,{class:`empty`,children:[Z(`div`,{class:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function An(e){return Z(jn,{query:e})}function jn(){let[e,t]=J([]),[n,r]=J(``),[i,a]=J(null),o=async()=>{try{let e=await U.skills();t(e?.skills||[]),a(null)}catch(e){t([]),a(String(e.message||e))}};Y(()=>{o()},[]);let s=(e,t)=>!t||`${e.name} ${e.description}`.toLowerCase().includes(t),c=He(()=>e.filter(e=>s(e,n)),[e,n]);return Z(`div`,{children:[Z(`div`,{class:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{class:`page-title`,children:`Skills`}),Z(`p`,{class:`page-sub`,children:`What Archie can do, in plain language.`})]}),Z(`div`,{class:`page-actions`,children:Z(`button`,{class:`btn`,onClick:o,children:`Refresh`})})]}),Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Catalogue`}),Z(`p`,{class:`card-sub`,children:`Project, shared, and user-global skills`})]}),Z(`input`,{class:`skill-search`,type:`search`,placeholder:`Search skills…`,onInput:e=>r(e.target.value.trim().toLowerCase())})]}),Z(`div`,{class:`grid grid-2`,children:i?Z(kn,{title:`Cannot reach archied`,detail:i}):e.length?c.length?c.map(e=>Z(`div`,{class:`card skill-card`,children:[Z(`div`,{class:`card-head`,children:[Z(`h3`,{class:`card-title`,children:e.name||`Untitled skill`}),e.workflow&&Z(Q,{text:e.workflow,kind:`info`})]}),Z(`p`,{class:`skill-desc`,children:e.description||`No description provided.`}),Z(`div`,{class:`skill-source`,children:e.source||`Unknown source`})]},e.name)):Z(kn,{title:`No skills match`,detail:`Nothing found for "${n}".`}):Z(kn,{title:`No skills discovered yet`,detail:`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`})})]})]})}var Mn={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function Nn(e){return Mn[e]?Mn[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function Pn(e,t){return t?Math.round(e/t*100):0}function Fn(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function In({title:e,detail:t}){return Z(`div`,{class:`empty`,children:[Z(`div`,{class:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Ln({fraction:e,kind:t=`ok`}){let n=Math.min(100,Math.max(0,e));return Z(`div`,{class:`wf-bar`,children:Z(`div`,{class:`wf-bar-fill wf-bar-${t}`,style:{width:`${n}%`}})})}function Rn(e){return Z(zn,{query:e})}function zn(){let[e,t]=J([]),[n,r]=J([]),[i,a]=J([]),[o,s]=J(null),c=async()=>{try{let e=await U.workflows();t(e?.definitions||[]),r(e?.workflows||[]),a(e?.stages||[]),s(null)}catch(e){s(String(e.message||e))}};return Y(()=>{c()},[]),Z(`div`,{children:[Z(`div`,{class:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{class:`page-title`,children:`Workflows`}),Z(`p`,{class:`page-sub`,children:`Run outcomes and spend per workflow, and where stages get stuck.`})]}),Z(`div`,{class:`page-actions`,children:Z(`button`,{class:`btn`,onClick:c,children:`Refresh`})})]}),Z(Bn,{definitions:e}),o?Z(`div`,{class:`card`,children:Z(In,{title:`Cannot reach archied`,detail:o})}):Z(S,{children:[Z(Vn,{workflows:n,definitions:e}),Z(Hn,{stages:i})]})]})}function Bn({definitions:e}){if(!e.length)return null;let t=e.filter(e=>e.enabled)[0]?.id||``,[n,r]=J(``),[i,a]=J(``),[o,s]=J(t),[c,l]=J(``),[u,d]=J(``),[f,p]=J(!1),[m,h]=J(``);return Y(()=>{!o&&t&&s(t)},[t,o]),Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Start work`}),Z(`p`,{class:`card-sub`,children:`This enters Archie’s normal admitted task queue.`})]})}),Z(`form`,{class:`wf-form`,onSubmit:async e=>{e.preventDefault(),p(!0),h(``);try{let e=await U.workRequest({identity:n,repository:i,workflow:o,title:c,instructions:u});h(`Queued task #${e.task_id}.`),r(``),a(``),s(t),l(``),d(``)}catch(e){h(String(e.message||e))}finally{p(!1)}},children:[Z(`input`,{placeholder:`Identity`,required:!0,value:n,onInput:e=>r(e.target.value)}),Z(`input`,{placeholder:`owner/repository`,required:!0,value:i,onInput:e=>a(e.target.value)}),Z(`select`,{required:!0,value:o,onInput:e=>s(e.target.value),children:e.filter(e=>e.enabled).map(e=>Z(`option`,{value:e.id,children:Nn(e.name||e.id)},e.id))}),Z(`input`,{placeholder:`Short task title`,required:!0,value:c,onInput:e=>l(e.target.value)}),Z(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3,value:u,onInput:e=>d(e.target.value)}),Z(`button`,{class:`btn`,type:`submit`,disabled:f,children:`Start work`}),m&&Z(`p`,{class:`card-sub`,children:m})]})]})}function Vn({workflows:e,definitions:t}){let n=new Map(e.map(e=>[e.workflow,e])),r=t.map(e=>({...e,...n.get(e.id)||{workflow:e.id,runs:0,merged:0}}));return r.length?Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Per workflow`}),Z(`p`,{class:`card-sub`,children:`Success rate is merged tasks over all runs`})]})}),Z(`div`,{class:`table-scroll`,children:Z(`table`,{class:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Workflow`}),Z(`th`,{children:`Origin`}),Z(`th`,{children:`Runs`}),Z(`th`,{children:`Success rate`}),Z(`th`,{children:`Avg tokens`}),Z(`th`,{children:`Avg steps`})]})}),Z(`tbody`,{children:r.map(e=>{let t=Pn(e.merged,e.runs);return Z(`tr`,{children:[Z(`td`,{class:`strong`,children:Nn(e.workflow)}),Z(`td`,{class:`mono`,children:e.origin||`registry`}),Z(`td`,{children:`${e.runs} run${e.runs===1?``:`s`}`}),Z(`td`,{children:[Z(`div`,{class:`wf-rate`,children:[t,`%`,Z(`span`,{class:`wf-rate-sub`,children:[e.merged,` of `,e.runs,` merged`]})]}),Z(Ln,{fraction:t,kind:t>=50?`ok`:`warn`})]}),Z(`td`,{class:`mono`,children:e.avg_tokens?e.avg_tokens.toLocaleString():`—`}),Z(`td`,{class:`mono`,children:e.avg_steps?e.avg_steps.toFixed(1):`—`})]},e.workflow)})})]})})]}):Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:Z(`h2`,{class:`card-title`,children:`Per workflow`})})}),Z(In,{title:`No workflow runs yet`,detail:`Stats appear here once a task has run through a workflow.`})]})}function Hn({stages:e}){if(!e.length)return Z(`div`,{class:`card wf-stage-card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:Z(`h2`,{class:`card-title`,children:`Per stage`})})}),Z(In,{title:`No stage data yet`,detail:`Stage timing and failures appear here once workflows have run.`})]});let t=Math.max(...e.map(e=>e.avg_ms||0),1),n=[...e].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),r=[...e].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);return Z(`div`,{class:`grid grid-2 wf-stage-card`,children:[Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Slowest stages`}),Z(`p`,{class:`card-sub`,children:`Average duration, this workflow's stages`})]})}),Z(`div`,{class:`table-scroll`,children:Z(`table`,{class:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Workflow`}),Z(`th`,{children:`Stage`}),Z(`th`,{children:`Runs`}),Z(`th`,{children:`Avg duration`})]})}),Z(`tbody`,{children:n.map((e,n)=>Z(`tr`,{children:[Z(`td`,{children:Nn(e.workflow)}),Z(`td`,{class:`strong`,children:e.stage}),Z(`td`,{children:e.runs}),Z(`td`,{children:[Z(`div`,{class:`wf-rate`,children:Fn(e.avg_ms)}),Z(Ln,{fraction:Pn(e.avg_ms,t),kind:`info`})]})]},n))})]})})]}),Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Most failures`}),Z(`p`,{class:`card-sub`,children:`Stages that error out, over their runs`})]})}),r.length?Z(`div`,{class:`table-scroll`,children:Z(`table`,{class:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Workflow`}),Z(`th`,{children:`Stage`}),Z(`th`,{children:`Failures`})]})}),Z(`tbody`,{children:r.map((e,t)=>Z(`tr`,{children:[Z(`td`,{children:Nn(e.workflow)}),Z(`td`,{class:`strong`,children:e.stage}),Z(`td`,{children:[Z(`div`,{class:`wf-rate`,children:[e.errors,` of `,e.runs]}),Z(Ln,{fraction:Pn(e.errors,e.runs),kind:`danger`})]})]},t))})]})}):Z(In,{title:`No failures recorded`,detail:`Every stage has completed cleanly so far.`})]})]})}function Un({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Wn(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function Gn(){let[e,t]=J([]),[n,r]=J(null),i=async()=>{try{let e=await U.channels();t(e?.channels||[]),r(null)}catch(e){r(String(e.message||e))}};return Y(()=>{i()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Channels`}),Z(`p`,{className:`page-sub`,children:`The conversational front-ends Archie can be reached through.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:i,children:`Refresh`})})]}),Z(`div`,{className:`grid grid-2`,children:n?Z(Un,{title:`Cannot reach archied`,detail:n}):e.length===0?Z(Un,{title:`No channels configured`,detail:`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`}):e.map(e=>Z(`div`,{className:`card channel-card`,children:[Z(`div`,{className:`card-head`,children:[Z(`h3`,{className:`card-title`,children:e.name}),Z(Q,{text:e.state||(e.configured?`configured`:`stopped`),kind:Wn(e.state,e.configured)})]}),Z(`p`,{className:`channel-desc`,children:e.description}),Z(`p`,{className:`channel-detail`,children:e.detail}),e.reload_supported?Z(`button`,{className:`btn`,onClick:async t=>{t.currentTarget.disabled=!0;try{await U.channelReload(e.id||e.name.toLowerCase()),await i()}catch{}finally{t.currentTarget&&(t.currentTarget.disabled=!1)}},children:`Reload`}):Z(`p`,{className:`channel-detail`,children:`Reload requires a daemon restart for this adapter.`})]},e.id||e.name))})]})}function Kn(e){return Z(Gn,{query:e})}function qn({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Jn(e){return Z(Yn,{query:e})}function Yn({query:e}){let[t,n]=J([]),[r,i]=J(null),a=async()=>{try{let e=await U.curators();n(e?.curators||[]),i(null)}catch(e){i(String(e.message||e))}};return Y(()=>{a()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Curators`}),Z(`p`,{className:`page-sub`,children:`Background agents that maintain memory and skills: what ran, and why.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:a,children:`Refresh`})})]}),Z(`div`,{className:`grid grid-2`,children:r?Z(qn,{title:`Cannot reach archied`,detail:r}):t.length?t.map(e=>Z(Zn,{curator:e},e.name)):Z(qn,{title:`No curators registered`,detail:`Curators are background agent loops that maintain memory and skills. None are registered on this daemon.`})})]})}function Xn(e){switch(e){case`healthy`:return`ok`;case`degraded`:return`warn`;case`unhealthy`:return`danger`;default:return`idle`}}function Zn({curator:e}){let t=e.recent_actions||[];return Z(`div`,{className:`card curator-card`,children:[Z(`div`,{className:`card-head`,children:[Z(`h3`,{className:`card-title`,children:e.name}),Z(Q,{text:e.health?.status||`unknown`,kind:Xn(e.health?.status)})]}),e.health?.message&&Z(`p`,{className:`curator-health-message`,children:e.health.message}),Z(`p`,{className:`curator-meta`,children:e.last_run_at?`Last ran ${Ee(e.last_run_at)} · ${e.last_run_actions} action${e.last_run_actions===1?``:`s`}`:`Has not run yet`}),t.length?Z(`ul`,{className:`curator-actions`,children:t.map((e,t)=>Z(`li`,{className:`curator-action`,children:[Z(`div`,{className:`curator-action-head`,children:[Z(`span`,{className:`curator-action-type`,children:e.type||`action`}),Z(`span`,{className:`curator-action-time`,children:Ee(e.at)})]}),e.detail&&Z(`p`,{className:`curator-action-detail`,children:e.detail}),e.reason&&Z(`p`,{className:`curator-action-reason`,children:[`Why: `,e.reason]})]},t))}):Z(`p`,{className:`curator-meta`,children:`No recorded activity yet.`})]})}function Qn(e){return e==null||e===``?`—`:String(e)}function $n({label:e,value:t,opts:n}){let r=Qn(t),[i,a]=J(!1),[o,s]=J(``),[c,l]=J(null),[u,d]=J(!1),[f,p]=J(!1),m=n?.key;if(!m)return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n?.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let h=n.locked?.[m];if(h)return Z(`div`,{className:`kv is-locked`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),Z(`span`,{className:`kv-note`,children:h})]});if(n.editable===!1)return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let g=n.overridden?.includes(m),_=()=>{s(String(n.raw??``)),l(null),a(!0)},v=async()=>{p(!0),l(null);try{await U.configReset(m),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{p(!1)}},y=async()=>{let e=er(n.type,o);if(e.error){l(e.error);return}d(!0),l(null);try{await(n.save||(e=>U.configUpdate({[m]:e})))(e.value),a(!1),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{d(!1)}};if(i){let t=X(null);Y(()=>{t.current&&t.current.focus()},[]);let r=e=>{e.key===`Enter`&&(e.preventDefault(),y()),e.key===`Escape`&&a(!1)},i;return i=n.type===`bool`?Z(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:[Z(`option`,{value:`true`,children:`true`}),Z(`option`,{value:`false`,children:`false`})]}):n.type===`enum`?Z(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:(n.options||[]).map(e=>Z(`option`,{value:e,children:e},e))}):Z(`input`,{className:`kv-input`,type:`text`,value:o,onInput:e=>s(e.target.value),onKeyDown:r,ref:t}),Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),i,Z(`div`,{className:`kv-actions`,children:[Z(`button`,{className:`kv-save`,type:`button`,onClick:y,disabled:u,children:`Save`}),Z(`button`,{className:`kv-cancel`,type:`button`,onClick:()=>a(!1),disabled:u,children:`Cancel`})]}),c&&Z(`span`,{className:`kv-note is-error`,children:c})]})}return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),Z(`div`,{className:`kv-actions`,children:[g&&Z(`span`,{className:`kv-flag`,title:`Set from the dashboard; this shadows the value in the config file`,children:`overridden`}),Z(`button`,{className:`kv-btn`,type:`button`,title:`Edit ${e}`,onClick:_,children:`Edit`}),g&&Z(`button`,{className:`kv-btn`,type:`button`,title:`Discard the dashboard value and fall back to the config file`,onClick:v,disabled:f,children:`Reset`})]}),c&&Z(`span`,{className:`kv-note is-error`,children:c})]})}function er(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}function tr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function nr({sub:e,title:t,children:n}){return Z(`div`,{className:`card cfg-section`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:t||`Update status`}),Z(`p`,{className:`card-sub`,children:e})]})}),n]})}var rr={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},ir={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function ar({components:e}){return!e||!e.length?Z(nr,{sub:`How each component is deployed, and whether what's running matches what's installed.`,children:Z(tr,{title:`No components reported`,detail:`The configured update-check command returned nothing.`})}):Z(nr,{sub:`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,children:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Component`}),Z(`th`,{children:`Install type`}),Z(`th`,{children:`Running`}),Z(`th`,{children:`Latest available`}),Z(`th`,{children:`Status`})]})}),Z(`tbody`,{children:e.map(e=>Z(`tr`,{title:[`Installed claim: ${e.installed_claim||`unknown`}`,`Running: ${e.running_version||`not observed`}`,e.reference?`Reference: ${e.reference}`:null].filter(Boolean).join(` -`),children:[Z(`td`,{className:`strong`,children:e.label||e.id}),Z(`td`,{className:`mono`,children:e.install_type||`—`}),Z(`td`,{className:`mono`,children:e.running_version||`—`}),Z(`td`,{className:`mono`,children:e.latest_available||`—`}),Z(`td`,{children:Z(Q,{text:rr[e.status]||e.status,kind:ir[e.status]||`idle`})})]},e.id||e.label))})]})})})}function $({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function or({title:e,sub:t,children:n}){return Z(`div`,{className:`card cfg-section`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:e}),Z(`p`,{className:`card-sub`,children:t})]})}),n]})}function sr({origins:e}){return e?.length?Z(or,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:Z(`div`,{className:`kv-list`,children:e.map((e,t)=>Z($n,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):Z(or,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:Z($,{title:`Source provenance is unavailable.`})})}function cr(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function lr({data:e,error:t}){if(t)return Z(or,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:Z($,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return Z(or,{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:[Z(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?Z(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??ye(e.id),n=e.kind??be(e.id);return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,children:e.id}),Z(`span`,{className:`kv-value`,children:Z(Q,{text:t,kind:n})})]},e.id)})}):Z($,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),Z(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?Z(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=cr(e.kind);return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,children:e.id}),Z(`span`,{className:`kv-value`,children:Z(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):Z($,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function ur({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=J(!1),[o,s]=J(null),[c,l]=J(!!e[t]);return r?Z(`td`,{children:[Z(`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 U.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&Z(`span`,{className:`kv-note is-error`,children:o})]}):Z(`td`,{children:c?`yes`:`no`})}function dr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=J(String(e[t]??0)),[o,s]=J(null),[c,l]=J(!1);return r?Z(`td`,{children:[Z(`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 U.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&&Z(`span`,{className:`kv-note is-error`,children:o})]}):Z(`td`,{className:`mono`,children:i})}function fr({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return Z(or,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:Z($,{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 Z(or,{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:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Repository`}),Z(`th`,{children:`Base branch`}),Z(`th`,{children:`Ecosystem`}),Z(`th`,{children:`Quality gate`}),Z(`th`,{children:`Protected paths`}),Z(`th`,{children:`Concurrent`}),Z(`th`,{children:`Max retries`}),Z(`th`,{children:`Self-review`})]})}),Z(`tbody`,{children:e.map((e,i)=>Z(`tr`,{children:[Z(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),Z(`td`,{className:`mono`,children:e.base}),Z(`td`,{children:e.ecosystem||`go`}),Z(`td`,{className:`mono`,children:r(e.gate)}),Z(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),Z(ur,{r:e,field:`allow_concurrent`,onSaved:t,editable:n}),Z(dr,{r:e,field:`max_retries`,onSaved:t,editable:n}),Z(ur,{r:e,field:`review_enabled`,onSaved:t,editable:n})]},i))})]})})})}function pr(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function mr({models:e,providers:t}){let n=Object.entries(e||{}),r=Object.entries(t||{});return Z(or,{title:`Models & providers`,sub:`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,children:[Z(`h3`,{className:`cfg-subhead`,children:`Model roles`}),n.length?Z(`div`,{className:`kv-list`,children:n.map(([e,t])=>Z($n,{label:pr(e),value:t},e))}):Z($,{title:`No model roles configured`,detail:`Assign a model to at least one role (e.g. "builder") in [models].`}),Z(`h3`,{className:`cfg-subhead`,children:`Providers`}),r.length?Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Provider`}),Z(`th`,{children:`Class`}),Z(`th`,{children:`Base URL`}),Z(`th`,{children:`API key env var`}),Z(`th`,{children:`Status`})]})}),Z(`tbody`,{children:r.map(([e,t])=>Z(`tr`,{children:[Z(`td`,{className:`strong`,children:e}),Z(`td`,{children:t.class}),Z(`td`,{className:`mono`,children:t.base_url||`default`}),Z(`td`,{className:`mono`,children:t.api_key_env||`—`}),Z(`td`,{children:t.configured?Z(Q,{text:`configured`,kind:`ok`}):Z(Q,{text:`missing credentials`,kind:`warn`})})]},e))})]})}):Z($,{title:`No providers configured`,detail:`Add a [providers.] entry so a model role above has something to run on.`})]})}function hr(){let[e,t]=J(null),[n,r]=J(null),[i,a]=J(null),[o,s]=J(null),[c,l]=J(!1),[u,d]=J(null),[f,p]=J(null),m=()=>{h(),g(),_()},h=async()=>{try{let e=await U.config();t(e),r(null)}catch(e){r(String(e.message||e))}},g=async()=>{try{let e=await U.version();a(e?.components||[]),s(null),l(!1)}catch(e){e?.status===501?l(!0):s(String(e.message||e))}},_=async()=>{try{let e=await U.taskMeta();d(e),p(null)}catch(e){p(String(e.message||e))}};return Y(()=>{m()},[]),Z(`div`,{className:`cfg-page`,children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Configuration`}),Z(`p`,{className:`page-sub`,children:`What archied is actually running with right now.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:m,children:`Refresh`})})]}),Z(`div`,{children:!c&&(o?Z(`div`,{className:`card`,children:Z($,{title:`Update status unavailable`,detail:o})}):i?Z(ar,{components:i}):null)}),Z(`div`,{children:Z(lr,{data:u,error:f})}),Z(`div`,{children:n?Z(`div`,{className:`card`,children:Z($,{title:`Cannot reach archied`,detail:n})}):!e||Object.keys(e).length===0?Z(`div`,{className:`card`,children:Z($,{title:`No configuration loaded`,detail:`archied is running without a config file wired into the dashboard, so there is nothing to show.`})}):Z(S,{children:[e.reload?.overlay_unavailable&&Z(`div`,{className:`card cfg-notice`,children:Z(`p`,{children:[`The runtime config overlay is not in effect: `,e.reload.overlay_unavailable]})}),e.reload?.last_error&&Z(`div`,{className:`card cfg-notice`,children:Z(`p`,{children:[`The last config reload failed; the running config is unchanged: `,e.reload.last_error]})}),(e.schema||[]).map((t,n)=>{let r=t.fields.filter(e=>e.type!==`structured`);return r.length?Z(or,{title:t.label,sub:t.description,children:Z(`div`,{className:`kv-list`,children:r.map(t=>Z($n,{label:t.label,value:t.value,opts:{key:t.key,type:t.type,options:t.options,raw:t.value,hint:t.description,editable:t.editable&&e.editable!==!1,locked:e.locked||{},overridden:e.overridden||[],onSaved:h}},t.key))})},n):null}),Z(fr,{repos:e.repositories,onSaved:h,editable:e.editable!==!1}),Z(mr,{models:e.models,providers:e.providers}),Z(sr,{origins:e.provenance})]})})]})}function gr(e){return Z(hr,{query:e})}function _r({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function vr(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function yr(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function br(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function xr({entry:e}){let t=e.fields||{};return Z(`div`,{className:`log-row log-${vr(e.level)}`,children:[Z(`span`,{className:`log-time mono`,children:br(e.time)}),Z(`span`,{className:`log-level`,children:(e.level||`info`).toUpperCase()}),Z(`span`,{className:`log-body`,children:[Z(`span`,{className:`log-msg`,children:e.message||e.msg||``}),Object.entries(t).map(([e,t])=>Z(`span`,{className:`log-field`,children:[Z(`span`,{className:`log-field-key`,children:e}),String(yr(t))]},e))]})]})}function Sr(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Cr(){let[e,t]=J({level:``,component:``,q:``}),[n,r]=J(!1),[i,a]=J([]),[o,s]=J([]),c=X(new Map),[l,u]=J(0),[d,f]=J(!1),[p,m]=J(`connecting`),[h,g]=J(`Refreshing…`),_=X(null),v=X(null),y=async()=>{g(`Refreshing…`);try{let t=await U.logs({level:e.level,component:e.component,q:e.q,limit:500});a(e=>{let n=t.components||[];return e.length===n.length&&e.every((e,t)=>e===n[t])?e:n}),f(!!t.disabled);let n=t.disabled?`Durable history unavailable; live daemon logs continue.`:t.truncated?`showing the most recent matches from ${t.file}`:t.file||``;g(n),s(t.entries||[])}catch{g(`Cannot read logs`)}};Y(()=>{y()},[e]),Y(()=>{let e=de(e=>{if(b.current)return;let t=e;S.current(t)&&(c.current.set(Sr(t),t),t.fields?.component&&a(e=>e.includes(t.fields.component)?e:[...e,t.fields.component]),u(e=>e+1))},e=>{m(e)});return()=>e()},[]);let b=X(n);b.current=n;let x=t=>{if(e.level&&!e.level.split(`,`).includes((t.level||``).toUpperCase())||e.component&&t.fields?.component!==e.component)return!1;if(e.q){let n=e.q.toLowerCase();if(!`${t.message||t.msg||``} ${JSON.stringify(t.fields||{})}`.toLowerCase().includes(n))return!1}return!0},S=X(x);S.current=x;let C=He(()=>{let e=new Map;for(let t of o)e.set(Sr(t),t);for(let[t,n]of c.current)e.set(t,n);return[...e.values()].filter(x).slice(-1e3)},[o,l,e]);return Y(()=>{_.current&&(_.current.scrollTop=_.current.scrollHeight)},[C]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Logs`}),Z(`p`,{className:`page-sub`,children:`What Archie has been doing, newest last.`})]}),Z(`div`,{className:`page-actions`,children:[Z(`button`,{className:`btn ${n?`btn-primary`:``}`,onClick:()=>r(!n),children:n?`Resume`:`Pause`}),Z(`button`,{className:`btn`,onClick:y,children:`Refresh`})]})]}),Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{className:`log-filters`,children:[Z(`select`,{className:`log-select`,value:e.level,onChange:e=>t(t=>({...t,level:e.target.value})),children:Et.map(e=>Z(`option`,{value:e.value,children:e.label},e.value))}),Z(`select`,{className:`log-select`,value:e.component,onChange:e=>t(t=>({...t,component:e.target.value})),children:[Z(`option`,{value:``,children:`All components`}),i.map(e=>Z(`option`,{value:e,children:e},e))]}),Z(`input`,{className:`log-search`,type:`search`,placeholder:`Search messages and fields…`,onInput:e=>{let n=e.target.value;v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{t(e=>({...e,q:n}))},250)}})]}),Z(`div`,{className:`log-status`,children:[Z(`span`,{className:`log-meta`,children:h}),Z(Q,{text:p,kind:p===`live`?`ok`:`warn`})]})]}),Z(`div`,{className:`log-list`,ref:_,children:h===`Cannot read logs`?Z(_r,{title:`Cannot read logs`}):C.length?C.map(e=>Z(xr,{entry:e},Sr(e))):Z(_r,{title:d?`Durable history unavailable`:`Nothing matches`,detail:d?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`})})]})]})}function wr(e){return Z(Cr,{query:e})}function Tr({capture:e,expanded:t,onToggle:n}){return Z(S,{children:[Z(`tr`,{className:`capture-row`,tabIndex:`0`,"aria-expanded":String(t),onClick:n,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n(e))},children:[Z(`td`,{className:`mono`,children:e.source||`(unknown)`}),Z(`td`,{title:e.received_at||``,children:Ee(e.received_at)}),Z(`td`,{children:Z(Q,{text:`Unbound`,kind:`idle`})}),Z(`td`,{className:`mono`,children:e.content_type||`—`}),Z(`td`,{children:Z(`button`,{className:`btn btn-small`,type:`button`,children:t?`Hide`:`View`})})]}),t&&Z(Er,{capture:e})]})}function Er({capture:e}){return Z(`tr`,{className:`capture-detail-row`,children:Z(`td`,{colSpan:`5`,children:Z(`div`,{className:`capture-detail`,children:[Z(`div`,{className:`capture-detail-section`,children:[Z(`div`,{className:`capture-detail-title`,children:`Payload`}),Z(Dr,{raw:e.body})]}),Z(`div`,{className:`capture-detail-section`,children:[Z(`div`,{className:`capture-detail-title`,children:`Headers`}),Z(Dr,{raw:e.headers})]})]})})})}function Dr({raw:e}){return e?Z(`pre`,{className:`capture-payload`,children:Or(e)}):Z(`div`,{className:`capture-empty`,children:`(empty)`})}function Or(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function kr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Ar(e){return Z(jr,{query:e})}function jr({query:e}){let[t,n]=J([]),[r,i]=J(null),[a,o]=J(null),[s,c]=J(!0),[l,u]=J({text:`connecting`,kind:`idle`}),d=async()=>{try{let e=await U.captures(100);c(e.enabled!==!1),n(e.captures||[]),o(null)}catch(e){o(String(e.message||e))}};return Y(()=>{d();let e=ue(e=>{e.kind===`capture`&&d()},e=>{u({text:e,kind:e===`live`?`ok`:`warn`})});return()=>e()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Event inspector`}),Z(`p`,{className:`page-sub`,children:`Real inbound payloads archie has captured, most recent first.`})]}),Z(`div`,{className:`page-actions`,children:[Z(Q,{text:l.text,kind:l.kind}),Z(`button`,{className:`btn`,onClick:d,children:`Refresh`})]})]}),Z(`div`,{className:`card`,children:a?Z(kr,{title:`Cannot reach archied`,detail:a}):s?t.length?Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Source`,`Received`,`Binding`,`Content type`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:t.map(e=>Z(Tr,{capture:e,expanded:r===e.id,onToggle:()=>i(r===e.id?null:e.id)},e.id))})]})}):Z(kr,{title:`No captures yet`,detail:`Point a webhook at /webhooks/capture/ and it will show up here.`}):Z(kr,{title:`Capture is not configured`,detail:`This deployment has no capture storage wired up.`})})]})}var Mr=[`string`,`number`,`bool`,`object`,`array`,`any`];function Nr(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function Pr(e,t){return e?`${e}.${t}`:t}function Fr(e,t){return`${e}[${t}]`}function Ir({value:e,path:t=``,name:n=``,onPick:r}){return typeof e==`object`&&e?Z(`ul`,{className:`mapping-tree-list`,children:(Array.isArray(e)?e.map((e,n)=>[String(n),e,Fr(t,n)]):Object.entries(e).map(([e,n])=>[e,n,Pr(t,e)])).map(([e,t,n])=>Z(`li`,{className:`mapping-tree-item`,children:[Z(`span`,{className:`mapping-tree-key`,onClick:i=>{i.stopPropagation(),r&&r({path:n,type:Nr(t),name:e})},children:e}),Z(Ir,{value:t,path:n,name:e,onPick:r})]},n))}):Z(`span`,{className:`mapping-tree-value`,onClick:i=>{i.stopPropagation(),r&&r({path:t,type:Nr(e),name:n})},children:JSON.stringify(e)})}function Lr({fields:e,preview:t,onRemove:n,onNameChange:r,onTypeChange:i,onRequiredChange:a}){if(!e.length)return Z(`div`,{className:`mapping-empty-fields`,children:`Click a value in the payload to bind a field.`});let o=new Map((t?.failures||[]).map(e=>[e.field_name,e]));return Z(`table`,{className:`table mapping-fields-table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:e.map((e,s)=>Z(`tr`,{children:[Z(`td`,{children:Z(`input`,{className:`mapping-input`,value:e.name,onInput:e=>r?.(s,e.target.value)})}),Z(`td`,{className:`mono`,children:e.path}),Z(`td`,{children:Z(`select`,{className:`mapping-select`,value:e.type,onChange:e=>i?.(s,e.target.value),children:Mr.map(e=>Z(`option`,{value:e,children:e},e))})}),Z(`td`,{children:Z(`input`,{type:`checkbox`,checked:e.required,onChange:e=>a?.(s,e.target.checked)})}),Z(`td`,{children:Z(Rr,{field:e,preview:t,failureByField:o})}),Z(`td`,{children:Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(s),children:`Remove`})})]},s))})]})}function Rr({field:e,preview:t,failureByField:n}){if(!t)return Z(Q,{text:`not previewed`,kind:`idle`});let r=n.get(e.name);return r?Z(Q,{text:r.reason,kind:`danger`}):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?Z(Q,{text:JSON.stringify(t.values[e.name]),kind:`ok`}):Z(Q,{text:`skipped (optional)`,kind:`idle`})}function zr({mapping:e,onEdit:t,onDelete:n}){return Z(`tr`,{children:[Z(`td`,{children:e.name}),Z(`td`,{className:`mono`,children:e.source_hint||`—`}),Z(`td`,{children:String(e.fields?.length??0)}),Z(`td`,{children:[Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(e),children:`Delete`})]})]})}function Br({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Vr(e){return Z(Hr,{query:e})}function Hr({query:e}){let[t,n]=J([]),[r,i]=J([]),[a,o]=J(null),[s,c]=J(null),l=async()=>{try{let[e,t]=await Promise.all([U.mappings(),U.captures(100)]);n(e.mappings||[]),i(t.captures||[]),o(null)}catch(e){o(String(e.message||e))}};Y(()=>{l()},[]);let u=()=>{c({id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},d=e=>{c({id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},f=async e=>{if(window.confirm(`Delete mapping "${e.name}"?`))try{await U.mappingDelete(e.id),await l()}catch(e){o(String(e.message||e))}},p=e=>{let t=r.find(t=>String(t.id)===String(e));c(e=>{let n={...e,captureId:t?t.id:null,preview:null};if(!t)n.payload=null,n.payloadError=null;else try{n.payload=JSON.parse(t.body),n.payloadError=null}catch{n.payload=null,n.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}return n})},m=({path:e,type:t,name:n})=>{c(r=>{let i=new Set(r.fields.map(e=>e.name)),a=n||`field`,o=1;for(;i.has(a);)a=`${n||`field`}_${++o}`;let s=[...r.fields,{name:a,path:e,type:t,required:!0}];return{...r,fields:s,preview:null}})},h=e=>{c(t=>{let n=t.fields.slice();return n.splice(e,1),{...t,fields:n,preview:null}})},g=(e,t)=>{c(n=>{let r=n.fields.slice();return r[e]={...r[e],...t},{...n,fields:r,preview:null}})};return s?Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:Z(`h1`,{className:`page-title`,children:s.id?`Edit mapping`:`New mapping`})}),Z(`div`,{className:`page-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:()=>{c(null)},children:`Cancel`}),Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:async()=>{let e={name:s.name,source_hint:s.sourceHint,fields:s.fields};try{s.id?await U.mappingUpdate(s.id,e):await U.mappingCreate(e),c(null),await l()}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Save`})]})]}),s.actionError&&Z(`div`,{className:`mapping-error`,children:s.actionError}),Z(`div`,{className:`card mapping-form`,children:[Z(`label`,{className:`mapping-form-row`,children:[`Name`,Z(`input`,{className:`mapping-input`,value:s.name,onInput:e=>c(t=>({...t,name:e.target.value}))})]}),Z(`label`,{className:`mapping-form-row`,children:[`Source hint (organisational only)`,Z(`input`,{className:`mapping-input`,value:s.sourceHint,onInput:e=>c(t=>({...t,sourceHint:e.target.value}))})]}),Z(`label`,{className:`mapping-form-row`,children:[`Preview against captured event`,Z(`select`,{className:`mapping-select`,value:s.captureId||``,onChange:e=>p(e.target.value),children:[Z(`option`,{value:``,children:`— pick a captured event —`}),r.map(e=>Z(`option`,{value:e.id,children:[e.source||`(unknown)`,` — `,e.received_at||``]},e.id))]})]})]}),Z(`div`,{className:`card mapping-fields`,children:[Z(`div`,{className:`mapping-section-title`,children:`Bound fields`}),Z(Lr,{fields:s.fields,preview:s.preview,onRemove:h,onNameChange:(e,t)=>g(e,{name:t}),onTypeChange:(e,t)=>g(e,{type:t}),onRequiredChange:(e,t)=>g(e,{required:t})}),Z(`button`,{className:`btn`,type:`button`,onClick:async()=>{if(!s.captureId){c(e=>({...e,actionError:`Pick a captured event to preview against.`}));return}try{let e=await U.mappingPreview(s.captureId,s.fields);c(t=>({...t,preview:e,actionError:null}))}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Preview`})]}),Z(`div`,{className:`card mapping-payload`,children:[Z(`div`,{className:`mapping-section-title`,children:`Payload — click a value to bind it`}),s.payloadError?Z(`div`,{className:`mapping-error`,children:s.payloadError}):s.payload===null?Z(`div`,{className:`mapping-empty-fields`,children:`Pick a captured event above to see its payload.`}):Z(Ir,{value:s.payload,onPick:m})]})]}):Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Field mappings`}),Z(`p`,{className:`page-sub`,children:`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:u,children:`New mapping`})})]}),a?Z(Br,{title:`Cannot reach archied`,detail:a}):t.length?Z(`div`,{className:`card`,children:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Name`,`Source hint`,`Fields`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:t.map(e=>Z(zr,{mapping:e,onEdit:()=>d(e),onDelete:()=>f(e)},e.id))})]})})}):Z(Br,{title:`No mappings yet`,detail:`Create one from a captured event to reuse fields in a future playbook binding.`})]})}var Ur={draft:`draft`,pending_approval:`pending approval`,armed:`armed`},Wr={draft:`idle`,pending_approval:`warn`,armed:`ok`};function Gr({status:e}){return Z(Q,{text:Ur[e]||e,kind:Wr[e]||`idle`})}function Kr({binding:e,onEdit:t,onApprove:n,onDelete:r}){let i=e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`;return Z(`tr`,{children:[Z(`td`,{children:e.name}),Z(`td`,{className:`mono`,children:e.matcher?.source||`—`}),Z(`td`,{children:e.workflow}),Z(`td`,{className:`mono`,children:i}),Z(`td`,{children:Z(Gr,{status:e.status})}),Z(`td`,{children:[Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),e.status===`pending_approval`&&Z(`button`,{className:`btn btn-small btn-primary`,type:`button`,onClick:()=>n?.(e),children:`Approve`}),Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>r?.(e),children:`Delete`})]})]})}function qr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Jr(e){return Z(Xr,{query:e})}function Yr(){return{id:null,name:``,source:``,mappingId:``,workflow:``,owner:``,repo:``,secret:``,actionError:null}}function Xr({query:e}){let[t,n]=J([]),[r,i]=J([]),[a,o]=J([]),[s,c]=J(null),[l,u]=J(null),d=async()=>{try{let[e,t,r]=await Promise.all([U.bindings(),U.mappings(),U.workflows()]);n(e.bindings||[]),i(t.mappings||[]),o((r.definitions||[]).filter(e=>e.enabled)),c(null)}catch(e){c(String(e.message||e))}};Y(()=>{d()},[]);let f=()=>{u(Yr())},p=e=>{u({id:e.id,name:e.name,source:e.matcher?.source||``,mappingId:e.mapping_id?String(e.mapping_id):``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,secret:``,actionError:null})},m=()=>u(null),h=async()=>{let e={name:l.name,matcher:{source:l.source},mapping_id:Number(l.mappingId)||0,workflow:l.workflow,owner:l.owner,repo:l.repo,secret:l.secret};try{l.id?await U.bindingUpdate(l.id,e):await U.bindingCreate(e),u(null),await d()}catch(e){u(t=>({...t,actionError:String(e.message||e)}))}},g=async e=>{try{await U.bindingApprove(e.id),await d()}catch(e){c(String(e.message||e))}},_=async e=>{if(window.confirm(`Delete binding "${e.name}"?`))try{await U.bindingDelete(e.id),await d()}catch(e){c(String(e.message||e))}};return l?Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:Z(`h1`,{className:`page-title`,children:l.id?`Edit binding`:`New binding`})}),Z(`div`,{className:`page-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:m,children:`Cancel`}),Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:h,children:`Save`})]})]}),l.actionError&&Z(`div`,{className:`binding-error`,children:l.actionError}),Z(`div`,{className:`card binding-form`,children:[Z(`label`,{className:`binding-form-row`,children:[`Name`,Z(`input`,{className:`binding-input`,value:l.name,onInput:e=>u(t=>({...t,name:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Source (the path segment senders POST to, e.g. "sentry")`,Z(`input`,{className:`binding-input`,value:l.source,onInput:e=>u(t=>({...t,source:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Field mapping`,Z(`select`,{className:`binding-select`,value:l.mappingId,onChange:e=>u(t=>({...t,mappingId:e.target.value})),children:[Z(`option`,{value:``,children:`— pick a saved mapping —`}),r.map(e=>Z(`option`,{value:e.id,children:e.name},e.id))]})]}),Z(`label`,{className:`binding-form-row`,children:[`Workflow`,Z(`select`,{className:`binding-select`,value:l.workflow,onChange:e=>u(t=>({...t,workflow:e.target.value})),children:[Z(`option`,{value:``,children:`— pick a workflow —`}),a.map(e=>Z(`option`,{value:e.id,children:e.name},e.id))]})]}),Z(`label`,{className:`binding-form-row`,children:[`Repo pin -- owner (optional; leave both blank for the single-configured-repo default)`,Z(`input`,{className:`binding-input`,value:l.owner,onInput:e=>u(t=>({...t,owner:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Repo pin -- repo`,Z(`input`,{className:`binding-input`,value:l.repo,onInput:e=>u(t=>({...t,repo:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Shared secret (`,l.id?`leave blank to keep the current secret`:`senders sign with this via HMAC-SHA256`,`)`,Z(`input`,{className:`binding-input`,type:`password`,value:l.secret,onInput:e=>u(t=>({...t,secret:e.target.value}))})]})]})]}):Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Playbook bindings`}),Z(`p`,{className:`page-sub`,children:`Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:f,children:`New binding`})})]}),s?Z(qr,{title:`Cannot reach archied`,detail:s}):t.length?Z(`div`,{className:`card`,children:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Name`,`Source`,`Workflow`,`Repo pin`,`Status`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:t.map(e=>Z(Kr,{binding:e,onEdit:()=>p(e),onApprove:()=>g(e),onDelete:()=>_(e)},e.id))})]})})}):Z(qr,{title:`No bindings yet`,detail:`Create one from a saved field mapping to turn a captured webhook into a workflow.`})]})}function Zr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Qr(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}function $r({provider:e}){let t=e.tools||[];return Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:e.name||`provider`}),Z(`p`,{className:`card-sub`,children:Qr(e.role)})]}),e.available?Z(Q,{text:`ready`,kind:`ok`}):Z(Q,{text:`unavailable`,kind:`danger`})]}),!e.available&&Z(`p`,{className:`mem-warning`,children:`Configured but not usable right now — a required binary or connection may be missing.`}),t.length?Z(`ul`,{className:`mem-tools`,children:t.map((e,t)=>Z(`li`,{className:`mem-tool`,children:[Z(`div`,{className:`mem-tool-name mono`,children:e.name}),e.description&&Z(`div`,{className:`mem-tool-desc`,children:e.description})]},t))}):Z(`p`,{className:`mem-warning`,children:`This provider exposes no tools, so the agent cannot use it.`})]})}function ei(){let[e,t]=J(null),[n,r]=J(!0),[i,a]=J(null),[o,s]=J(!0),c=async()=>{s(!0),a(null);try{let e=await U.memory();r(!!e.enabled),t(e.providers||[])}catch(e){a(String(e.message||e))}finally{s(!1)}};return Y(()=>{c()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Memory`}),Z(`p`,{className:`page-sub`,children:`What Archie can recall between conversations, and the tools it uses to do it.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:c,children:`Refresh`})})]}),Z(`div`,{children:o?Z(`div`,{className:`card`,children:Z(`div`,{className:`mem-loading`,children:`Loading…`})}):i?Z(`div`,{className:`card`,children:Z(Zr,{title:`Cannot read memory providers`,detail:i})}):!n||!e.length?Z(`div`,{className:`card`,children:Z(Zr,{title:`Memory is not configured`,detail:`Without a provider, Archie starts every conversation with no recollection of earlier ones.`})}):Z(`div`,{className:`grid grid-2`,children:e.map((e,t)=>Z($r,{provider:e},t))})})]})}function ti(e){return Z(ei,{query:e})}function ni(e){let t=document.createDocumentFragment(),n=/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g,r=0;for(let i of e.matchAll(n)){i.index>r&&t.append(document.createTextNode(e.slice(r,i.index)));let n=i[0];if(n.startsWith(`![`)){let e=n.match(/^!\[([^\]]*)\]\((.+)\)$/);e&&t.append(W(`img.chat-media-img`,{src:e[2],alt:e[1]||`Image`,loading:`lazy`}))}else if(n.startsWith(`~~`))t.append(W(`del`,n.slice(2,-2)));else if(n.startsWith(`**`)||n.startsWith(`__`))t.append(W(`strong`,n.slice(2,-2)));else if(n.startsWith("`"))t.append(W(`code`,n.slice(1,-1)));else if(n.startsWith(`[`)){let e=n.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);t.append(W(`a`,{href:e[2],target:`_blank`,rel:`noreferrer`},e[1]))}else t.append(W(`em`,n.slice(1,-1)));r=i.index+n.length}return r{r.length&&(t.append(W(`p`,ni(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;eW(`td`,ni(e)))));t.append(W(`table`,W(`thead`,W(`tr`,...l.map(e=>W(`th`,ni(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(W(`h${d[1].length}`,ni(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=W(e)),i.append(W(`li`,ni((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(W(`blockquote`,ni(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(W(`pre`,W(`code`,a.join(` -`)))),t}function ii(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 ai(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var oi=`archie.web.chat.channel`;function si(){let e=localStorage.getItem(oi);return e||(e=ie(),localStorage.setItem(oi,e)),e}function ci(e){return{text:e,sourceID:ie()}}function li(e){return{...e}}function ui(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?li(e.turn):ci(r),isRetry:n}}function di(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function fi(e){return e?.status===501?null:`Could not check for updates.`}function pi(){return location.hash.slice(1)||`/`}function mi({text:e}){let t=X(null);return Y(()=>{t.current&&t.current.replaceChildren(ri(e||``))},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function hi(){let[e,t]=J([]),[n,r]=J(``),[i,a]=J([]),[o,s]=J(``),[c,l]=J(`Ready`),[u,d]=J(!1),[f,p]=J({}),[m,h]=J(``),[g,_]=J(``),[v,y]=J(``),[b,x]=J([]),[C,w]=J([]),[T,E]=J(0),[D,O]=J(!1),[k,A]=J(null),[j,M]=J(null),[N,P]=J(null),[F,I]=J(``),[ee,te]=J(``),[L,R]=J(null),ne=X(null),z=X(null),B=X(null),re=X(null),ie=X(null),ae=X(u);ae.current=u,Y(()=>{ne.current&&(ne.current.scrollTop=ne.current.scrollHeight)},[i,L]),Y(()=>{ue().catch(e=>{l(e.message||`Chat unavailable`)}),V();let e=()=>{B.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),B.current?.abort()}},[]);async function V(){try{let e=await U.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=fi(e);A(t?{error:t}:null)}}async function oe(){if(j)try{await U.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function se(){if(j)try{l(`Installing…`);let e=await U.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function ce(){try{let e=await U.chatDangerous();P(e)}catch(e){P({error:e.message||`Dangerous actions unavailable`})}}async function le(e,t){if(t)try{await U.chatDangerousRequest(e,t),l(`Approval requested`),await ce()}catch(e){l(e.message||`Could not request action`)}}async function H(e,t){try{await U.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await ce()}catch(e){l(e.message||`Approval failed`)}}async function ue(){let e=await U.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 ce(),!n&&r[0]&&await de(r[0].session_id,e,r)}async function de(e,t,n){let i=t||f;r(e),a([]),R(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await U.chatMessage(si(),`/resume ${e}`);let[t,n]=await Promise.all([U.chatMessages(e),U.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 fe(e){if(n)try{l(`Working…`);let t=await U.chatMessage(si(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await ue(),(t.session_id||n)&&await de(t.session_id||n),re.current&&(re.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function pe(e,t){let n=window.prompt(t);n?.trim()&&fe(`${e} ${n.trim()}`)}function me(e){let t=e.target.value;h(t),!(!n||!t)&&U.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 he(e){let t=e.target.value;if(_(t),t)try{let e=await U.chatMessage(si(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await ue()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ge(e){let t=e.target.value;if(y(t),t)try{let e=await U.chatMessage(si(),`/model ${t}`);l(e.reply||`Model updated`),await ue()}catch(e){l(`Model update failed: ${e.message||e}`)}}function _e(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),Se({textOverride:`/restart`}))}function ve(){s(`/new`),Se({textOverride:`/new`})}function ye(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 be(e){let t=C[e];if(!t||!z.current)return;let n=z.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t.command.length+1;setTimeout(()=>{n.focus(),n.setSelectionRange(l,l)},0)}function xe(e){if(D&&C.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&C.some(e=>e.command===o.trim())){e.preventDefault(),O(!1),Se();return}if(e.key===`ArrowDown`){e.preventDefault(),E(e=>(e+1)%C.length);return}if(e.key===`ArrowUp`){e.preventDefault(),E(e=>(e+C.length-1)%C.length);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),be(T);return}if(e.key===`Escape`){e.preventDefault(),O(!1);return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Se())}async function Se(e=null){let t=e?.textOverride,{text:n,turn:i,isRetry:c}=ui(e,t===void 0?o:t);if(!n||ae.current)return;O(!1),d(!0),l(c?`Retrying…`:`Thinking…`),c||(a(e=>[...e,{from:`web`,text:n}]),s(``));let u=[];R({text:``,tools:[],isError:!1,turn:i,isRetry:c});let f=``,p=!1,m=!1,h=null;try{let e=new AbortController;B.current=e,h=setTimeout(()=>{m=!0,e.abort()},12e4);let t=(await U.chatStream({channel_id:si(),source_id:i.sourceID,text:i.text,page:pi()},{signal:e.signal})).body.getReader(),n=new TextDecoder,o=``;for(;;){let{value:e,done:i}=await t.read();o+=n.decode(e||new Uint8Array,{stream:!i});let a=o.split(` +(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;tt&&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;d0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:ic?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a+!!u){for(i=n-1,a=n+1;i>=0||a=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function P(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function F(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[c]==null)n[c]=d++;else if(n[c]0?e:_(e)?e.map(R):e.constructor===void 0?v({},e):null}function z(n,r,i,a,o,s,c,l,u){var d,f,p,h,g,v,b,x=i.props||m,S=r.props,C=r.type;if(C==`svg`?o=`http://www.w3.org/2000/svg`:C==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;d=n.__.length&&n.__.push({}),n.__[e]}function W(e){return oe=1,he(Ce,e)}function he(e,t,n){var r=me(re++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ce(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=H,!H.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};H.__f=!0;var a=H.shouldComponentUpdate,o=H.componentWillUpdate;H.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},H.shouldComponentUpdate=i}return r.__N||r.__}function G(e,t){var n=me(re++,3);!U.__s&&Se(n.__H,t)&&(n.__=e,n.u=t,H.__H.__h.push(n))}function K(e){return oe=5,ge(function(){return{current:e}},[])}function ge(e,t){var n=me(re++,7);return Se(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function _e(e,t){return oe=8,ge(function(){return e},t)}function ve(){for(var e;e=se.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(q),t.__h.some(xe),t.__h=[]}catch(n){t.__h=[],U.__e(n,e.__v)}}}U.__b=function(e){H=null,ce&&ce(e)},U.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),pe&&pe(e,t)},U.__r=function(e){le&&le(e),re=0;var t=(H=e.__c).__H;t&&(ie===H?(t.__h=[],H.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(q),t.__h.some(xe),t.__h=[],re=0)),ie=H},U.diffed=function(e){ue&&ue(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(se.push(t)!==1&&ae===U.requestAnimationFrame||((ae=U.requestAnimationFrame)||be)(ve)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),ie=H=null},U.__c=function(e,t){t.some(function(e){try{e.__h.some(q),e.__h=e.__h.filter(function(e){return!e.__||xe(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],U.__e(n,e.__v)}}),de&&de(e,t)},U.unmount=function(e){fe&&fe(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{q(e)}catch(e){t=e}}),n.__H=void 0,t&&U.__e(t,n.__v))};var ye=typeof requestAnimationFrame==`function`;function be(e){var t,n=function(){clearTimeout(r),ye&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);ye&&(t=requestAnimationFrame(n))}function q(e){var t=H,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),H=t}function xe(e){var t=H;e.__c=e.__(),H=t}function Se(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Ce(e,t){return typeof t==`function`?t(e):t}function we(e=globalThis.crypto){if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(typeof e?.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;ee.toString(16).padStart(2,`0`));return`${n.slice(0,4).join(``)}-${n.slice(4,6).join(``)}-${n.slice(6,8).join(``)}-${n.slice(8,10).join(``)}-${n.slice(10).join(``)}`}var Te=15e3;function Ee(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function De(e){try{let t=(await e.text()).trim();if(t)return t.split(` +`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Oe=class extends Error{constructor(e,t){super(e),this.status=t}};function ke(e){let t=e instanceof Oe?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ae(e,t){let n=await fetch(e,t);if(!n.ok)throw new Oe(await De(n),n.status);return n}async function J(e,{method:t=`GET`,body:n,timeoutMs:r=Te,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await Ae(e,o);return i?s.json():void 0}var Y={summary:()=>J(`/api/summary`),tasks:()=>J(`/api/tasks`),taskMeta:()=>J(`/api/task-meta`),task:e=>J(`/api/tasks/${e}`),taskAttempts:e=>J(`/api/tasks/${e}/attempts`),taskChanges:(e,t)=>J(`/api/tasks/${e}/changes`+Ee(t)),taskDebug:(e,t)=>J(`/api/tasks/${e}/debug`+Ee(t)),taskAction:(e,t)=>J(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>J(`/api/setup`),capabilities:()=>J(`/api/capabilities`),workflows:()=>J(`/api/workflows`),workRequest:e=>J(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>J(`/api/skills`),channels:()=>J(`/api/channels`),curators:()=>J(`/api/curators`),channelReload:e=>J(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>J(`/api/config`),version:()=>J(`/api/version`),configUpdate:e=>J(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>J(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>J(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>J(`/api/logs`+Ee(e)),taskLogs:(e,t)=>J(`/api/tasks/${e}/logs`+Ee(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>J(`/api/captures`+Ee({limit:e})),mappings:()=>J(`/api/mappings`),mappingCreate:e=>J(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>J(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>J(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>J(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>J(`/api/bindings`),bindingCreate:e=>J(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>J(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>J(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>J(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>J(`/api/memory`),chatSessions:()=>J(`/api/chat/sessions`),chatMessages:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>J(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>J(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:we(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>J(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>J(`/api/chat/update`),chatUpdateDefer:e=>J(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>J(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>J(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>Ae(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function je(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Me(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Ne(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var Pe=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Pe,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}var Fe={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,curators:``,captures:``,mappings:``,bindings:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,close:``,help:``};function Z({name:e,size:t=18,className:n=``}){return X(`svg`,{viewBox:`0 0 24 24`,width:t,height:t,fill:`none`,stroke:`currentColor`,"stroke-width":`1.6`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`,className:`ico ${n}`.trim(),dangerouslySetInnerHTML:{__html:Fe[e]||Fe.dashboard}})}function Ie(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function Le(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}var Re=[{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`}],ze=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quiet`,confirm:`Archive the local record for "{title}"?`},{id:`open_pr`,label:`Open PR`,kind:`link`},{id:`open_issue`,label:`Open issue`,kind:`link`}],Be=[...Re],Ve=[...ze],He=new Map(Be.map(e=>[e.id,e])),Ue=new Map(Ve.map(e=>[e.id,e]));function We(e){return He.get(e)?.label||e||`Unknown`}function Ge(e){return He.get(e)?.kind||`idle`}function Ke(){return Be.map(e=>e.id)}function qe(){return new Set(Be.filter(e=>e.needs_you).map(e=>e.id))}function Je(e){return Ue.get(e)||null}function Ye({label:e,value:t,unit:n,trend:r,compare:i,series:a=[],goodDirection:o=`up`}){let s=r==null?null:r>=0?`up`:`down`,c=s==null?null:s===o;return X(`div`,{className:`card stat`,children:[X(`div`,{className:`stat-head`,children:[X(`span`,{className:`stat-label`,children:e}),s?X(`span`,{className:`stat-trend ${c?`up`:`down`}`,children:[X(Z,{name:s===`up`?`trendUp`:`trendDown`,size:13}),`${Math.abs(r).toFixed(1)}%`]}):null]}),X(`div`,{className:`stat-value`,children:[t,n?X(`span`,{className:`stat-unit`,children:n}):null]}),i?X(`div`,{className:`stat-compare`,children:i}):null,a.length>1?X(Xe,{series:a,stroke:c===!1?`var(--danger)`:`var(--ok)`}):null]})}function Xe({series:e,stroke:t=`var(--ok)`,width:n=220,height:r=34}){let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=e.length>1?n/(e.length-1):n,c=e.map((e,t)=>`${(t*s).toFixed(1)},${(r-(e-a)/o*r).toFixed(1)}`).join(` `);return X(`svg`,{className:`spark`,viewBox:`0 0 ${n} ${r}`,preserveAspectRatio:`none`,"aria-hidden":`true`,children:X(`polyline`,{points:c,fill:`none`,stroke:t,"stroke-width":`1.5`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"vector-effect":`non-scaling-stroke`})})}function Ze({value:e,label:t,size:n=168}){let r=Math.max(0,Math.min(100,Number(e)||0)),i=r>=90?`var(--ok)`:r>=70?`var(--warn)`:`var(--danger)`,a=n/2,o=n/2,s=2*Math.PI*62*(240/360),c=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${a+62*Math.cos(n)} ${o+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${a+62*Math.cos(r)} ${o+62*Math.sin(r)}`].join(` `)};return X(`div`,{className:`gauge-wrap`,children:[X(`svg`,{className:`gauge`,viewBox:`0 0 ${n} ${n*.78}`,role:`img`,"aria-label":`${t}: ${r}%`,children:[X(`path`,{d:c(150,240),fill:`none`,stroke:`var(--border)`,"stroke-width":`12`,"stroke-linecap":`round`}),X(`path`,{d:c(150,240),fill:`none`,stroke:i,"stroke-width":`12`,"stroke-linecap":`round`,"stroke-dasharray":s,"stroke-dashoffset":s*(1-r/100),className:`gauge-value`})]}),X(`div`,{className:`gauge-center`,children:[X(`div`,{className:`gauge-pct`,children:`${Math.round(r)}%`}),X(`div`,{className:`gauge-label`,children:t})]})]})}function Qe({segments:e}){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return X(`div`,{children:[X(`div`,{className:`segbar`,children:e.filter(e=>e.value>0).map(e=>X(`span`,{className:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`},e.label))}),X(`div`,{className:`segbar-legend`,children:e.map(e=>X(`span`,{className:`segbar-key`,children:[X(`span`,{className:`segbar-dot segbar-${e.kind||`idle`}`}),e.label]},e.label))})]})}function Q({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({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function at(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 ot(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function st(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 ct(){let[e,t]=W([]),[n,r]=W(`connecting`),[i,a]=W(`idle`),[o,s]=W(new Map),[c,l]=W(null),[u,d]=W(null),[f,p]=W(null),[m,h]=W(null),[g,_]=W(null),[,v]=W(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([Y.summary(),Y.setup().catch(()=>null),Y.workflows().catch(()=>null),Y.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))}};G(()=>(y(),je(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?`${ot()}, ${u.operator}`:ot(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(Z,{name:`refresh`,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(Z,{name:`tasks`,size:15}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(Z,{name:`workflows`,size:15}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(Z,{name:`logs`,size:15}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(Z,{name:`refresh`,size:15}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(it,{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(Ye,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(Ye,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(Ye,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(Ye,{label:`Tokens used`,value:Le(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:st(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:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Finish setting up`}),X(`p`,{className:`card-sub`,children:`Archie needs these before it can work on its own.`})]}),X(`span`,{className:`setup-pct`,children:[t,`%`]})]}),X(`div`,{className:`setup-bar`,children:X(`div`,{className:`setup-bar-fill`,style:{width:`${t}%`}})}),X(`ul`,{className:`setup-list`,children:u.steps.map((e,t)=>X(`li`,{className:`setup-step ${e.done?`done`:``}`,children:[X(`span`,{className:`setup-check`,children:e.done?X(Z,{name:`check`,size:12}):``}),X(`div`,{children:[X(`div`,{className:`setup-step-title`,children:e.title}),e.detail&&X(`div`,{className:`setup-step-detail`,children:e.detail})]})]},t))})]})}else T=X(`div`,{className:`card setup setup-done`,children:X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Setup complete`}),X(`p`,{className:`card-sub`,children:`Archie is configured and ready to work.`})]}),X(`div`,{className:`setup-complete-actions`,children:[X(`span`,{className:`setup-pct`,children:X(Z,{name:`check`,size:16})}),X(`button`,{className:`icon-btn setup-dismiss`,type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onClick:b,children:`×`})]})]})})}let O=null;if(c){let e=f?.workflows||[],t=e.reduce((e,t)=>e+(t.runs||0),0),n=e.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),r=e.reduce((e,t)=>e+(t.parked||0),0);if(!t)O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Gate pulse`})}),X(it,{title:`No completed runs yet`,detail:`Once Archie finishes a task, its gate pass rate appears here.`})]});else{let i=n/t*100;O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Gate pulse`}),X(`p`,{className:`card-sub`,children:`Work that passed its quality gates`})]})}),X(Ze,{value:i,label:`pass rate`}),X(`ul`,{className:`pulse-list`,children:[e.slice(0,3).map((e,t)=>X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:e.workflow||`workflow`}),X(Q,{text:`${e.merged||0}/${e.runs||0}`,kind:(e.merged||0)===(e.runs||0)?`ok`:(e.parked||0)>0?`warn`:`info`})]},t)),r>0&&X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:`Parked, awaiting you`}),X(Q,{text:String(r),kind:`warn`})]})]})]})}}let k=null;if(c){let e=c?.tokens_by_day||[],t=e.reduce((e,t)=>e+(t.tokens||0),0);if(!e.length)k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Token outlook`})}),X(it,{title:`Nothing spent yet`,detail:`Usage appears here once Archie runs its first task.`})]});else{let n=t/e.length,r=Math.round(n*30),i=e.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Token outlook`}),X(`p`,{className:`card-sub`,children:`Next 30 days at the current rate`})]})}),X(`div`,{className:`forecast-value`,children:Le(r)}),X(`div`,{className:`forecast-note`,children:[`Based on `,Le(Math.round(n)),` per day over `,e.length,` days`]}),X(Qe,{segments:[{label:`Last 7 days (${Le(i)})`,value:i,kind:`info`},{label:`Earlier (${Le(t-i)})`,value:Math.max(t-i,0),kind:`idle`}]})]})}}return X(S,{children:[X(`div`,{className:`hero`,children:[X(`div`,{children:[X(`h1`,{className:`hero-title`,children:x}),X(`p`,{className:`hero-sub`,children:`Your agent's control room — what it is working on, what needs you, and what it is spending.`})]}),X(`div`,{className:`hero-actions`,children:X(`div`,{className:`hero-actions-inner`,children:C})})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Health`})}),X(`div`,{className:`dash-top ${D?`dash-top-standalone`:``}`,children:[X(`div`,{children:T}),X(`div`,{children:O})]})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:[X(`h2`,{className:`dash-section-title`,children:`Throughput`}),X(`span`,{className:`dash-section-note`,children:`Across all repositories`})]}),X(`div`,{className:`grid grid-4`,children:w})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Right now`})}),X(`div`,{className:`dash-split`,children:[X(`div`,{children:k}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Live activity`}),X(`p`,{className:`card-sub`,children:`Last 50, newest first`})]}),X(Q,{text:n,kind:i})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Event`}),X(`th`,{children:`Task`}),X(`th`,{children:`Detail`}),X(`th`,{children:`When`})]})}),X(`tbody`,{children:e.length?e.map((e,t)=>{let n=at(e,o),r=n>0,i=()=>{r&&(location.hash=`#/tasks?task=${encodeURIComponent(n)}`)};return X(`tr`,{className:r?`activity-row`:``,role:r?`link`:void 0,tabIndex:r?`0`:void 0,title:r?`Open task details`:void 0,onClick:r?i:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,children:[X(`td`,{className:`strong`,children:X(`span`,{children:e.kind||e.type||`event`})}),X(`td`,{className:`mono`,children:r?`#${n}`:`—`}),X(`td`,{children:e.detail||e.message||``}),X(`td`,{children:Ie(e.at||Date.now())})]},t)}):X(`tr`,{children:X(`td`,{colSpan:`4`,children:X(it,{title:`Waiting for activity`,detail:`Events appear here as Archie works.`})})})})]})})]})]})]})]})}function lt(){return X(ct,{})}function ut(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var dt=qe(),ft=new Set([`needs_you`,...Ke()]);function pt(e){let t=e?.get?.(`status`)||``;return ft.has(t)?t:``}function mt(e,t){return t?t===`needs_you`?dt.has(e.status):e.status===t:!0}function ht(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function gt(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function _t(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function vt(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=gt(t.duration_ms),i=[r,e&&`ran for ${e}`].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[i,t.error].filter(Boolean).join(` — `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[t.previous_stage&&`after ${t.previous_stage}`,t.previous_reason].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=_t(t.iterations),i=_t(t.tokens),a=Number(t.cached_tokens)||0,o=_t((Number(t.prompt_tokens)||0)-a),s=_t(t.completion_tokens),c=_t(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,t.model].filter(Boolean);return{title:`Agent ${t.status||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}if(e.kind===`config_captured`)return{title:`Configuration captured`,detail:`The effective task-runtime configuration for this run.`};if(e.kind===`changes_captured`){let e=Number(t.totals?.files);return{title:`Change capture recorded`,detail:[Number.isFinite(e)&&e>0?`${e} file${e===1?``:`s`} changed`:``,t.captured_after?`captured after ${t.captured_after}`:``].filter(Boolean).join(` · `)}}return{title:ht(e.kind||e.type),detail:e.detail||``}}var yt=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function bt(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function xt({entry:e}){let t=e.fields||{};return X(`div`,{className:`log-row log-${bt(e.level)}`,children:[X(`span`,{className:`log-time mono`,children:Ct(e.time)}),X(`span`,{className:`log-level`,children:(e.level||`info`).toUpperCase()}),X(`span`,{className:`log-body`,children:[X(`span`,{className:`log-msg`,children:e.message||e.msg||``}),Object.entries(t).map(([e,t])=>X(`span`,{className:`log-field`,children:[X(`span`,{className:`log-field-key`,children:e}),String(St(t))]},e))]})]})}function St(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Ct(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function wt(e,t){return`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`)}var Tt={level:``,stage:``};function Et(e,t,n=Tt){let r=n||Tt;return[e,Number(t)||0,r.level||``,r.stage||``].join(`|`)}function Dt({filters:e,onFilterChange:t,stages:n,attempt:r}){let i=n=>t?.({...e,...n}),a=Number(r)||0;return X(`div`,{className:`log-filters task-log-filters`,children:[X(`span`,{className:`task-log-attempt`,children:a>0?`Attempt ${a}`:`Current attempt`}),t?X(S,{children:[X(`label`,{className:`task-log-filter`,children:[X(`span`,{className:`task-log-filter-label`,children:`Level`}),X(`select`,{className:`task-filter`,value:e.level,"aria-label":`Filter log entries by level`,onChange:e=>i({level:e.target.value}),children:yt.map(e=>X(`option`,{value:e.value,children:e.label},e.value))})]}),X(`label`,{className:`task-log-filter`,children:[X(`span`,{className:`task-log-filter-label`,children:`Stage`}),X(`select`,{className:`task-filter`,value:e.stage,"aria-label":`Filter log entries by stage`,onChange:e=>i({stage:e.target.value}),children:[X(`option`,{value:``,children:`All stages`}),(n||[]).map(e=>X(`option`,{value:e,children:e},e))]})]}),e.stage?X(`p`,{className:`task-log-filter-note`,children:`A stage filter matches only log lines that record a stage. Agent and tool output carries none, so it is not shown while this filter is set.`}):null,!e.stage&&!(n||[]).length?X(`p`,{className:`task-log-filter-note`,children:`This attempt recorded no stage names, so the stage filter has nothing to match.`}):null]}):null]})}function Ot({text:e}){return X(`p`,{className:`visually-hidden`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:e})}function kt({state:e,onRetry:t,taskId:n,attempt:r,filters:i=Tt,onFilterChange:a,stages:o=[]}){let s=Number(r)||Number(e?.attempt)||0,c,l;if(e===void 0)c=`Loading this attempt's log`,l=X(`div`,{className:`task-log-loading`,children:`Loading attempt log…`});else if(e===null)c=`This attempt's log could not be loaded`,l=X(`div`,{className:`task-log-error`,children:[X(`div`,{className:`task-timeline-detail`,children:`Could not load this attempt's log.`}),X(`button`,{className:`btn`,onClick:t,children:`Retry`})]});else if(e.found===!1&&!e.disabled)c=`No log recorded for this attempt`,l=X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No log recorded for this attempt`}),X(`div`,{children:`This attempt produced no output, or it has not started writing yet.`})]});else if(e.disabled)c=`This dashboard cannot read task logs`,l=X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No persisted log for this attempt`}),X(`div`,{children:`This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.`})]});else{let t=e.entries||[],r=n==null?null:wt(n,s||null),i=r?X(`a`,{className:`btn btn-small task-log-download`,href:r,download:!0,children:`Download log`}):null;t.length?(c=`${t.length} log entr${t.length===1?`y`:`ies`} shown`,l=X(S,{children:[X(`div`,{className:`log-list task-log-list`,children:t.map((e,t)=>X(xt,{entry:e},t))}),i]})):(c=`This attempt's log has no entries matching the current filter`,l=X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`Nothing recorded`}),X(`div`,{children:`This attempt's log file has no entries matching the current filter.`}),i]}))}return X(S,{children:[X(Dt,{filters:i,onFilterChange:a,stages:o,attempt:s}),X(Ot,{text:c}),l]})}function At(){return typeof window<`u`&&window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches===!0}function jt(){return At()?`auto`:`smooth`}function Mt({kind:e,message:t}){return e===`session-expired`?X(`span`,{className:`task-action-error task-action-error-session`,children:[`Your session has expired.`,` `,X(`button`,{className:`button btn btn-small`,type:`button`,onClick:()=>window.location.reload(),children:`Reload to sign in`})]}):e===`refused`?X(`span`,{className:`task-action-error task-action-error-refused`,children:[t,` — you can't do that.`]}):X(`span`,{className:`task-action-error task-action-error-broken`,children:[t,` — try again, or check the daemon.`]})}function Nt({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Pt({taskId:e,attempt:t,state:n,onLoad:r,onRetry:i}){let a=K(r);return a.current=r,G(()=>{n===void 0&&a.current()},[n]),X(kt,{state:n,taskId:e,attempt:t,onRetry:i})}function Ft({query:e}){let[t,n]=W(null),[r,i]=W(null),[a,o]=W(()=>pt(e)),[s,c]=W(``),l=Number(e.get(`task`)),u=Number.isFinite(l)&&l>0?l:null,[d,f]=W(u),[p,m]=W(u!==null),[h,g]=W(new Map),[_,v]=W(new Map),y=K(new Set),[b,x]=W(new Set),[C,w]=W(new Map),[T,E]=W(new Set),D=async()=>{try{i(null);let e=await Y.tasks();return n(e),d&&e.some(e=>String(e.id)===String(d))&&(h.has(d)||O(d)),e}catch(e){return i(String(e.message||e)),n(null),null}};G(()=>{D()},[]);let O=async e=>{try{let t=await Y.task(e);g(n=>new Map(n).set(e,t||[]))}catch{g(t=>new Map(t).set(e,null))}},k=async(e,t,{force:n=!1}={})=>{let r=Et(e,t);if(!(y.current.has(r)&&!n)){y.current.add(r),n&&v(e=>{let t=new Map(e);return t.delete(r),t});try{let n=await Y.taskLogs(e,{attempt:t||void 0,limit:500});v(e=>new Map(e).set(r,n))}catch{v(e=>new Map(e).set(r,null))}}},A=e=>{g(t=>{let n=new Map(t);return n.delete(e),n})},j=async(e,t)=>{w(t=>{let n=new Map(t);return n.delete(e),n}),E(t=>new Set(t).add(e));try{await Y.taskAction(e,t),E(t=>{let n=new Set(t);return n.delete(e),n}),t===`archive`&&f(null),A(e);let n=await D();Array.isArray(n)&&n.find(t=>String(t.id)===String(e))&&d===e&&O(e)}catch(t){E(t=>{let n=new Set(t);return n.delete(e),n}),w(n=>new Map(n).set(e,ke(t)))}};G(()=>{p&&d&&t&&(m(!1),requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${d}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView?.({block:`center`,behavior:jt()}))}))},[p,d,t]);let M=(e,t)=>{t&&t.stopPropagation();let n=d!==e;f(n?e:null),n&&O(e)},N=e=>{x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},P=()=>{if(!t)return null;let e=t.length,n={};for(let e of t)n[e.status]=(n[e.status]||0)+1;let r=n.running||0,i=(n.waiting_human||0)+(n.parked||0),a=(n.merged||0)+(n.pr_open||0);return X(`div`,{className:`grid grid-4 task-summary`,children:[X(Ye,{label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),X(Ye,{label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),X(Ye,{label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(Ye,{label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`})]})},F=e=>{let t=C.get(e.id),n=t?Mt(t):null,r=T.has(e.id),i=e=>e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``,a=(e.actions||[]).map(t=>{let n=Je(t);if(!n)return null;let a=e.title||`this task`,o=n.confirm?n.confirm.replaceAll(`{title}`,a):void 0,s=[`button`,`btn`,`btn-small`,i(n.kind)].filter(Boolean).join(` `);if(n.kind===`link`){if(t===`open_pr`)return I(e,`pull_request`,e.pr_number,n.label);if(t===`open_issue`)return I(e,`issue`,e.issue_number,n.label)}return X(`button`,{className:s,type:`button`,disabled:r,onClick:n=>{n.stopPropagation(),!(o&&!window.confirm(o))&&j(e.id,t)},children:n.label},t)}).filter(Boolean);return!a.length&&!n?`—`:X(`div`,{className:`task-actions`,children:[n,a]})},I=(e,t,n,r)=>{let i=t===`issue`?e.issue_url:e.pr_url;return!i||!n||t===`issue`&&e.source===`chat`?X(`button`,{className:`btn btn-small`,type:`button`,disabled:!0,title:`${r} is unavailable`,children:r}):X(`a`,{className:`btn btn-small`,href:i,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:r})},L=e=>{let t=e.repo_url;return t?X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open ${e.owner}/${e.repo} on the forge`,onClick:e=>e.stopPropagation(),children:[e.owner,`/`,e.repo]}):null},ee=e=>{let t=e.issue_url;return e.source===`chat`||!t||!e.issue_number?null:X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open issue #${e.issue_number} on the forge`,onClick:e=>e.stopPropagation(),children:[`#`,e.issue_number]})},R=e=>{let t=Et(e.id,e.attempt),n=h.get(e.id),r=b.has(e.id);return X(`tr`,{className:`task-timeline-row`,id:`task-timeline-${e.id}`,children:X(`td`,{colSpan:8,children:[X(`div`,{className:`task-detail-actions`,children:[X(`div`,{className:`task-decision-title`,children:`Available actions`}),F(e)]}),e.status===`waiting_human`&&e.plan&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Decision required`}),X(`div`,{className:`task-decision-plan`,children:e.plan})]}),e.status===`parked`&&e.park_reason&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Park reason`}),X(`div`,{className:`task-decision-plan`,children:e.park_reason})]}),n===void 0?X(`div`,{className:`task-timeline-loading`,children:`Loading timeline…`}):n===null?X(`div`,{className:`task-timeline-error`,children:[X(`div`,{className:`task-timeline-title`,children:`Could not load timeline`}),X(`div`,{className:`task-timeline-detail`,children:`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`}),X(`button`,{className:`btn`,onClick:()=>O(e.id),children:`Retry`})]}):n.length?X(`ul`,{className:`task-timeline`,children:n.map((e,t)=>{let n=vt(e);return X(`li`,{className:`task-timeline-entry`,children:[X(`span`,{className:`task-timeline-dot`}),X(`div`,{children:[X(`div`,{className:`task-timeline-kind`,children:n.title}),n.detail&&X(`div`,{className:`task-timeline-detail`,children:n.detail}),X(`div`,{className:`task-timeline-when`,children:Ie(e.at)})]})]},t)})}):X(Nt,{title:`No events yet`,detail:`This task has not recorded any transitions.`}),X(`div`,{className:`task-logs-section`,children:[X(`div`,{className:`task-decision-title`,children:[`Attempt log`,X(`button`,{className:`btn btn-small`,onClick:()=>N(e.id),style:{marginLeft:`10px`},children:r?`Hide`:`Show`})]}),r&&X(Pt,{taskId:e.id,attempt:e.attempt,state:_.has(t)?_.get(t):void 0,onLoad:()=>k(e.id,e.attempt),onRetry:()=>k(e.id,e.attempt,{force:!0})})]})]})})};return X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Tasks`}),X(`p`,{className:`page-sub`,children:`Every issue archied has picked up, and where it stands.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:D,children:`Refresh`})})]}),r?X(`div`,{className:`grid grid-4 task-summary`,children:X(`div`,{className:`card`,children:X(Nt,{title:`Cannot reach archied`,detail:r})})}):P(),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`All tasks`}),X(`p`,{className:`card-sub`,children:`Click a row for its timeline`})]}),X(`div`,{className:`task-filters`,children:[X(`input`,{className:`task-search`,type:`search`,placeholder:`Search by title or repo…`,value:s,onInput:e=>c(e.target.value.trim().toLowerCase())}),X(`select`,{className:`task-filter`,value:a,onChange:e=>o(e.target.value),children:[X(`option`,{value:``,children:`All statuses`}),X(`option`,{value:`needs_you`,children:`Needs you`}),Ke().map(e=>X(`option`,{value:e,children:We(e)},e))]})]})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(e=>X(`th`,{children:e},e))})}),X(`tbody`,{children:(()=>{if(r)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(Nt,{title:`Cannot reach archied`,detail:r})})});if(!t)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(`div`,{className:`task-timeline-loading`,children:`Loading tasks...`})})});if(!t.length)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(Nt,{title:`No tasks yet`,detail:`Tasks appear here once archied picks up an issue to work.`})})});let e=t.filter(e=>mt(e,a)?!s||`${e.title} ${e.repo}`.toLowerCase().includes(s):!1);return e.length?e.map(e=>{let t=d===e.id,n=`task-timeline-${e.id}`;return X(S,{children:[X(`tr`,{className:`task-row`,id:`task-row-${e.id}`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),M(e.id,t))},onClick:t=>M(e.id,t),...ut(e,t),children:[X(`td`,{className:`mono`,"data-label":`Repository`,children:[X(`button`,{className:`task-expand`,type:`button`,"aria-expanded":String(t),"aria-controls":n,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${e.title||`untitled task`}`,onClick:t=>M(e.id,t),children:t?`−`:`+`}),L(e)??`${e.owner}/${e.repo}`]}),X(`td`,{className:`mono`,"data-label":`Issue`,children:ee(e)??`#${e.issue_number}`}),X(`td`,{className:`strong`,"data-label":`Title`,children:X(`a`,{className:`task-detail-link`,href:`#/tasks/${e.id}`,title:`Open the run detail for this task`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:e.title||`(untitled)`})}),X(`td`,{"data-label":`Status`,children:X(Q,{text:We(e.status),kind:Ge(e.status)})}),X(`td`,{"data-label":`Workflow`,children:e.workflow||`—`}),X(`td`,{"data-label":`Stage`,children:e.stage||`—`}),X(`td`,{"data-label":`Last activity`,title:e.created_at?`Created ${Ie(e.created_at)}`:``,children:Ie(e.updated_at)}),X(`td`,{"data-label":`Actions`,children:F(e)})]}),t&&R(e)]},e.id)}):X(`tr`,{children:X(`td`,{colSpan:8,children:X(Nt,{title:`No matching tasks`,detail:`Try a different search or status filter.`})})})})()})]})})]})]})}function It(e){return X(Ft,{query:e})}function Lt(e,t){return`${e}-tab-${t}`}function Rt(e,t){return`${e}-panel-${t}`}function zt({tabs:e,active:t,onSelect:n,prefix:r=`run`,label:i=`Run detail views`}){let a=K([]),o=t=>{let r=e[t];r&&(n?.(r.id),a.current[t]?.focus?.())};return X(`div`,{className:`tab-bar`,role:`tablist`,"aria-label":i,onKeyDown:n=>{let r=e.findIndex(e=>e.id===t);if(r<0)return;let i;if(n.key===`ArrowRight`)i=(r+1)%e.length;else if(n.key===`ArrowLeft`)i=(r-1+e.length)%e.length;else if(n.key===`Home`)i=0;else if(n.key===`End`)i=e.length-1;else return;n.preventDefault(),o(i)},children:e.map((e,i)=>{let o=e.id===t;return X(`button`,{ref:e=>{a.current[i]=e},id:Lt(r,e.id),className:`tab${o?` is-selected`:``}`,type:`button`,role:`tab`,"aria-selected":o,"aria-controls":Rt(r,e.id),tabIndex:o?0:-1,onClick:()=>n?.(e.id),children:e.label},e.id)})})}var Bt={ok:{label:`ok`,kind:`ok`},failed:{label:`failed`,kind:`danger`},interrupted:{label:`interrupted`,kind:`warn`},running:{label:`running`,kind:`info`},unknown:{label:`unknown`,kind:`idle`}};function Vt(e){return Bt[e]||{label:e||`unknown`,kind:`idle`}}function Ht(e,t,n){return(e||[]).filter(e=>e&&e.kind===`agent_finish`&&Number(e.attempt)===Number(t)&&(e.stage||``)===(n||``)).map(e=>vt(e))}function Ut(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`start time not recorded`:`started ${t.toISOString().replace(`T`,` `).slice(0,16)} UTC`}function Wt({stage:e,attemptNumber:t,events:n}){let r=Vt(e.status),i=gt(e.duration_ms),a=Ht(n,t,e.name);return X(`li`,{className:`run-stage`,"data-status":e.status||`unknown`,children:[X(`span`,{className:`run-stage-node`,"aria-hidden":`true`}),X(`div`,{className:`run-stage-body`,children:[X(`div`,{className:`run-stage-head`,children:[X(`span`,{className:`run-stage-name mono`,children:e.name||`(unnamed stage)`}),X(Q,{text:r.label,kind:r.kind}),X(`span`,{className:`run-stage-duration`,children:i?`ran for ${i}`:`duration not recorded`})]}),e.error?X(`div`,{className:`run-stage-error`,children:e.error}):null,a.map((e,t)=>X(`div`,{className:`run-agent-report`,children:[X(`span`,{className:`run-agent-report-label`,children:`Agent's own report, not verified by archie: `}),[e.title,e.detail].filter(Boolean).join(` · `)]},t))]})]})}function Gt({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Kt({count:e}){let t=Number(e)||0;return t?X(`p`,{className:`run-rail-note`,children:[t,` event`,t===1?``:`s`,` on this task predate attempt attribution and cannot be assigned to a run.`]}):null}function qt({state:e,attemptNumber:t,events:n,onRetry:r}){if(e===void 0)return X(`div`,{className:`run-loading`,children:`Loading this task's attempts…`});if(e===null)return X(`div`,{className:`run-error`,children:[X(`div`,{className:`run-error-title`,children:`Could not load this task's attempts`}),X(`div`,{className:`run-error-detail`,children:`archied did not answer for this task's run history. It may be restarting — retry, or check the daemon.`}),r?X(`button`,{className:`btn`,type:`button`,onClick:r,children:`Retry`}):null]});let i=e?.attempts||[];if(!i.length)return X(S,{children:[X(Gt,{title:`No attempts recorded`,detail:`This task has no recorded run. An attempt is written when a stage event is emitted, and none exist here.`}),X(Kt,{count:e?.unattributed_events})]});let a=i.find(e=>Number(e.attempt)===Number(t));if(!a)return X(S,{children:[X(Gt,{title:`Attempt ${t} is not recorded for this task`,detail:`This task recorded attempt ${i.map(e=>e.attempt).join(`, `)}.`}),X(Kt,{count:e?.unattributed_events})]});let o=a.stages||[],s=Vt(a.status);return X(`div`,{className:`run-rail`,children:[X(`div`,{className:`run-rail-head`,children:[X(`span`,{className:`run-rail-attempt`,children:[`Attempt `,a.attempt]}),X(Q,{text:s.label,kind:s.kind}),X(`span`,{className:`run-rail-when`,children:Ut(a.started_at)})]}),o.length?X(`ol`,{className:`run-stages`,"aria-label":`Stages recorded in attempt ${a.attempt}`,children:o.map((e,t)=>X(Wt,{stage:e,attemptNumber:a.attempt,events:n},`${e.seq??t}:${e.name}`))}):X(Gt,{title:`No stages recorded for this attempt`,detail:`The attempt exists, but nothing recorded a stage for it.`}),X(`p`,{className:`run-rail-legend`,children:[X(`strong`,{children:`ok`}),` means the stage returned without error. Archie records no exit code and does not verify that the work was correct, so this is a progress status, not a check result.`]}),X(Kt,{count:e?.unattributed_events})]})}var Jt={added:`Added`,modified:`Modified`,deleted:`Deleted`,renamed:`Renamed`,typechange:`Type changed`};function Yt(e){return Jt[e]||e||`unknown`}function Xt(e,t){let n=e?.repo_url||t?.repo_url||``,r=t&&String(t.pr_number??``)!==``&&String(t.pr_number)===String(e?.pr_number??``);return{repo:n,pr:e?.pr_url||r&&t.pr_url||``}}function Zt(e={}){let t=Number(e.files)||0,n=[`${t} file${t===1?``:`s`}`];return e.additions&&n.push(`+${e.additions}`),e.deletions&&n.push(`−${e.deletions}`),n.join(` · `)}function Qt({capture:e}){let t=e.files||[],n=Number(e.totals?.files)||t.length;return t.length?X(S,{children:[X(`table`,{className:`table run-changes-table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Path`}),X(`th`,{children:`Change`}),X(`th`,{className:`run-changes-count`,children:`Added`}),X(`th`,{className:`run-changes-count`,children:`Deleted`})]})}),X(`tbody`,{children:t.map((e,t)=>X(`tr`,{children:[X(`td`,{className:`mono run-changes-path`,children:[e.old_path?X(`span`,{className:`run-changes-old`,children:[e.old_path,` → `]}):null,e.path]}),X(`td`,{children:[Yt(e.status),e.binary?X(`span`,{className:`run-changes-hint`,children:`no textual hunks`}):null]}),X(`td`,{className:`run-changes-count mono`,children:e.additions?`+${e.additions}`:`—`}),X(`td`,{className:`run-changes-count mono`,children:e.deletions?`−${e.deletions}`:`—`})]},`${e.path}:${t}`))})]}),e.truncated?X(`p`,{className:`run-changes-note`,children:[`Showing the first `,t.length,` of `,n,` files. The totals above cover every file in this capture.`]}):null]}):X(`div`,{className:`run-changes-empty`,children:[`This capture recorded no file entries`,n?`, though its totals cover ${n} file${n===1?``:`s`}`:``,`.`]})}function $t({capture:e,task:t}){let n=Xt(e,t),r=e.pr_number;return X(`section`,{className:`run-capture`,children:[X(`div`,{className:`run-capture-head`,children:[X(`span`,{className:`run-capture-when`,children:[e.captured_after?`Captured after ${e.captured_after}`:`Captured`,e.stage?` in stage ${e.stage}`:``]}),X(`span`,{className:`run-capture-at`,children:e.captured_at?Ie(e.captured_at):``})]}),X(`div`,{className:`run-capture-meta`,children:[X(`span`,{className:`mono`,children:n.repo?X(`a`,{className:`run-capture-link`,href:n.repo,target:`_blank`,rel:`noreferrer`,children:[e.owner,`/`,e.repo]}):`${e.owner||``}/${e.repo||``}`}),e.branch?X(`span`,{className:`mono run-capture-branch`,children:[e.branch,e.base?` → ${e.base}`:``]}):null,e.head_sha?X(`span`,{className:`mono run-capture-sha`,children:String(e.head_sha).slice(0,8)}):null,r?n.pr?X(`a`,{className:`run-capture-link`,href:n.pr,target:`_blank`,rel:`noreferrer`,children:[`PR #`,r]}):X(`span`,{className:`mono`,children:[`PR #`,r]}):null,X(`span`,{className:`run-capture-totals`,children:Zt(e.totals)})]}),X(Qt,{capture:e})]})}function en({state:e,task:t,onRetry:n}){if(e===void 0)return X(`div`,{className:`run-loading`,children:`Loading changed files…`});if(e===null)return X(`div`,{className:`run-error`,children:[X(`div`,{className:`run-error-title`,children:`Could not load this attempt's changed files`}),X(`div`,{className:`run-error-detail`,children:`archied did not answer for this attempt. It may be restarting — retry, or check the daemon.`}),n?X(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]});let r=e.captures||[];return e.found===!0&&!r.length?X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`A change capture was recorded but could not be read`}),X(`div`,{children:`This attempt has a change capture event, but this dashboard could not decode its payload. That is a read failure, not a statement about what the attempt changed.`})]}):!e.found||!r.length?X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No change capture was recorded for this attempt`}),X(`div`,{children:`Archie records what an attempt changed when it commits or pushes that work. Nothing was recorded here — the attempt may predate capture, or it produced no commit. This is not the same as "no files changed".`})]}):X(`div`,{className:`run-changes`,children:r.map((e,n)=>X($t,{capture:e,task:t},`${e.captured_at||``}:${n}`))})}function tn(e,t){return(e||[]).find(e=>e&&e.kind===`config_captured`&&Number(e.attempt)===Number(t))||null}function nn({events:e,attempt:t,onRetry:n}){if(e===void 0)return X(`div`,{className:`run-loading`,children:`Loading this task's events…`});if(e===null)return X(`div`,{className:`run-error`,children:[X(`div`,{className:`run-error-title`,children:`Could not load this task's events`}),X(`div`,{className:`run-error-detail`,children:`The configuration is recorded as an event on the task, so it cannot be shown while the event stream is unreadable. archied did not answer — retry, or check the daemon.`}),n?X(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]});let r=tn(e,t);if(!r)return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`Not captured for this run`}),X(`div`,{children:[`Archie records the effective configuration when it dispatches an attempt. Attempt `,t,` `,`has no such record — it predates the record, or the capture did not run. Nothing here says the run used the defaults.`]})]});let i=r.data||{},a=i.schema||``,o=i.document;return X(`div`,{className:`run-config`,children:[X(`p`,{className:`run-config-scope`,children:[`This is attempt `,r.attempt,`'s effective task-runtime configuration: a non-secret subset covering bot identity, models, limits, budgets, dispatch, diff cap, notifications, forge host and tool policy. It is not the dashboard configuration view — providers, repositories, identities, credentials and lock state are not part of it.`]}),X(`div`,{className:`run-config-when`,children:[`Captured `,r.at||`at an unrecorded time`,r.stage?` in stage ${r.stage}`:``]}),a===`archie/task-config@1`?X(`pre`,{className:`run-json`,children:JSON.stringify(o??{},null,2)}):X(S,{children:[X(`div`,{className:`run-config-unknown`,children:[`Recorded in an unknown schema`,a?` (${a})`:``,`. The raw payload is shown verbatim; nothing here reinterprets it.`]}),X(`pre`,{className:`run-json`,children:JSON.stringify(i,null,2)})]})]})}function rn({state:e,attempt:t,onRetry:n}){return e===void 0?X(`div`,{className:`run-loading`,children:`Loading the stored record…`}):e===null?X(`div`,{className:`run-error`,children:[X(`div`,{className:`run-error-title`,children:`Could not load the stored record`}),X(`div`,{className:`run-error-detail`,children:`archied did not answer for this task's debug view. It may be restarting — retry, or check the daemon.`}),n?X(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]}):X(`div`,{className:`run-debug`,children:[X(`p`,{className:`run-debug-note`,children:[`The stored task record and its events, verbatim. Events are unfiltered on purpose: this is every event the task has, and each one carries the attempt it belongs to. Attempt `,t,` `,`is the one selected above.`]}),X(`pre`,{className:`run-json`,children:JSON.stringify(e,null,2)})]})}var an=[{id:`stages`,label:`Stages`},{id:`log`,label:`Log`},{id:`changes`,label:`Changed files`},{id:`config`,label:`Configuration`},{id:`debug`,label:`Debug`}],on=`run`,sn=new Set(an.map(e=>e.id));function cn(e){let t=String(e??``).trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:null}function ln(e){let t=e?.get?.(`tab`)||``;return sn.has(t)?t:an[0].id}function un(e){let t=e?.get?.(`attempt`);if(t==null||t===``)return null;let n=Number(t);return Number.isInteger(n)&&n>0?n:null}function dn(e,t,n){let r=new URLSearchParams;return r.set(`tab`,t||an[0].id),n&&r.set(`attempt`,String(n)),`#/tasks/${e}?${r.toString()}`}function fn(e,t,n){try{window.history.replaceState(null,``,`${location.pathname}${location.search}${dn(e,t,n)}`)}catch{}}function pn(e,t){return`${e}|${Number(t)||0}`}function mn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function hn({id:e}){return X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Task not found`}),X(`p`,{className:`page-sub`,children:[`No task with id `,e,` in this deployment.`]})]}),X(`div`,{className:`page-actions`,children:X(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`})})]}),X(`div`,{className:`card`,children:X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:[`Nothing is recorded for task `,e]}),X(`div`,{children:`archied answered that this task does not exist, so there is no run history to show.`})]})})]})}function gn({raw:e}){return X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Not a task id`}),X(`p`,{className:`page-sub`,children:`The run view addresses one task by its id: #/tasks/42`})]}),X(`div`,{className:`page-actions`,children:X(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`})})]}),X(`div`,{className:`card`,children:X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:[`“`,e,`” is not a task id`]}),X(`div`,{children:`A task id is a positive whole number. Nothing was requested.`})]})})]})}function _n({attempts:e,selected:t,onSelect:n}){let r=e?.attempts||[];return r.length?X(`div`,{className:`run-attempts`,role:`group`,"aria-label":`Attempts of this task`,children:r.map(e=>{let r=Vt(e.status),i=Number(e.attempt)===Number(t);return X(`button`,{type:`button`,className:`run-attempt${i?` is-selected`:``}`,"aria-pressed":i,onClick:()=>n(e.attempt),children:[X(`span`,{className:`run-attempt-id`,children:[`Attempt `,e.attempt]}),X(Q,{text:r.label,kind:r.kind}),X(`span`,{className:`run-attempt-meta`,children:[(e.stages||[]).length,` stage`,(e.stages||[]).length===1?``:`s`]})]},e.attempt)})}):null}function vn({id:e,query:t}){let[n,r]=W(()=>ln(t)),[i,a]=W(()=>un(t)),[o,s]=W(void 0),[c,l]=W(void 0),[u,d]=W(!1),[f,p]=W(void 0),[m,h]=W(Tt),[g,_]=W(new Map),[v,y]=W(new Map),[b,x]=W(new Map),[S,C]=W(!1),[w,T]=W(null),[E,D]=W(0),O=K(new Set),k=Array.isArray(o)&&o.find(t=>String(t.id)===String(e))||null,A=Number(c?.current_attempt)>0?Number(c.current_attempt):null,j=i??A,M=(c?.attempts||[]).find(e=>Number(e.attempt)===Number(j)),N=[...new Set((M?.stages||[]).map(e=>e.name).filter(Boolean))],P=(e,t,n,{force:r=!1}={})=>{O.current.has(e)&&!r||(O.current.add(e),n(t=>new Map(t).set(e,void 0)),t().then(t=>n(n=>new Map(n).set(e,t))).catch(()=>n(t=>new Map(t).set(e,null))))},F=()=>{s(void 0),Y.tasks().then(e=>s(e)).catch(()=>s(null))},I=()=>{l(void 0),d(!1),Y.taskAttempts(e).then(e=>l(e)).catch(e=>{e?.status===404&&d(!0),l(null)})},L=()=>{p(void 0),Y.task(e).then(e=>p(e||[])).catch(()=>p(null))},ee=(t,n)=>P(Et(e,t,m),()=>Y.taskLogs(e,{attempt:t||void 0,level:m.level,stage:m.stage,limit:500}),_,n),R=(t,n)=>P(pn(e,t),()=>Y.taskChanges(e,{attempt:t}),y,n),z=(t,n)=>P(pn(e,t),()=>Y.taskDebug(e,{attempt:t}),x,n),te=()=>{O.current=new Set,_(new Map),y(new Map),x(new Map),F(),I(),L(),D(e=>e+1)};G(()=>{F(),I(),L()},[]),G(()=>{j!=null&&(n===`log`?ee(j):n===`changes`?R(j):n===`debug`&&z(j))},[n,j,m,E]),G(()=>{fn(e,n,j)},[e,n,j]);let B=async()=>{let t=k?.title||`task ${e}`;if(window.confirm(`Start a new run for "${t}"? This is a new attempt, and the previous attempt's commits are discarded.`)){T(null),C(!0);try{await Y.taskAction(e,`retry`),O.current=new Set,_(new Map),y(new Map),x(new Map),a(null),F(),I(),L(),D(e=>e+1)}catch(e){T(ke(e))}finally{C(!1)}}};if(u)return X(hn,{id:e});let V=j==null?null:Et(e,j,m),ne=pn(e,j),re=pn(e,j),H=()=>{if(n===`stages`)return X(qt,{state:c,attemptNumber:j,events:f,onRetry:I});if(c===void 0)return X(`div`,{className:`run-loading`,children:`Loading this task's attempts…`});if(c===null)return X(`div`,{className:`run-error`,children:[X(`div`,{className:`run-error-title`,children:`Could not load this task's attempts`}),X(`div`,{className:`run-error-detail`,children:`This panel reads one attempt, and the task's run history could not be read.`}),X(`button`,{className:`btn`,type:`button`,onClick:I,children:`Retry`})]});if(j==null)return X(mn,{title:`No attempt recorded`,detail:`This task has no recorded run, so there is nothing to read for an attempt.`});switch(n){case`log`:return X(kt,{state:V&&g.has(V)?g.get(V):void 0,attempt:j,stages:N,filters:m,onFilterChange:h,taskId:e,onRetry:()=>ee(j,{force:!0})});case`changes`:return X(en,{state:v.has(ne)?v.get(ne):void 0,task:k,onRetry:()=>R(j,{force:!0})});case`config`:return X(nn,{events:f,attempt:j,onRetry:L});case`debug`:return X(rn,{state:b.has(re)?b.get(re):void 0,attempt:j,onRetry:()=>z(j,{force:!0})});default:return X(qt,{state:c,attemptNumber:j,events:f,onRetry:I})}},ie=Je(`retry`),ae=!!(ie&&(k?.actions||[]).includes(`retry`));return X(`div`,{className:`run-page`,children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:k?.title||`Task #${e}`}),X(`p`,{className:`page-sub`,children:[`One run of task `,e,k?.workflow?` · ${k.workflow} workflow`:``,k?.repo?` · ${k.owner}/${k.repo}`:``]})]}),X(`div`,{className:`page-actions`,children:[X(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`}),X(`button`,{className:`btn`,type:`button`,onClick:te,children:`Refresh`})]})]}),X(`div`,{className:`run-meta`,children:[X(`span`,{className:`run-meta-item`,children:[X(`span`,{className:`run-meta-label`,children:`Task status`}),o===void 0?X(`span`,{className:`run-meta-muted`,children:`loading…`}):k?X(Q,{text:We(k.status),kind:Ge(k.status)}):X(`span`,{className:`run-meta-muted`,children:`not read`})]}),X(`span`,{className:`run-meta-item`,children:[X(`span`,{className:`run-meta-label`,children:`Attempt`}),X(`span`,{className:`run-meta-value`,children:c===null?`run history unreadable`:c===void 0?`loading…`:j==null?`none recorded`:`attempt ${j} of ${A??j}`})]}),k?.repo_url?X(`a`,{className:`run-meta-link`,href:k.repo_url,target:`_blank`,rel:`noreferrer`,children:[k.owner,`/`,k.repo]}):null,k?.issue_url&&k.issue_number?X(`a`,{className:`run-meta-link`,href:k.issue_url,target:`_blank`,rel:`noreferrer`,children:[`Issue #`,k.issue_number]}):null,k?.pr_url&&k.pr_number?X(`a`,{className:`run-meta-link`,href:k.pr_url,target:`_blank`,rel:`noreferrer`,children:[`PR #`,k.pr_number]}):null]}),o===null?X(`p`,{className:`run-note`,children:`The task list could not be read, so this page cannot show the task's current status or its operator controls. The run history below comes from the task's own endpoints.`}):null,Array.isArray(o)&&!k?X(`p`,{className:`run-note`,children:[`Task `,e,` is not among the tasks this dashboard lists (the list covers the 100 most recently updated). Its recorded attempts are shown below; the Debug tab holds the stored record verbatim.`]}):null,X(`section`,{className:`run-restart`,"aria-label":`Start a new run`,children:[X(`button`,{className:`btn ${ie?.kind===`primary`?`btn-primary`:``}`,type:`button`,disabled:!ae||S,title:`Retry this task as a new run`,onClick:B,children:S?`Starting…`:`Start a new run`}),X(`p`,{className:`run-restart-copy`,children:`Starts a new attempt for this task: a fresh worktree reset onto the base branch. The previous attempt's commits are discarded — they are not carried into the new run.`}),!ae&&o!==void 0?X(`p`,{className:`run-restart-unavailable`,children:k?`A new run can only start from a parked task. This task is ${We(k.status)}.`:`This task's operator controls could not be read, so a new run cannot be started from here.`}):null,w?X(`p`,{className:`run-restart-error run-restart-error-${w.kind}`,children:w.kind===`session-expired`?`Your session has expired. Reload to sign in.`:w.kind===`refused`?`${w.message} — this run cannot be restarted from here.`:`${w.message} — try again, or check the daemon.`}):null]}),X(_n,{attempts:c,selected:j,onSelect:e=>a(e)}),X(`div`,{className:`card run-card`,children:[X(zt,{tabs:an,active:n,onSelect:r,prefix:on}),X(`div`,{className:`run-panel`,role:`tabpanel`,id:Rt(on,n),"aria-labelledby":Lt(on,n),tabIndex:0,children:H()})]})]})}function yn(e,t){let n=t?.id,r=cn(n);return r===null?X(gn,{raw:n??``}):X(vn,{id:r,query:e},r)}function bn({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function xn(e){return X(Sn,{query:e})}function Sn(){let[e,t]=W([]),[n,r]=W(``),[i,a]=W(null),o=async()=>{try{let e=await Y.skills();t(e?.skills||[]),a(null)}catch(e){t([]),a(String(e.message||e))}};G(()=>{o()},[]);let s=(e,t)=>!t||`${e.name} ${e.description}`.toLowerCase().includes(t),c=ge(()=>e.filter(e=>s(e,n)),[e,n]);return X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Skills`}),X(`p`,{class:`page-sub`,children:`What Archie can do, in plain language.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:o,children:`Refresh`})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:[X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Catalogue`}),X(`p`,{class:`card-sub`,children:`Project, shared, and user-global skills`})]}),X(`input`,{class:`skill-search`,type:`search`,placeholder:`Search skills…`,onInput:e=>r(e.target.value.trim().toLowerCase())})]}),X(`div`,{class:`grid grid-2`,children:i?X(bn,{title:`Cannot reach archied`,detail:i}):e.length?c.length?c.map(e=>X(`div`,{class:`card skill-card`,children:[X(`div`,{class:`card-head`,children:[X(`h3`,{class:`card-title`,children:e.name||`Untitled skill`}),e.workflow&&X(Q,{text:e.workflow,kind:`info`})]}),X(`p`,{class:`skill-desc`,children:e.description||`No description provided.`}),X(`div`,{class:`skill-source`,children:e.source||`Unknown source`})]},e.name)):X(bn,{title:`No skills match`,detail:`Nothing found for "${n}".`}):X(bn,{title:`No skills discovered yet`,detail:`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`})})]})]})}var Cn={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function wn(e){return Cn[e]?Cn[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function Tn(e,t){return t?Math.round(e/t*100):0}function En(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function Dn({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function On({fraction:e,kind:t=`ok`}){let n=Math.min(100,Math.max(0,e));return X(`div`,{class:`wf-bar`,children:X(`div`,{class:`wf-bar-fill wf-bar-${t}`,style:{width:`${n}%`}})})}function kn(e){return X(An,{query:e})}function An(){let[e,t]=W([]),[n,r]=W([]),[i,a]=W([]),[o,s]=W(null),c=async()=>{try{let e=await Y.workflows();t(e?.definitions||[]),r(e?.workflows||[]),a(e?.stages||[]),s(null)}catch(e){s(String(e.message||e))}};return G(()=>{c()},[]),X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Workflows`}),X(`p`,{class:`page-sub`,children:`Run outcomes and spend per workflow, and where stages get stuck.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:c,children:`Refresh`})})]}),X(jn,{definitions:e}),o?X(`div`,{class:`card`,children:X(Dn,{title:`Cannot reach archied`,detail:o})}):X(S,{children:[X(Mn,{workflows:n,definitions:e}),X(Nn,{stages:i})]})]})}function jn({definitions:e}){if(!e.length)return null;let t=e.filter(e=>e.enabled)[0]?.id||``,[n,r]=W(``),[i,a]=W(``),[o,s]=W(t),[c,l]=W(``),[u,d]=W(``),[f,p]=W(!1),[m,h]=W(``);return G(()=>{!o&&t&&s(t)},[t,o]),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Start work`}),X(`p`,{class:`card-sub`,children:`This enters Archie’s normal admitted task queue.`})]})}),X(`form`,{class:`wf-form`,onSubmit:async e=>{e.preventDefault(),p(!0),h(``);try{let e=await Y.workRequest({identity:n,repository:i,workflow:o,title:c,instructions:u});h(`Queued task #${e.task_id}.`),r(``),a(``),s(t),l(``),d(``)}catch(e){h(String(e.message||e))}finally{p(!1)}},children:[X(`input`,{placeholder:`Identity`,required:!0,value:n,onInput:e=>r(e.target.value)}),X(`input`,{placeholder:`owner/repository`,required:!0,value:i,onInput:e=>a(e.target.value)}),X(`select`,{required:!0,value:o,onInput:e=>s(e.target.value),children:e.filter(e=>e.enabled).map(e=>X(`option`,{value:e.id,children:wn(e.name||e.id)},e.id))}),X(`input`,{placeholder:`Short task title`,required:!0,value:c,onInput:e=>l(e.target.value)}),X(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3,value:u,onInput:e=>d(e.target.value)}),X(`button`,{class:`btn`,type:`submit`,disabled:f,children:`Start work`}),m&&X(`p`,{class:`card-sub`,children:m})]})]})}function Mn({workflows:e,definitions:t}){let n=new Map(e.map(e=>[e.workflow,e])),r=t.map(e=>({...e,...n.get(e.id)||{workflow:e.id,runs:0,merged:0}}));return r.length?X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Per workflow`}),X(`p`,{class:`card-sub`,children:`Success rate is merged tasks over all runs`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Origin`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Success rate`}),X(`th`,{children:`Avg tokens`}),X(`th`,{children:`Avg steps`})]})}),X(`tbody`,{children:r.map(e=>{let t=Tn(e.merged,e.runs);return X(`tr`,{children:[X(`td`,{class:`strong`,children:wn(e.workflow)}),X(`td`,{class:`mono`,children:e.origin||`registry`}),X(`td`,{children:`${e.runs} run${e.runs===1?``:`s`}`}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[t,`%`,X(`span`,{class:`wf-rate-sub`,children:[e.merged,` of `,e.runs,` merged`]})]}),X(On,{fraction:t,kind:t>=50?`ok`:`warn`})]}),X(`td`,{class:`mono`,children:e.avg_tokens?e.avg_tokens.toLocaleString():`—`}),X(`td`,{class:`mono`,children:e.avg_steps?e.avg_steps.toFixed(1):`—`})]},e.workflow)})})]})})]}):X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per workflow`})})}),X(Dn,{title:`No workflow runs yet`,detail:`Stats appear here once a task has run through a workflow.`})]})}function Nn({stages:e}){if(!e.length)return X(`div`,{class:`card wf-stage-card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per stage`})})}),X(Dn,{title:`No stage data yet`,detail:`Stage timing and failures appear here once workflows have run.`})]});let t=Math.max(...e.map(e=>e.avg_ms||0),1),n=[...e].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),r=[...e].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);return X(`div`,{class:`grid grid-2 wf-stage-card`,children:[X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Slowest stages`}),X(`p`,{class:`card-sub`,children:`Average duration, this workflow's stages`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Avg duration`})]})}),X(`tbody`,{children:n.map((e,n)=>X(`tr`,{children:[X(`td`,{children:wn(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:e.runs}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:En(e.avg_ms)}),X(On,{fraction:Tn(e.avg_ms,t),kind:`info`})]})]},n))})]})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Most failures`}),X(`p`,{class:`card-sub`,children:`Stages that error out, over their runs`})]})}),r.length?X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Failures`})]})}),X(`tbody`,{children:r.map((e,t)=>X(`tr`,{children:[X(`td`,{children:wn(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[e.errors,` of `,e.runs]}),X(On,{fraction:Tn(e.errors,e.runs),kind:`danger`})]})]},t))})]})}):X(Dn,{title:`No failures recorded`,detail:`Every stage has completed cleanly so far.`})]})]})}function Pn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Fn(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function In(){let[e,t]=W([]),[n,r]=W(null),i=async()=>{try{let e=await Y.channels();t(e?.channels||[]),r(null)}catch(e){r(String(e.message||e))}};return G(()=>{i()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Channels`}),X(`p`,{className:`page-sub`,children:`The conversational front-ends Archie can be reached through.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:i,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:n?X(Pn,{title:`Cannot reach archied`,detail:n}):e.length===0?X(Pn,{title:`No channels configured`,detail:`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`}):e.map(e=>X(`div`,{className:`card channel-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Q,{text:e.state||(e.configured?`configured`:`stopped`),kind:Fn(e.state,e.configured)})]}),X(`p`,{className:`channel-desc`,children:e.description}),X(`p`,{className:`channel-detail`,children:e.detail}),e.reload_supported?X(`button`,{className:`btn`,onClick:async t=>{t.currentTarget.disabled=!0;try{await Y.channelReload(e.id||e.name.toLowerCase()),await i()}catch{}finally{t.currentTarget&&(t.currentTarget.disabled=!1)}},children:`Reload`}):X(`p`,{className:`channel-detail`,children:`Reload requires a daemon restart for this adapter.`})]},e.id||e.name))})]})}function Ln(e){return X(In,{query:e})}function Rn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function zn(e){return X(Bn,{query:e})}function Bn({query:e}){let[t,n]=W([]),[r,i]=W(null),a=async()=>{try{let e=await Y.curators();n(e?.curators||[]),i(null)}catch(e){i(String(e.message||e))}};return G(()=>{a()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Curators`}),X(`p`,{className:`page-sub`,children:`Background agents that maintain memory and skills: what ran, and why.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:a,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:r?X(Rn,{title:`Cannot reach archied`,detail:r}):t.length?t.map(e=>X(Hn,{curator:e},e.name)):X(Rn,{title:`No curators registered`,detail:`Curators are background agent loops that maintain memory and skills. None are registered on this daemon.`})})]})}function Vn(e){switch(e){case`healthy`:return`ok`;case`degraded`:return`warn`;case`unhealthy`:return`danger`;default:return`idle`}}function Hn({curator:e}){let t=e.recent_actions||[];return X(`div`,{className:`card curator-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Q,{text:e.health?.status||`unknown`,kind:Vn(e.health?.status)})]}),e.health?.message&&X(`p`,{className:`curator-health-message`,children:e.health.message}),X(`p`,{className:`curator-meta`,children:e.last_run_at?`Last ran ${Ie(e.last_run_at)} · ${e.last_run_actions} action${e.last_run_actions===1?``:`s`}`:`Has not run yet`}),t.length?X(`ul`,{className:`curator-actions`,children:t.map((e,t)=>X(`li`,{className:`curator-action`,children:[X(`div`,{className:`curator-action-head`,children:[X(`span`,{className:`curator-action-type`,children:e.type||`action`}),X(`span`,{className:`curator-action-time`,children:Ie(e.at)})]}),e.detail&&X(`p`,{className:`curator-action-detail`,children:e.detail}),e.reason&&X(`p`,{className:`curator-action-reason`,children:[`Why: `,e.reason]})]},t))}):X(`p`,{className:`curator-meta`,children:`No recorded activity yet.`})]})}function Un(e){return e==null||e===``?`—`:String(e)}function Wn({label:e,value:t,opts:n}){let r=Un(t),[i,a]=W(!1),[o,s]=W(``),[c,l]=W(null),[u,d]=W(!1),[f,p]=W(!1),m=n?.key;if(!m)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n?.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let h=n.locked?.[m];if(h)return X(`div`,{className:`kv is-locked`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`span`,{className:`kv-note`,children:h})]});if(n.editable===!1)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let g=n.overridden?.includes(m),_=()=>{s(String(n.raw??``)),l(null),a(!0)},v=async()=>{p(!0),l(null);try{await Y.configReset(m),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{p(!1)}},y=async()=>{let e=Gn(n.type,o);if(e.error){l(e.error);return}d(!0),l(null);try{await(n.save||(e=>Y.configUpdate({[m]:e})))(e.value),a(!1),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{d(!1)}};if(i){let t=K(null);G(()=>{t.current&&t.current.focus()},[]);let r=e=>{e.key===`Enter`&&(e.preventDefault(),y()),e.key===`Escape`&&a(!1)},i;return i=n.type===`bool`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:[X(`option`,{value:`true`,children:`true`}),X(`option`,{value:`false`,children:`false`})]}):n.type===`enum`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:(n.options||[]).map(e=>X(`option`,{value:e,children:e},e))}):X(`input`,{className:`kv-input`,type:`text`,value:o,onInput:e=>s(e.target.value),onKeyDown:r,ref:t}),X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),i,X(`div`,{className:`kv-actions`,children:[X(`button`,{className:`kv-save`,type:`button`,onClick:y,disabled:u,children:`Save`}),X(`button`,{className:`kv-cancel`,type:`button`,onClick:()=>a(!1),disabled:u,children:`Cancel`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`div`,{className:`kv-actions`,children:[g&&X(`span`,{className:`kv-flag`,title:`Set from the dashboard; this shadows the value in the config file`,children:`overridden`}),X(`button`,{className:`kv-btn`,type:`button`,title:`Edit ${e}`,onClick:_,children:`Edit`}),g&&X(`button`,{className:`kv-btn`,type:`button`,title:`Discard the dashboard value and fall back to the config file`,onClick:v,disabled:f,children:`Reset`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}function Gn(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}function Kn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function qn({sub:e,title: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:t||`Update status`}),X(`p`,{className:`card-sub`,children:e})]})}),n]})}var Jn={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},Yn={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function Xn({components:e}){return!e||!e.length?X(qn,{sub:`How each component is deployed, and whether what's running matches what's installed.`,children:X(Kn,{title:`No components reported`,detail:`The configured update-check command returned nothing.`})}):X(qn,{sub:`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Component`}),X(`th`,{children:`Install type`}),X(`th`,{children:`Running`}),X(`th`,{children:`Latest available`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:e.map(e=>X(`tr`,{title:[`Installed claim: ${e.installed_claim||`unknown`}`,`Running: ${e.running_version||`not observed`}`,e.reference?`Reference: ${e.reference}`:null].filter(Boolean).join(` +`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Q,{text:Jn[e.status]||e.status,kind:Yn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function $({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Zn({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function Qn({origins:e}){return e?.length?X(Zn,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(Wn,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X(Zn,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X($,{title:`Source provenance is unavailable.`})})}function $n(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function er({data:e,error:t}){if(t)return X(Zn,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X($,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X(Zn,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??We(e.id),n=e.kind??Ge(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Q,{text:t,kind:n})})]},e.id)})}):X($,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=$n(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X($,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function tr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(!1),[o,s]=W(null),[c,l]=W(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function nr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(String(e[t]??0)),[o,s]=W(null),[c,l]=W(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function rr({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X(Zn,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X($,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X(Zn,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(tr,{r:e,field:`allow_concurrent`,onSaved:t,editable:n}),X(nr,{r:e,field:`max_retries`,onSaved:t,editable:n}),X(tr,{r:e,field:`review_enabled`,onSaved:t,editable:n})]},i))})]})})})}function ir(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function ar({models:e,providers:t}){let n=Object.entries(e||{}),r=Object.entries(t||{});return X(Zn,{title:`Models & providers`,sub:`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Model roles`}),n.length?X(`div`,{className:`kv-list`,children:n.map(([e,t])=>X(Wn,{label:ir(e),value:t},e))}):X($,{title:`No model roles configured`,detail:`Assign a model to at least one role (e.g. "builder") in [models].`}),X(`h3`,{className:`cfg-subhead`,children:`Providers`}),r.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Provider`}),X(`th`,{children:`Class`}),X(`th`,{children:`Base URL`}),X(`th`,{children:`API key env var`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:r.map(([e,t])=>X(`tr`,{children:[X(`td`,{className:`strong`,children:e}),X(`td`,{children:t.class}),X(`td`,{className:`mono`,children:t.base_url||`default`}),X(`td`,{className:`mono`,children:t.api_key_env||`—`}),X(`td`,{children:t.configured?X(Q,{text:`configured`,kind:`ok`}):X(Q,{text:`missing credentials`,kind:`warn`})})]},e))})]})}):X($,{title:`No providers configured`,detail:`Add a [providers.] entry so a model role above has something to run on.`})]})}function or(){let[e,t]=W(null),[n,r]=W(null),[i,a]=W(null),[o,s]=W(null),[c,l]=W(!1),[u,d]=W(null),[f,p]=W(null),m=()=>{h(),g(),_()},h=async()=>{try{let e=await Y.config();t(e),r(null)}catch(e){r(String(e.message||e))}},g=async()=>{try{let e=await Y.version();a(e?.components||[]),s(null),l(!1)}catch(e){e?.status===501?l(!0):s(String(e.message||e))}},_=async()=>{try{let e=await Y.taskMeta();d(e),p(null)}catch(e){p(String(e.message||e))}};return G(()=>{m()},[]),X(`div`,{className:`cfg-page`,children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Configuration`}),X(`p`,{className:`page-sub`,children:`What archied is actually running with right now.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:m,children:`Refresh`})})]}),X(`div`,{children:!c&&(o?X(`div`,{className:`card`,children:X($,{title:`Update status unavailable`,detail:o})}):i?X(Xn,{components:i}):null)}),X(`div`,{children:X(er,{data:u,error:f})}),X(`div`,{children:n?X(`div`,{className:`card`,children:X($,{title:`Cannot reach archied`,detail:n})}):!e||Object.keys(e).length===0?X(`div`,{className:`card`,children:X($,{title:`No configuration loaded`,detail:`archied is running without a config file wired into the dashboard, so there is nothing to show.`})}):X(S,{children:[e.reload?.overlay_unavailable&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The runtime config overlay is not in effect: `,e.reload.overlay_unavailable]})}),e.reload?.last_error&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The last config reload failed; the running config is unchanged: `,e.reload.last_error]})}),(e.schema||[]).map((t,n)=>{let r=t.fields.filter(e=>e.type!==`structured`);return r.length?X(Zn,{title:t.label,sub:t.description,children:X(`div`,{className:`kv-list`,children:r.map(t=>X(Wn,{label:t.label,value:t.value,opts:{key:t.key,type:t.type,options:t.options,raw:t.value,hint:t.description,editable:t.editable&&e.editable!==!1,locked:e.locked||{},overridden:e.overridden||[],onSaved:h}},t.key))})},n):null}),X(rr,{repos:e.repositories,onSaved:h,editable:e.editable!==!1}),X(ar,{models:e.models,providers:e.providers}),X(Qn,{origins:e.provenance})]})})]})}function sr(e){return X(or,{query:e})}function cr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function lr(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function ur(){let[e,t]=W({level:``,component:``,q:``}),[n,r]=W(!1),[i,a]=W([]),[o,s]=W([]),c=K(new Map),[l,u]=W(0),[d,f]=W(!1),[p,m]=W(`connecting`),[h,g]=W(`Refreshing…`),_=K(null),v=K(null),y=async()=>{g(`Refreshing…`);try{let t=await Y.logs({level:e.level,component:e.component,q:e.q,limit:500});a(e=>{let n=t.components||[];return e.length===n.length&&e.every((e,t)=>e===n[t])?e:n}),f(!!t.disabled);let n=t.disabled?`Durable history unavailable; live daemon logs continue.`:t.truncated?`showing the most recent matches from ${t.file}`:t.file||``;g(n),s(t.entries||[])}catch{g(`Cannot read logs`)}};G(()=>{y()},[e]),G(()=>{let e=Me(e=>{if(b.current)return;let t=e;S.current(t)&&(c.current.set(lr(t),t),t.fields?.component&&a(e=>e.includes(t.fields.component)?e:[...e,t.fields.component]),u(e=>e+1))},e=>{m(e)});return()=>e()},[]);let b=K(n);b.current=n;let x=t=>{if(e.level&&!e.level.split(`,`).includes((t.level||``).toUpperCase())||e.component&&t.fields?.component!==e.component)return!1;if(e.q){let n=e.q.toLowerCase();if(!`${t.message||t.msg||``} ${JSON.stringify(t.fields||{})}`.toLowerCase().includes(n))return!1}return!0},S=K(x);S.current=x;let C=ge(()=>{let e=new Map;for(let t of o)e.set(lr(t),t);for(let[t,n]of c.current)e.set(t,n);return[...e.values()].filter(x).slice(-1e3)},[o,l,e]);return G(()=>{_.current&&(_.current.scrollTop=_.current.scrollHeight)},[C]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Logs`}),X(`p`,{className:`page-sub`,children:`What Archie has been doing, newest last.`})]}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn ${n?`btn-primary`:``}`,onClick:()=>r(!n),children:n?`Resume`:`Pause`}),X(`button`,{className:`btn`,onClick:y,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{className:`log-filters`,children:[X(`select`,{className:`log-select`,value:e.level,onChange:e=>t(t=>({...t,level:e.target.value})),children:yt.map(e=>X(`option`,{value:e.value,children:e.label},e.value))}),X(`select`,{className:`log-select`,value:e.component,onChange:e=>t(t=>({...t,component:e.target.value})),children:[X(`option`,{value:``,children:`All components`}),i.map(e=>X(`option`,{value:e,children:e},e))]}),X(`input`,{className:`log-search`,type:`search`,placeholder:`Search messages and fields…`,onInput:e=>{let n=e.target.value;v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{t(e=>({...e,q:n}))},250)}})]}),X(`div`,{className:`log-status`,children:[X(`span`,{className:`log-meta`,children:h}),X(Q,{text:p,kind:p===`live`?`ok`:`warn`})]})]}),X(`div`,{className:`log-list`,ref:_,children:h===`Cannot read logs`?X(cr,{title:`Cannot read logs`}):C.length?C.map(e=>X(xt,{entry:e},lr(e))):X(cr,{title:d?`Durable history unavailable`:`Nothing matches`,detail:d?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`})})]})]})}function dr(e){return X(ur,{query:e})}function fr({capture:e,expanded:t,onToggle:n}){return X(S,{children:[X(`tr`,{className:`capture-row`,tabIndex:`0`,"aria-expanded":String(t),onClick:n,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n(e))},children:[X(`td`,{className:`mono`,children:e.source||`(unknown)`}),X(`td`,{title:e.received_at||``,children:Ie(e.received_at)}),X(`td`,{children:X(Q,{text:`Unbound`,kind:`idle`})}),X(`td`,{className:`mono`,children:e.content_type||`—`}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,children:t?`Hide`:`View`})})]}),t&&X(pr,{capture:e})]})}function pr({capture:e}){return X(`tr`,{className:`capture-detail-row`,children:X(`td`,{colSpan:`5`,children:X(`div`,{className:`capture-detail`,children:[X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Payload`}),X(mr,{raw:e.body})]}),X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Headers`}),X(mr,{raw:e.headers})]})]})})})}function mr({raw:e}){return e?X(`pre`,{className:`capture-payload`,children:hr(e)}):X(`div`,{className:`capture-empty`,children:`(empty)`})}function hr(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function gr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function _r(e){return X(vr,{query:e})}function vr({query:e}){let[t,n]=W([]),[r,i]=W(null),[a,o]=W(null),[s,c]=W(!0),[l,u]=W({text:`connecting`,kind:`idle`}),d=async()=>{try{let e=await Y.captures(100);c(e.enabled!==!1),n(e.captures||[]),o(null)}catch(e){o(String(e.message||e))}};return G(()=>{d();let e=je(e=>{e.kind===`capture`&&d()},e=>{u({text:e,kind:e===`live`?`ok`:`warn`})});return()=>e()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Event inspector`}),X(`p`,{className:`page-sub`,children:`Real inbound payloads archie has captured, most recent first.`})]}),X(`div`,{className:`page-actions`,children:[X(Q,{text:l.text,kind:l.kind}),X(`button`,{className:`btn`,onClick:d,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:a?X(gr,{title:`Cannot reach archied`,detail:a}):s?t.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Source`,`Received`,`Binding`,`Content type`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(fr,{capture:e,expanded:r===e.id,onToggle:()=>i(r===e.id?null:e.id)},e.id))})]})}):X(gr,{title:`No captures yet`,detail:`Point a webhook at /webhooks/capture/ and it will show up here.`}):X(gr,{title:`Capture is not configured`,detail:`This deployment has no capture storage wired up.`})})]})}var yr=[`string`,`number`,`bool`,`object`,`array`,`any`];function br(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function xr(e,t){return e?`${e}.${t}`:t}function Sr(e,t){return`${e}[${t}]`}function Cr({value:e,path:t=``,name:n=``,onPick:r}){return typeof e==`object`&&e?X(`ul`,{className:`mapping-tree-list`,children:(Array.isArray(e)?e.map((e,n)=>[String(n),e,Sr(t,n)]):Object.entries(e).map(([e,n])=>[e,n,xr(t,e)])).map(([e,t,n])=>X(`li`,{className:`mapping-tree-item`,children:[X(`span`,{className:`mapping-tree-key`,onClick:i=>{i.stopPropagation(),r&&r({path:n,type:br(t),name:e})},children:e}),X(Cr,{value:t,path:n,name:e,onPick:r})]},n))}):X(`span`,{className:`mapping-tree-value`,onClick:i=>{i.stopPropagation(),r&&r({path:t,type:br(e),name:n})},children:JSON.stringify(e)})}function wr({fields:e,preview:t,onRemove:n,onNameChange:r,onTypeChange:i,onRequiredChange:a}){if(!e.length)return X(`div`,{className:`mapping-empty-fields`,children:`Click a value in the payload to bind a field.`});let o=new Map((t?.failures||[]).map(e=>[e.field_name,e]));return X(`table`,{className:`table mapping-fields-table`,children:[X(`thead`,{children:X(`tr`,{children:[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:e.map((e,s)=>X(`tr`,{children:[X(`td`,{children:X(`input`,{className:`mapping-input`,value:e.name,onInput:e=>r?.(s,e.target.value)})}),X(`td`,{className:`mono`,children:e.path}),X(`td`,{children:X(`select`,{className:`mapping-select`,value:e.type,onChange:e=>i?.(s,e.target.value),children:yr.map(e=>X(`option`,{value:e,children:e},e))})}),X(`td`,{children:X(`input`,{type:`checkbox`,checked:e.required,onChange:e=>a?.(s,e.target.checked)})}),X(`td`,{children:X(Tr,{field:e,preview:t,failureByField:o})}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(s),children:`Remove`})})]},s))})]})}function Tr({field:e,preview:t,failureByField:n}){if(!t)return X(Q,{text:`not previewed`,kind:`idle`});let r=n.get(e.name);return r?X(Q,{text:r.reason,kind:`danger`}):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?X(Q,{text:JSON.stringify(t.values[e.name]),kind:`ok`}):X(Q,{text:`skipped (optional)`,kind:`idle`})}function Er({mapping:e,onEdit:t,onDelete:n}){return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.source_hint||`—`}),X(`td`,{children:String(e.fields?.length??0)}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(e),children:`Delete`})]})]})}function Dr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Or(e){return X(kr,{query:e})}function kr({query:e}){let[t,n]=W([]),[r,i]=W([]),[a,o]=W(null),[s,c]=W(null),l=async()=>{try{let[e,t]=await Promise.all([Y.mappings(),Y.captures(100)]);n(e.mappings||[]),i(t.captures||[]),o(null)}catch(e){o(String(e.message||e))}};G(()=>{l()},[]);let u=()=>{c({id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},d=e=>{c({id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},f=async e=>{if(window.confirm(`Delete mapping "${e.name}"?`))try{await Y.mappingDelete(e.id),await l()}catch(e){o(String(e.message||e))}},p=e=>{let t=r.find(t=>String(t.id)===String(e));c(e=>{let n={...e,captureId:t?t.id:null,preview:null};if(!t)n.payload=null,n.payloadError=null;else try{n.payload=JSON.parse(t.body),n.payloadError=null}catch{n.payload=null,n.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}return n})},m=({path:e,type:t,name:n})=>{c(r=>{let i=new Set(r.fields.map(e=>e.name)),a=n||`field`,o=1;for(;i.has(a);)a=`${n||`field`}_${++o}`;let s=[...r.fields,{name:a,path:e,type:t,required:!0}];return{...r,fields:s,preview:null}})},h=e=>{c(t=>{let n=t.fields.slice();return n.splice(e,1),{...t,fields:n,preview:null}})},g=(e,t)=>{c(n=>{let r=n.fields.slice();return r[e]={...r[e],...t},{...n,fields:r,preview:null}})};return s?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:s.id?`Edit mapping`:`New mapping`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>{c(null)},children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:async()=>{let e={name:s.name,source_hint:s.sourceHint,fields:s.fields};try{s.id?await Y.mappingUpdate(s.id,e):await Y.mappingCreate(e),c(null),await l()}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Save`})]})]}),s.actionError&&X(`div`,{className:`mapping-error`,children:s.actionError}),X(`div`,{className:`card mapping-form`,children:[X(`label`,{className:`mapping-form-row`,children:[`Name`,X(`input`,{className:`mapping-input`,value:s.name,onInput:e=>c(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Source hint (organisational only)`,X(`input`,{className:`mapping-input`,value:s.sourceHint,onInput:e=>c(t=>({...t,sourceHint:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Preview against captured event`,X(`select`,{className:`mapping-select`,value:s.captureId||``,onChange:e=>p(e.target.value),children:[X(`option`,{value:``,children:`— pick a captured event —`}),r.map(e=>X(`option`,{value:e.id,children:[e.source||`(unknown)`,` — `,e.received_at||``]},e.id))]})]})]}),X(`div`,{className:`card mapping-fields`,children:[X(`div`,{className:`mapping-section-title`,children:`Bound fields`}),X(wr,{fields:s.fields,preview:s.preview,onRemove:h,onNameChange:(e,t)=>g(e,{name:t}),onTypeChange:(e,t)=>g(e,{type:t}),onRequiredChange:(e,t)=>g(e,{required:t})}),X(`button`,{className:`btn`,type:`button`,onClick:async()=>{if(!s.captureId){c(e=>({...e,actionError:`Pick a captured event to preview against.`}));return}try{let e=await Y.mappingPreview(s.captureId,s.fields);c(t=>({...t,preview:e,actionError:null}))}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Preview`})]}),X(`div`,{className:`card mapping-payload`,children:[X(`div`,{className:`mapping-section-title`,children:`Payload — click a value to bind it`}),s.payloadError?X(`div`,{className:`mapping-error`,children:s.payloadError}):s.payload===null?X(`div`,{className:`mapping-empty-fields`,children:`Pick a captured event above to see its payload.`}):X(Cr,{value:s.payload,onPick:m})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Field mappings`}),X(`p`,{className:`page-sub`,children:`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:u,children:`New mapping`})})]}),a?X(Dr,{title:`Cannot reach archied`,detail:a}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source hint`,`Fields`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(Er,{mapping:e,onEdit:()=>d(e),onDelete:()=>f(e)},e.id))})]})})}):X(Dr,{title:`No mappings yet`,detail:`Create one from a captured event to reuse fields in a future playbook binding.`})]})}var Ar={draft:`draft`,pending_approval:`pending approval`,armed:`armed`},jr={draft:`idle`,pending_approval:`warn`,armed:`ok`};function Mr({status:e}){return X(Q,{text:Ar[e]||e,kind:jr[e]||`idle`})}function Nr({binding:e,onEdit:t,onApprove:n,onDelete:r}){let i=e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`;return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.matcher?.source||`—`}),X(`td`,{children:e.workflow}),X(`td`,{className:`mono`,children:i}),X(`td`,{children:X(Mr,{status:e.status})}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),e.status===`pending_approval`&&X(`button`,{className:`btn btn-small btn-primary`,type:`button`,onClick:()=>n?.(e),children:`Approve`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>r?.(e),children:`Delete`})]})]})}function Pr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Fr(e){return X(Lr,{query:e})}function Ir(){return{id:null,name:``,source:``,mappingId:``,workflow:``,owner:``,repo:``,secret:``,actionError:null}}function Lr({query:e}){let[t,n]=W([]),[r,i]=W([]),[a,o]=W([]),[s,c]=W(null),[l,u]=W(null),d=async()=>{try{let[e,t,r]=await Promise.all([Y.bindings(),Y.mappings(),Y.workflows()]);n(e.bindings||[]),i(t.mappings||[]),o((r.definitions||[]).filter(e=>e.enabled)),c(null)}catch(e){c(String(e.message||e))}};G(()=>{d()},[]);let f=()=>{u(Ir())},p=e=>{u({id:e.id,name:e.name,source:e.matcher?.source||``,mappingId:e.mapping_id?String(e.mapping_id):``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,secret:``,actionError:null})},m=()=>u(null),h=async()=>{let e={name:l.name,matcher:{source:l.source},mapping_id:Number(l.mappingId)||0,workflow:l.workflow,owner:l.owner,repo:l.repo,secret:l.secret};try{l.id?await Y.bindingUpdate(l.id,e):await Y.bindingCreate(e),u(null),await d()}catch(e){u(t=>({...t,actionError:String(e.message||e)}))}},g=async e=>{try{await Y.bindingApprove(e.id),await d()}catch(e){c(String(e.message||e))}},_=async e=>{if(window.confirm(`Delete binding "${e.name}"?`))try{await Y.bindingDelete(e.id),await d()}catch(e){c(String(e.message||e))}};return l?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:l.id?`Edit binding`:`New binding`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:m,children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:h,children:`Save`})]})]}),l.actionError&&X(`div`,{className:`binding-error`,children:l.actionError}),X(`div`,{className:`card binding-form`,children:[X(`label`,{className:`binding-form-row`,children:[`Name`,X(`input`,{className:`binding-input`,value:l.name,onInput:e=>u(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Source (the path segment senders POST to, e.g. "sentry")`,X(`input`,{className:`binding-input`,value:l.source,onInput:e=>u(t=>({...t,source:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Field mapping`,X(`select`,{className:`binding-select`,value:l.mappingId,onChange:e=>u(t=>({...t,mappingId:e.target.value})),children:[X(`option`,{value:``,children:`— pick a saved mapping —`}),r.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Workflow`,X(`select`,{className:`binding-select`,value:l.workflow,onChange:e=>u(t=>({...t,workflow:e.target.value})),children:[X(`option`,{value:``,children:`— pick a workflow —`}),a.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- owner (optional; leave both blank for the single-configured-repo default)`,X(`input`,{className:`binding-input`,value:l.owner,onInput:e=>u(t=>({...t,owner:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- repo`,X(`input`,{className:`binding-input`,value:l.repo,onInput:e=>u(t=>({...t,repo:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Shared secret (`,l.id?`leave blank to keep the current secret`:`senders sign with this via HMAC-SHA256`,`)`,X(`input`,{className:`binding-input`,type:`password`,value:l.secret,onInput:e=>u(t=>({...t,secret:e.target.value}))})]})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Playbook bindings`}),X(`p`,{className:`page-sub`,children:`Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:f,children:`New binding`})})]}),s?X(Pr,{title:`Cannot reach archied`,detail:s}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source`,`Workflow`,`Repo pin`,`Status`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(Nr,{binding:e,onEdit:()=>p(e),onApprove:()=>g(e),onDelete:()=>_(e)},e.id))})]})})}):X(Pr,{title:`No bindings yet`,detail:`Create one from a saved field mapping to turn a captured webhook into a workflow.`})]})}function Rr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function zr(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}function Br({provider:e}){let t=e.tools||[];return X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:e.name||`provider`}),X(`p`,{className:`card-sub`,children:zr(e.role)})]}),e.available?X(Q,{text:`ready`,kind:`ok`}):X(Q,{text:`unavailable`,kind:`danger`})]}),!e.available&&X(`p`,{className:`mem-warning`,children:`Configured but not usable right now — a required binary or connection may be missing.`}),t.length?X(`ul`,{className:`mem-tools`,children:t.map((e,t)=>X(`li`,{className:`mem-tool`,children:[X(`div`,{className:`mem-tool-name mono`,children:e.name}),e.description&&X(`div`,{className:`mem-tool-desc`,children:e.description})]},t))}):X(`p`,{className:`mem-warning`,children:`This provider exposes no tools, so the agent cannot use it.`})]})}function Vr(){let[e,t]=W(null),[n,r]=W(!0),[i,a]=W(null),[o,s]=W(!0),c=async()=>{s(!0),a(null);try{let e=await Y.memory();r(!!e.enabled),t(e.providers||[])}catch(e){a(String(e.message||e))}finally{s(!1)}};return G(()=>{c()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Memory`}),X(`p`,{className:`page-sub`,children:`What Archie can recall between conversations, and the tools it uses to do it.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:c,children:`Refresh`})})]}),X(`div`,{children:o?X(`div`,{className:`card`,children:X(`div`,{className:`mem-loading`,children:`Loading…`})}):i?X(`div`,{className:`card`,children:X(Rr,{title:`Cannot read memory providers`,detail:i})}):!n||!e.length?X(`div`,{className:`card`,children:X(Rr,{title:`Memory is not configured`,detail:`Without a provider, Archie starts every conversation with no recollection of earlier ones.`})}):X(`div`,{className:`grid grid-2`,children:e.map((e,t)=>X(Br,{provider:e},t))})})]})}function Hr(e){return X(Vr,{query:e})}var Ur=/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;function Wr(e){let t=[],n=0,r=0;for(let i of String(e).matchAll(Ur)){i.index>n&&t.push(e.slice(n,i.index));let a=i[0];if(a.startsWith(`![`)){let e=a.match(/^!\[([^\]]*)\]\((.+)\)$/);e&&t.push(X(`img`,{className:`chat-media-img`,src:e[2],alt:e[1]||`Image`,loading:`lazy`},r++))}else if(a.startsWith(`~~`))t.push(X(`del`,{children:a.slice(2,-2)},r++));else if(a.startsWith(`**`)||a.startsWith(`__`))t.push(X(`strong`,{children:a.slice(2,-2)},r++));else if(a.startsWith("`"))t.push(X(`code`,{children:a.slice(1,-1)},r++));else if(a.startsWith(`[`)){let e=a.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);e&&t.push(X(`a`,{href:e[2],target:`_blank`,rel:`noreferrer`,children:e[1]},r++))}else t.push(X(`em`,{children:a.slice(1,-1)},r++));n=i.index+a.length}return n{i.length&&(n.push(X(`p`,{children:Wr(i.join(` `))},s++)),i=[])},l=()=>{if(!a)return;let e=a.items.map((e,t)=>X(`li`,{children:Wr(e)},t));n.push(a.tag===`ol`?X(`ol`,{children:e},s++):X(`ul`,{children:e},s++)),a=null};for(let e=0;eX(`th`,{children:Wr(e)},t))})}),X(`tbody`,{children:t.map((e,t)=>X(`tr`,{children:e.map((e,t)=>X(`td`,{children:Wr(e)},t))},t))})]},s++));continue}if(!t.trim()){c(),l();continue}let f=t.match(/^(#{1,3})\s+(.+)$/);if(f){c(),l();let e=`h${f[1].length}`;n.push(X(e,{children:Wr(f[2])},s++));continue}let p=t.match(/^\s*[-*]\s+(.+)$/),m=t.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){c();let e=m?`ol`:`ul`;(!a||a.tag!==e)&&(l(),a={tag:e,items:[]}),a.items.push((p||m)[1]);continue}if(t.startsWith(`>`)){c(),l(),n.push(X(`blockquote`,{children:Wr(t.replace(/^>\s?/,``))},s++));continue}i.push(t)}return c(),l(),o&&n.push(X(`pre`,{children:X(`code`,{children:o.join(` +`)})},s++)),X(`div`,{className:t,children:n})}function Kr(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function qr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var Jr=`archie.web.chat.channel`;function Yr(){let e=localStorage.getItem(Jr);return e||(e=we(),localStorage.setItem(Jr,e)),e}function Xr(e){return{text:e,sourceID:we()}}function Zr(e){return{...e}}function Qr(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Zr(e.turn):Xr(r),isRetry:n}}function $r(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function ei(e){return e?.status===501?null:`Could not check for updates.`}function ti(){return location.hash.slice(1)||`/`}function ni(){let[e,t]=W([]),[n,r]=W(``),[i,a]=W([]),[o,s]=W(``),[c,l]=W(`Ready`),[u,d]=W(!1),[f,p]=W({}),[m,h]=W(``),[g,_]=W(``),[v,y]=W(``),[b,x]=W([]),[C,w]=W([]),[T,E]=W(0),[D,O]=W(!1),[k,A]=W(null),[j,M]=W(null),[N,P]=W(null),[F,I]=W(``),[L,ee]=W(``),[R,z]=W(null),te=K(null),B=K(null),V=K(null),ne=K(null),re=K(null),H=K(u);H.current=u,G(()=>{te.current&&(te.current.scrollTop=te.current.scrollHeight)},[i,R]),G(()=>{le().catch(e=>{l(e.message||`Chat unavailable`)}),ie();let e=()=>{V.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),V.current?.abort()}},[]);async function ie(){try{let e=await Y.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=ei(e);A(t?{error:t}:null)}}async function ae(){if(j)try{await Y.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function oe(){if(j)try{l(`Installing…`);let e=await Y.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function se(){try{let e=await Y.chatDangerous();P(e)}catch(e){P({error:e.message||`Dangerous actions unavailable`})}}async function U(e,t){if(t)try{await Y.chatDangerousRequest(e,t),l(`Approval requested`),await se()}catch(e){l(e.message||`Could not request action`)}}async function ce(e,t){try{await Y.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await se()}catch(e){l(e.message||`Approval failed`)}}async function le(){let e=await Y.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await se(),!n&&r[0]&&await ue(r[0].session_id,e,r)}async function ue(e,t,n){let i=t||f;r(e),a([]),z(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await Y.chatMessage(Yr(),`/resume ${e}`);let[t,n]=await Promise.all([Y.chatMessages(e),Y.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function de(e){if(n)try{l(`Working…`);let t=await Y.chatMessage(Yr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await le(),(t.session_id||n)&&await ue(t.session_id||n),ne.current&&(ne.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function fe(e,t){let n=window.prompt(t);n?.trim()&&de(`${e} ${n.trim()}`)}function pe(e){let t=e.target.value;h(t),!(!n||!t)&&Y.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function me(e){let t=e.target.value;if(_(t),t)try{let e=await Y.chatMessage(Yr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await le()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function he(e){let t=e.target.value;if(y(t),t)try{let e=await Y.chatMessage(Yr(),`/model ${t}`);l(e.reply||`Model updated`),await le()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ge(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),q({textOverride:`/restart`}))}function _e(){s(`/new`),q({textOverride:`/new`})}function ve(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function ye(e){let t=C[e];if(!t||!B.current)return;let n=B.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t.command.length+1;setTimeout(()=>{n.focus(),n.setSelectionRange(l,l)},0)}function be(e){if(D&&C.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&C.some(e=>e.command===o.trim())){e.preventDefault(),O(!1),q();return}if(e.key===`ArrowDown`){e.preventDefault(),E(e=>(e+1)%C.length);return}if(e.key===`ArrowUp`){e.preventDefault(),E(e=>(e+C.length-1)%C.length);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),ye(T);return}if(e.key===`Escape`){e.preventDefault(),O(!1);return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),q())}async function q(e=null){let t=e?.textOverride,{text:n,turn:i,isRetry:c}=Qr(e,t===void 0?o:t);if(!n||H.current)return;O(!1),d(!0),l(c?`Retrying…`:`Thinking…`),c||(a(e=>[...e,{from:`web`,text:n}]),s(``));let u=[];z({text:``,tools:[],isError:!1,turn:i,isRetry:c});let f=``,p=!1,m=!1,h=null;try{let e=new AbortController;V.current=e,h=setTimeout(()=>{m=!0,e.abort()},12e4);let t=(await Y.chatStream({channel_id:Yr(),source_id:i.sourceID,text:i.text,page:ti()},{signal:e.signal})).body.getReader(),n=new TextDecoder,o=``;for(;;){let{value:e,done:i}=await t.read();o+=n.decode(e||new Uint8Array,{stream:!i});let a=o.split(` `);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,R(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],R(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],R(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}]),R(null),l(`Ready`),await ue()}catch(e){if(e.name===`AbortError`&&!m)R({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;R({text:t,tools:u,isError:!0,turn:li(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),B.current=null,d(!1),z.current&&z.current.focus()}}function Ce(){l(`Stopping…`),n&&U.chatCancel(n).catch(()=>{}),B.current?.abort()}let W=f.models_by_provider||{},we=g&&W[g]?W[g]:f.models||[];return Z(`div`,{className:`chat-page-content`,children:[Z(`header`,{className:`chat-topbar`,children:[Z(`div`,{children:[Z(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),Z(`h1`,{className:`page-title`,children:`Chat`})]}),Z(`div`,{className:`chat-topbar-actions`,children:[Z(`span`,{className:`chat-status`,children:c}),f.restart_available&&Z(`button`,{className:`btn`,type:`button`,onClick:_e,children:`Reload Telegram`}),Z(`button`,{className:`btn`,type:`button`,onClick:V,children:`Check updates`}),Z(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:me,children:[Z(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>Z(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&Z(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:he,children:[Z(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>Z(`option`,{value:e,children:e},e))]}),Z(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:ge,children:[Z(`option`,{value:``,children:`Model`}),we.map(e=>Z(`option`,{value:e,children:e},e))]})]})]}),k&&Z(`div`,{className:`chat-update-panel`,children:k.error?Z(`span`,{children:k.error}):k.available?.length?Z(S,{children:[Z(`div`,{children:[Z(`strong`,{children:`Update available`}),Z(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),Z(`div`,{className:`chat-update-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:oe,children:`Defer`}),k.can_install&&Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:se,children:`Install update`})]})]}):Z(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&N&&Z(`div`,{className:`chat-dangerous-panel`,children:[Z(`div`,{className:`chat-dangerous-head`,children:[Z(`strong`,{children:`Dangerous actions`}),Z(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),Z(`div`,{className:`chat-dangerous-controls`,children:[Z(`div`,{children:[Z(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:F,onChange:e=>I(e.target.value),children:[Z(`option`,{value:``,children:`Select checkpoint`}),(N.checkpoints||[]).map(e=>Z(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>le(`rollback`,F),children:`Request rollback`})]}),Z(`div`,{children:[Z(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ee,onInput:e=>te(e.target.value)}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>le(`stop`,ee),children:`Request stop`})]})]}),Z(`div`,{className:`chat-dangerous-pending-list`,children:(N.pending||[]).length?N.pending.map(e=>Z(`div`,{className:`chat-dangerous-pending`,children:[Z(`span`,{children:e.description}),Z(`div`,{className:`chat-update-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:()=>H(e.id,`approve`),children:`Approve`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>H(e.id,`permanent`),children:`Approve for 24h`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>H(e.id,`deny`),children:`Deny`})]})]},e.id)):Z(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),Z(`div`,{className:`chat-layout`,children:[Z(`aside`,{className:`chat-sidebar`,children:[Z(`div`,{className:`chat-sidebar-head`,children:[Z(`strong`,{children:`Conversations`}),Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:ve,children:`+ New chat`})]}),Z(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>Z(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>de(e.session_id),children:[Z(`strong`,{children:di(e)}),Z(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):Z(`div`,{className:`chat-empty`,children:`Your conversations will appear here.`})})]}),Z(`section`,{className:`chat-workspace`,children:[Z(`div`,{className:`chat-workspace-head`,children:[Z(`span`,{className:`chat-workspace-label`,children:`PERSONAL ASSISTANT`}),Z(`details`,{className:`chat-command-help`,children:[Z(`summary`,{children:[`Available commands (`,b.length,`)`]}),Z(`div`,{className:`chat-command-list`,children:b.length?b.map(e=>Z(`div`,{className:`chat-command-item`,children:[Z(`code`,{children:e.usage||e.command}),Z(`span`,{children:e.description||``})]},e.command)):Z(`span`,{children:`Send a message to begin.`})})]}),Z(`details`,{className:`chat-session-tools`,ref:re,hidden:!n,children:[Z(`summary`,{children:`Session actions`}),Z(`div`,{className:`chat-session-tool-list`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/retry`),children:`Retry`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/undo`),children:`Undo`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`/title`,`Session title`),children:`Rename`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`/branch`,`Branch name (optional)`),children:`Branch`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/compress --preview`),children:`Preview compression`})]})]})]}),Z(`div`,{className:`chat-transcript`,ref:ne,children:!i.length&&!L?Z(`div`,{className:`chat-empty-state`,children:[Z(`span`,{className:`chat-empty-mark`,children:`A`}),Z(`h2`,{children:`What are we working on?`}),Z(`p`,{children:`Ask Archie anything, or start with one of these prompts.`}),Z(`div`,{className:`chat-prompt-grid`,children:[Z(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Summarise active tasks`),z.current?.focus()},children:`Summarise active tasks`}),Z(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Show running agents`),z.current?.focus()},children:`Show running agents`}),Z(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Check system status`),z.current?.focus()},children:`Check system status`})]})]}):Z(S,{children:[i.map((e,t)=>{let n=e.from??e.From??``,r=e.text??e.Text??``,i=n!==`web`,a=e.tool_calls||e.ToolCalls||[];return Z(`div`,{className:`chat-bubble-row ${i?`assistant`:`user`}`,children:Z(`div`,{className:`chat-bubble`,children:[Z(`div`,{className:`chat-bubble-meta`,children:i?`Archie`:`You`}),i?Z(S,{children:[a.length>0&&Z(`div`,{className:`chat-tools`,children:a.map((e,t)=>{if(e.path)return Z(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[Z(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),Z(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.Name||e.tool||`tool`,r=e.parameters||e.Parameters||``,i=e.summary||e.Summary||e.text||e.err||e.Err||`done`;return Z(`div`,{className:`chat-tool ${e.err||e.Err||e.failed?`failed`:``}`,children:[Z(`span`,{className:`chat-tool-icon`,children:`🔧`}),Z(`span`,{className:`chat-tool-name`,children:n}),r&&Z(`code`,{className:`chat-tool-parameters`,children:r}),Z(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),Z(mi,{text:r})]}):Z(`div`,{className:`chat-bubble-text`,children:r})]})},t)}),L&&Z(`div`,{className:`chat-bubble-row assistant`,children:Z(`div`,{className:`chat-bubble`,children:[Z(`div`,{className:`chat-bubble-meta`,children:`Archie`}),L.tools?.length>0&&Z(`div`,{className:`chat-tools`,children:L.tools.map((e,t)=>{if(e.path)return Z(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[Z(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),Z(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.tool||`tool`,r=e.parameters||``,i=e.summary||e.text||(e.failed?`failed`:`running…`);return Z(`div`,{className:`chat-tool ${e.failed?`failed`:``}`,children:[Z(`span`,{className:`chat-tool-icon`,children:`🔧`}),Z(`span`,{className:`chat-tool-name`,children:n}),r&&Z(`code`,{className:`chat-tool-parameters`,children:r}),Z(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),Z(mi,{text:L.text||`…`}),L.isError&&Z(`button`,{className:`btn chat-retry`,type:`button`,onClick:()=>Se({turn:L.turn}),children:`Retry`})]})})]})}),Z(`div`,{className:`chat-compose`,children:Z(`div`,{className:`chat-composer-shell`,children:[Z(`textarea`,{ref:z,className:`chat-composer`,rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`,disabled:u,value:o,onInput:ye,onKeyDown:xe}),D&&C.length>0&&Z(`div`,{className:`chat-command-menu`,ref:ie,role:`listbox`,"aria-label":`Commands`,children:C.map((e,t)=>Z(`button`,{type:`button`,role:`option`,"aria-selected":String(t===T),className:`chat-command-option`,onMouseDown:e=>e.preventDefault(),onClick:()=>be(t),children:[Z(`code`,{children:e.command}),Z(`span`,{children:e.description||e.usage||``})]},e.command))}),Z(`div`,{className:`chat-compose-actions`,children:[Z(`span`,{className:`chat-hint`,children:`Enter to send · Shift+Enter for a new line`}),Z(`button`,{className:`btn`,type:`button`,disabled:!u,onClick:Ce,children:`Stop`}),Z(`button`,{className:`btn btn-primary`,type:`button`,disabled:u||!o.trim(),onClick:()=>Se(),children:`Send`})]})]})})]})]})]})}function gi(){let e=document.createElement(`div`);return e.className=`chat-page`,re(Z(hi,{}),e),e}function _i(e,t){let n=yi(t);for(let t of e){let e=bi(t.path,n);if(e)return{route:t,params:e}}return null}function vi(e){return e?.navPath||e?.path||`/`}function yi(e){let t=String(e??`/`).split(`?`,1)[0].split(`#`,1)[0];return t?t.length>1&&t.endsWith(`/`)?t.slice(0,-1):t:`/`}function bi(e,t){let n=String(e).split(`/`),r=String(t).split(`/`);if(n.length!==r.length)return null;let i={};for(let e=0;e[...xi.filter(e=>e.nav!==!1).map(t=>{let r=W(`a.nav-item`,{href:`#${t.path}`,onclick:n=>{t.soon?n.preventDefault():e(t.path)},"aria-disabled":t.soon||void 0,title:t.soon?`Coming soon`:void 0},G(t.icon),W(`span.nav-label`,t.label),t.soon&&W(`span.nav-soon`,`soon`));return n.set(t.path,r),r})])),i=W(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Ci(wi()===`dark`?`light`:`dark`),Te(i,G(wi()===`dark`?`moon`:`sun`))}});Te(i,G(wi()===`dark`?`moon`:`sun`));let a,o=()=>{a?.classList.remove(`is-open`),s.setAttribute(`aria-expanded`,`false`)},s=W(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{a.classList.add(`is-open`),s.setAttribute(`aria-expanded`,`true`),c.focus()}},G(`search`,{size:15})),c=W(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:t=>{if(t.key===`Escape`){t.preventDefault(),o(),t.target.blur();return}if(t.key!==`Enter`)return;let n=t.target.value.trim().toLowerCase(),r=xi.find(e=>e.nav!==!1&&!e.soon&&e.label.toLowerCase().startsWith(n));r&&(e(r.path),t.target.value=``,t.target.blur(),o())}});return a=W(`div.topbar-search`,W(`span.topbar-search-icon`,{"aria-hidden":`true`},G(`search`,{size:15})),s,c),{node:W(`header.topbar`,W(`div.brand`,W(`span.brand-mark`,`A`),`Archie`),r,W(`div.topbar-end`,a,W(`button.icon-btn.icon-btn-chat`,{"aria-label":`Open chat`,title:`Chat with Archie`,"aria-expanded":`false`,onclick:()=>t?.()},G(`chat`)),W(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},G(`help`)),i,W(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,r]of n)t===e?r.setAttribute(`aria-current`,`page`):r.removeAttribute(`aria-current`)},hide(e){for(let t of e)n.get(t)?.remove()}}}function Ei(){Ci(wi());let e=W(`main.main`),t=W(`aside.chat-drawer`,{"aria-label":`Chat with Archie`}),n=W(`button.icon-btn.chat-drawer-close`,{"aria-label":`Close chat`,title:`Close chat`,onclick:()=>o(!1)},G(`close`)),r=W(`div.chat-drawer-head`,W(`strong`,`Archie`),n);t.append(W(`div.chat-drawer-panel`,r,gi()),W(`div.chat-scrim`,{onclick:()=>o(!1)}));let i=Ti(s,()=>o());U.capabilities().then(e=>i.hide(fe(e?.sections,xi))).catch(()=>{});let a=W(`div.shell`,i.node,e,t);Te(document.getElementById(`app`),a);function o(e){let n=e===void 0?!t.classList.contains(`is-open`):e;t.classList.toggle(`is-open`,n),document.body.classList.toggle(`chat-open`,n);let r=a.querySelector(`.icon-btn-chat`);r&&r.setAttribute(`aria-expanded`,String(n))}window.__archieToggleChat=o;function s(e){location.hash===`#`+e?c(e):location.hash=e}function c(t){e.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[n,r=``]=t.split(`?`,2),a=_i(xi,n),s=a?.route||xi[0];if(i.highlight(vi(s)),s.path===`/chat`){Te(e),o(!0);return}let c=s.view?s.view(new URLSearchParams(r),a?.params||{}):Di(s);c instanceof Node?Te(e,c):re(c,e),o(!1)}window.addEventListener(`hashchange`,()=>c(location.hash.slice(1)||`/`)),window.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Escape`&&t.classList.contains(`is-open`)&&o(!1)}),c(location.hash.slice(1)||`/`)}function Di(e){return W(`div`,W(`div.page-head`,W(`div`,W(`h1.page-title`,e.label))),W(`div.card`,W(`div.empty`,W(`div.empty-title`,`${e.label} is not built yet`),W(`div`,`This section is next up. Nothing is broken.`))))}Ei(); \ No newline at end of file +`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&r(n.session_id),n.type===`delta`&&(f+=n.text,z(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),z(null),l(`Ready`),await le()}catch(e){if(e.name===`AbortError`&&!m)z({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;z({text:t,tools:u,isError:!0,turn:Zr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),V.current=null,d(!1),B.current&&B.current.focus()}}function xe(){l(`Stopping…`),n&&Y.chatCancel(n).catch(()=>{}),V.current?.abort()}let Se=f.models_by_provider||{},Ce=g&&Se[g]?Se[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:ge,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ie,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:pe,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:me,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:he,children:[X(`option`,{value:``,children:`Model`}),Ce.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:ae,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:oe,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&N&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:F,onChange:e=>I(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(N.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`rollback`,F),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:L,onInput:e=>ee(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`stop`,L),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(N.pending||[]).length?N.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:_e,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>ue(e.session_id),children:[X(`strong`,{children:$r(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will appear here.`})})]}),X(`section`,{className:`chat-workspace`,children:[X(`div`,{className:`chat-workspace-head`,children:[X(`span`,{className:`chat-workspace-label`,children:`PERSONAL ASSISTANT`}),X(`details`,{className:`chat-command-help`,children:[X(`summary`,{children:[`Available commands (`,b.length,`)`]}),X(`div`,{className:`chat-command-list`,children:b.length?b.map(e=>X(`div`,{className:`chat-command-item`,children:[X(`code`,{children:e.usage||e.command}),X(`span`,{children:e.description||``})]},e.command)):X(`span`,{children:`Send a message to begin.`})})]}),X(`details`,{className:`chat-session-tools`,ref:ne,hidden:!n,children:[X(`summary`,{children:`Session actions`}),X(`div`,{className:`chat-session-tool-list`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>de(`/retry`),children:`Retry`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>de(`/undo`),children:`Undo`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/title`,`Session title`),children:`Rename`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/branch`,`Branch name (optional)`),children:`Branch`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>de(`/compress --preview`),children:`Preview compression`})]})]})]}),X(`div`,{className:`chat-transcript`,ref:te,children:!i.length&&!R?X(`div`,{className:`chat-empty-state`,children:[X(`span`,{className:`chat-empty-mark`,children:`A`}),X(`h2`,{children:`What are we working on?`}),X(`p`,{children:`Ask Archie anything, or start with one of these prompts.`}),X(`div`,{className:`chat-prompt-grid`,children:[X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Summarise active tasks`),B.current?.focus()},children:`Summarise active tasks`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Show running agents`),B.current?.focus()},children:`Show running agents`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Check system status`),B.current?.focus()},children:`Check system status`})]})]}):X(S,{children:[i.map((e,t)=>{let n=e.from??e.From??``,r=e.text??e.Text??``,i=n!==`web`,a=e.tool_calls||e.ToolCalls||[];return X(`div`,{className:`chat-bubble-row ${i?`assistant`:`user`}`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:i?`Archie`:`You`}),i?X(S,{children:[a.length>0&&X(`div`,{className:`chat-tools`,children:a.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.Name||e.tool||`tool`,r=e.parameters||e.Parameters||``,i=e.summary||e.Summary||e.text||e.err||e.Err||`done`;return X(`div`,{className:`chat-tool ${e.err||e.Err||e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(Gr,{text:r})]}):X(`div`,{className:`chat-bubble-text`,children:r})]})},t)}),R&&X(`div`,{className:`chat-bubble-row assistant`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:`Archie`}),R.tools?.length>0&&X(`div`,{className:`chat-tools`,children:R.tools.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.tool||`tool`,r=e.parameters||``,i=e.summary||e.text||(e.failed?`failed`:`running…`);return X(`div`,{className:`chat-tool ${e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(Gr,{text:R.text||`…`}),R.isError&&X(`button`,{className:`btn chat-retry`,type:`button`,onClick:()=>q({turn:R.turn}),children:`Retry`})]})})]})}),X(`div`,{className:`chat-compose`,children:X(`div`,{className:`chat-composer-shell`,children:[X(`textarea`,{ref:B,className:`chat-composer`,rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`,disabled:u,value:o,onInput:ve,onKeyDown:be}),D&&C.length>0&&X(`div`,{className:`chat-command-menu`,ref:re,role:`listbox`,"aria-label":`Commands`,children:C.map((e,t)=>X(`button`,{type:`button`,role:`option`,"aria-selected":String(t===T),className:`chat-command-option`,onMouseDown:e=>e.preventDefault(),onClick:()=>ye(t),children:[X(`code`,{children:e.command}),X(`span`,{children:e.description||e.usage||``})]},e.command))}),X(`div`,{className:`chat-compose-actions`,children:[X(`span`,{className:`chat-hint`,children:`Enter to send · Shift+Enter for a new line`}),X(`button`,{className:`btn`,type:`button`,disabled:!u,onClick:xe,children:`Stop`}),X(`button`,{className:`btn btn-primary`,type:`button`,disabled:u||!o.trim(),onClick:()=>q(),children:`Send`})]})]})})]})]})]})}function ri(){return X(ni,{})}function ii(e,t){let n=oi(t);for(let t of e){let e=si(t.path,n);if(e)return{route:t,params:e}}return null}function ai(e){return e?.navPath||e?.path||`/`}function oi(e){let t=String(e??`/`).split(`?`,1)[0].split(`#`,1)[0];return t?t.length>1&&t.endsWith(`/`)?t.slice(0,-1):t:`/`}function si(e,t){let n=String(e).split(`/`),r=String(t).split(`/`);if(n.length!==r.length)return null;let i={};for(let e=0;et.nav!==!1&&!e.includes(t.path))}function pi({activePath:e,hidden:t,onNavigate:n,chatOpen:r,onToggleChat:i,theme:a,onToggleTheme:o}){let[s,c]=W(!1),l=()=>c(!1);return X(`header`,{className:`topbar`,children:[X(`div`,{className:`brand`,children:[X(`span`,{className:`brand-mark`,children:`A`}),`Archie`]}),X(`nav`,{className:`nav`,children:fi(t).map(t=>X(`a`,{className:`nav-item`,href:`#${t.path}`,"aria-current":t.path===e?`page`:void 0,"aria-disabled":t.soon||void 0,title:t.soon?`Coming soon`:void 0,onClick:e=>{t.soon?e.preventDefault():n(t.path)},children:[X(Z,{name:t.icon}),X(`span`,{className:`nav-label`,children:t.label}),t.soon?X(`span`,{className:`nav-soon`,children:`soon`}):null]},t.path))}),X(`div`,{className:`topbar-end`,children:[X(`div`,{className:`topbar-search${s?` is-open`:``}`,children:[X(`span`,{className:`topbar-search-icon`,"aria-hidden":`true`,children:X(Z,{name:`search`,size:15})}),X(`button`,{className:`icon-btn mobile-search-toggle`,type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":s?`true`:`false`,onClick:()=>c(!0),children:X(Z,{name:`search`,size:15})}),X(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onKeyDown:e=>{if(e.key===`Escape`){e.preventDefault(),l(),e.target.blur();return}if(e.key!==`Enter`)return;let t=e.target.value.trim().toLowerCase(),r=ci.find(e=>e.nav!==!1&&!e.soon&&e.label.toLowerCase().startsWith(t));r&&(n(r.path),e.target.value=``,l())}})]}),X(`button`,{className:`icon-btn icon-btn-chat`,"aria-label":`Open chat`,title:`Chat with Archie`,"aria-expanded":r?`true`:`false`,onClick:()=>i(),children:X(Z,{name:`chat`})}),X(`button`,{className:`icon-btn`,title:`Documentation`,"aria-label":`Documentation`,children:X(Z,{name:`help`})}),X(`button`,{className:`icon-btn`,title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onClick:o,children:X(Z,{name:a===`dark`?`moon`:`sun`})}),X(`div`,{className:`avatar`,title:`Signed in locally`,children:`A`})]})]})}function mi({open:e,onClose:t}){return X(`aside`,{className:`chat-drawer${e?` is-open`:``}`,"aria-label":`Chat with Archie`,children:[X(`div`,{className:`chat-drawer-panel`,children:[X(`div`,{className:`chat-drawer-head`,children:[X(`strong`,{children:`Archie`}),X(`button`,{className:`icon-btn chat-drawer-close`,"aria-label":`Close chat`,title:`Close chat`,onClick:t,children:X(Z,{name:`close`})})]}),X(ri,{})]}),X(`div`,{className:`chat-scrim`,onClick:t})]})}function hi({label:e}){return X(`div`,{children:[X(`div`,{className:`page-head`,children:X(`div`,{children:X(`h1`,{className:`page-title`,children:e})})}),X(`div`,{className:`card`,children:X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`${e} is not built yet`}),X(`div`,{children:`This section is next up. Nothing is broken.`})]})})]})}function gi({view:e,search:t,params:n}){return e(t,n)}var _i=null,vi=null;function yi(e){let[t,n=``]=String(e).split(`?`,2),r=ii(ci,t),i=r?.route||ci[0],a=r?.params||{};_i?.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`)),vi?.setActive(ai(i));let o=i.path===`/chat`;if(vi?.setChatOpen(o),_i){if(o){ne(null,_i);return}ne(i.view?X(gi,{view:i.view,search:new URLSearchParams(n),params:a},`${i.path}|${Object.values(a).join(`/`)}`):X(hi,{label:i.label}),_i)}}function bi(e){location.hash===`#${e}`?yi(e):location.hash=e}window.addEventListener(`hashchange`,()=>yi(location.hash.slice(1)||`/`)),window.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Escape`&&vi?.setChatOpen(!1)});function xi(){let[e,t]=W(`/`),[n,r]=W(ui),[i,a]=W(!1),[o,s]=W([]),c=_e(e=>{_i=e,vi={setActive:t,setChatOpen:a}},[]);return G(()=>{di(n)},[n]),G(()=>{document.body.classList.toggle(`chat-open`,i)},[i]),G(()=>{Y.capabilities().then(e=>s(Ne(e?.sections,ci))).catch(()=>{})},[]),X(`div`,{className:`shell`,children:[X(pi,{activePath:e,hidden:o,onNavigate:bi,chatOpen:i,onToggleChat:()=>a(e=>!e),theme:n,onToggleTheme:()=>r(e=>e===`dark`?`light`:`dark`)}),X(`main`,{className:`main`,ref:c}),X(mi,{open:i,onClose:()=>a(!1)})]})}di(ui()),ne(X(xi,{}),document.getElementById(`app`)),yi(location.hash.slice(1)||`/`); \ No newline at end of file diff --git a/ui/src/base/dom.jsx b/ui/src/base/dom.jsx deleted file mode 100644 index 2a2117335..000000000 --- a/ui/src/base/dom.jsx +++ /dev/null @@ -1,89 +0,0 @@ -// Tiny DOM helpers. Deliberately not a framework: the dashboard is a handful -// of pages over a read-mostly API, and a build-free vanilla layer keeps the -// embedded bundle small. - -/** - * el("div.card", {onclick}, child, child) -> HTMLElement - * The tag string accepts CSS-ish shorthand: "button.btn.btn-primary". - */ -export function el(spec, attrs, ...children) { - const [tag, ...classes] = spec.split("."); - const node = document.createElement(tag || "div"); - if (classes.length) node.className = classes.join(" "); - - // A falsy scalar first child (0, "", false) is a value, not a missing - // attrs object: unshift it so append() renders it instead of dropping it. - // undefined stays "no attrs" so `el("div", undefined, child)` still works. - if (attrs !== undefined && (typeof attrs !== "object" || attrs instanceof Node)) { - children.unshift(attrs); - attrs = null; - } - for (const [k, v] of Object.entries(attrs || {})) { - if (v == null || v === false) continue; - if (k.startsWith("on") && typeof v === "function") { - node.addEventListener(k.slice(2).toLowerCase(), v); - } else if (k === "class") { - node.className = [node.className, v].filter(Boolean).join(" "); - } else if (k === "html") { - node.innerHTML = v; - } else { - node.setAttribute(k, v === true ? "" : String(v)); - } - } - append(node, children); - return node; -} - -function append(node, children) { - for (const c of children.flat(Infinity)) { - if (c == null || c === false) continue; - node.append(c instanceof Node ? c : document.createTextNode(String(c))); - } -} - -export function mount(parent, ...children) { - parent.replaceChildren(); - append(parent, children); - return parent; -} - -/** Status pill. Kind maps to the semantic colour tokens. */ -export function pill(text, kind = "idle") { - return el(`span.pill.pill-${kind}`, text); -} - -// Re-exported from task-meta.js so the pill severity vocabulary has a single -// source (the server catalog). Importers that pull statusKind from dom.js -- -// e.g. dashboard.js -- keep working, and the hardcoded switch is gone. -export { statusKind } from "./task-meta.jsx"; - -/** Humanised relative time: "2 min ago". Raw timestamps make people do maths. */ -export function ago(value) { - if (!value) return "—"; - const then = value instanceof Date ? value : new Date(value); - const secs = Math.floor((Date.now() - then.getTime()) / 1000); - if (!Number.isFinite(secs)) return "—"; - if (secs < 45) return "just now"; - const units = [ - ["min", 60], - ["hr", 3600], - ["day", 86400], - ["wk", 604800], - ]; - let label = "min", size = 60; - for (const [l, s] of units) { - if (secs >= s) [label, size] = [l, s]; - } - const n = Math.floor(secs / size); - return `${n} ${label}${n === 1 ? "" : "s"} ago`; -} - -/** Compact number: 2_400_000 -> "2.4M". Long digit strings do not scan. */ -export function compact(n) { - if (n == null || Number.isNaN(n)) return "—"; - return new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n); -} - -export function empty(title, detail) { - return el("div.empty", el("div.empty-title", title), detail && el("div", detail)); -} diff --git a/ui/src/base/format.jsx b/ui/src/base/format.jsx new file mode 100644 index 000000000..08b02dbf1 --- /dev/null +++ b/ui/src/base/format.jsx @@ -0,0 +1,32 @@ +/** + * Display formatting shared across the dashboard pages. Pure functions: no + * DOM, no framework. + */ + +/** Humanised relative time: "2 min ago". Raw timestamps make people do maths. */ +export function ago(value) { + if (!value) return "—"; + const then = value instanceof Date ? value : new Date(value); + const secs = Math.floor((Date.now() - then.getTime()) / 1000); + if (!Number.isFinite(secs)) return "—"; + if (secs < 45) return "just now"; + const units = [ + ["min", 60], + ["hr", 3600], + ["day", 86400], + ["wk", 604800], + ]; + let label = "min", + size = 60; + for (const [l, s] of units) { + if (secs >= s) [label, size] = [l, s]; + } + const n = Math.floor(secs / size); + return `${n} ${label}${n === 1 ? "" : "s"} ago`; +} + +/** Compact number: 2_400_000 -> "2.4M". Long digit strings do not scan. */ +export function compact(n) { + if (n == null || Number.isNaN(n)) return "—"; + return new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n); +} diff --git a/ui/src/base/gauge.jsx b/ui/src/base/gauge.jsx index 3e24b9bcd..6a1837fe4 100644 --- a/ui/src/base/gauge.jsx +++ b/ui/src/base/gauge.jsx @@ -1,4 +1,4 @@ -import { el } from "./dom.jsx"; +import { h } from "preact"; /** * Arc gauge for a single headline percentage. @@ -8,7 +8,7 @@ import { el } from "./dom.jsx"; * number is not. Colour follows the value, so "is this bad" is answered before * the digits are read. */ -export function gauge({ value, label, size = 168 }) { +export function Gauge({ value, label, size = 168 }) { const pct = Math.max(0, Math.min(100, Number(value) || 0)); const stroke = pct >= 90 ? "var(--ok)" : pct >= 70 ? "var(--warn)" : "var(--danger)"; @@ -30,24 +30,26 @@ export function gauge({ value, label, size = 168 }) { ].join(" "); }; - const svg = el("svg.gauge", { - viewBox: `0 0 ${size} ${size * 0.78}`, - role: "img", - "aria-label": `${label}: ${pct}%`, - }); - svg.innerHTML = ` - - `; - - return el( - "div.gauge-wrap", - svg, - el("div.gauge-center", el("div.gauge-pct", `${Math.round(pct)}%`), el("div.gauge-label", label)), + return ( +
+ + + + +
+
{`${Math.round(pct)}%`}
+
{label}
+
+
); } @@ -59,31 +61,30 @@ export function gauge({ value, label, size = 168 }) { * because three related quantities are easier to compare in one bar than in * three separate numbers. */ -export function segmentBar(segments) { +export function SegmentBar({ segments }) { const total = segments.reduce((a, s) => a + (s.value || 0), 0) || 1; - return el( - "div", - el( - "div.segbar", - ...segments - .filter((s) => s.value > 0) - .map((s) => - el("span", { - class: `segbar-part segbar-${s.kind || "idle"}`, - style: `width:${((s.value / total) * 100).toFixed(1)}%`, - title: `${s.label}: ${s.value}`, - }), - ), - ), - el( - "div.segbar-legend", - ...segments.map((s) => - el( - "span.segbar-key", - el("span", { class: `segbar-dot segbar-${s.kind || "idle"}` }), - s.label, - ), - ), - ), + return ( +
+
+ {segments + .filter((s) => s.value > 0) + .map((s) => ( + + ))} +
+
+ {segments.map((s) => ( + + + {s.label} + + ))} +
+
); } diff --git a/ui/src/base/icons.jsx b/ui/src/base/icons.jsx index ce5f49d11..22ff1f7f6 100644 --- a/ui/src/base/icons.jsx +++ b/ui/src/base/icons.jsx @@ -1,3 +1,5 @@ +import { h } from "preact"; + /** * Icon set. * @@ -34,21 +36,28 @@ const paths = { }; /** - * icon("tasks") -> SVGElement. size is the rendered box; the grid is always 24 - * so stroke weight stays optically consistent at any size. + * Icon draws one glyph from the set. size is the rendered box; the grid is + * always 24 so stroke weight stays optically consistent at any size. + * + * The glyph bodies are the `paths` strings above, injected as raw SVG. They are + * in-repo constants and Preact cannot turn markup into elements, so re-authoring + * twenty multi-element glyphs as JSX would trade a data table for code without + * changing a single drawn pixel. */ -export function icon(name, { size = 18, className = "" } = {}) { - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - svg.setAttribute("viewBox", "0 0 24 24"); - svg.setAttribute("width", String(size)); - svg.setAttribute("height", String(size)); - svg.setAttribute("fill", "none"); - svg.setAttribute("stroke", "currentColor"); - svg.setAttribute("stroke-width", "1.6"); - svg.setAttribute("stroke-linecap", "round"); - svg.setAttribute("stroke-linejoin", "round"); - svg.setAttribute("aria-hidden", "true"); - svg.setAttribute("class", `ico ${className}`.trim()); - svg.innerHTML = paths[name] || paths.dashboard; - return svg; +export function Icon({ name, size = 18, className = "" }) { + return ( + + ); } diff --git a/ui/src/base/log-row.jsx b/ui/src/base/log-row.jsx index 68feb2df9..cf3ec5d46 100644 --- a/ui/src/base/log-row.jsx +++ b/ui/src/base/log-row.jsx @@ -1,9 +1,9 @@ -import { el } from "./dom.jsx"; +import { h } from "preact"; /** * Shared log-entry rendering. Both the daemon-wide log page - * (ui/src/logs/logs.js) and a task's own attempt log - * (ui/src/tasks/task-logs.js) render the same Entry shape from + * (ui/src/logs/logs.jsx) and a task's own attempt log + * (ui/src/tasks/task-logs.jsx) render the same Entry shape from * internal/logging, so the row markup lives here rather than being * duplicated a second time -- see CLAUDE.md's "extract to base on the * second distinct consumer". @@ -34,19 +34,22 @@ export function levelKind(level) { } } -export function logRow(entry) { +export function LogRow({ entry }) { const fields = entry.fields || {}; - return el( - `div.log-row.log-${levelKind(entry.level)}`, - el("span.log-time.mono", shortTime(entry.time)), - el("span.log-level", (entry.level || "info").toUpperCase()), - el( - "span.log-body", - el("span.log-msg", entry.message || entry.msg || ""), - ...Object.entries(fields).map(([k, v]) => - el("span.log-field", el("span.log-field-key", k), String(fmtValue(v))), - ), - ), + return ( +
+ {shortTime(entry.time)} + {(entry.level || "info").toUpperCase()} + + {entry.message || entry.msg || ""} + {Object.entries(fields).map(([k, v]) => ( + + {k} + {String(fmtValue(v))} + + ))} + +
); } diff --git a/ui/src/base/statTile.jsx b/ui/src/base/statTile.jsx index 80f4970c7..2e13fc700 100644 --- a/ui/src/base/statTile.jsx +++ b/ui/src/base/statTile.jsx @@ -1,5 +1,5 @@ -import { el } from "./dom.jsx"; -import { icon } from "./icons.jsx"; +import { h } from "preact"; +import { Icon } from "./icons.jsx"; /** * A KPI tile: label, big value, trend against a stated comparison window, and @@ -8,26 +8,33 @@ import { icon } from "./icons.jsx"; * * trend > 0 renders as an increase. `goodDirection` says whether that is good, * because rising latency and rising success rate are not the same news. + * + * The headline value is rendered whatever its type, including 0 and "": a tile + * that showed a label and a comparison line with no number above them read as + * a broken dashboard on every fresh install. */ -export function statTile({ label, value, unit, trend, compare, series = [], goodDirection = "up" }) { +export function StatTile({ label, value, unit, trend, compare, series = [], goodDirection = "up" }) { const dir = trend == null ? null : trend >= 0 ? "up" : "down"; const good = dir == null ? null : dir === goodDirection; - return el( - "div.card.stat", - el( - "div.stat-head", - el("span.stat-label", label), - dir && - el( - `span.stat-trend.${good ? "up" : "down"}`, - icon(dir === "up" ? "trendUp" : "trendDown", { size: 13 }), - `${Math.abs(trend).toFixed(1)}%`, - ), - ), - el("div.stat-value", value, unit && el("span.stat-unit", unit)), - compare && el("div.stat-compare", compare), - series.length > 1 && sparkline(series, good === false ? "var(--danger)" : "var(--ok)"), + return ( +
+
+ {label} + {dir ? ( + + + {`${Math.abs(trend).toFixed(1)}%`} + + ) : null} +
+
+ {value} + {unit ? {unit} : null} +
+ {compare ?
{compare}
: null} + {series.length > 1 ? : null} +
); } @@ -35,7 +42,7 @@ export function statTile({ label, value, unit, trend, compare, series = [], good * Inline SVG sparkline. Shows shape, not exact values -- the tile's headline * number carries the precision. */ -export function sparkline(series, stroke = "var(--ok)", { width = 220, height = 34 } = {}) { +export function Sparkline({ series, stroke = "var(--ok)", width = 220, height = 34 }) { const max = Math.max(...series, 1); const min = Math.min(...series, 0); const span = max - min || 1; @@ -45,13 +52,17 @@ export function sparkline(series, stroke = "var(--ok)", { width = 220, height = .map((v, i) => `${(i * step).toFixed(1)},${(height - ((v - min) / span) * height).toFixed(1)}`) .join(" "); - const svg = el("svg.spark", { - viewBox: `0 0 ${width} ${height}`, - preserveAspectRatio: "none", - "aria-hidden": "true", - }); - svg.innerHTML = - ``; - return svg; + return ( + + ); } diff --git a/ui/src/captures/capture-row.jsx b/ui/src/captures/capture-row.jsx index f31aefcce..280f69403 100644 --- a/ui/src/captures/capture-row.jsx +++ b/ui/src/captures/capture-row.jsx @@ -1,5 +1,5 @@ import { h, Fragment } from "preact"; -import { ago } from "../base/dom.jsx"; +import { ago } from "../base/format.jsx"; import { Pill } from "../base/pill.jsx"; /** diff --git a/ui/src/chat/chat-render.jsx b/ui/src/chat/chat-render.jsx index 137e71bdf..263fa373d 100644 --- a/ui/src/chat/chat-render.jsx +++ b/ui/src/chat/chat-render.jsx @@ -1,50 +1,12 @@ -import { el } from "../base/dom.jsx"; -import { renderMarkdown } from "./markdown.jsx"; +/** + * Chat presentation helpers that are not components. + * + * The bubble row markup that used to live here is gone with the imperative DOM + * layer: `assistantBubble`/`chatBubble` were a parallel, unreachable renderer + * (nothing in `src/` called them except the equally unreachable chat-tools + * helpers), and chat.jsx builds those rows as JSX itself. + */ export function sessionTitle(session) { return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`; } - -// assistantBubble builds the row a live reply streams into. The tool list is -// created empty and up front so tool activity has somewhere to land that the -// streaming text replacement cannot destroy, and so its position above the -// reply is fixed by the bubble rather than by insertion order. -export function assistantBubble() { - return el( - "div.chat-bubble-row.assistant", - el( - "div.chat-bubble", - el("div.chat-bubble-meta", "Archie"), - el("div.chat-tools"), - el("div.chat-bubble-text"), - ), - ); -} - -export function chatBubble(message) { - const from = message.from ?? message.From ?? ""; - const text = message.text ?? message.Text ?? ""; - const isAssistant = from !== "web"; - return el( - `div.chat-bubble-row.${isAssistant ? "assistant" : "user"}`, - el( - "div.chat-bubble", - el("div.chat-bubble-meta", isAssistant ? "Archie" : "You"), - isAssistant ? assistantContent(message, text) : el("div.chat-bubble-text", text), - ), - ); -} - -function assistantContent(message, text) { - const tools = message.tool_calls || message.ToolCalls || []; - const children = [el("div.chat-tools")]; - for (const tool of tools) { - const failed = Boolean(tool.err || tool.Err); - children[0].append(el("div.chat-tool" + (failed ? ".failed" : ""), - el("span.chat-tool-icon", "🔧"), - el("span.chat-tool-name", tool.name || tool.Name || "tool"), - el("span.chat-tool-summary", tool.summary || tool.Summary || tool.err || tool.Err || "done"))); - } - children.push(renderMarkdown(text)); - return children; -} diff --git a/ui/src/chat/chat-tools.jsx b/ui/src/chat/chat-tools.jsx deleted file mode 100644 index c713e6c1e..000000000 --- a/ui/src/chat/chat-tools.jsx +++ /dev/null @@ -1,68 +0,0 @@ -import { el } from "../base/dom.jsx"; - -// Tool activity is rendered into its own list inside the assistant bubble -// rather than folded into the reply text: the text node is replaced wholesale -// on every streamed frame, and again on the final reply, so anything written -// into it is lost the next time the answer grows. -// -// The list is part of the bubble from the start (see assistantBubble) and -// sits above the reply, matching the shape the same turn takes in Telegram: -// the work first, then the answer built from it. -export function appendToolCall(host, event) { - const name = event?.tool ?? ""; - if (!host || !name) return null; - - const parameters = event.parameters ?? ""; - const summary = event.text ?? ""; - const line = el( - "div.chat-tool", - el("span.chat-tool-icon", "🔧"), - el("span.chat-tool-name", name), - parameters && el("code.chat-tool-parameters", parameters), - el("span.chat-tool-summary", summary), - ); - // A failure reads as a completed step unless it is marked as one. Styled - // from the structured `failed` field the server sends, not by sniffing - // the summary text: a successful tool can print output that itself starts - // with "failed:" (e.g. a grep hit, a log line), which a string prefix - // check would misread as the tool call itself having failed. - if (event.failed) line.className = "chat-tool failed"; - - toolList(host).append(line); - return line; -} - -// toolList returns the bubble's tool list. A bubble built elsewhere may not -// have one, in which case the list is appended rather than dropped -- tool -// activity out of position still beats tool activity nowhere. -function toolList(host) { - const existing = host.querySelector(".chat-tools"); - if (existing) return existing; - const list = el("div.chat-tools"); - host.append(list); - return list; -} - -// appendNavigateChip renders a dashboard_navigate result as a clickable chip -// that routes the operator to a dashboard page. It is an action, not a tool -// narration line: the model called dashboard_navigate to point the operator -// somewhere, so the chip is a real link (the app routes on location.hash), -// and it is the only clickable navigation surface the transcript offers. The -// label is the tool's resolved page name, never a markdown link the model -// invented. -export function appendNavigateChip(host, event) { - const path = event?.path ?? ""; - const label = event?.label || path; - if (!host || !path) return null; - const chip = el("a.chat-nav-chip", - { - href: "#" + path, - title: "Go to " + label, - "aria-label": "Go to " + label, - }, - el("span.chat-nav-chip-icon", { "aria-hidden": "true" }, "↗"), - el("span.chat-nav-chip-label", label), - ); - toolList(host).append(chip); - return chip; -} diff --git a/ui/src/chat/chat.jsx b/ui/src/chat/chat.jsx index fa7a1c1fa..29555c963 100644 --- a/ui/src/chat/chat.jsx +++ b/ui/src/chat/chat.jsx @@ -1,8 +1,7 @@ -import { h, Fragment, render } from "preact"; +import { h, Fragment } from "preact"; import { useState, useEffect, useRef } from "preact/hooks"; import { api } from "../base/api.jsx"; -import { renderMarkdown } from "./markdown.jsx"; -import { appendToolCall, appendNavigateChip } from "./chat-tools.jsx"; +import { ChatMarkdown } from "./markdown.jsx"; import { channelID } from "./chat-state.jsx"; import { newChatTurn, retryChatTurn, resolveTurn } from "./chat-retry.jsx"; import { sessionTitle } from "./chat-render.jsx"; @@ -14,26 +13,6 @@ function currentPage() { return location.hash.slice(1) || "/"; } -function DOMWrap({ node }) { - const ref = useRef(null); - useEffect(() => { - if (ref.current && node) { - ref.current.replaceChildren(node); - } - }, [node]); - return
; -} - -function MarkdownView({ text }) { - const ref = useRef(null); - useEffect(() => { - if (ref.current) { - ref.current.replaceChildren(renderMarkdown(text || "")); - } - }, [text]); - return
; -} - export function ChatApp() { const [sessions, setSessions] = useState([]); const [currentSession, setCurrentSession] = useState(""); @@ -879,7 +858,7 @@ export function ChatApp() { })}
)} - + ) : (
{text}
@@ -934,7 +913,7 @@ export function ChatApp() { })}
)} - + {streamingTurn.isError && ( ); } else if (tasks !== null) { @@ -149,19 +123,19 @@ function DashboardApp() { {blocked > 0 && ( - {blocked} need{blocked === 1 ? "s" : ""} you + {blocked} need{blocked === 1 ? "s" : ""} you )} {running > 0 && ( - {running} running + {running} running )} - Logs + Logs ); @@ -237,7 +211,7 @@ function DashboardApp() {
    {setup.steps.map((step, i) => (
  • - {step.done ? : ""} + {step.done ? : ""}
    {step.title}
    {step.detail &&
    {step.detail}
    } @@ -256,7 +230,7 @@ function DashboardApp() {

    Archie is configured and ready to work.

    - +
    - ); -} - - function entryKey(entry) { return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`; } diff --git a/ui/src/main.jsx b/ui/src/main.jsx index e7479f29a..719c2dce1 100644 --- a/ui/src/main.jsx +++ b/ui/src/main.jsx @@ -1,9 +1,9 @@ import "./css/_main.css"; -import { render } from "preact"; +import { h, render } from "preact"; +import { useCallback, useEffect, useState } from "preact/hooks"; 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 { Icon } from "./base/icons.jsx"; import { dashboardPage } from "./dashboard/dashboard.jsx"; import { tasksPage } from "./tasks/tasks.jsx"; import { taskDetailPage } from "./tasks/task-detail.jsx"; @@ -17,7 +17,7 @@ import { capturesPage } from "./captures/captures.jsx"; import { mappingsPage } from "./mappings/mappings.jsx"; import { bindingsPage } from "./bindings/bindings.jsx"; import { memoryPage } from "./memory/memory.jsx"; -import { chatPage } from "./chat/chat.jsx"; +import { ChatPage } from "./chat/chat.jsx"; import { matchRoute, navPath } from "./routing.jsx"; /** @@ -44,7 +44,7 @@ import { matchRoute, navPath } from "./routing.jsx"; // :name -- one captured path segment, e.g. /tasks/:id const routes = [ { path: "/", label: "Dashboard", icon: "dashboard", view: dashboardPage }, - { path: "/chat", label: "Chat", icon: "chat", view: chatPage, section: "chat" }, + { path: "/chat", label: "Chat", icon: "chat", view: ChatPage, section: "chat" }, { path: "/tasks", label: "Tasks", icon: "tasks", view: tasksPage }, { path: "/tasks/:id", label: "Task run", view: taskDetailPage, nav: false, navPath: "/tasks" }, { path: "/logs", label: "Logs", icon: "logs", view: logsPage, section: "logs" }, @@ -61,244 +61,293 @@ const routes = [ const THEME_KEY = "archie.theme"; +function currentTheme() { + return localStorage.getItem(THEME_KEY) || "dark"; +} + function applyTheme(theme) { document.documentElement.dataset.theme = theme; localStorage.setItem(THEME_KEY, theme); } -function currentTheme() { - return localStorage.getItem(THEME_KEY) || "dark"; +// navEntries lists what gets a navigation item: a detail route (nav:false) is +// addressed by URL but reached from its section, so it is not an entry. +function navEntries(hidden) { + return routes.filter((route) => route.nav !== false && !hidden.includes(route.path)); } -function commandBar(onNavigate, onToggleChat) { - const items = new Map(); +function Topbar({ activePath, hidden, onNavigate, chatOpen, onToggleChat, theme, onToggleTheme }) { + const [searchOpen, setSearchOpen] = useState(false); - const nav = el( - "nav.nav", - ...[null].flatMap(() => [ - ...routes - .filter((route) => route.nav !== false) - .map((route) => { - const item = el( - "a.nav-item", - { - href: `#${route.path}`, - onclick: (e) => { - if (route.soon) e.preventDefault(); - else onNavigate(route.path); - }, - "aria-disabled": route.soon || undefined, - title: route.soon ? "Coming soon" : undefined, - }, - icon(route.icon), - el("span.nav-label", route.label), - route.soon && el("span.nav-soon", "soon"), - ); - items.set(route.path, item); - return item; - }), - ]), - ); + const closeSearch = () => setSearchOpen(false); - const themeBtn = el("button.icon-btn", { - title: "Toggle light and dark", - "aria-label": "Toggle light and dark", - onclick: () => { - applyTheme(currentTheme() === "dark" ? "light" : "dark"); - mount(themeBtn, icon(currentTheme() === "dark" ? "moon" : "sun")); - }, - }); - mount(themeBtn, icon(currentTheme() === "dark" ? "moon" : "sun")); - - // Search jumps between sections. It is deliberately not a data search: the - // sections own their own filtering, and a second search that means something - // different in each place is worse than none. - let searchWrap; - const closeMobileSearch = () => { - searchWrap?.classList.remove("is-open"); - searchToggle.setAttribute("aria-expanded", "false"); + const onSearchKeyDown = (event) => { + if (event.key === "Escape") { + // preventDefault so the window-level handler (chat drawer close) does not + // also fire: dismissing the search should not dismiss the drawer. + event.preventDefault(); + closeSearch(); + event.target.blur(); + return; + } + if (event.key !== "Enter") return; + // Search jumps between sections. It is deliberately not a data search: the + // sections own their own filtering, and a second search that means + // something different in each place is worse than none. + const query = event.target.value.trim().toLowerCase(); + const hit = routes.find( + (route) => route.nav !== false && !route.soon && route.label.toLowerCase().startsWith(query), + ); + if (hit) { + onNavigate(hit.path); + event.target.value = ""; + closeSearch(); + } }; - const searchToggle = el( - "button.icon-btn.mobile-search-toggle", - { - type: "button", - "aria-label": "Open Jump to navigation", - "aria-expanded": "false", - onclick: () => { - searchWrap.classList.add("is-open"); - searchToggle.setAttribute("aria-expanded", "true"); - search.focus(); - }, - }, - icon("search", { size: 15 }), - ); - const search = el("input", { - type: "search", - placeholder: "Jump to\u2026", - "aria-label": "Jump to a section", - onkeydown: (e) => { - if (e.key === "Escape") { - // preventDefault so the window-level handler (chat drawer close) does - // not also fire: dismissing the search should not dismiss the drawer. - e.preventDefault(); - closeMobileSearch(); - e.target.blur(); - return; - } - if (e.key !== "Enter") return; - const q = e.target.value.trim().toLowerCase(); - const hit = routes.find((r) => r.nav !== false && !r.soon && r.label.toLowerCase().startsWith(q)); - if (hit) { - onNavigate(hit.path); - e.target.value = ""; - e.target.blur(); - closeMobileSearch(); - } - }, - }); - searchWrap = el( - "div.topbar-search", - el("span.topbar-search-icon", { "aria-hidden": "true" }, icon("search", { size: 15 })), - searchToggle, - search, - ); - return { - node: el( - "header.topbar", - el("div.brand", el("span.brand-mark", "A"), "Archie"), - nav, - el( - "div.topbar-end", - searchWrap, - el("button.icon-btn.icon-btn-chat", { - "aria-label": "Open chat", - title: "Chat with Archie", - "aria-expanded": "false", - onclick: () => onToggleChat?.(), - }, icon("chat")), - el("button.icon-btn", { title: "Documentation", "aria-label": "Documentation" }, icon("help")), - themeBtn, - el("div.avatar", { title: "Signed in locally" }, "A"), - ), + return ( +
    +
    + A + Archie +
    + +
    +
    + + + +
    + + + +
    + A +
    +
    +
    + ); +} + +// The chat drawer lives beside the outlet, mounted once. It is closed by +// default and opened from the topbar launcher; because it is a slide-over +// rather than a route, the operator can talk to Archie from any page without +// leaving the work that prompted the question. It hosts a single ChatPage +// instance, so session state and the stream survive navigation and are not +// duplicated per page. +function ChatDrawer({ open, onClose }) { + return ( + + ); +} + +function ComingSoon({ label }) { + return ( +
    +
    +
    +

    {label}

    +
    +
    +
    +
    +
    {`${label} is not built yet`}
    +
    This section is next up. Nothing is broken.
    +
    +
    +
    + ); +} + +// RouteView gives the router a keyed boundary. A page is a function of its +// query and its path parameters, and two ids on the same parameterised route +// must be two instances: without the key the second id diffs the first one in +// place and the operator's open tab from the previous task stays open on the +// next (W11). +function RouteView({ view, search, params }) { + return view(search, params); +} + +// Routing is wired once, at import, and pages render into one long-lived outlet +// rather than as children of App. +// +// The listeners cannot live in an effect: a page installs its own +// hash-sensitive state as it mounts, and the outgoing page has to be gone in +// the same tick the hash changes. Task detail writes the tab selection back +// with replaceState as it settles; if it is still mounted when the hashchange +// lands, it canonicalises the URL back to its own route and the navigation is +// silently lost. App publishes its outlet and its two navigation-owned pieces +// of chrome through a callback ref, which runs at commit time -- before any +// page effect can run. +let outlet = null; +let chrome = null; + +function show(rawPath) { + const [path, query = ""] = String(rawPath).split("?", 2); + const match = matchRoute(routes, path); + const route = match?.route || routes[0]; + const params = match?.params || {}; + + // Let a page release its subscriptions before it is replaced, so the SSE + // stream does not leak a connection per navigation. The event goes to the + // outgoing page's root, before the swap. + outlet?.firstElementChild?.dispatchEvent(new CustomEvent("archie:teardown")); + // A detail route highlights the section it belongs to, so the nav item for + // Tasks stays current on #/tasks/42 instead of every item losing it. + chrome?.setActive(navPath(route)); + + // The chat is a drawer, not a page: /chat opens it rather than mounting a + // second ChatPage (which would duplicate session state and the stream). + const isChat = route.path === "/chat"; + chrome?.setChatOpen(isChat); + if (!outlet) return; + if (isChat) { + render(null, outlet); + return; + } + + // The key covers the path and its parameters, but NOT the query: the query + // string is an entry state, so a navigation that only changes the query of + // the page already mounted keeps the operator's own filter selection. + render( + route.view ? ( + + ) : ( + ), - highlight(path) { - for (const [p, node] of items) { - if (p === path) node.setAttribute("aria-current", "page"); - else node.removeAttribute("aria-current"); - } - }, - hide(paths) { - for (const path of paths) items.get(path)?.remove(); - }, - }; + outlet, + ); } -function start() { - applyTheme(currentTheme()); +function navigate(next) { + if (location.hash !== `#${next}`) location.hash = next; + else show(next); +} + +window.addEventListener("hashchange", () => show(location.hash.slice(1) || "/")); +window.addEventListener("keydown", (event) => { + // A focused control (the composer dismissing its command menu, or the topbar + // search) already handled Escape via preventDefault; closing the drawer too + // would make the menu impossible to dismiss alone. + if (event.defaultPrevented) return; + if (event.key === "Escape") chrome?.setChatOpen(false); +}); + +function App() { + const [active, setActive] = useState("/"); + const [theme, setTheme] = useState(currentTheme); + const [chatOpen, setChatOpen] = useState(false); + const [hidden, setHidden] = useState([]); + + // Publishes the router's handles. A callback ref runs at commit time, so a + // hashchange that lands right after the first paint already finds them. + const publish = useCallback((element) => { + outlet = element; + chrome = { setActive, setChatOpen }; + }, []); + + useEffect(() => { + applyTheme(theme); + }, [theme]); + + useEffect(() => { + document.body.classList.toggle("chat-open", chatOpen); + }, [chatOpen]); - const outlet = el("main.main"); - // The chat drawer lives beside the outlet, mounted once. It is closed by - // default and opened from the topbar launcher; because it is a slide-over - // rather than a route, the operator can talk to Archie from any page - // without leaving the work that prompted the question. It hosts a single - // chatPage() instance, so session state and the stream survive navigation - // and are not duplicated per page. - const chatDrawer = el("aside.chat-drawer", { "aria-label": "Chat with Archie" }); - const chatClose = el("button.icon-btn.chat-drawer-close", { - "aria-label": "Close chat", - title: "Close chat", - onclick: () => toggleChat(false), - }, icon("close")); - const drawerHead = el("div.chat-drawer-head", el("strong", "Archie"), chatClose); - 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); + useEffect(() => { + api + .capabilities() + .then((caps) => setHidden(hiddenRoutes(caps?.sections, routes))) + .catch(() => {}); + }, []); - function toggleChat(open) { - const shouldOpen = open === undefined ? !chatDrawer.classList.contains("is-open") : open; - chatDrawer.classList.toggle("is-open", shouldOpen); - document.body.classList.toggle("chat-open", shouldOpen); - const btn = shell.querySelector(".icon-btn-chat"); - if (btn) btn.setAttribute("aria-expanded", String(shouldOpen)); - } - window.__archieToggleChat = toggleChat; - - function navigate(path) { - if (location.hash !== '#' + path) location.hash = path; - else show(path); - } - - function show(rawPath) { - // Let a page release its subscriptions before it is replaced, so the SSE - // stream does not leak a connection per navigation. - outlet.firstElementChild?.dispatchEvent(new CustomEvent("archie:teardown")); - const [path, query = ""] = rawPath.split("?", 2); - const match = matchRoute(routes, path); - const route = match?.route || routes[0]; - // A detail route highlights the section it belongs to, so the nav item for - // Tasks stays current on #/tasks/42 instead of every item losing it. - bar.highlight(navPath(route)); - // The chat is a drawer, not a page: /chat opens it rather than mounting a - // second chatPage() (which would duplicate session state and the stream). - if (route.path === "/chat") { - mount(outlet); - toggleChat(true); - return; - } - // Every registered page returns a Preact VNode (all views import `h` - // from "preact"), which mount()/append() cannot render -- append() - // only knows real DOM Nodes and strings, so a bare VNode object became - // the literal text "[object Object]". Preact's own render() diffs and - // mounts a VNode correctly, including running the previous page's - // effect-cleanup on unmount. comingSoon() (the `!route.view` fallback, - // currently unused -- no route declares `soon: true`) still returns a - // real DOM Node, so it keeps going through mount() -- render() and - // mount()/replaceChildren() should not alternate on the same outlet - // across navigations, since Preact tracks its own vdom state on the - // container node; if a `soon: true` route is ever added, revisit this. - const rendered = route.view ? route.view(new URLSearchParams(query), match?.params || {}) : comingSoon(route); - if (rendered instanceof Node) { - mount(outlet, rendered); - } else { - render(rendered, outlet); - } - // Navigating to a page dismisses the chat drawer; the operator has moved on. - toggleChat(false); - } - - window.addEventListener("hashchange", () => show(location.hash.slice(1) || "/")); - window.addEventListener("keydown", (e) => { - // A focused control (the composer dismissing its command menu, or the - // topbar search) already handled Escape via preventDefault; closing the - // drawer too would make the menu impossible to dismiss alone. - if (e.defaultPrevented) return; - if (e.key === "Escape" && chatDrawer.classList.contains("is-open")) toggleChat(false); - }); - show(location.hash.slice(1) || "/"); -} - -function comingSoon(route) { - return el( - "div", - el("div.page-head", el("div", el("h1.page-title", route.label))), - el( - "div.card", - el( - "div.empty", - el("div.empty-title", `${route.label} is not built yet`), - el("div", "This section is next up. Nothing is broken."), - ), - ), + return ( +
    +
    ); } -start(); +applyTheme(currentTheme()); +render(, document.getElementById("app")); +show(location.hash.slice(1) || "/"); diff --git a/ui/src/tasks/changed-files.jsx b/ui/src/tasks/changed-files.jsx index ff781ddba..c2e3c1916 100644 --- a/ui/src/tasks/changed-files.jsx +++ b/ui/src/tasks/changed-files.jsx @@ -1,4 +1,4 @@ -import { ago } from "../base/dom.jsx"; +import { ago } from "../base/format.jsx"; // Changed files for one attempt (R3), from `GET /api/tasks/{id}/changes`. // diff --git a/ui/src/tasks/task-logs.jsx b/ui/src/tasks/task-logs.jsx index 5fdd7e2e4..13e8588b5 100644 --- a/ui/src/tasks/task-logs.jsx +++ b/ui/src/tasks/task-logs.jsx @@ -1,5 +1,4 @@ -import { useRef, useEffect } from "preact/hooks"; -import { logRow as renderLogRow, LOG_LEVELS } from "../base/log-row.jsx"; +import { LogRow, LOG_LEVELS } from "../base/log-row.jsx"; // A task attempt's log pane (R5). // @@ -21,14 +20,6 @@ import { logRow as renderLogRow, LOG_LEVELS } from "../base/log-row.jsx"; // reports which one it is showing, so the pane can never read attempt 1's log // while claiming attempt 2. -function LogRowNode({ entry }) { - const ref = useRef(null); - useEffect(() => { - if (ref.current) ref.current.replaceChildren(renderLogRow(entry)); - }, [entry]); - return
    ; -} - // Task-log download URL. The attempt is named explicitly so a download matches // the attempt the panel is showing rather than whatever is current by the time // the operator clicks. @@ -195,7 +186,7 @@ export function TaskLogPanel({ <>
    {entries.map((entry, i) => ( - + ))}
    {footer} diff --git a/ui/src/tasks/tasks.jsx b/ui/src/tasks/tasks.jsx index b5a990516..fcd25ece2 100644 --- a/ui/src/tasks/tasks.jsx +++ b/ui/src/tasks/tasks.jsx @@ -2,9 +2,9 @@ import { Fragment } from "preact"; import { useState, useEffect, useRef } from "preact/hooks"; import "./tasks.css"; import { api, classifyActionError } from "../base/api.jsx"; -import { ago } from "../base/dom.jsx"; +import { ago } from "../base/format.jsx"; import { Pill } from "../base/pill.jsx"; -import { statTile as renderStatTile } from "../base/statTile.jsx"; +import { StatTile } from "../base/statTile.jsx"; import { taskRowA11y } from "./task-row.jsx"; import { initialTaskFilter, taskMatchesStatus } from "./task-filters.jsx"; import { describeTimelineEvent } from "./timeline-event.jsx"; @@ -24,15 +24,6 @@ export function revealBehavior() { return prefersReducedMotion() ? "auto" : "smooth"; } -function StatTileNode(props) { - const ref = useRef(null); - useEffect(() => { - if (ref.current) ref.current.replaceChildren(renderStatTile(props)); - }, [props]); - return
    ; -} - - // renderActionError distinguishes a refused action ("you cannot do that" -- // bad input, a conflicting task state) from a broken one (5xx, network drop, // timeout -- "try again or check the daemon"), and special-cases an expired @@ -242,23 +233,23 @@ function TasksApp({ query }) { return (
    - - - - { const { container, unmount } = render(); @@ -23,12 +23,3 @@ test("ChatApp renders empty state with prompt chips when messages are empty", () assert.ok(prompts.length >= 3, "should have prompt buttons"); unmount(); }); - -test("chatPage bridge function returns a DOM element containing the ChatApp", () => { - // chatPage() renders a Preact ChatApp into a container and returns that - // container as a real DOM node (used by the chat drawer / router). - const node = chatPage(); - assert.ok(node instanceof HTMLElement, "chatPage should return a DOM element"); - assert.ok(node.querySelector(".chat-page-content"), "chat-page-content should be inside node"); - cleanup(); -}); diff --git a/ui/test/chat-markdown.test.js b/ui/test/chat-markdown.test.js index 1e0a31179..316fa1f47 100644 --- a/ui/test/chat-markdown.test.js +++ b/ui/test/chat-markdown.test.js @@ -1,12 +1,18 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import "./shim.js"; -import { renderMarkdown } from "../src/chat/markdown.js"; +import { h } from "preact"; +import { render, cleanup } from "@testing-library/preact"; +import { ChatMarkdown } from "../src/chat/markdown.jsx"; test("chat Markdown renders Telegram-style rich blocks as semantic HTML", () => { - const rendered = renderMarkdown( - "# Summary\n\n**bold**, *italic*, ~~removed~~, and [docs](https://example.com)\n\n- first\n- second\n\n> quoted\n\n```go\nfmt.Println(\"hi\")\n```\n\n| Name | State |\n| --- | --- |\n| Archie | **live** |", + const { container } = render( + quoted\n\n```go\nfmt.Println(\"hi\")\n```\n\n| Name | State |\n| --- | --- |\n| Archie | **live** |" + } + />, ); + const rendered = container.querySelector(".chat-bubble-text"); assert.equal(rendered.querySelector("h1").textContent, "Summary"); assert.equal(rendered.querySelector("strong").textContent, "bold"); @@ -18,12 +24,32 @@ test("chat Markdown renders Telegram-style rich blocks as semantic HTML", () => assert.match(rendered.querySelector("pre").textContent, /fmt\.Println/); assert.equal(rendered.querySelector("table").querySelector("th").textContent, "Name"); assert.equal(rendered.querySelector("table").querySelector("td").textContent, "Archie"); + cleanup(); }); test("chat Markdown renders images as img elements with src and alt", () => { - const rendered = renderMarkdown("Here is the generated image: ![generated preview](https://example.com/image.png)"); - const img = rendered.querySelector("img"); + const { container } = render( + , + ); + const img = container.querySelector("img"); assert.ok(img, "img element should be present"); assert.equal(img.getAttribute("src"), "https://example.com/image.png"); assert.equal(img.getAttribute("alt"), "generated preview"); + cleanup(); +}); + +// The blocks are keyed, so a streamed reply that grows by one line re-renders +// only what changed. Preact reports a duplicate-key mistake by rendering the +// wrong thing, so the shapes with sibling lists and tables are worth pinning. +test("chat Markdown keeps sibling blocks distinct when the text grows", () => { + const { container, rerender } = render(); + assert.equal(container.querySelectorAll("ul").length, 1); + rerender(); + assert.equal(container.querySelectorAll("ul").length, 1); + assert.equal(container.querySelector("ul").children.length, 3); + + rerender(); + assert.equal(container.querySelectorAll("ul").length, 1); + assert.equal(container.querySelectorAll("ol").length, 1); + cleanup(); }); diff --git a/ui/test/chat-tools.test.js b/ui/test/chat-tools.test.js deleted file mode 100644 index aaa431af1..000000000 --- a/ui/test/chat-tools.test.js +++ /dev/null @@ -1,118 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import "./shim.js"; -import { assistantBubble } from "../src/chat/chat-render.js"; -import { appendToolCall, appendNavigateChip } from "../src/chat/chat-tools.js"; - -// childIndex reports where a node sits among its parent's children, which is -// how the tests assert that the work is listed above the answer. -function childIndex(parent, selector) { - const node = parent.querySelector(selector); - return parent.childNodes.indexOf(node); -} - -test("a tool call is listed above the answer it produced", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendToolCall(host, { tool: "shell", parameters: '{"cmd":"true"}', text: "exit 0" }); - - const tools = host.querySelector(".chat-tools"); - assert.equal(tools.childNodes.length, 1); - assert.equal(host.querySelector(".chat-tool-name").textContent, "shell"); - assert.equal(host.querySelector(".chat-tool-parameters").textContent, '{"cmd":"true"}'); - assert.equal(host.querySelector(".chat-tool-summary").textContent, "exit 0"); - assert.ok( - childIndex(host, ".chat-tools") < childIndex(host, ".chat-bubble-text"), - "tool activity must render above the reply text", - ); -}); - -test("further tool calls join the same list in order", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendToolCall(host, { tool: "memory_edit", text: "added entry" }); - appendToolCall(host, { tool: "shell", text: "exit 0" }); - - const list = host.querySelector(".chat-tools"); - const names = list.childNodes.map((line) => line.querySelector(".chat-tool-name").textContent); - assert.deepEqual(names, ["memory_edit", "shell"]); -}); - -test("a failed tool call is marked so it does not read as success", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendToolCall(host, { tool: "read", text: "failed: no such file", failed: true }); - - const line = host.querySelector(".chat-tool"); - assert.match(line.className, /failed/); -}); - -test("a successful tool call is not marked as failed", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendToolCall(host, { tool: "read", text: "42 lines", failed: false }); - - assert.doesNotMatch(host.querySelector(".chat-tool").className, /failed/); -}); - -// The styling decision reads the structured `failed` field, not the summary -// text: a successful tool's own output can start with "failed:" (a grep -// hit, a log line it read back), and that must not be styled as an error. -test("a successful tool whose output starts with 'failed:' is not marked as failed", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendToolCall(host, { tool: "shell", text: "failed: no such file (grep match, exit 0)", failed: false }); - - assert.doesNotMatch(host.querySelector(".chat-tool").className, /failed/); -}); - -test("a tool event with no name is ignored rather than rendered blank", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendToolCall(host, { tool: "", text: "exit 0" }); - - assert.equal(host.querySelector(".chat-tools").childNodes.length, 0); -}); - -// A bubble that predates the tool list -- a retried turn reusing an older -// one -- must still show tool activity rather than silently dropping it. -test("a bubble without a tool list still records tool activity", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - host.childNodes = host.childNodes.filter((node) => node.className !== "chat-tools"); - - appendToolCall(host, { tool: "shell", text: "exit 0" }); - - assert.equal(host.querySelector(".chat-tool-name").textContent, "shell"); -}); - -// A dashboard_navigate call is an explicit point-the-operator-somewhere -// result, so it renders as a clickable chip link rather than a muted tool -// line, and the chip must be a real link (the app routes on location.hash). -test("a navigate chip is a clickable link to the resolved page", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendNavigateChip(host, { path: "/tasks", label: "Tasks" }); - - const chip = host.querySelector(".chat-nav-chip"); - assert.ok(chip, "navigate chip should render"); - assert.equal(chip.getAttribute("href"), "#/tasks"); - assert.equal(chip.querySelector(".chat-nav-chip-label").textContent, "Tasks"); - assert.equal(chip.getAttribute("aria-label"), "Go to Tasks"); -}); - -test("a navigate chip without a path is not rendered", () => { - const row = assistantBubble(); - const host = row.querySelector(".chat-bubble"); - - appendNavigateChip(host, { path: "", label: "Tasks" }); - - assert.equal(host.querySelector(".chat-nav-chip"), null); -}); diff --git a/ui/test/dom.test.js b/ui/test/dom.test.js deleted file mode 100644 index 8a54e7a85..000000000 --- a/ui/test/dom.test.js +++ /dev/null @@ -1,65 +0,0 @@ -// Regression coverage for the DOM-building primitives. -// -// The KPI regression this pins: `el("div.stat-value", 0, ...)` used to treat a -// falsy first child (0, "", false) as "no attributes" and drop it, so stat -// tiles rendered an empty headline whenever the value was zero. The dashboards -// of fresh installs show exactly that -- labels and comparison text, no number. - -import { test } from "node:test"; -import assert from "node:assert/strict"; -import "./shim.js"; -import { el, mount } from "../src/base/dom.js"; -import { statTile } from "../src/base/statTile.js"; - -test("el renders a falsy numeric value instead of dropping it", () => { - const node = el("div.stat-value", 0); - assert.equal(node.textContent, "0"); -}); - -test("el renders an empty string first child without dropping later children", () => { - const node = el("div", "", "tail"); - assert.equal(node.textContent, "tail"); -}); - -test("el keeps falsy non-child values out of the output but keeps real children", () => { - const node = el("div", false, "x"); - assert.equal(node.textContent, "x"); -}); - -test("el still treats an attrs object as attributes", () => { - const node = el("a.btn", { href: "#/tasks", "aria-label": "Tasks" }, "Tasks"); - assert.equal(node.getAttribute("href"), "#/tasks"); - assert.equal(node.getAttribute("aria-label"), "Tasks"); - assert.equal(node.textContent, "Tasks"); -}); - -test("el still treats a Node first argument as a child", () => { - const child = el("span", "inner"); - const node = el("div", child); - assert.equal(node.textContent, "inner"); -}); - -test("mount replaces prior children", () => { - const root = el("div", "old"); - mount(root, el("p", "new")); - assert.equal(root.textContent, "new"); -}); - -test("statTile renders a zero headline value", () => { - const tile = statTile({ label: "Working now", value: 0, compare: "Nothing running" }); - assert.equal(tile.querySelector(".stat-label").textContent, "Working now"); - assert.equal(tile.querySelector(".stat-value").textContent, "0"); - assert.equal(tile.querySelector(".stat-compare").textContent, "Nothing running"); -}); - -test("statTile renders a string headline value", () => { - const tile = statTile({ label: "Tokens used", value: "2.4M", compare: "Across 14 days" }); - assert.equal(tile.querySelector(".stat-value").textContent, "2.4M"); -}); - -test("statTile shows a trend direction only when a trend is supplied", () => { - const plain = statTile({ label: "Delivered", value: 3, compare: "3% of all tasks" }); - assert.equal(plain.querySelector(".stat-trend"), null); - const trended = statTile({ label: "Tokens used", value: 5, trend: 12.5, compare: "x", goodDirection: "down" }); - assert.match(trended.querySelector(".stat-trend").textContent, /12\.5/); -}); diff --git a/ui/test/log-row.test.js b/ui/test/log-row.test.js index 5efde4334..9bfc1cb41 100644 --- a/ui/test/log-row.test.js +++ b/ui/test/log-row.test.js @@ -1,7 +1,8 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import "./shim.js"; -import { logRow, levelKind, fmtValue, shortTime } from "../src/base/log-row.js"; +import { h } from "preact"; +import { render, cleanup } from "@testing-library/preact"; +import { LogRow, levelKind, fmtValue, shortTime } from "../src/base/log-row.jsx"; test("levelKind maps known levels to their pill kind", () => { assert.equal(levelKind("ERROR"), "danger"); @@ -22,23 +23,36 @@ test("shortTime falls back to a placeholder for an unparsable time", () => { assert.equal(shortTime("not a date"), "--:--:--"); }); -test("logRow renders every field generically, including the ones the daemon-wide feed drops", () => { - const row = logRow({ - time: "2026-01-01T00:00:00Z", - level: "info", - msg: "attempt finished", - fields: { - stage: "tdd", - prompt_tokens: 100, - completion_tokens: 40, - cached_tokens: 10, - stop_reason: "end_turn", - model: "sonnet-5", - }, - }); +test("LogRow renders every field generically, including the ones the daemon-wide feed drops", () => { + const { container } = render( + , + ); + const row = container.querySelector(".log-row"); assert.match(row.className, /log-row/); assert.match(row.textContent, /attempt finished/); for (const key of ["stage", "prompt_tokens", "completion_tokens", "cached_tokens", "stop_reason", "model"]) { assert.match(row.textContent, new RegExp(key), `missing field ${key}`); } + cleanup(); +}); + +test("LogRow colours the row by level", () => { + const { container } = render(); + assert.match(container.querySelector(".log-row").className, /log-danger/); + assert.equal(container.querySelector(".log-level").textContent, "ERROR"); + cleanup(); }); diff --git a/ui/test/register.js b/ui/test/register.js index 758c01424..590f475a9 100644 --- a/ui/test/register.js +++ b/ui/test/register.js @@ -3,11 +3,9 @@ import { JSDOM } from "jsdom"; register("./hooks.js", import.meta.url); -// A real DOM for @testing-library/preact. The custom shim in shim.js covers -// only the el() DOM-building primitives; the testing library needs full DOM -// globals (document, window, getComputedStyle, MutationObserver, ...), which -// jsdom provides. Applied here so every test file sees them before importing -// source modules. +// A real DOM for @testing-library/preact: full DOM globals (document, window, +// getComputedStyle, MutationObserver, ...), which jsdom provides. Applied here +// so every test file sees them before importing source modules. const dom = new JSDOM("", { url: "http://localhost/" }); const { window } = dom; diff --git a/ui/test/statTile.test.js b/ui/test/statTile.test.js new file mode 100644 index 000000000..155e01471 --- /dev/null +++ b/ui/test/statTile.test.js @@ -0,0 +1,55 @@ +// KPI tile regression coverage, moved here when base/statTile.jsx stopped +// building DOM by hand. +// +// The regression this pins: `el("div.stat-value", 0, ...)` treated a falsy +// first child (0, "", false) as "no attributes" and dropped it, so stat tiles +// rendered an empty headline whenever the value was zero. The dashboards of +// fresh installs showed exactly that -- labels and comparison text, no number. +// JSX does not have that bug, which is precisely why the case is worth keeping: +// it is what a future `value &&
    ` refactor would break. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { h } from "preact"; +import { render, cleanup } from "@testing-library/preact"; +import { StatTile, Sparkline } from "../src/base/statTile.jsx"; + +test("StatTile renders a zero headline value", () => { + const { container } = render(); + const tile = container.querySelector(".card.stat"); + assert.equal(tile.querySelector(".stat-label").textContent, "Working now"); + assert.equal(tile.querySelector(".stat-value").textContent, "0"); + assert.equal(tile.querySelector(".stat-compare").textContent, "Nothing running"); + cleanup(); +}); + +test("StatTile renders an empty-string headline value without dropping it", () => { + const { container } = render(); + assert.equal(container.querySelector(".stat-value").textContent, ""); + assert.equal(container.querySelector(".stat-compare").textContent, "Across 14 days"); + cleanup(); +}); + +test("StatTile renders a string headline value", () => { + const { container } = render(); + assert.equal(container.querySelector(".stat-value").textContent, "2.4M"); + cleanup(); +}); + +test("StatTile shows a trend direction only when a trend is supplied", () => { + const plain = render(); + assert.equal(plain.container.querySelector(".stat-trend"), null); + cleanup(); + const trended = render(); + assert.match(trended.container.querySelector(".stat-trend").textContent, /12\.5/); + cleanup(); +}); + +test("StatTile draws a sparkline only when a series has a shape to show", () => { + const flat = render(); + assert.equal(flat.container.querySelector("svg.spark"), null); + cleanup(); + const shaped = render(); + assert.ok(shaped.container.querySelector("svg.spark polyline")); + cleanup(); +});