test(webui): migrate UI tests to Preact testing library and fix tasks Fragment render
Use @testing-library/preact rendered under jsdom (registered via test/register.js) so the Post-Preact .jsx components and pages are exercised through the real automatic-runtime render path instead of the legacy el() DOM-helper API the tests were written against. - Add jsdom + @testing-library/preact dev deps and a jsdom globals setup in ui/test/register.js (window/document/navigator/getComputedStyle/...). - Switch the .jsx loader hook to the automatic JSX runtime to match @preact/preset-vite, so source files that shadow h (mapping-editor) and Fragment/children arrays work exactly as in the Vite build. - Migrate captures, config-row, mappings, settings-update-status, task-logs, settings-lifecycle, settings-schema, tasks-actions and the chat-app tests to render the Preact components and query the DOM via testing-library. - Fix a real render bug in tasks.jsx: <h.Fragment> is not rendered by the automatic runtime (rows came out as [object Object]); use the imported <Fragment> instead, matching the other migrated modules.
This commit is contained in:
1 parent
4a329fb43d
commit
5965f3158a
15 files changed
+1984
-202
No files matched your search
Vendored
+7
-7
@@ -1,16 +1,16 @@
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e=globalThis.crypto){if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(typeof e?.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return`${n.slice(0,4).join(``)}-${n.slice(4,6).join(``)}-${n.slice(6,8).join(``)}-${n.slice(8,10).join(``)}-${n.slice(10).join(``)}`}async function t(e){let t=await fetch(e,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(15e3)});if(t.status===401)throw new i(`unauthorised`,401);if(!t.ok)throw new i(`${t.status} ${t.statusText}`,t.status);return t.json()}function n(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function r(e){try{let t=(await e.text()).trim();if(t)return t.split(`
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var i=class extends Error{constructor(e,t){super(e),this.status=t}},a={summary:()=>t(`/api/summary`),tasks:()=>t(`/api/tasks`),taskMeta:()=>t(`/api/task-meta`),task:e=>t(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},setup:()=>t(`/api/setup`),workflows:()=>t(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},skills:()=>t(`/api/skills`),channels:()=>t(`/api/channels`),curators:()=>t(`/api/curators`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},config:()=>t(`/api/config`),version:()=>t(`/api/version`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},configRepoUpdate:async(e,t,n,a)=>{let o=await fetch(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({field:n,value:a}),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new i(await r(o),o.status);return o.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},logs:e=>t(`/api/logs`+n(e)),taskLogs:(e,r)=>t(`/api/tasks/${e}/logs`+n(r)),captures:e=>t(`/api/captures`+n({limit:e})),mappings:()=>t(`/api/mappings`),mappingCreate:async e=>{let t=await fetch(`/api/mappings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},mappingUpdate:async(e,t)=>{let n=await fetch(`/api/mappings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},mappingDelete:async e=>{let t=await fetch(`/api/mappings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status)},mappingPreview:async(e,t)=>{let n=await fetch(`/api/mappings/preview`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({capture_id:e,fields:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},memory:()=>t(`/api/memory`),chatSessions:()=>t(`/api/chat/sessions`),chatMessages:e=>t(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>t(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},chatMessage:async(t,n)=>{let a=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:t,source_id:e(),text:n,page:location.hash.slice(1)||`/`}),signal:AbortSignal.timeout(15e3)});if(!a.ok)throw new i(await r(a),a.status);return a.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},chatUpdate:()=>t(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/cLine truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var i=class extends Error{constructor(e,t){super(e),this.status=t}},a={summary:()=>t(`/api/summary`),tasks:()=>t(`/api/tasks`),taskMeta:()=>t(`/api/task-meta`),task:e=>t(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},setup:()=>t(`/api/setup`),workflows:()=>t(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},skills:()=>t(`/api/skills`),channels:()=>t(`/api/channels`),curators:()=>t(`/api/curators`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},config:()=>t(`/api/config`),version:()=>t(`/api/version`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},configRepoUpdate:async(e,t,n,a)=>{let o=await fetch(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({field:n,value:a}),signal:AbortSignal.timeout(15e3)});if(!o.ok)throw new i(await r(o),o.status);return o.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},logs:e=>t(`/api/logs`+n(e)),taskLogs:(e,r)=>t(`/api/tasks/${e}/logs`+n(r)),captures:e=>t(`/api/captures`+n({limit:e})),mappings:()=>t(`/api/mappings`),mappingCreate:async e=>{let t=await fetch(`/api/mappings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},mappingUpdate:async(e,t)=>{let n=await fetch(`/api/mappings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},mappingDelete:async e=>{let t=await fetch(`/api/mappings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status)},mappingPreview:async(e,t)=>{let n=await fetch(`/api/mappings/preview`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({capture_id:e,fields:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},memory:()=>t(`/api/memory`),chatSessions:()=>t(`/api/chat/sessions`),chatMessages:e=>t(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>t(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},chatMessage:async(t,n)=>{let a=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:t,source_id:e(),text:n,page:location.hash.slice(1)||`/`}),signal:AbortSignal.timeout(15e3)});if(!a.ok)throw new i(await r(a),a.status);return a.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new i(await r(n),n.status);return n.json()},chatUpdate:()=>t(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new i(await r(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/cLine 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"/>`,y(`div.gauge-wrap`,l,y(`div.gauge-center`,y(`div.gauge-pct`,`${Math.round(r)}%`),y(`div.gauge-label`,t)))}function Ze(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return y(`div`,y(`div.segbar`,...e.filter(e=>e.value>0).map(e=>y(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),y(`div.segbar-legend`,...e.map(e=>y(`span.segbar-key`,y(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var Qe=`archie.setup-complete.dismissed.v1`;function $e(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?.(Qe),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function et(e=globalThis.localStorage){e?.setItem?.(Qe,`1`)}var tt=new Set([`waiting_human`,`parked`]);function nt(e=[]){let t=e.filter(e=>tt.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`}}}var rt=0;Array.isArray;function Z(e,t,n,r,i,a){t||={};var o,s,c=t;if(`ref`in c)for(s in c={},t)s==`ref`?o=t[s]:c[s]=t[s];var l={type:e,props:c,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--rt,__i:-1,__u:0,__source:i,__self:a};if(typeof e==`function`&&(o=e.defaultProps))for(s in o)c[s]===void 0&&(c[s]=o[s]);return k.vnode&&k.vnode(l),l}function it({node:e}){let t=X();return Y(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function at(e){return Z(it,{node:Je(e)})}function ot(e){return Z(it,{node:Xe(e)})}function st({segments:e}){return Z(it,{node:Ze(e)})}function ct({name:e,opts:t}){return Z(it,{node:D(e,t)})}function lt({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function ut({text:e,kind:t=`idle`}){return Z(`span`,{className:`pill pill-${t}`,children:e})}function dt(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function ft(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function pt(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function mt(){let[e,t]=J([]),[n,r]=J(`connecting`),[i,s]=J(`idle`),[c,l]=J(new Map),[u,d]=J(null),[f,p]=J(null),[m,h]=J(null),[g,_]=J(null),[v,y]=J(null),[,b]=J(!1),x=async()=>{y(null);try{let[e,t,n,r]=await Promise.all([a.summary(),a.setup().catch(()=>null),a.workflows().catch(()=>null),a.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);l(i),d(e),p(t),h(n),_(r)}catch(e){y(String(e.message||e))}};Y(()=>(x(),o(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),s(e===`live`?`ok`:`warn`)})),[]);let S=()=>{et(),b(e=>!e)},T=f?.operator?`${ft()}, ${f.operator}`:ft(),E=null;if(v)E=Z(`button`,{className:`btn btn-primary`,onClick:x,children:[Z(ct,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(g!==null){let e=nt(g),t=e.attention.count,n=e.running.count;E=Z(H,{children:[t>0&&Z(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[Z(ct,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&Z(`a`,{className:`btn`,href:e.running.href,children:[Z(ct,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),Z(`a`,{className:`btn`,href:`#/logs`,children:[Z(ct,{name:`logs`,opts:{size:15}}),` Logs`]}),Z(`button`,{className:`btn btn-primary`,onClick:x,children:[Z(ct,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let D=null;if(v)D=Z(`div`,{className:`card`,children:Z(lt,{title:`Cannot reach archied`,detail:v})});else if(u){let e=u?.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=u?.tokens_by_day||[];D=Z(H,{children:[Z(at,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),Z(at,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),Z(at,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),Z(at,{label:`Tokens used`,value:w(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:pt(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let O=null,k=$e(f),A=k.kind===`omit`||k.kind===`dismissed`;if(!A){let e=k.remaining;if(e.length){let t=Math.round((f.steps.length-e.length)/f.steps.length*100);O=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(sn,{text:un[e.status]||e.status,kind:dn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function pn({text:e,kind:t=`idle`}){return Z(`span`,{className:`pill pill-${t}`,children:e})}function Q({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function $({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 mn({origins:e}){return e?.length?Z($,{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(an,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):Z($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:Z(Q,{title:`Source provenance is unavailable.`})})}function hn(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function gn({data:e,error:t}){if(t)return Z($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:Z(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return Z($,{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??m(e.id),n=e.kind??h(e.id);return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,children:e.id}),Z(`span`,{className:`kv-value`,children:Z(pn,{text:t,kind:n})})]},e.id)})}):Z(Q,{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=hn(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(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function _n({r:e,field:t,onSaved:n}){let[r,i]=J(!1),[o,s]=J(null),[c,l]=J(!!e[t]);return Z(`td`,{children:[Z(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let o=r.target.checked;l(o),i(!0),s(null);try{await a.configRepoUpdate(e.owner,e.name,t,o),n?.()}catch(e){l(!o),s(String(e.message||e))}finally{i(!1)}},disabled:r}),o&&Z(`span`,{className:`kv-note is-error`,children:o})]})}function vn({r:e,field:t,onSaved:n}){let[r,i]=J(String(e[t]??0)),[o,s]=J(null),[c,l]=J(!1);return Z(`td`,{children:[Z(`input`,{className:`kv-input`,type:`text`,value:r,onChange:e=>i(e.target.value),onBlur:async()=>{let i=parseInt(r,10);if(Number.isNaN(i)){s(`Enter a whole number`);return}l(!0),s(null);try{await a.configRepoUpdate(e.owner,e.name,t,i),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})]})}function yn({repos:e,onSaved:t}){if(!e?.length)return Z($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:Z(Q,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let n=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return Z($,{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,r)=>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:n(e.gate)}),Z(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),Z(_n,{r:e,field:`allow_concurrent`,onSaved:t}),Z(vn
Line truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(y(`p`,er(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(y(`pre`,y(`code`,a.join(`
|
||||
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=nr(c),u=e+1<n.length?nr(n[e+1]):null;if(l&&u&&rr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=nr(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=y(`tbody`);for(let e of r)i.append(y(`tr`,...e.map(e=>y(`td`,er(e)))));t.append(y(`table`,y(`thead`,y(`tr`,...l.map(e=>y(`th`,er(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(y(`h${d[1].length}`,er(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=y(e)),i.append(y(`li`,er((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(y(`blockquote`,er(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(y(`pre`,y(`code`,a.join(`
|
||||
`)))),t}function nr(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 rr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var ir=`archie.web.chat.channel`;function ar(){let t=localStorage.getItem(ir);return t||(t=e(),localStorage.setItem(ir,t)),t}function or(t){return{text:t,sourceID:e()}}function sr(e){return{...e}}function cr(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?sr(e.turn):or(r),isRetry:n}}function lr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function ur(e){return e?.status===501?null:`Could not check for updates.`}function dr(){return location.hash.slice(1)||`/`}function fr({text:e}){let t=X(null);return Y(()=>{t.current&&t.current.replaceChildren(tr(e||``))},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function pr(){let[e,t]=J([]),[n,r]=J(``),[i,o]=J([]),[s,c]=J(``),[l,u]=J(`Ready`),[d,f]=J(!1),[p,m]=J({}),[h,g]=J(``),[_,v]=J(``),[y,b]=J(``),[x,S]=J([]),[C,w]=J([]),[T,E]=J(0),[D,O]=J(!1),[k,A]=J(null),[j,M]=J(null),[N,ee]=J(null),[P,te]=J(``),[F,ne]=J(``),[I,L]=J(null),R=X(null),z=X(null),B=X(null),re=X(null),ie=X(null),V=X(d);V.current=d,Y(()=>{R.current&&(R.current.scrollTop=R.current.scrollHeight)},[i,I]),Y(()=>{ue().catch(e=>{u(e.message||`Chat unavailable`)}),ae();let e=()=>{B.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),B.current?.abort()}},[]);async function ae(){try{let e=await a.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=ur(e);A(t?{error:t}:null)}}async function oe(){if(j)try{await a.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),u(`Update deferred`)}catch(e){u(e.message||`Could not defer update`)}}async function se(){if(j)try{u(`Installing…`);let e=await a.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),u(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){u(e.message||`Update install failed`)}}async function ce(){try{let e=await a.chatDangerous();ee(e)}catch(e){ee({error:e.message||`Dangerous actions unavailable`})}}async function U(e,t){if(t)try{await a.chatDangerousRequest(e,t),u(`Approval requested`),await ce()}catch(e){u(e.message||`Could not request action`)}}async function le(e,t){try{await a.chatDangerousDecision(e,t),u(t===`deny`?`Action denied`:`Action approved`),await ce()}catch(e){u(e.message||`Approval failed`)}}async function ue(){let e=await a.chatSessions(),r=e.sessions||[];t(r),m(e),g(e.active_persona||``);let i=e.providers||[],o=e.active_provider||i[0]||``;v(o),b(e.active_model||``);let s=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);S(s),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||p;r(e),o([]),L(null);let s=i.active_personas?.[e]||i.active_persona||``;g(s);try{await a.chatMessage(ar(),`/resume ${e}`);let[t,n]=await Promise.all([a.chatMessages(e),a.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});o(i)}catch(e){u(e.message||`Could not load session messages`)}}async function W(e){if(n)try{u(`Working…`);let t=await a.chatMessage(ar(),e);t.session_id&&r(t.session_id),u(t.reply||`Session updated`),await ue(),(t.session_id||n)&&await de(t.session_id||n),re.current&&(re.current.open=!1)}catch(e){u(e.message||`Session action failed`)}}function fe(e,t){let n=window.prompt(t);n?.trim()&&W(`${e} ${n.trim()}`)}function pe(e){let t=e.target.value;g(t),!(!n||!t)&&a.chatPersona(n,t).then(()=>{m(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),u(`Personality: ${t}`)}).catch(e=>{u(e.message||`Failed to set personality`)})}async function me(e){let t=e.target.value;if(v(t),t)try{let e=await a.chatMessage(ar(),`/model --provider ${t}`);u(e.reply||`Provider updated`),await ue()}catch(e){u(`Provider update failed: ${e.message||e}`)}}async function he(e){let t=e.target.value;if(b(t),t)try{let e=await a.chatMessage(ar(),`/model ${t}`);u(e.reply||`Model updated`),await ue()}catch(e){u(`Model update failed: ${e.message||e}`)}}function ge(){window.confirm(`Reload the Telegram chat adapter?`)&&(c(`/restart`),G({textOverride:`/restart`}))}function _e(){c(`/new`),G({textOverride:`/new`})}function ve(e){let t=e.target.value;c(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=x.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||!z.current)return;let n=z.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:
Line truncated
|
||||
class="gauge-value"/>`,y(`div.gauge-wrap`,l,y(`div.gauge-center`,y(`div.gauge-pct`,`${Math.round(r)}%`),y(`div.gauge-label`,t)))}function Xe(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return y(`div`,y(`div.segbar`,...e.filter(e=>e.value>0).map(e=>y(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),y(`div.segbar-legend`,...e.map(e=>y(`span.segbar-key`,y(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var Ze=`archie.setup-complete.dismissed.v1`;function Qe(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?.(Ze),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function $e(e=globalThis.localStorage){e?.setItem?.(Ze,`1`)}var et=new Set([`waiting_human`,`parked`]);function tt(e=[]){let t=e.filter(e=>et.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`}}}var nt=0;Array.isArray;function X(e,t,n,r,i,a){t||={};var o,s,c=t;if(`ref`in c)for(s in c={},t)s==`ref`?o=t[s]:c[s]=t[s];var l={type:e,props:c,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--nt,__i:-1,__u:0,__source:i,__self:a};if(typeof e==`function`&&(o=e.defaultProps))for(s in o)c[s]===void 0&&(c[s]=o[s]);return D.vnode&&D.vnode(l),l}function rt({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function it(e){return X(rt,{node:qe(e)})}function at(e){return X(rt,{node:Ye(e)})}function ot({segments:e}){return X(rt,{node:Xe(e)})}function Z({name:e,opts:t}){return X(rt,{node:T(e,t)})}function st({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function ct({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}function lt(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 ut(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function dt(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 ft(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,s]=q(`idle`),[c,l]=q(new Map),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[v,y]=q(null),[,b]=q(!1),x=async()=>{y(null);try{let[e,t,n,r]=await Promise.all([a.summary(),a.setup().catch(()=>null),a.workflows().catch(()=>null),a.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);l(i),d(e),p(t),h(n),_(r)}catch(e){y(String(e.message||e))}};J(()=>(x(),o(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),s(e===`live`?`ok`:`warn`)})),[]);let w=()=>{$e(),b(e=>!e)},T=f?.operator?`${ut()}, ${f.operator}`:ut(),E=null;if(v)E=X(`button`,{className:`btn btn-primary`,onClick:x,children:[X(Z,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(g!==null){let e=tt(g),t=e.attention.count,n=e.running.count;E=X(V,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(Z,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(Z,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(Z,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:x,children:[X(Z,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let D=null;if(v)D=X(`div`,{className:`card`,children:X(st,{title:`Cannot reach archied`,detail:v})});else if(u){let e=u?.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=u?.tokens_by_day||[];D=X(V,{children:[X(it,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(it,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(it,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(it,{label:`Tokens used`,value:C(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:dt(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let O=null,k=Qe(f),A=k.kind===`omit`||k.kind===`dismissed`;if(!A){let e=k.remaining;if(e.length){let t=Math.round((f.steps.length-e.length)/f.steps.length*100);O=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children:[X(`diLine 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(un,{text:pn[e.status]||e.status,kind:mn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function gn({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function _n({origins:e}){return e?.length?X($,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(cn,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function vn(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function yn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??m(e.id),n=e.kind??h(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(gn,{text:t,kind:n})})]},e.id)})}):X(Q,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=vn(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function bn({r:e,field:t,onSaved:n}){let[r,i]=q(!1),[o,s]=q(null),[c,l]=q(!!e[t]);return X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let o=r.target.checked;l(o),i(!0),s(null);try{await a.configRepoUpdate(e.owner,e.name,t,o),n?.()}catch(e){l(!o),s(String(e.message||e))}finally{i(!1)}},disabled:r}),o&&X(`span`,{className:`kv-note is-error`,children:o})]})}function xn({r:e,field:t,onSaved:n}){let[r,i]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!1);return X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:r,onChange:e=>i(e.target.value),onBlur:async()=>{let i=parseInt(r,10);if(Number.isNaN(i)){s(`Enter a whole number`);return}l(!0),s(null);try{await a.configRepoUpdate(e.owner,e.name,t,i),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})]})}function Sn({repos:e,onSaved:t}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let n=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X($,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,r)=>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:n(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(bn,{r:e,field:`allow_concurrent`,onSaved:t}),X(xn
Line truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(y(`p`,lr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(y(`pre`,y(`code`,a.join(`
|
||||
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=dr(c),u=e+1<n.length?dr(n[e+1]):null;if(l&&u&&fr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=dr(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=y(`tbody`);for(let e of r)i.append(y(`tr`,...e.map(e=>y(`td`,lr(e)))));t.append(y(`table`,y(`thead`,y(`tr`,...l.map(e=>y(`th`,lr(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(y(`h${d[1].length}`,lr(d[2])));continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tagName.toLowerCase()!==e)&&(s(),i=y(e)),i.append(y(`li`,lr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(y(`blockquote`,lr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(y(`pre`,y(`code`,a.join(`
|
||||
`)))),t}function dr(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function fr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var pr=`archie.web.chat.channel`;function mr(){let t=localStorage.getItem(pr);return t||(t=e(),localStorage.setItem(pr,t)),t}function hr(t){return{text:t,sourceID:e()}}function gr(e){return{...e}}function _r(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?gr(e.turn):hr(r),isRetry:n}}function vr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function yr(e){return e?.status===501?null:`Could not check for updates.`}function br(){return location.hash.slice(1)||`/`}function xr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(ur(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Sr(){let[e,t]=q([]),[n,r]=q(``),[i,o]=q([]),[s,c]=q(``),[l,u]=q(`Ready`),[d,f]=q(!1),[p,m]=q({}),[h,g]=q(``),[_,v]=q(``),[y,b]=q(``),[x,S]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,M]=q(null),[N,ee]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),L=Y(null),R=Y(null),z=Y(null),B=Y(null),ie=Y(null),ae=Y(d);ae.current=d,J(()=>{L.current&&(L.current.scrollTop=L.current.scrollHeight)},[i,F]),J(()=>{U().catch(e=>{u(e.message||`Chat unavailable`)}),oe();let e=()=>{z.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),z.current?.abort()}},[]);async function oe(){try{let e=await a.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=yr(e);A(t?{error:t}:null)}}async function se(){if(j)try{await a.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),u(`Update deferred`)}catch(e){u(e.message||`Could not defer update`)}}async function H(){if(j)try{u(`Installing…`);let e=await a.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),u(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){u(e.message||`Update install failed`)}}async function ce(){try{let e=await a.chatDangerous();ee(e)}catch(e){ee({error:e.message||`Dangerous actions unavailable`})}}async function le(e,t){if(t)try{await a.chatDangerousRequest(e,t),u(`Approval requested`),await ce()}catch(e){u(e.message||`Could not request action`)}}async function ue(e,t){try{await a.chatDangerousDecision(e,t),u(t===`deny`?`Action denied`:`Action approved`),await ce()}catch(e){u(e.message||`Approval failed`)}}async function U(){let e=await a.chatSessions(),r=e.sessions||[];t(r),m(e),g(e.active_persona||``);let i=e.providers||[],o=e.active_provider||i[0]||``;v(o),b(e.active_model||``);let s=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);S(s),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||p;r(e),o([]),I(null);let s=i.active_personas?.[e]||i.active_persona||``;g(s);try{await a.chatMessage(mr(),`/resume ${e}`);let[t,n]=await Promise.all([a.chatMessages(e),a.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});o(i)}catch(e){u(e.message||`Could not load session messages`)}}async function fe(e){if(n)try{u(`Working…`);let t=await a.chatMessage(mr(),e);t.session_id&&r(t.session_id),u(t.reply||`Session updated`),await U(),(t.session_id||n)&&await de(t.session_id||n),B.current&&(B.current.open=!1)}catch(e){u(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;g(t),!(!n||!t)&&a.chatPersona(n,t).then(()=>{m(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),u(`Personality: ${t}`)}).catch(e=>{u(e.message||`Failed to set personality`)})}async function he(e){let t=e.target.value;if(v(t),t)try{let e=await a.chatMessage(mr(),`/model --provider ${t}`);u(e.reply||`Provider updated`),await U()}catch(e){u(`Provider update failed: ${e.message||e}`)}}async function ge(e){let t=e.target.value;if(b(t),t)try{let e=await a.chatMessage(mr(),`/model ${t}`);u(e.reply||`Model updated`),await U()}catch(e){u(`Model update failed: ${e.message||e}`)}}function _e(){window.confirm(`Reload the Telegram chat adapter?`)&&(c(`/restart`),W({textOverride:`/restart`}))}function ve(){c(`/new`),W({textOverride:`/new`})}function ye(e){let t=e.target.value;c(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=x.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||!R.current)return;let n=R.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\
Line truncated
|
||||
|
||||
`);s=i.pop()||``;for(let e of i){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&r(n.session_id),n.type===`delta`&&(d+=n.text,L(e=>e?{...e,text:d}:null)),n.type===`tool`&&(l=[...l,n],L(e=>e?{...e,tools:l}:null)),n.type===`navigate`&&(l=[...l,n],L(e=>e?{...e,tools:l}:null)),n.type===`done`&&(p=!0,d||=n.text),n.type===`error`)throw Error(n.text)}if(t)break}if(!p)throw Error(`chat stream ended before completion`);o(e=>[...e,{from:`assistant`,text:d,tool_calls:l}]),L(null),u(`Ready`),await ue()}catch(e){if(e.name===`AbortError`&&!m)L({text:`Turn stopped.`,tools:l,isError:!1,turn:i,isRetry:a}),u(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;L({text:t,tools:l,isError:!0,turn:sr(i),isRetry:a}),u(`Error — retry available`)}}finally{clearTimeout(h),B.current=null,f(!1),z.current&&z.current.focus()}}function xe(){u(`Stopping…`),n&&a.chatCancel(n).catch(()=>{}),B.current?.abort()}let Se=p.models_by_provider||{},Ce=_&&Se[_]?Se[_]:p.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:l}),p.restart_available&&Z(`button`,{className:`btn`,type:`button`,onClick:ge,children:`Reload Telegram`}),Z(`button`,{className:`btn`,type:`button`,onClick:ae,children:`Check updates`}),Z(`select`,{className:`chat-select`,"aria-label":`Personality`,value:h,onChange:pe,children:[Z(`option`,{value:``,children:`Personality`}),(p.personas||[]).map(e=>Z(`option`,{value:e,children:e},e))]}),(p.providers||[]).length>0&&Z(`select`,{className:`chat-select`,"aria-label":`Provider`,value:_,onChange:me,children:[Z(`option`,{value:``,children:`Provider`}),(p.providers||[]).map(e=>Z(`option`,{value:e,children:e},e))]}),Z(`select`,{className:`chat-select`,"aria-label":`Model`,value:y,onChange:he,children:[Z(`option`,{value:``,children:`Model`}),Ce.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(H,{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.`})}),p.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:P,onChange:e=>te(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:()=>U(`rollback`,P),children:`Request rollback`})]}),Z(`div`,{children:[Z(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:F,onInput:e=>ne(e.target.value)}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>U(`stop`,F),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:()=>le(e.id,`approve`),children:`Approve`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>le(e.id,`permanent`),children:`Approve for 24h`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>le(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:_e,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:lr(e)}),Z(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):Z(`div`,{className:`chat-empty`,children:`Your conversations will
Line 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`&&(d+=n.text,I(e=>e?{...e,text:d}:null)),n.type===`tool`&&(l=[...l,n],I(e=>e?{...e,tools:l}:null)),n.type===`navigate`&&(l=[...l,n],I(e=>e?{...e,tools:l}:null)),n.type===`done`&&(p=!0,d||=n.text),n.type===`error`)throw Error(n.text)}if(t)break}if(!p)throw Error(`chat stream ended before completion`);o(e=>[...e,{from:`assistant`,text:d,tool_calls:l}]),I(null),u(`Ready`),await U()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:l,isError:!1,turn:i,isRetry:a}),u(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:l,isError:!0,turn:gr(i),isRetry:a}),u(`Error — retry available`)}}finally{clearTimeout(h),z.current=null,f(!1),R.current&&R.current.focus()}}function Se(){u(`Stopping…`),n&&a.chatCancel(n).catch(()=>{}),z.current?.abort()}let Ce=p.models_by_provider||{},we=_&&Ce[_]?Ce[_]:p.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:l}),p.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:_e,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:oe,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:h,onChange:me,children:[X(`option`,{value:``,children:`Personality`}),(p.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(p.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:_,onChange:he,children:[X(`option`,{value:``,children:`Provider`}),(p.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:y,onChange:ge,children:[X(`option`,{value:``,children:`Model`}),we.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(V,{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:se,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:H,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),p.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:P,onChange:e=>te(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:()=>le(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>le(`stop`,ne),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:()=>ue(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ue(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>ue(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:ve,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:()=>de(e.session_id),children:[X(`strong`,{children:vr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations wilLine truncated
|
||||
Generated
+1697
File diff suppressed because it is too large.
Load diff
@@ -12,6 +12,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/preset-vite": "^2.10.0",
|
||||
"@testing-library/preact": "^3.2.4",
|
||||
"jsdom": "^30.0.1",
|
||||
"vite": "^8.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { h } from "preact";
|
||||
import { Fragment } from "preact";
|
||||
import { useState, useEffect, useRef } from "preact/hooks";
|
||||
import "./tasks.css";
|
||||
import { api } from "../base/api.jsx";
|
||||
@@ -398,7 +398,7 @@ function TasksApp({ query }) {
|
||||
const expanded = expandedId === t.id;
|
||||
const timelineID = `task-timeline-${t.id}`;
|
||||
return (
|
||||
<h.Fragment key={t.id}>
|
||||
<Fragment key={t.id}>
|
||||
<tr
|
||||
className="task-row"
|
||||
id={`task-row-${t.id}`}
|
||||
@@ -445,7 +445,7 @@ function TasksApp({ query }) {
|
||||
<td data-label="Actions">{renderTaskActions(t)}</td>
|
||||
</tr>
|
||||
{expanded && renderTimelineRow(t)}
|
||||
</h.Fragment>
|
||||
</Fragment>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
+61
-15
@@ -1,7 +1,16 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { captureRow, captureDetailRow, prettyPrint } from "../src/captures/capture-row.js";
|
||||
import { h } from "preact";
|
||||
import { render, cleanup } from "@testing-library/preact";
|
||||
import { CaptureRow, CaptureDetailRow, prettyPrint } from "../src/captures/capture-row.jsx";
|
||||
|
||||
let container;
|
||||
const afterRender = (cb) => {
|
||||
const r = render(cb());
|
||||
container = r.container;
|
||||
return container;
|
||||
};
|
||||
const reset = () => cleanup();
|
||||
|
||||
test("prettyPrint indents valid JSON", () => {
|
||||
const out = prettyPrint('{"action":"opened","n":1}');
|
||||
@@ -12,54 +21,91 @@ test("prettyPrint returns non-JSON payloads unchanged rather than failing", () =
|
||||
assert.equal(prettyPrint("not json"), "not json");
|
||||
});
|
||||
|
||||
function renderRow(capture, opts = {}) {
|
||||
afterRender(() => (
|
||||
<table>
|
||||
<tbody>
|
||||
<CaptureRow capture={capture} expanded={opts.expanded} onToggle={opts.onToggle} />
|
||||
</tbody>
|
||||
</table>
|
||||
));
|
||||
return container.querySelector("tbody");
|
||||
}
|
||||
|
||||
test("collapsed capture row renders only the summary row", () => {
|
||||
const nodes = captureRow(
|
||||
const tbody = renderRow(
|
||||
{ id: 1, source: "github", content_type: "application/json" },
|
||||
{ expanded: false, onToggle: () => {} },
|
||||
);
|
||||
assert.equal(nodes.length, 1);
|
||||
assert.equal(tbody.children.length, 1);
|
||||
reset();
|
||||
});
|
||||
|
||||
test("expanded capture row appends a detail row", () => {
|
||||
const nodes = captureRow(
|
||||
const tbody = renderRow(
|
||||
{ id: 1, source: "github", content_type: "application/json" },
|
||||
{ expanded: true, onToggle: () => {} },
|
||||
);
|
||||
assert.equal(nodes.length, 2);
|
||||
assert.equal(tbody.children.length, 2);
|
||||
reset();
|
||||
});
|
||||
|
||||
test("capture row reflects expanded state via aria-expanded", () => {
|
||||
const [collapsedRow] = captureRow({ id: 1 }, { expanded: false, onToggle: () => {} });
|
||||
const [expandedRow] = captureRow({ id: 1 }, { expanded: true, onToggle: () => {} });
|
||||
assert.equal(collapsedRow.getAttribute("aria-expanded"), "false");
|
||||
assert.equal(expandedRow.getAttribute("aria-expanded"), "true");
|
||||
const coll = renderRow({ id: 1 }, { expanded: false, onToggle: () => {} });
|
||||
assert.equal(coll.querySelector(".capture-row").getAttribute("aria-expanded"), "false");
|
||||
reset();
|
||||
const exp = renderRow({ id: 1 }, { expanded: true, onToggle: () => {} });
|
||||
assert.equal(exp.querySelector(".capture-row").getAttribute("aria-expanded"), "true");
|
||||
reset();
|
||||
});
|
||||
|
||||
test("capture row shows the source and content type", () => {
|
||||
const [row] = captureRow(
|
||||
const tbody = renderRow(
|
||||
{ id: 1, source: "github", content_type: "application/json" },
|
||||
{ expanded: false, onToggle: () => {} },
|
||||
);
|
||||
const row = tbody.querySelector(".capture-row");
|
||||
assert.match(row.textContent, /github/);
|
||||
assert.match(row.textContent, /application\/json/);
|
||||
reset();
|
||||
});
|
||||
|
||||
test("capture row shows an unknown source as a placeholder rather than blank", () => {
|
||||
const [row] = captureRow({ id: 1 }, { expanded: false, onToggle: () => {} });
|
||||
const tbody = renderRow({ id: 1 }, { expanded: false, onToggle: () => {} });
|
||||
const row = tbody.querySelector(".capture-row");
|
||||
assert.match(row.textContent, /\(unknown\)/);
|
||||
reset();
|
||||
});
|
||||
|
||||
test("every capture row shows Unbound: no binding data model exists yet (t2db.4)", () => {
|
||||
const [row] = captureRow({ id: 1, source: "github" }, { expanded: false, onToggle: () => {} });
|
||||
const tbody = renderRow({ id: 1, source: "github" }, { expanded: false, onToggle: () => {} });
|
||||
const row = tbody.querySelector(".capture-row");
|
||||
assert.match(row.textContent, /Unbound/);
|
||||
reset();
|
||||
});
|
||||
|
||||
test("capture detail row pretty-prints a JSON payload", () => {
|
||||
const detail = captureDetailRow({ body: '{"a":1}', headers: "{}" });
|
||||
afterRender(() => (
|
||||
<table>
|
||||
<tbody>
|
||||
<CaptureDetailRow capture={{ body: '{"a":1}', headers: "{}" }} />
|
||||
</tbody>
|
||||
</table>
|
||||
));
|
||||
const detail = container.querySelector(".capture-detail-row");
|
||||
assert.match(detail.textContent, /"a": 1/);
|
||||
reset();
|
||||
});
|
||||
|
||||
test("capture detail row shows a placeholder for an empty payload", () => {
|
||||
const detail = captureDetailRow({ body: "", headers: "" });
|
||||
afterRender(() => (
|
||||
<table>
|
||||
<tbody>
|
||||
<CaptureDetailRow capture={{ body: "", headers: "" }} />
|
||||
</tbody>
|
||||
</table>
|
||||
));
|
||||
const detail = container.querySelector(".capture-detail-row");
|
||||
assert.match(detail.textContent, /\(empty\)/);
|
||||
reset();
|
||||
});
|
||||
@@ -1,33 +1,34 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { h, render } from "preact";
|
||||
import { ChatApp, ChatPage, chatPage } from "../src/chat/chat.jsx";
|
||||
import { render, cleanup } from "@testing-library/preact";
|
||||
import { ChatApp, chatPage } from "../src/chat/chat.jsx";
|
||||
|
||||
test("ChatApp renders structure with topbar, sidebar, transcript and composer", () => {
|
||||
const container = document.createElement("div");
|
||||
render(h(ChatApp, null), container);
|
||||
const { container, unmount } = render(<ChatApp />);
|
||||
|
||||
assert.ok(container.querySelector(".chat-topbar"), "topbar should render");
|
||||
assert.ok(container.querySelector(".chat-sidebar"), "sidebar should render");
|
||||
assert.ok(container.querySelector(".chat-transcript"), "transcript should render");
|
||||
assert.ok(container.querySelector(".chat-composer"), "composer textarea should render");
|
||||
assert.ok(container.querySelector(".chat-sidebar button"), "+ New chat button should exist");
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("ChatApp renders empty state with prompt chips when messages are empty", () => {
|
||||
const container = document.createElement("div");
|
||||
render(h(ChatApp, null), container);
|
||||
const { container, unmount } = render(<ChatApp />);
|
||||
|
||||
const emptyState = container.querySelector(".chat-empty-state");
|
||||
assert.ok(emptyState, "empty state should be present");
|
||||
const prompts = container.querySelectorAll(".chat-prompt");
|
||||
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 Element, "chatPage should return an Element");
|
||||
assert.equal(node.className, "chat-page");
|
||||
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();
|
||||
});
|
||||
+34
-22
@@ -1,14 +1,15 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { row, valueText, parseEdit } from "../src/settings/config-row.js";
|
||||
import { h } from "preact";
|
||||
import { render, cleanup } from "@testing-library/preact";
|
||||
import { Row, valueText, parseEdit } from "../src/settings/config-row.jsx";
|
||||
|
||||
// Walks a rendered row and returns the concatenated text of each direct
|
||||
// child, so a test can assert on the row's *structure* rather than on a
|
||||
// flattened string. The bugs this file guards against were all cases of
|
||||
// two fields rendering as one visual run.
|
||||
function cells(rowEl) {
|
||||
return rowEl.childNodes.map((child) => text(child));
|
||||
return Array.from(rowEl.childNodes).map((child) => text(child));
|
||||
}
|
||||
|
||||
function text(node) {
|
||||
@@ -16,7 +17,18 @@ function text(node) {
|
||||
}
|
||||
|
||||
function classOf(node) {
|
||||
return node.className || "";
|
||||
return (node && node.className) || "";
|
||||
}
|
||||
|
||||
function titleOf(node) {
|
||||
return node && node.getAttribute ? node.getAttribute("title") : undefined;
|
||||
}
|
||||
|
||||
// Render a Row component and return its rendered .kv element.
|
||||
function renderRow(label, value, opts = {}) {
|
||||
const { container, unmount } = render(<Row label={label} value={value} opts={opts} />);
|
||||
const el = container.querySelector(".kv");
|
||||
return { el, unmount };
|
||||
}
|
||||
|
||||
test("a locked row keeps its reason in a separate element from the value", () => {
|
||||
@@ -25,7 +37,7 @@ test("a locked row keeps its reason in a separate element from the value", () =>
|
||||
// working layout". Assert on the cell count and per-cell text, never on
|
||||
// the row's flattened text, so a future layout change cannot pass by
|
||||
// merging them back into one node.
|
||||
const rowEl = row("Work directory", "/home/sam/.local/share/archie/work", {
|
||||
const { el: rowEl } = renderRow("Work directory", "/home/sam/.local/share/archie/work", {
|
||||
key: "work_dir",
|
||||
locked: { work_dir: "pins the daemon's working layout; cannot be changed at runtime" },
|
||||
});
|
||||
@@ -39,18 +51,18 @@ test("a locked row keeps its reason in a separate element from the value", () =>
|
||||
});
|
||||
|
||||
test("a locked row offers no edit control", () => {
|
||||
const rowEl = row("State path prefix", "/home/sam/.local/share/archie/archie.db", {
|
||||
const { el: rowEl } = renderRow("State path prefix", "/home/sam/.local/share/archie/archie.db", {
|
||||
key: "db_path",
|
||||
locked: { db_path: "required for bootstrap" },
|
||||
});
|
||||
assert.equal(rowEl.childNodes.filter((c) => classOf(c).includes("kv-actions")).length, 0);
|
||||
assert.equal(Array.from(rowEl.childNodes).filter((c) => classOf(c).includes("kv-actions")).length, 0);
|
||||
});
|
||||
|
||||
test("an editable row separates value from its actions", () => {
|
||||
// Regression: the value overflowed into the action column, so "400"
|
||||
// rendered as "40" with Edit sitting on top of the last digit. Assert
|
||||
// the value and the actions are distinct children.
|
||||
const rowEl = row("Max diff size (lines)", 400, { key: "diff_cap_lines", type: "int", raw: 400 });
|
||||
const { el: rowEl } = renderRow("Max diff size (lines)", 400, { key: "diff_cap_lines", type: "int", raw: 400 });
|
||||
const parts = cells(rowEl);
|
||||
assert.equal(parts.length, 3);
|
||||
assert.equal(parts[1], "400", "the value must not be merged with the action label");
|
||||
@@ -58,21 +70,21 @@ test("an editable row separates value from its actions", () => {
|
||||
});
|
||||
|
||||
test("an overridden row shows the marker and a reset alongside edit", () => {
|
||||
const rowEl = row("Max steps", 90, {
|
||||
const { el: rowEl } = renderRow("Max steps", 90, {
|
||||
key: "budgets.max_steps",
|
||||
type: "int",
|
||||
raw: 90,
|
||||
overridden: ["budgets.max_steps"],
|
||||
});
|
||||
const actions = rowEl.childNodes.find((c) => classOf(c).includes("kv-actions"));
|
||||
assert.deepEqual(actions.childNodes.map(text), ["overridden", "Edit", "Reset"]);
|
||||
const actions = Array.from(rowEl.childNodes).find((c) => classOf(c).includes("kv-actions"));
|
||||
assert.deepEqual(Array.from(actions.childNodes).map(text), ["overridden", "Edit", "Reset"]);
|
||||
});
|
||||
|
||||
test("the full value is recoverable from the title when the column truncates", () => {
|
||||
const long = "go vet ./... → go build ./... → go test ./... -count=1";
|
||||
const rowEl = row("Quality gate", long);
|
||||
const value = rowEl.childNodes.find((c) => classOf(c).includes("kv-value"));
|
||||
assert.equal(value.attrs.title, long);
|
||||
const { el: rowEl } = renderRow("Quality gate", long);
|
||||
const value = Array.from(rowEl.childNodes).find((c) => classOf(c).includes("kv-value"));
|
||||
assert.equal(titleOf(value), long);
|
||||
});
|
||||
|
||||
test("zero and false are real values, not missing ones", () => {
|
||||
@@ -99,7 +111,7 @@ test("int edits reject a non-numeric entry before the round trip", () => {
|
||||
// though it has a key -- distinct from a locked row, which does have a key
|
||||
// and a reason.
|
||||
test("a field marked editable: false renders read-only with no note", () => {
|
||||
const rowEl = row("Model roles", "{...}", { key: "models", type: "structured", editable: false });
|
||||
const { el: rowEl } = renderRow("Model roles", "{...}", { key: "models", type: "structured", editable: false });
|
||||
const parts = cells(rowEl);
|
||||
assert.equal(parts.length, 2, "expected only label and value, no actions or note");
|
||||
assert.ok(!classOf(rowEl).includes("is-locked"));
|
||||
@@ -108,7 +120,7 @@ test("a field marked editable: false renders read-only with no note", () => {
|
||||
// A locked reason still takes priority over editable: true -- the runtime
|
||||
// state (overlay.DeniedKeys) wins over the schema's static claim.
|
||||
test("a locked reason is shown even when the field claims editable: true", () => {
|
||||
const rowEl = row("Work directory", "/work/archie", {
|
||||
const { el: rowEl } = renderRow("Work directory", "/work/archie", {
|
||||
key: "work_dir",
|
||||
editable: true,
|
||||
locked: { work_dir: "pins the daemon's working layout; cannot be changed at runtime" },
|
||||
@@ -120,13 +132,13 @@ test("a locked reason is shown even when the field claims editable: true", () =>
|
||||
// tooltip on the label, so a generic renderer can carry "0 means
|
||||
// unlimited." without any field-specific frontend code.
|
||||
test("a field's hint becomes the label's title attribute", () => {
|
||||
const rowEl = row("Max steps", 0, { hint: "0 means unlimited." });
|
||||
const label = rowEl.childNodes.find((c) => classOf(c).includes("kv-label"));
|
||||
assert.equal(label.attrs.title, "0 means unlimited.");
|
||||
const { el: rowEl } = renderRow("Max steps", 0, { hint: "0 means unlimited." });
|
||||
const label = Array.from(rowEl.childNodes).find((c) => classOf(c).includes("kv-label"));
|
||||
assert.equal(titleOf(label), "0 means unlimited.");
|
||||
});
|
||||
|
||||
test("a field with no hint renders a plain label with no title", () => {
|
||||
const rowEl = row("Max steps", 0, {});
|
||||
const label = rowEl.childNodes.find((c) => classOf(c).includes("kv-label"));
|
||||
assert.equal(label.attrs.title, undefined);
|
||||
const { el: rowEl } = renderRow("Max steps", 0, {});
|
||||
const label = Array.from(rowEl.childNodes).find((c) => classOf(c).includes("kv-label"));
|
||||
assert.equal(titleOf(label), null);
|
||||
});
|
||||
+9
-2
@@ -27,14 +27,21 @@ export async function load(url, context, nextLoad) {
|
||||
return { format: "module", source: 'export default "";', shortCircuit: true };
|
||||
}
|
||||
}
|
||||
if (url.endsWith(".jsx")) {
|
||||
if (url.endsWith(".jsx") || url.endsWith(".test.js")) {
|
||||
const result = await nextLoad(url, { ...context, format: "module" });
|
||||
let source = result.source;
|
||||
if (typeof source !== "string") {
|
||||
source = new TextDecoder().decode(source);
|
||||
}
|
||||
const transformed = babel.transformSync(source, {
|
||||
plugins: [["@babel/plugin-transform-react-jsx", { pragma: "h", pragmaFrag: "Fragment" }]],
|
||||
plugins: [[
|
||||
"@babel/plugin-transform-react-jsx",
|
||||
// The automatic runtime matches @preact/preset-vite, so JSX compiles
|
||||
// to `import { jsx } from "preact/jsx-runtime"` rather than a bare `h`.
|
||||
// This lets source files shadow `h` (e.g. a .map((h, i) => ...) in
|
||||
// mapping-editor.jsx) without breaking, exactly as the Vite build does.
|
||||
{ runtime: "automatic", importSource: "preact" },
|
||||
]],
|
||||
filename: fileURLToPath(url),
|
||||
configFile: false,
|
||||
babelrc: false,
|
||||
|
||||
+37
-37
@@ -1,14 +1,15 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { h } from "preact";
|
||||
import { render } from "@testing-library/preact";
|
||||
import {
|
||||
fieldTypeFromValue,
|
||||
fieldsTable,
|
||||
mappingRow,
|
||||
FieldsTable,
|
||||
MappingRow,
|
||||
pathAppendIndex,
|
||||
pathAppendKey,
|
||||
payloadTree,
|
||||
} from "../src/mappings/mapping-editor.js";
|
||||
PayloadTree,
|
||||
} from "../src/mappings/mapping-editor.jsx";
|
||||
|
||||
test("fieldTypeFromValue infers a FieldType from an example value", () => {
|
||||
assert.equal(fieldTypeFromValue("x"), "string");
|
||||
@@ -31,44 +32,42 @@ test("pathAppendIndex appends a bracketed index", () => {
|
||||
});
|
||||
|
||||
test("payloadTree renders every object key", () => {
|
||||
const tree = payloadTree({ issue: { title: "bug found" }, count: 3 });
|
||||
assert.match(tree.textContent, /issue/);
|
||||
assert.match(tree.textContent, /title/);
|
||||
assert.match(tree.textContent, /"bug found"/);
|
||||
assert.match(tree.textContent, /count/);
|
||||
assert.match(tree.textContent, /3/);
|
||||
const { container } = render(h(PayloadTree, { value: { issue: { title: "bug found" }, count: 3 } }));
|
||||
assert.match(container.textContent, /issue/);
|
||||
assert.match(container.textContent, /title/);
|
||||
assert.match(container.textContent, /"bug found"/);
|
||||
assert.match(container.textContent, /count/);
|
||||
assert.match(container.textContent, /3/);
|
||||
});
|
||||
|
||||
test("payloadTree renders array indices", () => {
|
||||
const tree = payloadTree({ items: [{ id: 1 }, { id: 2 }] });
|
||||
assert.match(tree.textContent, /items/);
|
||||
assert.match(tree.textContent, /id/);
|
||||
const { container } = render(h(PayloadTree, { value: { items: [{ id: 1 }, { id: 2 }] } }));
|
||||
assert.match(container.textContent, /items/);
|
||||
assert.match(container.textContent, /id/);
|
||||
});
|
||||
|
||||
test("fieldsTable shows a hint instead of a table when there are no fields", () => {
|
||||
const node = fieldsTable([], {});
|
||||
assert.match(node.textContent, /Click a value in the payload/);
|
||||
const { container } = render(h(FieldsTable, { fields: [], preview: null }));
|
||||
assert.match(container.textContent, /Click a value in the payload/);
|
||||
});
|
||||
|
||||
test("fieldsTable shows 'not previewed' for every field before a preview runs", () => {
|
||||
const fields = [{ name: "title", path: "issue.title", type: "string", required: true }];
|
||||
const node = fieldsTable(fields, { preview: null });
|
||||
assert.match(node.textContent, /not previewed/);
|
||||
const { container } = render(h(FieldsTable, { fields, preview: null }));
|
||||
assert.match(container.textContent, /not previewed/);
|
||||
});
|
||||
|
||||
test("fieldsTable surfaces a resolved value after a successful preview", () => {
|
||||
const fields = [{ name: "title", path: "issue.title", type: "string", required: true }];
|
||||
const node = fieldsTable(fields, { preview: { values: { title: "bug found" }, failures: [] } });
|
||||
assert.match(node.textContent, /bug found/);
|
||||
assert.doesNotMatch(node.textContent, /not previewed/);
|
||||
const { container } = render(h(FieldsTable, { fields, preview: { values: { title: "bug found" }, failures: [] } }));
|
||||
assert.match(container.textContent, /bug found/);
|
||||
assert.doesNotMatch(container.textContent, /not previewed/);
|
||||
});
|
||||
|
||||
test("fieldsTable surfaces a failure reason loudly, never a blank value", () => {
|
||||
const fields = [{ name: "title", path: "issue.title", type: "string", required: true }];
|
||||
const node = fieldsTable(fields, {
|
||||
preview: { values: {}, failures: [{ field_name: "title", path: "issue.title", reason: "missing" }] },
|
||||
});
|
||||
assert.match(node.textContent, /missing/);
|
||||
const { container } = render(h(FieldsTable, { fields, preview: { values: {}, failures: [{ field_name: "title", path: "issue.title", reason: "missing" }] } }));
|
||||
assert.match(container.textContent, /missing/);
|
||||
});
|
||||
|
||||
test("fieldsTable shows every bound field's name and path", () => {
|
||||
@@ -76,22 +75,23 @@ test("fieldsTable shows every bound field's name and path", () => {
|
||||
{ name: "title", path: "issue.title", type: "string", required: true },
|
||||
{ name: "count", path: "count", type: "number", required: false },
|
||||
];
|
||||
const node = fieldsTable(fields, { preview: null });
|
||||
assert.match(node.textContent, /issue\.title/);
|
||||
assert.match(node.textContent, /count/);
|
||||
const { container } = render(h(FieldsTable, { fields, preview: null }));
|
||||
assert.match(container.textContent, /issue\.title/);
|
||||
assert.match(container.textContent, /count/);
|
||||
});
|
||||
|
||||
test("mappingRow shows name, source hint, and field count", () => {
|
||||
const row = mappingRow(
|
||||
{ id: 1, name: "sentry issue opened", source_hint: "sentry", fields: [{}, {}] },
|
||||
{ onEdit: () => {}, onDelete: () => {} },
|
||||
);
|
||||
assert.match(row.textContent, /sentry issue opened/);
|
||||
assert.match(row.textContent, /sentry/);
|
||||
assert.match(row.textContent, /2/);
|
||||
const { container } = render(h(MappingRow, {
|
||||
mapping: { id: 1, name: "sentry issue opened", source_hint: "sentry", fields: [{}, {}] },
|
||||
onEdit: () => {},
|
||||
onDelete: () => {},
|
||||
}));
|
||||
assert.match(container.textContent, /sentry issue opened/);
|
||||
assert.match(container.textContent, /sentry/);
|
||||
assert.match(container.textContent, /2/);
|
||||
});
|
||||
|
||||
test("mappingRow shows a placeholder when there is no source hint", () => {
|
||||
const row = mappingRow({ id: 1, name: "m", fields: [] }, { onEdit: () => {}, onDelete: () => {} });
|
||||
assert.match(row.textContent, /—/);
|
||||
const { container } = render(h(MappingRow, { mapping: { id: 1, name: "m", fields: [] }, onEdit: () => {}, onDelete: () => {} }));
|
||||
assert.match(container.textContent, /—/);
|
||||
});
|
||||
@@ -1,2 +1,45 @@
|
||||
import { register } from "node:module";
|
||||
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.
|
||||
const dom = new JSDOM("<!doctype html><html><body></body></html>", { url: "http://localhost/" });
|
||||
const { window } = dom;
|
||||
|
||||
// Some globals (navigator, location) are read-only accessors on Node's
|
||||
// globalThis, so assign via defineProperty rather than direct assignment.
|
||||
const setGlobal = (key, value) => {
|
||||
Object.defineProperty(globalThis, key, { value, configurable: true, writable: true });
|
||||
};
|
||||
|
||||
setGlobal("window", window);
|
||||
setGlobal("document", window.document);
|
||||
setGlobal("navigator", window.navigator);
|
||||
setGlobal("HTMLElement", window.HTMLElement);
|
||||
setGlobal("Element", window.Element);
|
||||
setGlobal("Node", window.Node);
|
||||
setGlobal("Text", window.Text);
|
||||
setGlobal("TextNode", window.TextNode);
|
||||
setGlobal("DocumentFragment", window.DocumentFragment);
|
||||
setGlobal("CustomEvent", window.CustomEvent);
|
||||
setGlobal("Event", window.Event);
|
||||
setGlobal("AbortController", window.AbortController);
|
||||
setGlobal("getComputedStyle", window.getComputedStyle.bind(window));
|
||||
setGlobal("MutationObserver", window.MutationObserver);
|
||||
if (typeof window.requestAnimationFrame === "function") {
|
||||
setGlobal("requestAnimationFrame", window.requestAnimationFrame.bind(window));
|
||||
} else {
|
||||
setGlobal("requestAnimationFrame", (cb) => setTimeout(() => cb(Date.now()), 0));
|
||||
}
|
||||
if (typeof window.cancelAnimationFrame === "function") {
|
||||
setGlobal("cancelAnimationFrame", window.cancelAnimationFrame.bind(window));
|
||||
} else {
|
||||
setGlobal("cancelAnimationFrame", (id) => clearTimeout(id));
|
||||
}
|
||||
setGlobal("localStorage", window.localStorage);
|
||||
setGlobal("location", window.location);
|
||||
@@ -1,12 +1,8 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { register } from "node:module";
|
||||
import "./shim.js";
|
||||
import { render } from "@testing-library/preact";
|
||||
|
||||
// settings.js imports ./settings.css, which Node's ESM loader cannot parse.
|
||||
// Install a runtime loader hook (inline via a data: URL, as tasks-actions.test.js
|
||||
// does for tasks.css) that stubs .css imports to an empty module, then load
|
||||
// settings.js so the page can be driven under plain node --test.
|
||||
const cssLoad = "data:text/javascript," + encodeURIComponent(`
|
||||
export async function load(url, context, nextLoad) {
|
||||
if (url.endsWith(".css")) {
|
||||
@@ -17,21 +13,19 @@ const cssLoad = "data:text/javascript," + encodeURIComponent(`
|
||||
`);
|
||||
register(cssLoad, import.meta.url);
|
||||
|
||||
const { api } = await import("../src/base/api.js");
|
||||
const { settingsPage } = await import("../src/settings/settings.js");
|
||||
const { api } = await import("../src/base/api.jsx");
|
||||
const { settingsPage } = await import("../src/settings/settings.jsx");
|
||||
|
||||
// renderSettings builds the settings page with config/version/taskMeta stubbed
|
||||
// to canned payloads, then returns the root once the background loads settle.
|
||||
// The stubs are restored in a finally so they never leak.
|
||||
async function renderSettings(meta) {
|
||||
const original = { config: api.config, version: api.version, taskMeta: api.taskMeta };
|
||||
api.config = async () => ({});
|
||||
api.version = async () => ({ components: [] });
|
||||
api.taskMeta = async () => meta;
|
||||
try {
|
||||
const root = settingsPage();
|
||||
const vnode = settingsPage(new URLSearchParams());
|
||||
const { container } = render(vnode);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
return root;
|
||||
return container;
|
||||
} finally {
|
||||
api.config = original.config;
|
||||
api.version = original.version;
|
||||
@@ -54,13 +48,11 @@ test("work lifecycle card renders a status pill and an action button from /api/t
|
||||
const text = root.textContent;
|
||||
assert.ok(text.includes("Work lifecycle"), "the lifecycle card should be present");
|
||||
|
||||
// Statuses render as pills carrying their severity token.
|
||||
const warnPill = root.querySelector(".pill-warn");
|
||||
assert.ok(warnPill, "a warn-kind status should render a warn pill");
|
||||
assert.equal(warnPill.textContent, "Waiting for you");
|
||||
assert.ok(text.includes("Queued"), "a second status should render its label");
|
||||
|
||||
// Actions render as buttons carrying their variant token.
|
||||
const cancelBtn = root.querySelector(".btn-quiet");
|
||||
assert.ok(cancelBtn, "a quiet action should render a quiet-variant button");
|
||||
assert.equal(cancelBtn.textContent, "Cancel");
|
||||
@@ -75,7 +67,8 @@ test("work lifecycle card shows a quiet empty state when the catalog fetch fails
|
||||
throw new Error("boom");
|
||||
};
|
||||
try {
|
||||
const root = settingsPage();
|
||||
const vnode = settingsPage(new URLSearchParams());
|
||||
const { container: root } = render(vnode);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.ok(root.textContent.includes("Work lifecycle"), "the card should still render");
|
||||
assert.ok(root.textContent.includes("Lifecycle unavailable"), "a failure should show the empty/error state");
|
||||
|
||||
@@ -3,10 +3,8 @@ import assert from "node:assert/strict";
|
||||
import { register } from "node:module";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import "./shim.js";
|
||||
import { render } from "@testing-library/preact";
|
||||
|
||||
// settings.js imports ./settings.css, which Node's ESM loader cannot parse.
|
||||
// Same stub as settings-lifecycle.test.js.
|
||||
const cssLoad = "data:text/javascript," + encodeURIComponent(`
|
||||
export async function load(url, context, nextLoad) {
|
||||
if (url.endsWith(".css")) {
|
||||
@@ -17,16 +15,12 @@ const cssLoad = "data:text/javascript," + encodeURIComponent(`
|
||||
`);
|
||||
register(cssLoad, import.meta.url);
|
||||
|
||||
const { api } = await import("../src/base/api.js");
|
||||
const { settingsPage } = await import("../src/settings/settings.js");
|
||||
const { api } = await import("../src/base/api.jsx");
|
||||
const { settingsPage } = await import("../src/settings/settings.jsx");
|
||||
|
||||
const settingsJsPath = fileURLToPath(new URL("../src/settings/settings.js", import.meta.url));
|
||||
const settingsJsPath = fileURLToPath(new URL("../src/settings/settings.jsx", import.meta.url));
|
||||
const settingsJsSource = readFileSync(settingsJsPath, "utf8");
|
||||
|
||||
// A schema fixture with a field settings.js has never heard of. If the
|
||||
// renderer needed a field-specific branch to show it correctly, this key
|
||||
// would render blank, mislabeled, or not at all -- proving genericity
|
||||
// requires a field the source code cannot possibly special-case.
|
||||
const FIXTURE_SCHEMA = [
|
||||
{
|
||||
id: "budgets",
|
||||
@@ -68,9 +62,10 @@ async function renderSettings(cfg) {
|
||||
api.version = async () => ({ components: [] });
|
||||
api.taskMeta = async () => ({ statuses: [], actions: [] });
|
||||
try {
|
||||
const root = settingsPage();
|
||||
const vnode = settingsPage(new URLSearchParams());
|
||||
const { container } = render(vnode);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
return root;
|
||||
return container;
|
||||
} finally {
|
||||
api.config = original.config;
|
||||
api.version = original.version;
|
||||
@@ -86,34 +81,15 @@ test("a field the renderer has never seen still renders its label, value, and ed
|
||||
});
|
||||
|
||||
test("an enum field's options reach the row's opts rather than being dropped", async () => {
|
||||
// The row itself is exercised directly in config-row.test.js; here the
|
||||
// point is that settings.js's schema-walking code passes opts.options
|
||||
// through at all, for a field type settings.js does not special-case.
|
||||
const root = await renderSettings({ schema: FIXTURE_SCHEMA });
|
||||
assert.ok(root.textContent.includes("How images are refreshed"));
|
||||
});
|
||||
|
||||
test("a structured field in a schema section renders no card of its own here", async () => {
|
||||
// "repos" is type=structured; the generic renderer must skip it (the
|
||||
// dedicated repositories card, built from cfg.repositories, owns that
|
||||
// display). If the generic path accidentally rendered it too, "[]"
|
||||
// would appear as the field's value text.
|
||||
const root = await renderSettings({ schema: FIXTURE_SCHEMA, repositories: [] });
|
||||
assert.ok(!root.textContent.includes("Repositories\n[]"), "a structured field should not get a generic value row");
|
||||
});
|
||||
|
||||
// The real contract: settings.js must not know any individual field key by
|
||||
// name for the sections the generic renderer owns (identity, budgets,
|
||||
// storage, web). A literal key string in the source is exactly the
|
||||
// regression archie-core-b6ew.3 removed -- a hardcoded row(...) call
|
||||
// re-appearing for one field while the rest stay generic.
|
||||
// archie-core-b6ew.6: repositories gained inline editors for
|
||||
// allow_concurrent/max_retries/review_enabled. The shim's addEventListener
|
||||
// is a no-op (see ui/test/shim.js), so the save round trip itself is not
|
||||
// exercisable here -- this pins the structural half: the right initial
|
||||
// control with the right initial value renders per repo, matching the
|
||||
// existing config-row.test.js convention of testing structure, not the
|
||||
// live event round trip.
|
||||
test("repositories render a checkbox and a text input reflecting each repo's current field values", async () => {
|
||||
const root = await renderSettings({
|
||||
repositories: [
|
||||
@@ -121,27 +97,19 @@ test("repositories render a checkbox and a text input reflecting each repo's cur
|
||||
],
|
||||
});
|
||||
|
||||
const checkboxes = [];
|
||||
const textInputs = [];
|
||||
const walk = (node) => {
|
||||
for (const c of node.childNodes || []) {
|
||||
if (c.tagName === "INPUT" && c.attrs.type === "checkbox") checkboxes.push(c);
|
||||
if (c.tagName === "INPUT" && c.attrs.type === "text") textInputs.push(c);
|
||||
walk(c);
|
||||
}
|
||||
};
|
||||
walk(root);
|
||||
const checkboxes = Array.from(root.querySelectorAll('input[type="checkbox"]'));
|
||||
const textInputs = Array.from(root.querySelectorAll('input[type="text"]'));
|
||||
|
||||
assert.equal(checkboxes.length, 2, "allow_concurrent and review_enabled should each render a checkbox");
|
||||
assert.equal(checkboxes[0].attrs.checked, "", "allow_concurrent=true should render checked");
|
||||
assert.equal(checkboxes[1].attrs.checked, undefined, "review_enabled=false should render unchecked");
|
||||
assert.ok(checkboxes[0].checked, "allow_concurrent=true should render checked");
|
||||
assert.equal(checkboxes[1].checked, false, "review_enabled=false should render unchecked");
|
||||
assert.ok(
|
||||
textInputs.some((i) => i.attrs.value === "3"),
|
||||
textInputs.some((i) => String(i.value) === "3"),
|
||||
"max_retries' current value should populate a text input",
|
||||
);
|
||||
});
|
||||
|
||||
test("settings.js contains no literal field-specific branch for the generically-rendered sections", () => {
|
||||
test("settings.jsx contains no literal field-specific branch for the generically-rendered sections", () => {
|
||||
const genericFieldKeys = [
|
||||
"bot_user", "bot_email", "\"label\"", "forge.type", "forge.host", "diff_cap_lines",
|
||||
"budgets.max_steps", "budgets.wall_clock", "budgets.gate_max_failures",
|
||||
@@ -153,7 +121,7 @@ test("settings.js contains no literal field-specific branch for the generically-
|
||||
for (const key of genericFieldKeys) {
|
||||
assert.ok(
|
||||
!settingsJsSource.includes(key),
|
||||
`settings.js still references ${key} literally -- the generic renderer must not need per-field knowledge`,
|
||||
`settings.jsx still references ${key} literally -- the generic renderer must not need per-field knowledge`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,19 +1,24 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { updateStatusCard } from "../src/settings/update-status.js";
|
||||
import { render, cleanup } from "@testing-library/preact";
|
||||
import { UpdateStatusCard } from "../src/settings/update-status.jsx";
|
||||
|
||||
function renderCard(components) {
|
||||
const { container, unmount } = render(<UpdateStatusCard components={components} />);
|
||||
return { root: container, unmount };
|
||||
}
|
||||
|
||||
test("update status card shows an empty state with no components", () => {
|
||||
const card = updateStatusCard([]);
|
||||
assert.equal(card.querySelector("table"), null);
|
||||
const { root } = renderCard([]);
|
||||
assert.equal(root.querySelector("table"), null);
|
||||
});
|
||||
|
||||
test("update status card renders one row per component with its status pill", () => {
|
||||
const card = updateStatusCard([
|
||||
const { root } = renderCard([
|
||||
{ id: "daemon", label: "Gateway", install_type: "binary", running_version: "1.0.0", latest_available: "1.1.0", status: "update_available" },
|
||||
{ id: "agent", label: "Runtime", install_type: "container", running_version: "1.0.0", status: "ok" },
|
||||
]);
|
||||
const rows = card.querySelector("tbody").children;
|
||||
const rows = root.querySelector("tbody").children;
|
||||
assert.equal(rows.length, 2);
|
||||
assert.match(rows[0].textContent, /Gateway/);
|
||||
assert.match(rows[0].textContent, /Update available/);
|
||||
@@ -21,17 +26,17 @@ test("update status card renders one row per component with its status pill", ()
|
||||
});
|
||||
|
||||
test("update status card's row title carries the comparison basis", () => {
|
||||
const card = updateStatusCard([
|
||||
const { root } = renderCard([
|
||||
{ id: "agent", label: "Runtime", installed_claim: "1.1.0", running_version: "1.0.0", reference: "img@sha256:abc", status: "drift" },
|
||||
]);
|
||||
const row = card.querySelector("tbody").children[0];
|
||||
assert.match(row.attrs.title, /Installed claim: 1\.1\.0/);
|
||||
assert.match(row.attrs.title, /Running: 1\.0\.0/);
|
||||
assert.match(row.attrs.title, /Reference: img@sha256:abc/);
|
||||
const row = root.querySelector("tbody").children[0];
|
||||
assert.match(row.getAttribute("title"), /Installed claim: 1\.1\.0/);
|
||||
assert.match(row.getAttribute("title"), /Running: 1\.0\.0/);
|
||||
assert.match(row.getAttribute("title"), /Reference: img@sha256:abc/);
|
||||
});
|
||||
|
||||
test("update status card shows an unrecognised status as its own label rather than crashing", () => {
|
||||
const card = updateStatusCard([{ id: "x", status: "something-new" }]);
|
||||
const row = card.querySelector("tbody").children[0];
|
||||
const { root } = renderCard([{ id: "x", status: "something-new" }]);
|
||||
const row = root.querySelector("tbody").children[0];
|
||||
assert.match(row.textContent, /something-new/);
|
||||
});
|
||||
+32
-20
@@ -1,34 +1,43 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { taskLogPanel } from "../src/tasks/task-logs.js";
|
||||
import { render, cleanup } from "@testing-library/preact";
|
||||
import { TaskLogPanel } from "../src/tasks/task-logs.jsx";
|
||||
|
||||
function renderPanel(state, opts = {}) {
|
||||
const { container, unmount } = render(<TaskLogPanel state={state} onRetry={opts.onRetry} />);
|
||||
return { root: container, unmount };
|
||||
}
|
||||
|
||||
test("loading state renders a loading placeholder", () => {
|
||||
const node = taskLogPanel(undefined, {});
|
||||
assert.match(node.className, /task-log-loading/);
|
||||
assert.match(node.textContent, /Loading/);
|
||||
const { root, unmount } = renderPanel(undefined);
|
||||
assert.match(root.querySelector(".task-log-loading")?.className || "", /task-log-loading/);
|
||||
assert.match(root.textContent, /Loading/);
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("fetch failure renders a retry control", () => {
|
||||
const node = taskLogPanel(null, { onRetry: () => {} });
|
||||
assert.match(node.className, /task-log-error/);
|
||||
const btn = node.querySelector("button");
|
||||
const { root, unmount } = renderPanel(null, { onRetry: () => {} });
|
||||
assert.match(root.querySelector(".task-log-error")?.className || "", /task-log-error/);
|
||||
const btn = root.querySelector("button");
|
||||
assert.ok(btn, "a retry button should render");
|
||||
assert.equal(btn.textContent, "Retry");
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("disabled response (task logging not enabled) renders a placeholder, not a crash", () => {
|
||||
const node = taskLogPanel({ disabled: true, entries: [] });
|
||||
assert.match(node.textContent, /No persisted log/);
|
||||
const { root, unmount } = renderPanel({ disabled: true, entries: [] });
|
||||
assert.match(root.textContent, /No persisted log/);
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("empty entries render a placeholder distinct from the disabled state", () => {
|
||||
const node = taskLogPanel({ disabled: false, entries: [] });
|
||||
assert.match(node.textContent, /Nothing recorded/);
|
||||
const { root, unmount } = renderPanel({ disabled: false, entries: [] });
|
||||
assert.match(root.textContent, /Nothing recorded/);
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("entries render one row per entry with fields visible, surfacing stage/token detail", () => {
|
||||
const node = taskLogPanel({
|
||||
const { root, unmount } = renderPanel({
|
||||
entries: [
|
||||
{
|
||||
time: "2026-01-01T00:00:00Z",
|
||||
@@ -44,11 +53,14 @@ test("entries render one row per entry with fields visible, surfacing stage/toke
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(node.children.length, 2, "one .log-row per entry");
|
||||
assert.match(node.textContent, /stage complete/);
|
||||
assert.match(node.textContent, /implement/);
|
||||
assert.match(node.textContent, /1234/);
|
||||
assert.match(node.textContent, /sonnet/);
|
||||
assert.match(node.textContent, /agent failed/);
|
||||
assert.match(node.textContent, /iteration/);
|
||||
const list = root.querySelector(".log-list");
|
||||
assert.ok(list, "the log list wrapper should render");
|
||||
assert.equal(list.children.length, 2, "one .log-row per entry");
|
||||
assert.match(root.textContent, /stage complete/);
|
||||
assert.match(root.textContent, /implement/);
|
||||
assert.match(root.textContent, /1234/);
|
||||
assert.match(root.textContent, /sonnet/);
|
||||
assert.match(root.textContent, /agent failed/);
|
||||
assert.match(root.textContent, /iteration/);
|
||||
unmount();
|
||||
});
|
||||
@@ -1,11 +1,8 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { register } from "node:module";
|
||||
import "./shim.js";
|
||||
import { render, waitFor } from "@testing-library/preact";
|
||||
|
||||
// tasks.js imports "./tasks.css", which Node's ESM loader cannot parse. Install
|
||||
// a runtime loader hook (inline, via a data: URL so nothing extra is written to
|
||||
// disk) that stubs .css imports to an empty module, then load tasks.js.
|
||||
const cssLoad = "data:text/javascript," + encodeURIComponent(`
|
||||
export async function load(url, context, nextLoad) {
|
||||
if (url.endsWith(".css")) {
|
||||
@@ -16,19 +13,19 @@ const cssLoad = "data:text/javascript," + encodeURIComponent(`
|
||||
`);
|
||||
register(cssLoad, import.meta.url);
|
||||
|
||||
const { api } = await import("../src/base/api.js");
|
||||
const { tasksPage } = await import("../src/tasks/tasks.js");
|
||||
const { api } = await import("../src/base/api.jsx");
|
||||
const { tasksPage } = await import("../src/tasks/tasks.jsx");
|
||||
|
||||
// renderTask builds a page with a single task by stubbing api.tasks to a fake
|
||||
// task, then returns the rendered root once tasksPage's background load() has
|
||||
// settled. api.tasks is restored in a finally so the stub never leaks.
|
||||
async function renderTask(task) {
|
||||
const original = api.tasks;
|
||||
api.tasks = async () => [task];
|
||||
try {
|
||||
const root = tasksPage(new URLSearchParams());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
return root;
|
||||
const vnode = tasksPage(new URLSearchParams());
|
||||
const { container } = render(vnode);
|
||||
await waitFor(() => {
|
||||
assert.ok(container.querySelector(".task-row"), "Wait for task to render");
|
||||
});
|
||||
return container;
|
||||
} finally {
|
||||
api.tasks = original;
|
||||
}
|
||||
@@ -62,7 +59,6 @@ test("an id NOT in the catalog renders nothing", async () => {
|
||||
actions: ["teleport"],
|
||||
};
|
||||
const root = await renderTask(task);
|
||||
// Unknown id -> no control renders, so no .task-actions container appears.
|
||||
assert.equal(root.querySelector(".task-actions"), null, "unknown action renders nothing");
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user