Merge pull request #885 from samcharles93/refactor/ui-finish-preact-port
refactor(ui): finish the Preact port and delete the imperative DOM layer
This commit is contained in:
26 files changed
+697
-940
No files matched your search
Vendored
+7
-14
@@ -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;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),I(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,te(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=I(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&ne(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),z(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function M(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function P(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function F(e){return function(n){if(this.l){var r=thiLine truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var 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
Line truncated
|
||||
<path d="${c(150,240)}" fill="none" stroke="var(--border)"
|
||||
stroke-width="12" stroke-linecap="round"/>
|
||||
<path d="${c(150,240)}" fill="none" stroke="${i}"
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${s}"
|
||||
stroke-dashoffset="${s*(1-r/100)}"
|
||||
class="gauge-value"/>`,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
Line truncated
|
||||
`),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:`alloLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(W(`p`,ni(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(W(`pre`,W(`code`,a.join(`
|
||||
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=ii(c),u=e+1<n.length?ii(n[e+1]):null;if(l&&u&&ai(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=ii(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=W(`tbody`);for(let e of r)i.append(W(`tr`,...e.map(e=>W(`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.sear
Line truncated
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),I(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,ee(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=I(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&te(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),B(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function M(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function P(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function F(e){return function(n){if(this.l){var r=thiLine truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Oe=class extends Error{constructor(e,t){super(e),this.status=t}};function ke(e){let t=e instanceof Oe?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ae(e,t){let n=await fetch(e,t);if(!n.ok)throw new Oe(await De(n),n.status);return n}async function J(e,{method:t=`GET`,body:n,timeoutMs:r=Te,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await Ae(e,o);return i?s.json():void 0}var Y={summary:()=>J(`/api/summary`),tasks:()=>J(`/api/tasks`),taskMeta:()=>J(`/api/task-meta`),task:e=>J(`/api/tasks/${e}`),taskAttempts:e=>J(`/api/tasks/${e}/attempts`),taskChanges:(e,t)=>J(`/api/tasks/${e}/changes`+Ee(t)),taskDebug:(e,t)=>J(`/api/tasks/${e}/debug`+Ee(t)),taskAction:(e,t)=>J(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>J(`/api/setup`),capabilities:()=>J(`/api/capabilities`),workflows:()=>J(`/api/workflows`),workRequest:e=>J(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>J(`/api/skills`),channels:()=>J(`/api/channels`),curators:()=>J(`/api/curators`),channelReload:e=>J(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>J(`/api/config`),version:()=>J(`/api/version`),configUpdate:e=>J(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>J(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>J(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>J(`/api/logs`+Ee(e)),taskLogs:(e,t)=>J(`/api/tasks/${e}/logs`+Ee(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>J(`/api/captures`+Ee({limit:e})),mappings:()=>J(`/api/mappings`),mappingCreate:e=>J(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>J(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>J(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>J(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>J(`/api/bindings`),bindingCreate:e=>J(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>J(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>J(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>J(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>J(`/api/memory`),chatSessions:()=>J(`/api/chat/sessions`),chatMessages:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>J(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>J(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>J(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:we(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>J(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>J(`/api/chat/update`),chatUpdateDefer:e=>J(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>J(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>J(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>J(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>Ae(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function je(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Me(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Ne(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var Pe=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Pe,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}var Fe={dashboard:`<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>`,chat:`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v7a2.5 2.5 0 0 1-2.5 2.5H11l-4.5 4v-4.1A2.5 2.5 0 0 1 4 12.5z"/><path d="M8 8h8M8 11h5"/>`,tasks:`Line truncated
|
||||
`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Q,{text:Jn[e.status]||e.status,kind:Yn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function $({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Zn({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function Qn({origins:e}){return e?.length?X(Zn,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(Wn,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X(Zn,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X($,{title:`Source provenance is unavailable.`})})}function $n(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function er({data:e,error:t}){if(t)return X(Zn,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X($,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X(Zn,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??We(e.id),n=e.kind??Ge(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Q,{text:t,kind:n})})]},e.id)})}):X($,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=$n(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X($,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function tr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(!1),[o,s]=W(null),[c,l]=W(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function nr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=W(String(e[t]??0)),[o,s]=W(null),[c,l]=W(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await Y.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function rr({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X(Zn,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X($,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X(Zn,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(tr,{r:e,field:`alloLine truncated
|
||||
`),i=[],a=null,o=null,s=0,c=()=>{i.length&&(n.push(X(`p`,{children:Wr(i.join(` `))},s++)),i=[])},l=()=>{if(!a)return;let e=a.items.map((e,t)=>X(`li`,{children:Wr(e)},t));n.push(a.tag===`ol`?X(`ol`,{children:e},s++):X(`ul`,{children:e},s++)),a=null};for(let e=0;e<r.length;e++){let t=r[e];if(t.startsWith("```")){c(),l(),o?(n.push(X(`pre`,{children:X(`code`,{children:o.join(`
|
||||
`)})},s++)),o=null):o=[];continue}if(o){o.push(t);continue}let u=Kr(t),d=e+1<r.length?Kr(r[e+1]):null;if(u&&d&&qr(d)&&u.length===d.length){c(),l();let t=[];for(e+=2;e<r.length;e++){let n=Kr(r[e]);if(!n||n.length!==u.length){e--;break}t.push(n)}n.push(X(`table`,{children:[X(`thead`,{children:X(`tr`,{children:u.map((e,t)=>X(`th`,{children:Wr(e)},t))})}),X(`tbody`,{children:t.map((e,t)=>X(`tr`,{children:e.map((e,t)=>X(`td`,{children:Wr(e)},t))},t))})]},s++));continue}if(!t.trim()){c(),l();continue}let f=t.match(/^(#{1,3})\s+(.+)$/);if(f){c(),l();let e=`h${f[1].length}`;n.push(X(e,{children:Wr(f[2])},s++));continue}let p=t.match(/^\s*[-*]\s+(.+)$/),m=t.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){c();let e=m?`ol`:`ul`;(!a||a.tag!==e)&&(l(),a={tag:e,items:[]}),a.items.push((p||m)[1]);continue}if(t.startsWith(`>`)){c(),l(),n.push(X(`blockquote`,{children:Wr(t.replace(/^>\s?/,``))},s++));continue}i.push(t)}return c(),l(),o&&n.push(X(`pre`,{children:X(`code`,{children:o.join(`
|
||||
`)})},s++)),X(`div`,{className:t,children:n})}function Kr(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function qr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var Jr=`archie.web.chat.channel`;function Yr(){let e=localStorage.getItem(Jr);return e||(e=we(),localStorage.setItem(Jr,e)),e}function Xr(e){return{text:e,sourceID:we()}}function Zr(e){return{...e}}function Qr(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Zr(e.turn):Xr(r),isRetry:n}}function $r(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function ei(e){return e?.status===501?null:`Could not check for updates.`}function ti(){return location.hash.slice(1)||`/`}function ni(){let[e,t]=W([]),[n,r]=W(``),[i,a]=W([]),[o,s]=W(``),[c,l]=W(`Ready`),[u,d]=W(!1),[f,p]=W({}),[m,h]=W(``),[g,_]=W(``),[v,y]=W(``),[b,x]=W([]),[C,w]=W([]),[T,E]=W(0),[D,O]=W(!1),[k,A]=W(null),[j,M]=W(null),[N,P]=W(null),[F,I]=W(``),[L,ee]=W(``),[R,z]=W(null),te=K(null),B=K(null),V=K(null),ne=K(null),re=K(null),H=K(u);H.current=u,G(()=>{te.current&&(te.current.scrollTop=te.current.scrollHeight)},[i,R]),G(()=>{le().catch(e=>{l(e.message||`Chat unavailable`)}),ie();let e=()=>{V.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),V.current?.abort()}},[]);async function ie(){try{let e=await Y.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=ei(e);A(t?{error:t}:null)}}async function ae(){if(j)try{await Y.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function oe(){if(j)try{l(`Installing…`);let e=await Y.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function se(){try{let e=await Y.chatDangerous();P(e)}catch(e){P({error:e.message||`Dangerous actions unavailable`})}}async function U(e,t){if(t)try{await Y.chatDangerousRequest(e,t),l(`Approval requested`),await se()}catch(e){l(e.message||`Could not request action`)}}async function ce(e,t){try{await Y.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await se()}catch(e){l(e.message||`Approval failed`)}}async function le(){let e=await Y.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await se(),!n&&r[0]&&await ue(r[0].session_id,e,r)}async function ue(e,t,n){let i=t||f;r(e),a([]),z(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await Y.chatMessage(Yr(),`/resume ${e}`);let[t,n]=await Promise.all([Y.chatMessages(e),Y.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function de(e){if(n)try{l(`Working…`);let t=await Y.chatMessage(Yr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await le(),(t.session_id||n)&&await ue(t.session_id||n),ne.current&&(ne.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function fe(e,t){let n=window.prompt(t);n?.trim()&&de(`${e} ${n.trim()}`)}function pe(e){let t=e.target.value;h(t),!(!n||!t)&&Y.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function me(e){let t=e.target.value;if(_(t),t)try{let e=await Y.chatMessage(Yr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await le()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function he(e){let t=e.target.value;if(y(t),t)try{let e=await Y.chatMessage(Yr(),`/model ${t}`);l(e.reply||`Model updated`),await le()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ge(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),q({textOverride:`/restart`}))}function _e(){s(`/new`),q({textOverride:`/new`})}function ve(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function ye(e){let t=C[e];if(!t||!B.current)return;let n=B.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t
Line truncated
|
||||
|
||||
`);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 appeLine truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&r(n.session_id),n.type===`delta`&&(f+=n.text,z(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],z(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),z(null),l(`Ready`),await le()}catch(e){if(e.name===`AbortError`&&!m)z({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;z({text:t,tools:u,isError:!0,turn:Zr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),V.current=null,d(!1),B.current&&B.current.focus()}}function xe(){l(`Stopping…`),n&&Y.chatCancel(n).catch(()=>{}),V.current?.abort()}let Se=f.models_by_provider||{},Ce=g&&Se[g]?Se[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:ge,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ie,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:pe,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:me,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:he,children:[X(`option`,{value:``,children:`Model`}),Ce.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:ae,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:oe,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&N&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:F,onChange:e=>I(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(N.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`rollback`,F),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:L,onInput:e=>ee(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>U(`stop`,L),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(N.pending||[]).length?N.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ce(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:_e,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>ue(e.session_id),children:[X(`strong`,{children:$r(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will aLine truncated
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+46
-45
@@ -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 = `
|
||||
<path d="${arc(start, sweep)}" fill="none" stroke="var(--border)"
|
||||
stroke-width="12" stroke-linecap="round"/>
|
||||
<path d="${arc(start, sweep)}" fill="none" stroke="${stroke}"
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${circumference}"
|
||||
stroke-dashoffset="${circumference * (1 - pct / 100)}"
|
||||
class="gauge-value"/>`;
|
||||
|
||||
return el(
|
||||
"div.gauge-wrap",
|
||||
svg,
|
||||
el("div.gauge-center", el("div.gauge-pct", `${Math.round(pct)}%`), el("div.gauge-label", label)),
|
||||
return (
|
||||
<div className="gauge-wrap">
|
||||
<svg className="gauge" viewBox={`0 0 ${size} ${size * 0.78}`} role="img" aria-label={`${label}: ${pct}%`}>
|
||||
<path d={arc(start, sweep)} fill="none" stroke="var(--border)" stroke-width="12" stroke-linecap="round" />
|
||||
<path
|
||||
d={arc(start, sweep)}
|
||||
fill="none"
|
||||
stroke={stroke}
|
||||
stroke-width="12"
|
||||
stroke-linecap="round"
|
||||
stroke-dasharray={circumference}
|
||||
stroke-dashoffset={circumference * (1 - pct / 100)}
|
||||
className="gauge-value"
|
||||
/>
|
||||
</svg>
|
||||
<div className="gauge-center">
|
||||
<div className="gauge-pct">{`${Math.round(pct)}%`}</div>
|
||||
<div className="gauge-label">{label}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 (
|
||||
<div>
|
||||
<div className="segbar">
|
||||
{segments
|
||||
.filter((s) => s.value > 0)
|
||||
.map((s) => (
|
||||
<span
|
||||
key={s.label}
|
||||
className={`segbar-part segbar-${s.kind || "idle"}`}
|
||||
style={`width:${((s.value / total) * 100).toFixed(1)}%`}
|
||||
title={`${s.label}: ${s.value}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="segbar-legend">
|
||||
{segments.map((s) => (
|
||||
<span className="segbar-key" key={s.label}>
|
||||
<span className={`segbar-dot segbar-${s.kind || "idle"}`} />
|
||||
{s.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+25
-16
@@ -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 (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width={size}
|
||||
height={size}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.6"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
className={`ico ${className}`.trim()}
|
||||
dangerouslySetInnerHTML={{ __html: paths[name] || paths.dashboard }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+18
-15
@@ -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 (
|
||||
<div className={`log-row log-${levelKind(entry.level)}`}>
|
||||
<span className="log-time mono">{shortTime(entry.time)}</span>
|
||||
<span className="log-level">{(entry.level || "info").toUpperCase()}</span>
|
||||
<span className="log-body">
|
||||
<span className="log-msg">{entry.message || entry.msg || ""}</span>
|
||||
{Object.entries(fields).map(([k, v]) => (
|
||||
<span className="log-field" key={k}>
|
||||
<span className="log-field-key">{k}</span>
|
||||
{String(fmtValue(v))}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+39
-28
@@ -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 (
|
||||
<div className="card stat">
|
||||
<div className="stat-head">
|
||||
<span className="stat-label">{label}</span>
|
||||
{dir ? (
|
||||
<span className={`stat-trend ${good ? "up" : "down"}`}>
|
||||
<Icon name={dir === "up" ? "trendUp" : "trendDown"} size={13} />
|
||||
{`${Math.abs(trend).toFixed(1)}%`}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="stat-value">
|
||||
{value}
|
||||
{unit ? <span className="stat-unit">{unit}</span> : null}
|
||||
</div>
|
||||
{compare ? <div className="stat-compare">{compare}</div> : null}
|
||||
{series.length > 1 ? <Sparkline series={series} stroke={good === false ? "var(--danger)" : "var(--ok)"} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 =
|
||||
`<polyline points="${points}" fill="none" stroke="${stroke}" stroke-width="1.5" ` +
|
||||
`stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>`;
|
||||
return svg;
|
||||
return (
|
||||
<svg className="spark" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" aria-hidden="true">
|
||||
<polyline
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke={stroke}
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
vector-effect="non-scaling-stroke"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
/**
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+4
-32
@@ -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 <div ref={ref} style={{ display: "contents" }} />;
|
||||
}
|
||||
|
||||
function MarkdownView({ text }) {
|
||||
const ref = useRef(null);
|
||||
useEffect(() => {
|
||||
if (ref.current) {
|
||||
ref.current.replaceChildren(renderMarkdown(text || ""));
|
||||
}
|
||||
}, [text]);
|
||||
return <div ref={ref} style={{ display: "contents" }} />;
|
||||
}
|
||||
|
||||
export function ChatApp() {
|
||||
const [sessions, setSessions] = useState([]);
|
||||
const [currentSession, setCurrentSession] = useState("");
|
||||
@@ -879,7 +858,7 @@ export function ChatApp() {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<MarkdownView text={text} />
|
||||
<ChatMarkdown text={text} />
|
||||
</Fragment>
|
||||
) : (
|
||||
<div className="chat-bubble-text">{text}</div>
|
||||
@@ -934,7 +913,7 @@ export function ChatApp() {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<MarkdownView text={streamingTurn.text || "…"} />
|
||||
<ChatMarkdown text={streamingTurn.text || "…"} />
|
||||
{streamingTurn.isError && (
|
||||
<button
|
||||
className="btn chat-retry"
|
||||
@@ -1018,10 +997,3 @@ export function ChatApp() {
|
||||
export function ChatPage() {
|
||||
return <ChatApp />;
|
||||
}
|
||||
|
||||
export function chatPage() {
|
||||
const container = document.createElement("div");
|
||||
container.className = "chat-page";
|
||||
render(<ChatApp />, container);
|
||||
return container;
|
||||
}
|
||||
+100
-35
@@ -1,59 +1,94 @@
|
||||
import { el } from "../base/dom.jsx";
|
||||
import { h } from "preact";
|
||||
|
||||
/**
|
||||
* Chat markdown.
|
||||
*
|
||||
* Telegram-style rich blocks -- headings, lists, quotes, fenced code, tables,
|
||||
* inline emphasis/links/images -- rendered as semantic HTML. It is a
|
||||
* component rather than a DOM builder so a streamed reply can be diffed: the
|
||||
* transcript re-renders on every frame, and diffing is what stops the whole
|
||||
* bubble being rebuilt each time the answer grows.
|
||||
*/
|
||||
|
||||
const INLINE =
|
||||
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
|
||||
|
||||
// inlineMarkdown returns the children of one line: plain text and the element
|
||||
// each matched span becomes, in order.
|
||||
function inlineMarkdown(text) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const pattern = /(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
|
||||
const children = [];
|
||||
let cursor = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > cursor) fragment.append(document.createTextNode(text.slice(cursor, match.index)));
|
||||
let key = 0;
|
||||
for (const match of String(text).matchAll(INLINE)) {
|
||||
if (match.index > cursor) children.push(text.slice(cursor, match.index));
|
||||
const value = match[0];
|
||||
if (value.startsWith("![")) {
|
||||
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
|
||||
if (img) {
|
||||
fragment.append(el("img.chat-media-img", {
|
||||
src: img[2],
|
||||
alt: img[1] || "Image",
|
||||
loading: "lazy",
|
||||
}));
|
||||
children.push(
|
||||
<img className="chat-media-img" src={img[2]} alt={img[1] || "Image"} loading="lazy" key={key++} />,
|
||||
);
|
||||
}
|
||||
} else if (value.startsWith("~~")) fragment.append(el("del", value.slice(2, -2)));
|
||||
else if (value.startsWith("**") || value.startsWith("__")) fragment.append(el("strong", value.slice(2, -2)));
|
||||
else if (value.startsWith("`")) fragment.append(el("code", value.slice(1, -1)));
|
||||
else if (value.startsWith("[")) {
|
||||
} else if (value.startsWith("~~")) {
|
||||
children.push(<del key={key++}>{value.slice(2, -2)}</del>);
|
||||
} else if (value.startsWith("**") || value.startsWith("__")) {
|
||||
children.push(<strong key={key++}>{value.slice(2, -2)}</strong>);
|
||||
} else if (value.startsWith("`")) {
|
||||
children.push(<code key={key++}>{value.slice(1, -1)}</code>);
|
||||
} else if (value.startsWith("[")) {
|
||||
const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);
|
||||
fragment.append(el("a", { href: link[2], target: "_blank", rel: "noreferrer" }, link[1]));
|
||||
} else fragment.append(el("em", value.slice(1, -1)));
|
||||
if (link) {
|
||||
children.push(
|
||||
<a href={link[2]} target="_blank" rel="noreferrer" key={key++}>
|
||||
{link[1]}
|
||||
</a>,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
children.push(<em key={key++}>{value.slice(1, -1)}</em>);
|
||||
}
|
||||
cursor = match.index + value.length;
|
||||
}
|
||||
if (cursor < text.length) fragment.append(document.createTextNode(text.slice(cursor)));
|
||||
return fragment;
|
||||
if (cursor < text.length) children.push(text.slice(cursor));
|
||||
return children;
|
||||
}
|
||||
|
||||
export function renderMarkdown(text) {
|
||||
const root = el("div.chat-bubble-text");
|
||||
export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
|
||||
const blocks = [];
|
||||
const lines = String(text || "").split("\n");
|
||||
let paragraph = [];
|
||||
let list = null;
|
||||
let code = null;
|
||||
let key = 0;
|
||||
|
||||
const flushParagraph = () => {
|
||||
if (paragraph.length) {
|
||||
root.append(el("p", inlineMarkdown(paragraph.join(" "))));
|
||||
blocks.push(<p key={key++}>{inlineMarkdown(paragraph.join(" "))}</p>);
|
||||
paragraph = [];
|
||||
}
|
||||
};
|
||||
const flushList = () => {
|
||||
if (list) root.append(list);
|
||||
if (!list) return;
|
||||
const items = list.items.map((item, i) => <li key={i}>{inlineMarkdown(item)}</li>);
|
||||
blocks.push(list.tag === "ol" ? <ol key={key++}>{items}</ol> : <ul key={key++}>{items}</ul>);
|
||||
list = null;
|
||||
};
|
||||
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
if (line.startsWith("```")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) {
|
||||
root.append(el("pre", el("code", code.join("\n"))));
|
||||
blocks.push(
|
||||
<pre key={key++}>
|
||||
<code>{code.join("\n")}</code>
|
||||
</pre>,
|
||||
);
|
||||
code = null;
|
||||
} else code = [];
|
||||
} else {
|
||||
code = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (code) {
|
||||
@@ -62,7 +97,12 @@ export function renderMarkdown(text) {
|
||||
}
|
||||
const headerCells = tableCells(line);
|
||||
const separatorCells = index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
|
||||
if (headerCells && separatorCells && isTableSeparator(separatorCells) && headerCells.length === separatorCells.length) {
|
||||
if (
|
||||
headerCells &&
|
||||
separatorCells &&
|
||||
isTableSeparator(separatorCells) &&
|
||||
headerCells.length === separatorCells.length
|
||||
) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
const rows = [];
|
||||
@@ -74,9 +114,26 @@ export function renderMarkdown(text) {
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
const body = el("tbody");
|
||||
for (const row of rows) body.append(el("tr", ...row.map((cell) => el("td", inlineMarkdown(cell)))));
|
||||
root.append(el("table", el("thead", el("tr", ...headerCells.map((cell) => el("th", inlineMarkdown(cell))))), body));
|
||||
blocks.push(
|
||||
<table key={key++}>
|
||||
<thead>
|
||||
<tr>
|
||||
{headerCells.map((cell, i) => (
|
||||
<th key={i}>{inlineMarkdown(cell)}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, r) => (
|
||||
<tr key={r}>
|
||||
{row.map((cell, c) => (
|
||||
<td key={c}>{inlineMarkdown(cell)}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!line.trim()) {
|
||||
@@ -88,7 +145,8 @@ export function renderMarkdown(text) {
|
||||
if (heading) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el(`h${heading[1].length}`, inlineMarkdown(heading[2])));
|
||||
const Tag = `h${heading[1].length}`;
|
||||
blocks.push(<Tag key={key++}>{inlineMarkdown(heading[2])}</Tag>);
|
||||
continue;
|
||||
}
|
||||
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
|
||||
@@ -96,25 +154,32 @@ export function renderMarkdown(text) {
|
||||
if (bullet || ordered) {
|
||||
flushParagraph();
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
if (!list || list.tagName.toLowerCase() !== tag) {
|
||||
if (!list || list.tag !== tag) {
|
||||
flushList();
|
||||
list = el(tag);
|
||||
list = { tag, items: [] };
|
||||
}
|
||||
list.append(el("li", inlineMarkdown((bullet || ordered)[1])));
|
||||
list.items.push((bullet || ordered)[1]);
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(">")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el("blockquote", inlineMarkdown(line.replace(/^>\s?/, ""))));
|
||||
blocks.push(<blockquote key={key++}>{inlineMarkdown(line.replace(/^>\s?/, ""))}</blockquote>);
|
||||
continue;
|
||||
}
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) root.append(el("pre", el("code", code.join("\n"))));
|
||||
return root;
|
||||
if (code) {
|
||||
blocks.push(
|
||||
<pre key={key++}>
|
||||
<code>{code.join("\n")}</code>
|
||||
</pre>,
|
||||
);
|
||||
}
|
||||
|
||||
return <div className={className}>{blocks}</div>;
|
||||
}
|
||||
|
||||
function tableCells(line) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { h, Fragment } from "preact";
|
||||
import { useState, useEffect } from "preact/hooks";
|
||||
import "./curators.css";
|
||||
import { api } from "../base/api.jsx";
|
||||
import { ago } from "../base/dom.jsx";
|
||||
import { ago } from "../base/format.jsx";
|
||||
import { Pill } from "../base/pill.jsx";
|
||||
|
||||
function Empty({ title, detail }) {
|
||||
|
||||
@@ -2,41 +2,15 @@ import { h, Fragment } from "preact";
|
||||
import { useState, useEffect, useRef } from "preact/hooks";
|
||||
import "./dashboard.css";
|
||||
import { api, subscribeEvents } from "../base/api.jsx";
|
||||
import { ago, compact, statusKind } from "../base/dom.jsx";
|
||||
import { statTile } from "../base/statTile.jsx";
|
||||
import { gauge, segmentBar } from "../base/gauge.jsx";
|
||||
import { icon } from "../base/icons.jsx";
|
||||
import { ago, compact } from "../base/format.jsx";
|
||||
import { statusKind } from "../base/task-meta.jsx";
|
||||
import { StatTile } from "../base/statTile.jsx";
|
||||
import { Gauge, SegmentBar } from "../base/gauge.jsx";
|
||||
import { Icon } from "../base/icons.jsx";
|
||||
import { Pill } from "../base/pill.jsx";
|
||||
import { dismissSetupComplete, setupPanelState } from "./setup-preference.jsx";
|
||||
import { dashboardTaskTargets } from "./task-targets.jsx";
|
||||
|
||||
// Preact wrapper for base DOM components that still use `el()`
|
||||
function DOMWrap({ node }) {
|
||||
const ref = useRef();
|
||||
useEffect(() => {
|
||||
if (ref.current && node) {
|
||||
ref.current.replaceChildren(node);
|
||||
}
|
||||
}, [node]);
|
||||
return <div ref={ref} style={{ display: "contents" }} />;
|
||||
}
|
||||
|
||||
function StatTile(props) {
|
||||
return <DOMWrap node={statTile(props)} />;
|
||||
}
|
||||
|
||||
function Gauge(props) {
|
||||
return <DOMWrap node={gauge(props)} />;
|
||||
}
|
||||
|
||||
function SegmentBar({ segments }) {
|
||||
return <DOMWrap node={segmentBar(segments)} />;
|
||||
}
|
||||
|
||||
function Icon({ name, opts }) {
|
||||
return <DOMWrap node={icon(name, opts)} />;
|
||||
}
|
||||
|
||||
function Empty({ title, detail }) {
|
||||
return (
|
||||
<div className="empty">
|
||||
@@ -138,7 +112,7 @@ function DashboardApp() {
|
||||
if (error) {
|
||||
actions = (
|
||||
<button className="btn btn-primary" onClick={load}>
|
||||
<Icon name="refresh" opts={{ size: 15 }} /> Retry
|
||||
<Icon name="refresh" size={15} /> Retry
|
||||
</button>
|
||||
);
|
||||
} else if (tasks !== null) {
|
||||
@@ -149,19 +123,19 @@ function DashboardApp() {
|
||||
<Fragment>
|
||||
{blocked > 0 && (
|
||||
<a className="btn btn-attention" href={targets.attention.href}>
|
||||
<Icon name="tasks" opts={{ size: 15 }} /> {blocked} need{blocked === 1 ? "s" : ""} you
|
||||
<Icon name="tasks" size={15} /> {blocked} need{blocked === 1 ? "s" : ""} you
|
||||
</a>
|
||||
)}
|
||||
{running > 0 && (
|
||||
<a className="btn" href={targets.running.href}>
|
||||
<Icon name="workflows" opts={{ size: 15 }} /> {running} running
|
||||
<Icon name="workflows" size={15} /> {running} running
|
||||
</a>
|
||||
)}
|
||||
<a className="btn" href="#/logs">
|
||||
<Icon name="logs" opts={{ size: 15 }} /> Logs
|
||||
<Icon name="logs" size={15} /> Logs
|
||||
</a>
|
||||
<button className="btn btn-primary" onClick={load}>
|
||||
<Icon name="refresh" opts={{ size: 15 }} /> Refresh
|
||||
<Icon name="refresh" size={15} /> Refresh
|
||||
</button>
|
||||
</Fragment>
|
||||
);
|
||||
@@ -237,7 +211,7 @@ function DashboardApp() {
|
||||
<ul className="setup-list">
|
||||
{setup.steps.map((step, i) => (
|
||||
<li key={i} className={`setup-step ${step.done ? "done" : ""}`}>
|
||||
<span className="setup-check">{step.done ? <Icon name="check" opts={{ size: 12 }} /> : ""}</span>
|
||||
<span className="setup-check">{step.done ? <Icon name="check" size={12} /> : ""}</span>
|
||||
<div>
|
||||
<div className="setup-step-title">{step.title}</div>
|
||||
{step.detail && <div className="setup-step-detail">{step.detail}</div>}
|
||||
@@ -256,7 +230,7 @@ function DashboardApp() {
|
||||
<p className="card-sub">Archie is configured and ready to work.</p>
|
||||
</div>
|
||||
<div className="setup-complete-actions">
|
||||
<span className="setup-pct"><Icon name="check" opts={{ size: 16 }} /></span>
|
||||
<span className="setup-pct"><Icon name="check" size={16} /></span>
|
||||
<button
|
||||
className="icon-btn setup-dismiss"
|
||||
type="button"
|
||||
|
||||
+1
-41
@@ -2,7 +2,7 @@ import { h } from "preact";
|
||||
import { useState, useEffect, useRef, useMemo } from "preact/hooks";
|
||||
import "./logs.css";
|
||||
import { api, subscribeLogs } from "../base/api.jsx";
|
||||
import { LOG_LEVELS } from "../base/log-row.jsx";
|
||||
import { LOG_LEVELS, LogRow } from "../base/log-row.jsx";
|
||||
import { Pill } from "../base/pill.jsx";
|
||||
|
||||
function Empty({ title, detail }) {
|
||||
@@ -14,46 +14,6 @@ function Empty({ title, detail }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function levelKind(level) {
|
||||
switch ((level || "").toUpperCase()) {
|
||||
case "ERROR": return "danger";
|
||||
case "WARN": return "warn";
|
||||
case "DEBUG": return "idle";
|
||||
default: return "info";
|
||||
}
|
||||
}
|
||||
|
||||
export function fmtValue(v) {
|
||||
if (v == null) return "";
|
||||
return typeof v === "object" ? JSON.stringify(v) : v;
|
||||
}
|
||||
|
||||
export function shortTime(value) {
|
||||
const d = value instanceof Date ? value : new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return "--:--:--";
|
||||
return d.toTimeString().slice(0, 8);
|
||||
}
|
||||
|
||||
function LogRow({ entry }) {
|
||||
const fields = entry.fields || {};
|
||||
return (
|
||||
<div className={`log-row log-${levelKind(entry.level)}`}>
|
||||
<span className="log-time mono">{shortTime(entry.time)}</span>
|
||||
<span className="log-level">{(entry.level || "info").toUpperCase()}</span>
|
||||
<span className="log-body">
|
||||
<span className="log-msg">{entry.message || entry.msg || ""}</span>
|
||||
{Object.entries(fields).map(([k, v]) => (
|
||||
<span className="log-field" key={k}>
|
||||
<span className="log-field-key">{k}</span>
|
||||
{String(fmtValue(v))}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function entryKey(entry) {
|
||||
return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`;
|
||||
}
|
||||
|
||||
+273
-224
@@ -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 (
|
||||
<header className="topbar">
|
||||
<div className="brand">
|
||||
<span className="brand-mark">A</span>
|
||||
Archie
|
||||
</div>
|
||||
<nav className="nav">
|
||||
{navEntries(hidden).map((route) => (
|
||||
<a
|
||||
className="nav-item"
|
||||
key={route.path}
|
||||
href={`#${route.path}`}
|
||||
aria-current={route.path === activePath ? "page" : undefined}
|
||||
aria-disabled={route.soon || undefined}
|
||||
title={route.soon ? "Coming soon" : undefined}
|
||||
onClick={(event) => {
|
||||
if (route.soon) event.preventDefault();
|
||||
else onNavigate(route.path);
|
||||
}}
|
||||
>
|
||||
<Icon name={route.icon} />
|
||||
<span className="nav-label">{route.label}</span>
|
||||
{route.soon ? <span className="nav-soon">soon</span> : null}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
<div className="topbar-end">
|
||||
<div className={`topbar-search${searchOpen ? " is-open" : ""}`}>
|
||||
<span className="topbar-search-icon" aria-hidden="true">
|
||||
<Icon name="search" size={15} />
|
||||
</span>
|
||||
<button
|
||||
className="icon-btn mobile-search-toggle"
|
||||
type="button"
|
||||
aria-label="Open Jump to navigation"
|
||||
aria-expanded={searchOpen ? "true" : "false"}
|
||||
onClick={() => setSearchOpen(true)}
|
||||
>
|
||||
<Icon name="search" size={15} />
|
||||
</button>
|
||||
<input
|
||||
type="search"
|
||||
placeholder="Jump to…"
|
||||
aria-label="Jump to a section"
|
||||
onKeyDown={onSearchKeyDown}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
className="icon-btn icon-btn-chat"
|
||||
aria-label="Open chat"
|
||||
title="Chat with Archie"
|
||||
aria-expanded={chatOpen ? "true" : "false"}
|
||||
onClick={() => onToggleChat()}
|
||||
>
|
||||
<Icon name="chat" />
|
||||
</button>
|
||||
<button className="icon-btn" title="Documentation" aria-label="Documentation">
|
||||
<Icon name="help" />
|
||||
</button>
|
||||
<button
|
||||
className="icon-btn"
|
||||
title="Toggle light and dark"
|
||||
aria-label="Toggle light and dark"
|
||||
onClick={onToggleTheme}
|
||||
>
|
||||
<Icon name={theme === "dark" ? "moon" : "sun"} />
|
||||
</button>
|
||||
<div className="avatar" title="Signed in locally">
|
||||
A
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<aside className={`chat-drawer${open ? " is-open" : ""}`} aria-label="Chat with Archie">
|
||||
<div className="chat-drawer-panel">
|
||||
<div className="chat-drawer-head">
|
||||
<strong>Archie</strong>
|
||||
<button className="icon-btn chat-drawer-close" aria-label="Close chat" title="Close chat" onClick={onClose}>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<ChatPage />
|
||||
</div>
|
||||
<div className="chat-scrim" onClick={onClose} />
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function ComingSoon({ label }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="page-head">
|
||||
<div>
|
||||
<h1 className="page-title">{label}</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="empty">
|
||||
<div className="empty-title">{`${label} is not built yet`}</div>
|
||||
<div>This section is next up. Nothing is broken.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// RouteView gives the router a keyed boundary. A page is a function of its
|
||||
// query and its path parameters, and two ids on the same parameterised route
|
||||
// must be two instances: without the key the second id diffs the first one in
|
||||
// place and the operator's open tab from the previous task stays open on the
|
||||
// next (W11).
|
||||
function RouteView({ view, search, params }) {
|
||||
return view(search, params);
|
||||
}
|
||||
|
||||
// Routing is wired once, at import, and pages render into one long-lived outlet
|
||||
// rather than as children of App.
|
||||
//
|
||||
// The listeners cannot live in an effect: a page installs its own
|
||||
// hash-sensitive state as it mounts, and the outgoing page has to be gone in
|
||||
// the same tick the hash changes. Task detail writes the tab selection back
|
||||
// with replaceState as it settles; if it is still mounted when the hashchange
|
||||
// lands, it canonicalises the URL back to its own route and the navigation is
|
||||
// silently lost. App publishes its outlet and its two navigation-owned pieces
|
||||
// of chrome through a callback ref, which runs at commit time -- before any
|
||||
// page effect can run.
|
||||
let outlet = null;
|
||||
let chrome = null;
|
||||
|
||||
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 ? (
|
||||
<RouteView
|
||||
key={`${route.path}|${Object.values(params).join("/")}`}
|
||||
view={route.view}
|
||||
search={new URLSearchParams(query)}
|
||||
params={params}
|
||||
/>
|
||||
) : (
|
||||
<ComingSoon label={route.label} />
|
||||
),
|
||||
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 (
|
||||
<div className="shell">
|
||||
<Topbar
|
||||
activePath={active}
|
||||
hidden={hidden}
|
||||
onNavigate={navigate}
|
||||
chatOpen={chatOpen}
|
||||
onToggleChat={() => setChatOpen((open) => !open)}
|
||||
theme={theme}
|
||||
onToggleTheme={() => setTheme((current) => (current === "dark" ? "light" : "dark"))}
|
||||
/>
|
||||
<main className="main" ref={publish} />
|
||||
<ChatDrawer open={chatOpen} onClose={() => setChatOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
start();
|
||||
applyTheme(currentTheme());
|
||||
render(<App />, document.getElementById("app"));
|
||||
show(location.hash.slice(1) || "/");
|
||||
@@ -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`.
|
||||
//
|
||||
|
||||
@@ -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 <div ref={ref} style={{ display: "contents" }} />;
|
||||
}
|
||||
|
||||
// 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({
|
||||
<>
|
||||
<div className="log-list task-log-list">
|
||||
{entries.map((entry, i) => (
|
||||
<LogRowNode key={i} entry={entry} />
|
||||
<LogRow key={i} entry={entry} />
|
||||
))}
|
||||
</div>
|
||||
{footer}
|
||||
|
||||
+6
-15
@@ -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 <div ref={ref} style={{ display: 'contents' }} />;
|
||||
}
|
||||
|
||||
|
||||
// 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 (
|
||||
<div className="grid grid-4 task-summary">
|
||||
<StatTileNode
|
||||
<StatTile
|
||||
label="Total tasks"
|
||||
value={total}
|
||||
compare={total ? "Everything archied has ever picked up" : "No tasks yet"}
|
||||
/>
|
||||
<StatTileNode
|
||||
<StatTile
|
||||
label="Working now"
|
||||
value={working}
|
||||
compare={total ? `${working} of ${total} in progress` : "Nothing running"}
|
||||
/>
|
||||
<StatTileNode
|
||||
<StatTile
|
||||
label="Needs you"
|
||||
value={needsYou}
|
||||
compare={needsYou ? "Parked or awaiting a reply" : "Nothing is blocked"}
|
||||
goodDirection="down"
|
||||
/>
|
||||
<StatTileNode
|
||||
<StatTile
|
||||
label="Delivered"
|
||||
value={delivered}
|
||||
compare={total ? `${Math.round((delivered / total) * 100)}% of all tasks` : "No tasks yet"}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { render, cleanup } from "@testing-library/preact";
|
||||
import { ChatApp, chatPage } from "../src/chat/chat.jsx";
|
||||
import { ChatApp } from "../src/chat/chat.jsx";
|
||||
|
||||
test("ChatApp renders structure with topbar, sidebar, transcript and composer", () => {
|
||||
const { container, unmount } = render(<ChatApp />);
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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(
|
||||
<ChatMarkdown
|
||||
text={
|
||||
"# 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 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: ");
|
||||
const img = rendered.querySelector("img");
|
||||
const { container } = render(
|
||||
<ChatMarkdown text="Here is the generated image: " />,
|
||||
);
|
||||
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(<ChatMarkdown text={"- one\n- two"} />);
|
||||
assert.equal(container.querySelectorAll("ul").length, 1);
|
||||
rerender(<ChatMarkdown text={"- one\n- two\n- three"} />);
|
||||
assert.equal(container.querySelectorAll("ul").length, 1);
|
||||
assert.equal(container.querySelector("ul").children.length, 3);
|
||||
|
||||
rerender(<ChatMarkdown text={"- one\n\n1. first\n2. second"} />);
|
||||
assert.equal(container.querySelectorAll("ul").length, 1);
|
||||
assert.equal(container.querySelectorAll("ol").length, 1);
|
||||
cleanup();
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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/);
|
||||
});
|
||||
+30
-16
@@ -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(
|
||||
<LogRow
|
||||
entry={{
|
||||
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",
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
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(<LogRow entry={{ level: "ERROR", msg: "boom" }} />);
|
||||
assert.match(container.querySelector(".log-row").className, /log-danger/);
|
||||
assert.equal(container.querySelector(".log-level").textContent, "ERROR");
|
||||
cleanup();
|
||||
});
|
||||
+3
-5
@@ -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("<!doctype html><html><body></body></html>", { url: "http://localhost/" });
|
||||
const { window } = dom;
|
||||
|
||||
|
||||
@@ -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 && <div>` 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(<StatTile label="Working now" value={0} compare="Nothing running" />);
|
||||
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(<StatTile label="Tokens used" value="" compare="Across 14 days" />);
|
||||
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(<StatTile label="Tokens used" value="2.4M" compare="Across 14 days" />);
|
||||
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(<StatTile label="Delivered" value={3} compare="3% of all tasks" />);
|
||||
assert.equal(plain.container.querySelector(".stat-trend"), null);
|
||||
cleanup();
|
||||
const trended = render(<StatTile label="Tokens used" value={5} trend={12.5} compare="x" goodDirection="down" />);
|
||||
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(<StatTile label="Delivered" value={3} compare="x" series={[1]} />);
|
||||
assert.equal(flat.container.querySelector("svg.spark"), null);
|
||||
cleanup();
|
||||
const shaped = render(<StatTile label="Delivered" value={3} compare="x" series={[1, 4, 2]} />);
|
||||
assert.ok(shaped.container.querySelector("svg.spark polyline"));
|
||||
cleanup();
|
||||
});
|
||||
Reference in new issue
Block a user