diff --git a/pm-stack/aggregator/src/actions.ts b/pm-stack/aggregator/src/actions.ts index bd56f0a8f3..5550048727 100644 --- a/pm-stack/aggregator/src/actions.ts +++ b/pm-stack/aggregator/src/actions.ts @@ -77,13 +77,21 @@ export type DashActionVerb = | "dismiss" | "approve-proposal" | "reject-proposal" + // triage β€” quick actions + restore (#1449/#1450): "mark-done" is the + // one-tap "Already done" (the consumer closes the item out; for gh: + // refs it performs the Done status write). "restore" undoes a + // suppression β€” it MUST name the suppressing action in `supersedes`. + | "mark-done" + | "restore" // status-request (#1154) | "request-status" // session (#1156) | "poke" | "stop" // preference (#1290) - | "set-delegation-default"; + | "set-delegation-default" + // preference β€” Needs-you card order (#1456) + | "set-needs-order"; export const VERBS_BY_KIND: Record = { triage: [ @@ -96,10 +104,12 @@ export const VERBS_BY_KIND: Record = "dismiss", "approve-proposal", "reject-proposal", + "mark-done", + "restore", ], "status-request": ["request-status"], session: ["poke", "answer", "stop"], - preference: ["set-delegation-default"], + preference: ["set-delegation-default", "set-needs-order"], }; export interface DashActionPayload { @@ -130,6 +140,9 @@ export interface DashActionPayload { proposalUpdatedAt?: string; /** set-delegation-default: the standing auto toggle value. */ standingAuto?: boolean; + /** set-needs-order: the Needs-you card ordering (#1456). "urgency" is + * the orchestrator's published order; the rest sort at render. */ + needsOrder?: "urgency" | "newest" | "oldest" | "deadline"; } export interface DashAction { @@ -288,6 +301,17 @@ export function validateNewAction(body: unknown): { ok: true; value: NewAction } } payload.standingAuto = rawPayload.standingAuto; } + if (rawPayload.needsOrder !== undefined) { + if ( + rawPayload.needsOrder !== "urgency" && + rawPayload.needsOrder !== "newest" && + rawPayload.needsOrder !== "oldest" && + rawPayload.needsOrder !== "deadline" + ) { + return { ok: false, error: "payload.needsOrder must be urgency | newest | oldest | deadline" }; + } + payload.needsOrder = rawPayload.needsOrder; + } let targetRef: RefKey | undefined; if (b.targetRef !== undefined) { @@ -333,6 +357,12 @@ export function validateNewAction(body: unknown): { ok: true; value: NewAction } if (verb === "set-delegation-default" && payload.standingAuto === undefined) { return { ok: false, error: "set-delegation-default requires payload.standingAuto (boolean)" }; } + if (verb === "set-needs-order" && payload.needsOrder === undefined) { + return { ok: false, error: "set-needs-order requires payload.needsOrder" }; + } + if (verb === "restore" && supersedes === undefined) { + return { ok: false, error: "restore requires supersedes (the id of the action it undoes)" }; + } if ((verb === "dismiss" || verb === "reject-proposal") && payload.reason === undefined) { return { ok: false, error: `${verb} requires payload.reason` }; } @@ -506,6 +536,7 @@ export const VERB_FAMILIES: Partial> = { "de-escalate": "tier", delegate: "delegation", dismiss: "dismiss", + "mark-done": "done", "request-status": "status", poke: "poke", stop: "stop", diff --git a/pm-stack/aggregator/src/assets/datastar.js b/pm-stack/aggregator/src/assets/datastar.js new file mode 100644 index 0000000000..3cceb551f6 --- /dev/null +++ b/pm-stack/aggregator/src/assets/datastar.js @@ -0,0 +1,9 @@ +// Datastar v1.0.0 +var yt=/πŸ–•JS_DSπŸš€/.source,Ue=yt.slice(0,5),Je=yt.slice(4),B="datastar-fetch",te="datastar-prop-change",vt="datastar-ready",Ke="datastar-scope-children",ne="datastar-signal-patch";var x=Object.hasOwn??Object.prototype.hasOwnProperty.call;var K=e=>e!==null&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),bt=e=>{for(let t in e)if(x(e,t))return!1;return!0},re=(e,t)=>{for(let n in e){let r=e[n];K(r)||Array.isArray(r)?re(r,t):e[n]=t(r)}},Le=e=>{let t={};for(let[n,r]of e){let s=n.split("."),i=s.pop(),o=s.reduce((a,c)=>a[c]??={},t);o[i]=r}return t};var xe=[],ze=[],He=0,Ne=0,Ze=0,Qe,j,Pe=0,N=()=>{He++},P=()=>{--He||(Tt(),z())},_=e=>{Qe=j,j=e},k=()=>{j=Qe,Qe=void 0},me=e=>cn.bind(0,{previousValue:e,t:e,e:1}),Ye=Symbol("computed"),_e=e=>{let t=ln.bind(0,{e:17,getter:e});return t[Ye]=1,t},R=e=>{let t={d:e,e:2};j&&et(t,j),_(t),N();try{t.d()}finally{P(),k()}return Mt.bind(0,t)},Tt=()=>{for(;Ne"getter"in e?At(e):Rt(e,e.t),At=e=>{_(e),Lt(e);try{let t=e.t;return t!==(e.t=e.getter(t))}finally{k(),xt(e)}},Rt=(e,t)=>(e.e=1,e.previousValue!==(e.previousValue=t)),Xe=e=>{let t=e.e;if(!(t&64)){e.e=t|64;let n=e.r;n?Xe(n.o):ze[Ze++]=e}},wt=(e,t)=>{if(t&16||t&32&&Nt(e.s,e)){_(e),Lt(e),N();try{e.d()}finally{P(),k(),xt(e)}return}t&32&&(e.e=t&-33);let n=e.s;for(;n;){let r=n.c,s=r.e;s&64&&wt(r,r.e=s&-65),n=n.i}},cn=(e,...t)=>{if(t.length){if(e.t!==(e.t=t[0])){e.e=17;let r=e.r;return r&&(un(r),He||Tt()),!0}return!1}let n=e.t;if(e.e&16&&Rt(e,n)){let r=e.r;r&&Fe(r)}return j&&et(e,j),n},ln=e=>{let t=e.e;if(t&16||t&32&&Nt(e.s,e)){if(At(e)){let n=e.r;n&&Fe(n)}}else t&32&&(e.e=t&-33);return j&&et(e,j),e.t},Mt=e=>{let t=e.s;for(;t;)t=Ce(t,e);let n=e.r;n&&Ce(n),e.e=0},et=(e,t)=>{let n=t.a;if(n&&n.c===e)return;let r=n?n.i:t.s;if(r&&r.c===e){r.p=Pe,t.a=r;return}let s=e.m;if(s&&s.p===Pe&&s.o===t)return;let i=t.a=e.m={p:Pe,c:e,o:t,l:n,i:r,u:s};r&&(r.l=i),n?n.i=i:t.s=i,s?s.n=i:e.r=i},Ce=(e,t=e.o)=>{let n=e.c,r=e.l,s=e.i,i=e.n,o=e.u;if(s?s.l=r:t.a=r,r?r.i=s:t.s=s,i?i.u=o:n.m=o,o)o.n=i;else if(!(n.r=i))if("getter"in n){let a=n.s;if(a){n.e=17;do a=Ce(a,n);while(a)}}else"previousValue"in n||Mt(n);return s},un=e=>{let t=e.n,n;e:for(;;){let r=e.o,s=r.e;if(s&60?s&12?s&4?!(s&48)&&fn(e,r)?(r.e=s|40,s&=1):s=0:r.e=s&-9|32:s=0:r.e=s|32,s&2&&Xe(r),s&1){let i=r.r;if(i){let o=(e=i).n;o&&(n={t,f:n},t=o);continue}}if(e=t){t=e.n;continue}for(;n;)if(e=n.t,n=n.f,e){t=e.n;continue e}break}},Lt=e=>{Pe++,e.a=void 0,e.e=e.e&-57|4},xt=e=>{let t=e.a,n=t?t.i:e.s;for(;n;)n=Ce(n,e);e.e&=-5},Nt=(e,t)=>{let n,r=0,s=!1;e:for(;;){let i=e.c,o=i.e;if(t.e&16)s=!0;else if((o&17)===17){if(Et(i)){let a=i.r;a.n&&Fe(a),s=!0}}else if((o&33)===33){(e.n||e.u)&&(n={t:e,f:n}),e=i.s,t=i,++r;continue}if(!s){let a=e.i;if(a){e=a;continue}}for(;r--;){let a=t.r,c=a.n;if(c?(e=n.t,n=n.f):e=a,s){if(Et(t)){c&&Fe(a),t=e.o;continue}s=!1}else t.e&=-33;if(t=e.o,e.i){e=e.i;continue e}}return s}},Fe=e=>{do{let t=e.o,n=t.e;(n&48)===32&&(t.e=n|16,n&2&&Xe(t))}while(e=e.n)},fn=(e,t)=>{let n=t.a;for(;n;){if(n===e)return!0;n=n.l}return!1},W=e=>{let t=se,n=e.split(".");for(let r of n){if(t==null||!x(t,r))return;t=t[r]}return t},Oe=(e,t="")=>{let n=Array.isArray(e);if(n||K(e)){let r=n?[]:{};for(let i in e)r[i]=me(Oe(e[i],`${t+i}.`));let s=me(0);return new Proxy(r,{get(i,o){if(!(o==="toJSON"&&!x(r,o)))return n&&o in Array.prototype?(s(),r[o]):typeof o=="symbol"?r[o]:((!x(r,o)||r[o]()==null)&&(r[o]=me(""),z(t+o,""),s(s()+1)),r[o]())},set(i,o,a){let c=t+o;if(n&&o==="length"){let l=r[o]-a;if(r[o]=a,l>0){let u={};for(let f=a;f{if(e!==void 0&&t!==void 0&&xe.push([e,t]),!He&&xe.length){let n=Le(xe);xe.length=0,document.dispatchEvent(new CustomEvent(ne,{detail:n}))}},D=(e,{ifMissing:t}={})=>{N();for(let n in e)e[n]==null?t||delete se[n]:Pt(e[n],n,se,"",t);P()},S=(e,t)=>D(Le(e),t),Pt=(e,t,n,r,s)=>{if(K(e)){x(n,t)&&(K(n[t])||Array.isArray(n[t]))||(n[t]={});for(let i in e)e[i]==null?s||delete n[t][i]:Pt(e[i],i,n[t],`${r+t}.`,s)}else s&&x(n,t)||(n[t]=e)},St=e=>typeof e=="string"?RegExp(e.replace(/^\/|\/$/g,"")):e,$=({include:e=/.*/,exclude:t=/(?!)/}={},n=se)=>{let r=St(e),s=St(t),i=[],o=[[n,""]];for(;o.length;){let[a,c]=o.pop();for(let l in a){let u=c+l;K(a[l])?o.push([a[l],`${u}.`]):r.test(u)&&!s.test(u)&&i.push([u,W(u)])}}return Le(i)},se=Oe({});var Z=e=>e instanceof HTMLElement||e instanceof SVGElement||e instanceof MathMLElement;var ge=e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([a-z])([0-9]+)/gi,"$1-$2").replace(/([0-9]+)([a-z])/gi,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase();var Ot=e=>ge(e).replace(/-/g,"_");var dn=/^(?:(?:async\s+)?function\b|(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/,ae=(e,t={})=>{let{reviveFunctionStrings:n=!1}=t;try{return n?JSON.parse(e,(r,s)=>{if(typeof s!="string")return s;let i=s.trim();if(!dn.test(i))return s;try{let o=Function(`return (${i})`)();return typeof o=="function"?o:s}catch{return s}}):JSON.parse(e)}catch{return Function(`return (${e})`)()}},Ct={camel:e=>e.replace(/-[a-z]/g,t=>t[1].toUpperCase()),snake:e=>e.replace(/-/g,"_"),pascal:e=>e[0].toUpperCase()+Ct.camel(e.slice(1))},O=(e,t,n="camel")=>{for(let r of t.get("case")||[n])e=Ct[r]?.(e)||e;return e},U=e=>`data-${e}`,tt=e=>e;var pn="https://data-star.dev/errors",he=(e,t,n={})=>{Object.assign(n,e);let r=new Error,s=Ot(t),i=new URLSearchParams({metadata:JSON.stringify(n)}).toString(),o=JSON.stringify(n,null,2);return r.message=`${t} +More info: ${pn}/${s}?${i} +Context: ${o}`,r},ye=new Map,nt=new Map,_t=new Map,kt=new Proxy({},{get:(e,t)=>ye.get(t)?.apply,has:(e,t)=>ye.has(t),ownKeys:()=>Reflect.ownKeys(ye),set:()=>!1,deleteProperty:()=>!1}),be=new Map,ke=[],rt=new Set,ve=new Set,Ft=!1,g=e=>{ke.push(e),ke.length===1&&setTimeout(()=>{for(let n of ke)rt.add(n.name),nt.set(n.name,n);ke.length=0;let t=ve.size?[...ve]:[document.documentElement];for(let n of t)En(n,!ve.has(n));rt.clear()})},V=e=>{ye.set(e.name,e)};document.addEventListener(B,e=>{let t=_t.get(e.detail.type);t&&t.apply({error:he.bind(0,{plugin:{type:"watcher",name:t.name},element:{id:e.target.id,tag:e.target.tagName}})},e.detail.argsRaw)});var Ee=e=>{_t.set(e.name,e)},Ht=e=>{for(let t of e){let n=be.get(t);if(n&&be.delete(t))for(let r of n.values())for(let s of r.values())s()}},Dt=U("ignore"),mn=`[${Dt}]`,Vt=e=>e.hasAttribute(`${Dt}__self`)||!!e.closest(mn),De=(e,t)=>{for(let n of e)if(!Vt(n)){let r=new Set;for(let s in n.dataset){let i=s.replace(/[A-Z]/g,"-$&").toLowerCase();r.add(i),st(n,i,n.dataset[s],t)}for(let s of Array.from(n.attributes)){if(!s.name.startsWith("data-"))continue;let i=s.name.slice(5);r.has(i)||st(n,i,s.value,t)}}},gn=e=>{for(let{target:t,type:n,attributeName:r,addedNodes:s,removedNodes:i}of e)if(n==="childList"){for(let o of i)Z(o)&&(Ht([o]),Ht(o.querySelectorAll("*")));for(let o of s)Z(o)&&(De([o]),De(o.querySelectorAll("*")))}else if(n==="attributes"&&r.startsWith("data-")&&Z(t)&&!Vt(t)){let o=r.slice(5),a=tt(o);if(!a)continue;let c=t.getAttribute(r);if(c===null){let l=be.get(t);if(l){let u=l.get(a);if(u){for(let f of u.values())f();l.delete(a)}}}else st(t,o,c)}},hn=new MutationObserver(gn),yn=e=>{let[t,...n]=e.split("__"),[r,s]=t.split(/:(.+)/),i=new Map;for(let o of n){let[a,...c]=o.split(".");i.set(a,new Set(c))}return{pluginName:r,key:s,mods:i}},vn=()=>ve.has(document.documentElement),bn=()=>{Ft||!vn()||(Ft=!0,document.dispatchEvent(new Event(vt)))},En=(e=document.documentElement,t=!0)=>{Z(e)&&De([e],!0),De(e.querySelectorAll("*"),!0),t&&(hn.observe(e,{subtree:!0,childList:!0,attributes:!0}),ve.add(e),bn())};var st=(e,t,n,r)=>{let s=tt(t);if(!s)return;let{pluginName:i,key:o,mods:a}=yn(s),c=nt.get(i);if((!r||rt.has(i))&&!!c){let u={el:e,rawKey:s,mods:a,error:he.bind(0,{plugin:{type:"attribute",name:c.name},element:{id:e.id,tag:e.tagName},expression:{rawKey:s,key:o,value:n}}),key:o,value:n,loadedPluginNames:{actions:new Set(ye.keys()),attributes:new Set(nt.keys())},rx:void 0},f=c.requirement&&(typeof c.requirement=="string"?c.requirement:c.requirement.key)||"allowed",h=c.requirement&&(typeof c.requirement=="string"?c.requirement:c.requirement.value)||"allowed",d=o!=null&&o!=="",p=n!=null&&n!=="";if(d){if(f==="denied")throw u.error("KeyNotAllowed")}else if(f==="must")throw u.error("KeyRequired");if(p){if(h==="denied")throw u.error("ValueNotAllowed")}else if(h==="must")throw u.error("ValueRequired");if(f==="exclusive"||h==="exclusive"){if(d&&p)throw u.error("KeyAndValueProvided");if(!d&&!p)throw u.error("KeyOrValueRequired")}let m=new Map;if(p){let v;u.rx=(...F)=>(v||(v=Sn(n,{returnsValue:c.returnsValue,argNames:c.argNames,cleanups:m})),v(e,...F))}let y=c.apply(u);y&&m.set("attribute",y);let T=be.get(e);if(T){let v=T.get(s);if(v)for(let F of v.values())F()}else T=new Map,be.set(e,T);T.set(s,m)}},Sn=(e,{returnsValue:t=!1,argNames:n=[],cleanups:r=new Map}={})=>{let s="";if(t){let c=/(\/(\\\/|[^/])*\/|"(\\"|[^"])*"|'(\\'|[^'])*'|`(\\`|[^`])*`|\(\s*((function)\s*\(\s*\)|(\(\s*\))\s*=>)\s*(?:\{[\s\S]*?\}|[^;){]*)\s*\)\s*\(\s*\)|[^;])+/gm,l=e.trim().match(c);if(l){let u=l.length-1,f=l[u].trim();f.startsWith("return")||(l[u]=`return (${f});`),s=l.join(`; +`)}}else s=e.trim();let i=new Map,o=RegExp(`(?:${Ue})(.*?)(?:${Je})`,"gm"),a=0;for(let c of s.matchAll(o)){let l=c[1],u=`__escaped${a++}`;i.set(u,l),s=s.replace(Ue+l+Je,u)}s=s.replace(/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\$]|\$(?!\{))*`)|\$\{([^{}]*)\}|\$([a-zA-Z_\d]\w*(?:[.-]\w+)*)/g,(c,l,u,f)=>l?c:u!==void 0?`\${${u.replace(/\$([a-zA-Z_\d]\w*(?:[.-]\w+)*)/g,(h,d)=>d.split(".").reduce((p,m)=>`${p}['${m}']`,"$"))}}`:f.split(".").reduce((h,d)=>`${h}['${d}']`,"$")),s=s.replaceAll(/@([A-Za-z_$][\w$]*)\(/g,'__action("$1",evt,');for(let[c,l]of i)s=s.replace(c,l);try{let c=Function("el","$","__action","evt",...n,s);return(l,...u)=>{let f=(h,d,...p)=>{let m=he.bind(0,{plugin:{type:"action",name:h},element:{id:l.id,tag:l.tagName},expression:{fnContent:s,value:e}}),y=kt[h];if(y)return y({el:l,evt:d,error:m,cleanups:r},...p);throw m("UndefinedAction")};try{return c(l,se,f,void 0,...u)}catch(h){throw console.error(h),he({element:{id:l.id,tag:l.tagName},expression:{fnContent:s,value:e},error:h.message},"ExecuteExpression")}}}catch(c){throw console.error(c),he({expression:{fnContent:s,value:e},error:c.message},"GenerateExpression")}};V({name:"peek",apply(e,t){_();try{return t()}finally{k()}}});V({name:"setAll",apply(e,t,n){_();let r=$(n);re(r,()=>t),D(r),k()}});V({name:"toggleAll",apply(e,t){_();let n=$(t);re(n,r=>!r),D(n),k()}});var It=new WeakMap,it=e=>!["GET","DELETE"].includes(e),Se=(e,t,n=!0)=>V({name:e,apply:async({el:r,evt:s,error:i,cleanups:o},a,{selector:c,headers:l,contentType:u="json",filterSignals:{include:f=/.*/,exclude:h=/(^|\.)_/}={},openWhenHidden:d=n,payload:p,requestCancellation:m="auto",retry:y="auto",retryInterval:T=1e3,retryScaler:v=2,retryMaxWait:F=3e4,retryMaxCount:Re=10}={})=>{let X=m instanceof AbortController?m:new AbortController;(m==="auto"||m==="cleanup")&&(It.get(r)?.abort(),It.set(r,X)),m==="cleanup"&&(o.get(`@${e}`)?.(),o.set(`@${e}`,async()=>{X.abort(),await Promise.resolve()}));let ee=()=>{};try{if(!a?.length)throw i("FetchNoUrlProvided",{action:V});let fe={Accept:"text/event-stream, text/html, application/json","Datastar-Request":!0};u==="json"&&it(t)&&(fe["Content-Type"]="application/json");let q=Object.assign({},fe,l),C={input:"",method:t,headers:q,openWhenHidden:d,retry:y,retryInterval:T,retryScaler:v,retryMaxWait:F,retryMaxCount:Re,signal:X.signal,onopen:async b=>{b.status>=400&&ie(Tn,r,{status:b.status.toString()})},onmessage:b=>{if(!b.event.startsWith("datastar"))return;let J=b.event,w={};for(let E of b.data.split(` +`)){let A=E.indexOf(" "),H=E.slice(0,A),M=E.slice(A+1);(w[H]||=[]).push(M)}let L=Object.fromEntries(Object.entries(w).map(([E,A])=>[E,A.join(` +`)]));ie(J,r,L)},onerror:b=>{if($t(b))throw b("FetchExpectedTextEventStream",{url:a});b&&(console.error(b.message),ie(An,r,{message:b.message}))}},qe=()=>{let b=new URL(a,document.baseURI),J=new URLSearchParams(b.search);if(u==="json"){_();let w=p!==void 0?p:$({include:f,exclude:h});k();let L=JSON.stringify(w);it(t)?C.body=L:J.set("datastar",L)}else if(u==="form"){let w=c?document.querySelector(c):r.closest("form");if(!w)throw i("FetchFormNotFound",{action:V,selector:c});if(!w.noValidate&&!w.checkValidity()){w.reportValidity();return}let L=new FormData(w),E=r;if(r===w&&s instanceof SubmitEvent)E=s.submitter;else{let M=de=>de.preventDefault();w.addEventListener("submit",M),ee=()=>{w.removeEventListener("submit",M)}}if(E instanceof HTMLButtonElement||E instanceof HTMLInputElement&&E.type==="submit"){let M=E.getAttribute("name");M&&L.append(M,E.value)}let A=w.getAttribute("enctype")==="multipart/form-data";A||(q["Content-Type"]="application/x-www-form-urlencoded");let H=new URLSearchParams(L);if(it(t))A?C.body=L:C.body=H;else for(let[M,de]of H)J.append(M,de)}else throw i("FetchInvalidContentType",{action:V,contentType:u});return b.search=J.toString(),C.input=b.toString(),C};ie(ot,r,{});try{await Nn(r,qe)}catch(b){if(!$t(b))throw i("FetchFailed",{method:t,url:a,error:b.message})}}finally{ie(at,r,{}),ee(),o.delete(`@${e}`)}}});Se("get","GET",!1);Se("patch","PATCH");Se("post","POST");Se("put","PUT");Se("delete","DELETE");var ot="started",at="finished",Tn="error",An="retrying",Rn="retries-failed",ie=(e,t,n)=>document.dispatchEvent(new CustomEvent(B,{detail:{type:e,el:t,argsRaw:n}})),$t=e=>`${e}`.includes("text/event-stream"),wn=async(e,t)=>{let n=e.getReader(),r=await n.read();for(;!r.done;)t(r.value),r=await n.read()},Mn=e=>{let t,n,r,s=!1;return i=>{t?t=xn(t,i):(t=i,n=0,r=-1);let o=t.length,a=0;for(;n{let r=qt(),s=new TextDecoder;return(i,o)=>{if(!i.length)n?.(r),r=qt();else if(o>0){let a=s.decode(i.subarray(0,o)),c=o+(i[o+1]===32?2:1),l=s.decode(i.subarray(c));switch(a){case"data":r.data=r.data?`${r.data} +${l}`:l;break;case"event":r.event=l;break;case"id":e(r.id=l);break;case"retry":{let u=+l;Number.isNaN(u)||t(r.retry=u);break}}}}},xn=(e,t)=>{let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n},qt=()=>({data:"",event:"",id:"",retry:void 0}),Nn=(e,t)=>new Promise((n,r)=>{let s=t();if(!s)return;let{input:i,signal:o,headers:a,onopen:c,onmessage:l,onclose:u,onerror:f,openWhenHidden:h,fetch:d,retry:p="auto",retryInterval:m=1e3,retryScaler:y=2,retryMaxWait:T=3e4,retryMaxCount:v=10,responseOverrides:F,...Re}=s,X={...a},ee,fe=()=>{if(ee.abort(),!document.hidden){let E=t();if(!E)return;i=E.input,Re.body=E.body,L()}};h||document.addEventListener("visibilitychange",fe);let q,C=()=>{document.removeEventListener("visibilitychange",fe),clearTimeout(q),ee.abort()};o?.addEventListener("abort",()=>{C(),n()});let qe=d||window.fetch,b=c||(()=>{}),J=0,w=m,L=async()=>{ee=new AbortController;let E=ee.signal;try{let A=await qe(i,{...Re,headers:X,signal:E});await b(A);let H=async(G,pe,Be,we,...an)=>{let ht={[Be]:await pe.text()};for(let je of an){let We=pe.headers.get(`datastar-${ge(je)}`);if(we){let Me=we[je];Me&&(We=typeof Me=="string"?Me:JSON.stringify(Me))}We&&(ht[je]=We)}ie(G,e,ht),C(),n()},M=A.status,de=M===204,gt=M>=300&&M<400,on=M>=400&&M<600;if(M!==200){if(u?.(),p!=="never"&&!de&&!gt&&(p==="always"||p==="error"&&on)){clearTimeout(q),q=setTimeout(L,m);return}C(),n();return}J=0,m=w;let Ge=A.headers.get("Content-Type");if(Ge?.includes("text/html"))return await H("datastar-patch-elements",A,"elements",F,"selector","mode","namespace","useViewTransition");if(Ge?.includes("application/json"))return await H("datastar-patch-signals",A,"signals",F,"onlyIfMissing");if(Ge?.includes("text/javascript")){let G=document.createElement("script"),pe=A.headers.get("datastar-script-attributes");if(pe)for(let[Be,we]of Object.entries(JSON.parse(pe)))G.setAttribute(Be,we);G.textContent=await A.text(),document.head.appendChild(G),C();return}if(await wn(A.body,Mn(Ln(G=>{G?X["last-event-id"]=G:delete X["last-event-id"]},G=>{w=m=G},l))),u?.(),p==="always"&&!gt){clearTimeout(q),q=setTimeout(L,m);return}C(),n()}catch(A){if(!E.aborted)try{let H=f?.(A)||m;clearTimeout(q),q=setTimeout(L,H),m=Math.min(m*y,T),++J>=v?(ie(Rn,e,{}),C(),r("Max retries reached.")):console.error(`Datastar failed to reach ${i.toString()} retrying in ${H}ms.`)}catch(H){C(),r(H)}}};L()});g({name:"attr",requirement:{value:"must"},returnsValue:!0,apply({el:e,key:t,rx:n}){let r=(a,c)=>{c===""||c===!0?e.setAttribute(a,""):c===!1||c==null?e.removeAttribute(a):typeof c=="string"?e.setAttribute(a,c):typeof c=="function"?e.setAttribute(a,c.toString()):e.setAttribute(a,JSON.stringify(c,(l,u)=>typeof u=="function"?u.toString():u))},s=t?()=>{i.disconnect();let a=n();r(t,a),i.observe(e,{attributeFilter:[t]})}:()=>{i.disconnect();let a=n(),c=Object.keys(a);for(let l of c)r(l,a[l]);i.observe(e,{attributeFilter:c})},i=new MutationObserver(s),o=R(s);return()=>{i.disconnect(),o()}}});var Ve=(e,...t)=>({get:n=>n[e],set:(n,r)=>{n[e]=r},events:t}),Gt=(e,...t)=>({get:n=>n.getAttribute(e),set:(n,r)=>{n.setAttribute(e,`${r}`)},events:t}),ct=(e=!1,...t)=>({get:(n,r)=>r==="string"||e&&r==="undefined"?n.value:+n.value,set:(n,r)=>{n.value=`${r}`},events:t}),Pn=/^data:(?[^;]+);base64,(?.*)$/,lt=Symbol("empty"),Ie=U("bind"),Bt=(e,t,n,r,s,i)=>{if(i===void 0&&e instanceof HTMLInputElement&&e.type==="radio"){let u=t||n,f=[...document.querySelectorAll(`[${Ie}\\:${CSS.escape(u)}],[${Ie}="${CSS.escape(u)}"]`)].find(h=>h instanceof HTMLInputElement&&h.checked);f&&S([[r,f.value]],{ifMissing:!0})}if(!Array.isArray(i)||e instanceof HTMLSelectElement&&e.multiple)return S([[r,s.get(e,typeof i)]],{ifMissing:!0}),r;let o=t||n,a=document.querySelectorAll(`[${Ie}\\:${CSS.escape(o)}],[${Ie}="${CSS.escape(o)}"]`),c=[],l=0;for(let u of a){if(c.push([`${r}.${l}`,s.get(u,typeof(x(i,l)?i[l]:void 0))]),e===u)break;l++}return S(c,{ifMissing:!0}),`${r}.${l}`};g({name:"bind",requirement:"exclusive",apply({el:e,key:t,mods:n,value:r,error:s}){let i=t!=null?O(t,n):r,o=n.get("prop"),a=n.get("event"),c=null;if(o){let d=[...o][0];if(!d?.length)throw s("BindPropNameMissing");if(!a?.size)throw s("BindEventRequired");c=Ve(d,...a)}else if(a)throw s("BindPropRequiredWhenEventProvided");if(c){let d=W(i),p=Bt(e,t,r,i,c,d),m=()=>{let T=W(p);if(T!=null){let v=c?.get(e,typeof T);v!==lt&&S([[p,v]])}};for(let T of c?.events??[])e.addEventListener(T,m);e.addEventListener(te,m);let y=R(()=>{c?.set(e,W(p))});return()=>{y();for(let T of c?.events??[])e.removeEventListener(T,m);e.removeEventListener(te,m)}}if(e instanceof HTMLInputElement)switch(e.type){case"range":case"number":c=ct(!1,"input");break;case"checkbox":c={get:(d,p)=>d.value!=="on"?p==="boolean"?d.checked:d.checked?d.value:"":p==="string"?d.checked?d.value:"":d.checked,set:(d,p)=>{d.checked=typeof p=="string"?p===d.value:p},events:["change"]};break;case"radio":e.getAttribute("name")?.length||e.setAttribute("name",i),c={get:(d,p)=>d.checked?p==="number"?+d.value:d.value:lt,set:(d,p)=>{d.checked=p===(typeof p=="number"?+d.value:d.value)},events:["change"]};break;case"file":{let d=()=>{let p=[...e.files||[]],m=[];Promise.all(p.map(y=>new Promise(T=>{let v=new FileReader;v.onload=()=>{if(typeof v.result!="string")throw s("InvalidFileResultType",{resultType:typeof v.result});let F=v.result.match(Pn);if(!F?.groups)throw s("InvalidDataUri",{result:v.result});m.push({name:y.name,contents:F.groups.contents,mime:F.groups.mime})},v.onloadend=()=>T(),v.readAsDataURL(y)}))).then(()=>{S([[i,m]])})};return e.addEventListener("change",d),()=>{e.removeEventListener("change",d)}}default:c=ct(!0,"input")}else if(e instanceof HTMLSelectElement&&e.multiple){let d=new Map;c={get:p=>[...p.selectedOptions].map(m=>{let y=d.get(m.value);return y==="string"||y==null?m.value:+m.value}),set:(p,m)=>{for(let y of p.options)m.includes(y.value)?(d.set(y.value,"string"),y.selected=!0):m.includes(+y.value)?(d.set(y.value,"number"),y.selected=!0):y.selected=!1},events:["change"]}}else e instanceof HTMLSelectElement?c=ct(!1,"change"):e instanceof HTMLTextAreaElement?c=Ve("value","input"):e instanceof HTMLElement&&e.tagName.includes("-")?c="value"in e?Ve("value","input","change"):Gt("value","input","change"):e instanceof HTMLElement&&"value"in e?c=Ve("value","change"):c=Gt("value","change");if(!c)throw s("InvalidBindAdapter");let l=W(i),u=Bt(e,t,r,i,c,l),f=()=>{let d=W(u);if(d!=null){let p=c.get(e,typeof d);p!==lt&&S([[u,p]])}};for(let d of c.events)e.addEventListener(d,f);e.addEventListener(te,f);let h=R(()=>{c.set(e,W(u))});return()=>{h();for(let d of c.events)e.removeEventListener(d,f);e.removeEventListener(te,f)}}});g({name:"class",requirement:{value:"must"},returnsValue:!0,apply({key:e,el:t,mods:n,rx:r}){e&&=O(e,n,"kebab");let s,i=()=>{o.disconnect(),s=e?{[e]:r()}:r();for(let c in s){let l=c.split(/\s+/).filter(u=>u.length>0);if(s[c])for(let u of l)t.classList.contains(u)||t.classList.add(u);else for(let u of l)t.classList.contains(u)&&t.classList.remove(u)}o.observe(t,{attributeFilter:["class"]})},o=new MutationObserver(i),a=R(i);return()=>{o.disconnect(),a();for(let c in s){let l=c.split(/\s+/).filter(u=>u.length>0);for(let u of l)t.classList.remove(u)}}}});g({name:"computed",requirement:{value:"must"},returnsValue:!0,apply({key:e,mods:t,rx:n,error:r}){if(e)S([[O(e,t),_e(n)]]);else{let s=Object.assign({},n());re(s,i=>{if(typeof i=="function")return _e(i);throw r("ComputedExpectedFunction")}),D(s)}}});g({name:"effect",requirement:{key:"denied",value:"must"},apply:({rx:e})=>R(e)});g({name:"indicator",requirement:"exclusive",apply({el:e,key:t,mods:n,value:r}){let s=t!=null?O(t,n):r,i=0;S([[s,!1]]);let o=a=>{let{type:c,el:l}=a.detail;if(l===e)switch(c){case ot:i++,S([[s,!0]]);break;case at:i=Math.max(0,i-1),S([[s,i>0]]);break}};return document.addEventListener(B,o),()=>{i=0,S([[s,!1]]),document.removeEventListener(B,o)}}});var Q=e=>{if(!e||e.size<=0)return 0;for(let t of e){if(t.endsWith("ms"))return+t.replace("ms","");if(t.endsWith("s"))return+t.replace("s","")*1e3;try{return Number.parseFloat(t)}catch{}}return 0},oe=(e,t,n=!1)=>e?e.has(t.toLowerCase()):n,jt=(e,t="")=>{if(e&&e.size>0)for(let n of e)return n;return t};var ut=(e,t)=>(...n)=>{setTimeout(()=>{e(...n)},t)},Wt=(e,t,n=!0,r=!1,s=!1)=>{let i=null,o=0;return(...a)=>{n&&!o?(e(...a),i=null):i=a,(!o||s)&&(o&&clearTimeout(o),o=setTimeout(()=>{r&&i!==null&&e(...i),i=null,o=0},t))}},ce=(e,t)=>{let n=t.get("delay");if(n){let i=Q(n);e=ut(e,i)}let r=t.get("debounce");if(r){let i=Q(r),o=oe(r,"leading",!1),a=!oe(r,"notrailing",!1);e=Wt(e,i,o,a,!0)}let s=t.get("throttle");if(s){let i=Q(s),o=!oe(s,"noleading",!1),a=oe(s,"trailing",!1);e=Wt(e,i,o,a)}return e};var ft=!!document.startViewTransition,Y=(e,t)=>{if(t.has("viewtransition")&&ft){let n=e;e=(...r)=>document.startViewTransition(()=>n(...r))}return e};g({name:"init",requirement:{key:"denied",value:"must"},apply({rx:e,mods:t}){let n=()=>{N(),e(),P()};n=Y(n,t);let r=0,s=t.get("delay");s&&(r=Q(s),r>0&&(n=ut(n,r))),n()}});g({name:"json-signals",requirement:{key:"denied"},apply({el:e,value:t,mods:n}){let r=n.has("terse")?0:2,s={};t&&(s=ae(t));let i=()=>{o.disconnect(),e.textContent=JSON.stringify($(s),null,r),o.observe(e,{childList:!0,characterData:!0,subtree:!0})},o=new MutationObserver(i),a=R(i);return()=>{o.disconnect(),a()}}});g({name:"on",requirement:"must",argNames:["evt"],apply({el:e,key:t,mods:n,rx:r}){let s=e;n.has("window")?s=window:n.has("document")&&(s=document);let i=l=>{N(),r(l),P()};i=Y(i,n),i=ce(i,n);let o=O(t,n,"kebab"),a={capture:n.has("capture"),passive:n.has("passive"),once:n.has("once")};if(n.has("outside")){s=document;let l=i;i=u=>{e.contains(u?.target)||l(u)}}(o===B||o===ne)&&(s=document);let c=l=>{l&&(n.has("prevent")&&l.preventDefault(),n.has("stop")&&l.stopPropagation(),e instanceof HTMLFormElement&&o==="submit"&&l.preventDefault()),i(l)};return s.addEventListener(o,c,a),()=>{s.removeEventListener(o,c,a)}}});var Ut=(e,t,n)=>Math.max(t,Math.min(n,e));var dt=new WeakSet;g({name:"on-intersect",requirement:{key:"denied",value:"must"},apply({el:e,mods:t,rx:n}){let r=()=>{N(),n(),P()};r=Y(r,t),r=ce(r,t);let s={threshold:0};if(t.has("full"))s.threshold=1;else if(t.has("half"))s.threshold=.5;else{let a=t.get("threshold");a&&(s.threshold=Ut(Number(jt(a)),0,100)/100)}let i=t.has("exit"),o=new IntersectionObserver(a=>{for(let c of a)c.isIntersecting!==i&&(r(),o&&dt.has(e)&&o.disconnect())},s);return o.observe(e),t.has("once")&&dt.add(e),()=>{t.has("once")||dt.delete(e),o&&(o.disconnect(),o=null)}}});g({name:"on-interval",requirement:{key:"denied",value:"must"},apply({mods:e,rx:t}){let n=()=>{N(),t(),P()};n=Y(n,e);let r=1e3,s=e.get("duration");s&&(r=Q(s),oe(s,"leading",!1)&&n());let i=setInterval(n,r);return()=>{clearInterval(i)}}});g({name:"on-signal-patch",requirement:{value:"must"},argNames:["patch"],returnsValue:!0,apply({el:e,key:t,mods:n,rx:r,error:s}){if(t&&t!=="filter")throw s("KeyNotAllowed");let i=U(`${this.name}-filter`),o=e.getAttribute(i),a={};o&&(a=ae(o));let c=!1,l=ce(u=>{if(c)return;let f=$(a,u.detail);if(!bt(f)){c=!0,N();try{r(f)}finally{P(),c=!1}}},n);return document.addEventListener(ne,l),()=>{document.removeEventListener(ne,l)}}});g({name:"ref",requirement:"exclusive",apply({el:e,key:t,mods:n,value:r}){let s=t!=null?O(t,n):r;S([[s,e]])}});var Jt="none",Kt="display";g({name:"show",requirement:{key:"denied",value:"must"},returnsValue:!0,apply({el:e,rx:t}){let n=()=>{r.disconnect(),t()?e.style.display===Jt&&e.style.removeProperty(Kt):e.style.setProperty(Kt,Jt),r.observe(e,{attributeFilter:["style"]})},r=new MutationObserver(n),s=R(n);return()=>{r.disconnect(),s()}}});g({name:"signals",returnsValue:!0,apply({key:e,mods:t,rx:n}){let r=t.has("ifmissing");if(e){e=O(e,t);let s=n?.();S([[e,s]],{ifMissing:r})}else{let s=Object.assign({},n?.());D(s,{ifMissing:r})}}});g({name:"style",requirement:{value:"must"},returnsValue:!0,apply({key:e,el:t,rx:n}){let{style:r}=t,s=new Map,i=(l,u)=>{let f=s.get(l);!u&&u!==0?f!==void 0&&(f?r.setProperty(l,f):r.removeProperty(l)):(f===void 0&&s.set(l,r.getPropertyValue(l)),r.setProperty(l,String(u)))},o=()=>{if(a.disconnect(),e)i(e,n());else{let l=n();for(let[u,f]of s)u in l||(f?r.setProperty(u,f):r.removeProperty(u));for(let u in l)i(ge(u),l[u])}a.observe(t,{attributeFilter:["style"]})},a=new MutationObserver(o),c=R(o);return()=>{a.disconnect(),c();for(let[l,u]of s)u?r.setProperty(l,u):r.removeProperty(l)}}});g({name:"text",requirement:{key:"denied",value:"must"},returnsValue:!0,apply({el:e,rx:t}){let n=()=>{r.disconnect(),e.textContent=`${t()}`,r.observe(e,{childList:!0,characterData:!0,subtree:!0})},r=new MutationObserver(n),s=R(n);return()=>{r.disconnect(),s()}}});var zt=(e,t)=>e.includes(t),On=["remove","outer","inner","replace","prepend","append","before","after"],Cn=["html","svg","mathml"];Ee({name:"datastar-patch-elements",apply(e,t){let n=typeof t.selector=="string"?t.selector:"",r=typeof t.mode=="string"?t.mode:"outer",s=typeof t.namespace=="string"?t.namespace:"html",i=typeof t.useViewTransition=="string"?t.useViewTransition:"",o=t.elements;if(!zt(On,r))throw e.error("PatchElementsInvalidMode",{mode:r});if(!n&&r!=="outer"&&r!=="replace")throw e.error("PatchElementsExpectedSelector");if(!zt(Cn,s))throw e.error("PatchElementsInvalidNamespace",{namespace:s});let a={selector:n,mode:r,namespace:s,useViewTransition:i.trim()==="true",elements:o};ft&&a.useViewTransition?document.startViewTransition(()=>Zt(e,a)):Zt(e,a)}});var Zt=({error:e},{selector:t,mode:n,namespace:r,elements:s})=>{let i=document.createDocumentFragment(),o=typeof s!="string"&&!!s;if(typeof s=="string"){let a=s.replace(/]*>|>)([\s\S]*?)<\/svg>/gim,""),c=/<\/html>/.test(a),l=/<\/head>/.test(a),u=/<\/body>/.test(a),f=r==="svg"?"svg":r==="mathml"?"math":"",h=f?`<${f}>${s}`:s,d=new DOMParser().parseFromString(c||l||u?s:``,"text/html");if(c)i.appendChild(d.documentElement);else if(l&&u)i.appendChild(d.head),i.appendChild(d.body);else if(l)i.appendChild(d.head);else if(u)i.appendChild(d.body);else if(f){let p=d.querySelector("template").content.querySelector(f);for(let m of p.childNodes)i.appendChild(m)}else i=d.querySelector("template").content}else s&&(s instanceof DocumentFragment?i=s:s instanceof Element&&i.appendChild(s));if(!t&&(n==="outer"||n==="replace")){let a=Array.from(i.children);for(let c of a){let l;if(c instanceof HTMLHtmlElement)l=document.documentElement;else if(c instanceof HTMLBodyElement)l=document.body;else if(c instanceof HTMLHeadElement)l=document.head;else if(l=document.getElementById(c.id),!l){console.warn(e("PatchElementsNoTargetsFound"),{element:{id:c.id}});continue}Yt(n,c,[l],o)}}else{let a=document.querySelectorAll(t);if(!a.length){console.warn(e("PatchElementsNoTargetsFound"),{selector:t});return}let c=o&&n!=="remove"?[a[0]]:a;Yt(n,i,c,o)}},mt=new WeakSet;for(let e of document.querySelectorAll("script"))mt.add(e);var nn=e=>{let t=e instanceof HTMLScriptElement?[e]:e.querySelectorAll("script");for(let n of t)if(!mt.has(n)){let r=document.createElement("script");for(let{name:s,value:i}of n.attributes)r.setAttribute(s,i);r.text=n.text,n.replaceWith(r),mt.add(r)}},Qt=(e,t,n,r)=>{let s=!1;for(let i of e){if(r&&s)break;let o=r?t:t.cloneNode(!0);nn(o),i[n](o),s=!0}},Yt=(e,t,n,r)=>{switch(e){case"remove":for(let s of n)s.remove();break;case"outer":case"inner":{let s=!1;for(let i of n){if(r&&s)break;let o=r?t:t.cloneNode(!0);Hn(i,o,e),nn(i);let a=i.closest("[data-scope-children]");a&&a.dispatchEvent(new CustomEvent(Ke,{bubbles:!1})),s=!0}}break;case"replace":Qt(n,t,"replaceWith",r);break;case"prepend":case"append":case"before":case"after":Qt(n,t,e,r)}},I=new Map,ue=new Set,le=new Map,Te=new Set,$e=document.createElement("div");$e.hidden=!0;var Ae=U("ignore-morph"),Fn=`[${Ae}]`,Hn=(e,t,n="outer")=>{if(Z(e)&&Z(t)&&e.hasAttribute(Ae)&&t.hasAttribute(Ae)||e.parentElement?.closest(Fn))return;let r=document.createElement("div");r.append(t),document.body.insertAdjacentElement("afterend",$e);let s=e.querySelectorAll("[id]");for(let{id:a,tagName:c}of s)le.has(a)?Te.add(a):le.set(a,c);e instanceof Element&&e.id&&(le.has(e.id)?Te.add(e.id):le.set(e.id,e.tagName)),ue.clear();let i=r.querySelectorAll("[id]");for(let{id:a,tagName:c}of i)ue.has(a)?Te.add(a):le.get(a)===c&&ue.add(a);for(let a of Te)ue.delete(a);le.clear(),Te.clear(),I.clear();let o=n==="outer"?e.parentElement:e;tn(o,s),tn(r,i),rn(o,r,n==="outer"?e:null,e.nextSibling),$e.remove()},rn=(e,t,n=null,r=null)=>{e instanceof HTMLTemplateElement&&t instanceof HTMLTemplateElement&&(e=e.content,t=t.content),n??=e.firstChild;for(let s of t.childNodes){if(n&&n!==r){let i=_n(s,n,r);if(i){if(i!==n){let o=n;for(;o&&o!==i;){let a=o;o=o.nextSibling,en(a)}}pt(i,s),n=i.nextSibling;continue}}if(s instanceof Element&&ue.has(s.id)){let i=document.getElementById(s.id),o=i;for(;o=o.parentNode;){let a=I.get(o);a&&(a.delete(s.id),a.size||I.delete(o))}sn(e,i,n),pt(i,s),n=i.nextSibling;continue}if(I.has(s)){let i=s.namespaceURI,o=s.tagName,a=i&&i!=="http://www.w3.org/1999/xhtml"?document.createElementNS(i,o):document.createElement(o);e.insertBefore(a,n),pt(a,s),n=a.nextSibling}else{let i=document.importNode(s,!0);e.insertBefore(i,n),n=i.nextSibling}}for(;n&&n!==r;){let s=n;n=n.nextSibling,en(s)}},_n=(e,t,n)=>{let r=null,s=e.nextSibling,i=0,o=0,a=I.get(e)?.size||0,c=t;for(;c&&c!==n;){if(Xt(c,e)){let l=!1,u=I.get(c),f=I.get(e);if(f&&u){for(let h of u)if(f.has(h)){l=!0;break}}if(l)return c;if(!r&&!I.has(c)){if(!a)return c;r=c}}if(o+=I.get(c)?.size||0,o>a)break;r===null&&s&&Xt(c,s)&&(i++,s=s.nextSibling,i>=2&&(r=void 0)),c=c.nextSibling}return r||null},Xt=(e,t)=>e.nodeType===t.nodeType&&e.tagName===t.tagName&&(!e.id||e.id===t.id),en=e=>{I.has(e)?sn($e,e,null):e.parentNode?.removeChild(e)},sn=(e,t,n)=>{if("moveBefore"in e){e.moveBefore(t,n);return}e.insertBefore(t,n)},kn=U("preserve-attr"),pt=(e,t)=>{let n=t.nodeType;if(n===1){let r=e,s=t,i=r.hasAttribute("data-scope-children");if(r.hasAttribute(Ae)&&s.hasAttribute(Ae))return e;let o=(t.getAttribute(kn)??"").split(" "),a=(l,u,f)=>{let h=u.hasAttribute(f);return l.hasAttribute(f)!==h&&!o.includes(f)?(l[f]=h,!0):!1},c=!1;if(r instanceof HTMLInputElement&&s instanceof HTMLInputElement&&s.type!=="file"){let l=s.getAttribute("value");r.getAttribute("value")!==l&&!o.includes("value")&&(r.value=l??"",c=!0),c=a(r,s,"checked")||c,a(r,s,"disabled")}else if(r instanceof HTMLTextAreaElement&&s instanceof HTMLTextAreaElement){let l=s.value;r.defaultValue!==l&&(r.value=l,c=!0)}else r instanceof HTMLOptionElement&&s instanceof HTMLOptionElement&&(c=a(r,s,"selected")||c);for(let{name:l,value:u}of s.attributes)r.getAttribute(l)!==u&&!o.includes(l)&&r.setAttribute(l,u);for(let{name:l}of Array.from(r.attributes))!s.hasAttribute(l)&&!o.includes(l)&&r.removeAttribute(l);c&&(r instanceof HTMLOptionElement?r.closest("select"):r)?.dispatchEvent(new Event(te,{bubbles:!0})),i&&!r.hasAttribute("data-scope-children")&&r.setAttribute("data-scope-children",""),r instanceof HTMLTemplateElement&&s instanceof HTMLTemplateElement?r.innerHTML=s.innerHTML:r.isEqualNode(s)||rn(r,s),i&&r.dispatchEvent(new CustomEvent(Ke,{bubbles:!1}))}return(n===8||n===3)&&e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e},tn=(e,t)=>{for(let n of t)if(ue.has(n.id)){let r=n;for(;r&&r!==e;){let s=I.get(r);s||(s=new Set,I.set(r,s)),s.add(n.id),r=r.parentElement}}};Ee({name:"datastar-patch-signals",apply({error:e},{signals:t,onlyIfMissing:n}){if(typeof t!="string")throw e("PatchSignalsExpectedSignals");let r=typeof n=="string"&&n.trim()==="true";D(ae(t),{ifMissing:r})}});export{V as action,kt as actions,g as attribute,N as beginBatch,_e as computed,R as effect,P as endBatch,$ as filtered,W as getPath,D as mergePatch,S as mergePaths,se as root,me as signal,_ as startPeeking,k as stopPeeking,Ee as watcher}; +//# sourceMappingURL=datastar.js.map diff --git a/pm-stack/aggregator/src/card-state.ts b/pm-stack/aggregator/src/card-state.ts new file mode 100644 index 0000000000..02c1bb892b --- /dev/null +++ b/pm-stack/aggregator/src/card-state.ts @@ -0,0 +1,104 @@ +/** + * Render-time effective state for one dashboard card (#1443/#1449/ + * #1450/#1451, epic #1442). + * + * The bug this fixes: dashboard clicks recorded actions in the store, + * but the rendered card never changed β€” the only consumer runs hourly, + * so a snooze/dismiss sat invisible for up to an hour and the card + * "would not go away". The dashboard owns the store, so the card's + * effective state is derived HERE, at render, from the same records + * the consumers will later apply: + * + * - Suppression: the latest effective snooze (until in the future), + * dismiss, or mark-done action on the object takes the card out of + * its main list immediately β€” pending (state "new") counts exactly + * like applied. A consumer REJECTION lifts the suppression again + * (the item resurfaces, with the rejection badge explaining why). + * - Restore (#1450): a `restore` action cancels the action it names + * in `supersedes`, even one the consumer already applied β€” the card + * returns to its list with its full history intact. (The store's + * own supersede transition only reaches still-new actions; cancels + * of applied actions are a derivation concern, so they live here.) + * - Acknowledged: an effective acknowledge (pending or applied) marks + * the card quiet β€” seen, not resolved. + * - Survey answers (#1451): answer actions merge per question, the + * latest answer to a question wins, so partial submits accumulate + * on the card until every required question is answered. + * + * Pure derivation over the object's action list (oldest first, the + * store's order) β€” no I/O, so renderers and tests share one truth. + */ +import { latestInFamily, type DashAction } from "./actions.ts"; + +export type CardSuppression = + | { kind: "snoozed"; until: string; action: DashAction } + | { kind: "dismissed"; action: DashAction } + | { kind: "done"; action: DashAction }; + +export interface CardState { + /** The card leaves its main list while this is set. */ + suppressed: CardSuppression | null; + /** An effective acknowledge exists (pending or applied). */ + acked: boolean; + /** Actions still waiting for their consumer (state "new"). */ + pending: DashAction[]; + /** Merged survey answers by question id, latest answer wins. */ + answered: Map; + /** The option picked by the latest effective option answer, if any. */ + answeredOptionId?: string; +} + +/** Ids cancelled by a restore: any non-superseded restore action + * cancels the action it names in `supersedes`. */ +export function cancelledActionIds(actions: DashAction[]): Set { + const out = new Set(); + for (const a of actions) { + if (a.verb === "restore" && a.state !== "superseded" && a.supersedes) out.add(a.supersedes); + } + return out; +} + +/** The actions that still speak for the object: not superseded, not + * cancelled by a restore. Input order (oldest first) is preserved. */ +export function effectiveActions(actions: DashAction[] | undefined): DashAction[] { + if (!actions?.length) return []; + const cancelled = cancelledActionIds(actions); + return actions.filter((a) => a.state !== "superseded" && !cancelled.has(a.id)); +} + +export function cardState(actions: DashAction[] | undefined, now = Date.now()): CardState { + const eff = effectiveActions(actions); + const suppressors: CardSuppression[] = []; + const snooze = latestInFamily(eff, "snooze"); + if (snooze && snooze.state !== "rejected" && snooze.payload.until && Date.parse(snooze.payload.until) > now) { + suppressors.push({ kind: "snoozed", until: snooze.payload.until, action: snooze }); + } + const dismiss = latestInFamily(eff, "dismiss"); + if (dismiss && dismiss.state !== "rejected") suppressors.push({ kind: "dismissed", action: dismiss }); + const done = latestInFamily(eff, "done"); + if (done && done.state !== "rejected") suppressors.push({ kind: "done", action: done }); + suppressors.sort((a, b) => a.action.createdAt.localeCompare(b.action.createdAt)); + + const ack = latestInFamily(eff, "ack"); + const answered = new Map(); + let answeredOptionId: string | undefined; + for (const a of eff) { + if (a.verb !== "answer" || a.state === "rejected") continue; + for (const entry of a.payload.answers ?? []) answered.set(entry.questionId, entry.value); + if (a.payload.optionId) answeredOptionId = a.payload.optionId; + } + return { + suppressed: suppressors.at(-1) ?? null, + acked: ack !== undefined && ack.state !== "rejected", + pending: eff.filter((a) => a.state === "new"), + answered, + ...(answeredOptionId ? { answeredOptionId } : {}), + }; +} + +/** The pending action of one verb on a card, if any β€” the render uses + * it to disable the matching control so repeat clicks cannot pile up + * duplicate pending actions (#1443). */ +export function pendingVerb(cs: CardState, verb: DashAction["verb"]): DashAction | undefined { + return cs.pending.find((a) => a.verb === verb); +} diff --git a/pm-stack/aggregator/src/comments.ts b/pm-stack/aggregator/src/comments.ts index 0d0ca59f21..1bc4241f60 100644 --- a/pm-stack/aggregator/src/comments.ts +++ b/pm-stack/aggregator/src/comments.ts @@ -132,6 +132,14 @@ export class CommentsStore { return (await this.all()).filter((c) => c.objectRef === objectRef); } + /** Comments grouped by object ref, oldest first β€” the per-card + * comment boxes (#1446) render from this. */ + async byObject(): Promise> { + const out = new Map(); + for (const c of await this.all()) out.set(c.objectRef, [...(out.get(c.objectRef) ?? []), c]); + return out; + } + /** Counts per object ref, for πŸ’¬ badges across the views. */ async counts(): Promise> { const out = new Map(); diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 22d1fd9ea6..b2980622d1 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -21,11 +21,14 @@ import { windowPercent, } from "./derive.ts"; import { latestInFamily, newClientToken, type DashAction } from "./actions.ts"; +import { cardState, pendingVerb, type CardState } from "./card-state.ts"; import { DELEGATION_DEFAULT_OBJECT_REF, + NEEDS_ORDER_OBJECT_REF, effectiveStandingAuto, proposalExpired, proposalIdentity, + type NeedsOrder, } from "./tier-items.ts"; import { githubCommentUrl } from "./comments.ts"; import { aaCaiPoints, aaPoints, summarizeAa } from "./aa.ts"; @@ -204,6 +207,30 @@ meter { width: 140px; height: 14px; } nav select { background: #161b22; color: #e6edf3; border: 1px solid #30363d; border-radius: 6px; padding: 6px 8px; font: inherit; margin-left: auto; max-width: 45vw; } .foot { margin-top: 40px; border-top: 1px solid #30363d; padding-top: 10px; color: #8b949e; font-size: 12px; } .card.stale { opacity: .55; } +.card.acked { opacity: .72; } +.card .sentline { color: #3fb950; font-size: 12.5px; margin: 6px 0 2px; } +.card.tombstone { opacity: .6; } +details.carddetail { margin: 8px 0 2px; border-top: 1px solid #21262d; padding-top: 6px; } +details.carddetail summary { cursor: pointer; color: #58a6ff; font-size: 12.5px; padding: 4px 0; } +details.carddetail dl { display: grid; grid-template-columns: 110px 1fr; gap: 2px 10px; margin: 6px 0; font-size: 12.5px; } +details.carddetail dt { color: #8b949e; } +details.carddetail dd { margin: 0; overflow-wrap: anywhere; } +.histline { font-size: 12.5px; margin: 3px 0; } +.quickbar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin: 6px 0; } +.quickbar .qlabel { font-size: 12px; color: #8b949e; flex-basis: 100%; } +.qchip { background: #21262d; color: #e6edf3; border: 1px solid #30363d; border-radius: 999px; padding: 6px 12px; font: inherit; font-size: 12.5px; cursor: pointer; min-height: 36px; } +.qchip.primary { background: #1f6feb; border-color: #1f6feb; color: #fff; } +.qchip:disabled { opacity: .45; cursor: not-allowed; } +.aform.qform { display: inline-flex; margin: 0; } +.cbox { border-top: 1px solid #21262d; margin-top: 8px; padding-top: 6px; } +.cbox .cform { border: 0; padding: 4px 0 0; margin: 0; background: none; } +.cbox summary { cursor: pointer; color: #58a6ff; font-size: 12.5px; padding: 4px 0; } +.qblock .qanswered { color: #3fb950; font-size: 12px; } +.qblock .qremaining { color: #e3b341; font-size: 12px; } +.skel { border: 1px dashed #30363d; border-radius: 8px; padding: 14px 12px; margin: 8px 0; color: #8b949e; background: #0d1117; } +.orderctl { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 8px 0; font-size: 12.5px; color: #8b949e; } +.orderctl .aform { margin: 0; } +.stripcard .restore-note { font-size: 12.5px; } .badge.stale { background: #d2992233; border-color: #d29922; color: #e3b341; } .badge.conflict { background: #bc8cff33; border-color: #bc8cff; color: #bc8cff; } .flag { border: 1px solid #f85149; background: #f8514911; border-radius: 8px; padding: 8px 12px; margin: 8px 0; } @@ -256,12 +283,42 @@ body.xp-plan .xpl-costcol { display: none; } /** Canonical tailnet URL for this dashboard (MagicDNS β€” never the raw IP). */ export const TAILNET_URL = "http://amd-6.raptor-pumpkinseed.ts.net:4870"; +/** + * Shared post-submit feedback (#1443): the click must visibly land. + * The card's controls disable, a "βœ“ sent Β· pending" line appears in + * place, and a suppressing verb (snooze / dismiss / mark-done) + * tombstones the card immediately β€” the server render (via the + * Datastar fragment refresh this dispatches, or the next page load) + * then moves it to its strip for real. Pages without Datastar + * fragment containers keep the historical full reload. + */ +const DASH_AFTER_JS = ` +window.__dashAfter = window.__dashAfter || function (form, msg) { + var card = form.closest(".card"); + form.querySelectorAll("button, input, select, textarea").forEach(function (b) { b.disabled = true; }); + if (card) { + var line = document.createElement("div"); + line.className = "sentline"; + line.textContent = msg; + card.appendChild(line); + var verb = form.dataset.verb; + if (verb === "snooze" || verb === "dismiss" || verb === "mark-done") card.classList.add("tombstone"); + } + window.dispatchEvent(new CustomEvent("dashrefresh")); + if (!document.querySelector("[data-frag]")) location.reload(); +}; +`; + /** * The client side of the comment form (one delegated submit handler; * pages without a form never notice it). Kept dependency-free and - * inline, like everything else in this app. + * inline, like everything else in this app. The card comment box + * (#1446) posts kind "message" for the orchestrator and β€” when its + * "also post publicly" box is ticked and the card carries a gh: ref + * in data-ghref β€” a second, kind "github" comment the orchestrator + * posts to the issue (the aggregator holds no GitHub credentials). */ -const COMMENT_SCRIPT = ``; @@ -412,7 +482,7 @@ function layout( const dropdown = ``; return ` -${esc(title)} Β· aggregator +${esc(title)} Β· aggregator
${chipsHtml}${body}
source detailboard: ${esc(provenance.board)} Β· roadmap: ${esc(provenance.roadmap)} Β· items: ${esc(provenance.items)} Β· comments: ${esc(provenance.comments)} Β· quota: ${esc(provenance.quota)} Β· usage: ${esc(provenance.usage)} Β· attention: ${esc(provenance.attention)} Β· orchestration: ${esc(provenance.orchestration)} Β· dns: ${esc(provenance.dns)} Β· registry: ${esc(provenance.registry)} Β· aa: ${esc(provenance.aa)}
tailnet: ${TAILNET_URL.replace("http://", "")}
${extra}`; @@ -527,6 +597,9 @@ const VERB_BADGE_LABELS: Record = { answer: "answer", delegate: "delegate", dismiss: "dismiss", + "mark-done": "already done", + restore: "restore", + "set-needs-order": "card order", "approve-proposal": "approve proposal", "reject-proposal": "reject proposal", "request-status": "status change", @@ -611,6 +684,134 @@ export interface ActionFormOpts { disabledReason?: string; } +/** Stable DOM id for one card, from its object ref (#1444 fragments + * patch sections; #1443's in-place feedback finds cards by ref). */ +export function cardDomId(objectRef: string): string { + return `card-${objectRef.replace(/[^a-zA-Z0-9]+/g, "-")}`; +} + +/** The card's action history (#1445): every recorded action with its + * state β€” the audit trail the store keeps, readable on the card. */ +export function actionHistoryHtml(actions: DashAction[] | undefined): string { + if (!actions?.length) return `

No actions recorded on this card yet.

`; + return [...actions] + .reverse() + .map((a) => { + const bits = [ + `${esc(VERB_BADGE_LABELS[a.verb] ?? a.verb)}`, + a.state === "new" + ? "⏳ pending" + : a.state === "applied" + ? `βœ“ applied${a.appliedByRun ? ` by ${esc(a.appliedByRun)}` : ""}` + : a.state === "rejected" + ? "βœ— rejected" + : "superseded", + esc(relTime(a.createdAt)), + a.payload.reason ? `β€” ${esc(a.payload.reason)}` : "", + a.payload.until ? `until ${esc(fmtDate(a.payload.until))}` : "", + a.resultNote ? `Β· ${esc(a.resultNote)}` : "", + ].filter(Boolean); + return `
${bits.join(" ")}
`; + }) + .join(""); +} + +/** + * The per-card comment box (#1446): the card's existing dashboard + * comments with their queued/posted state, plus a compact form. The + * form posts kind "message" (the orchestrator's queue input); the + * "also post publicly" checkbox adds a kind "github" comment when + * the card carries a gh: ref β€” posted later by the orchestrator, + * never by the aggregator (no GitHub credentials here). + */ +export function cardCommentHtml( + objectRef: string, + ghRef: RefKey | undefined, + comments: DashComment[] | undefined, + opts: CommentFormOpts, +): string { + const list = comments?.length + ? comments.map((c) => dashCommentHtml(c)).join("") + : `

No comments on this card yet.

`; + const authorOptions = opts.identities + .map( + (i) => + ``, + ) + .join(""); + const ghBox = ghRef + ? `` + : `No GitHub issue on this card β€” the comment stays internal.`; + return `
πŸ’¬ Comments for the orchestrator${comments?.length ? ` (${comments.length})` : ""}${list}
+ + + +
${ghBox}
+
`; +} + +/** One-tap dismissal reasons (#1449): the common resolutions. */ +export const DISMISS_REASONS = ["Already handled", "No longer relevant", "Duplicate", "Won't do"] as const; +/** One-tap de-escalation reasons (#1449): Drew's "send why" chips. */ +export const DEESCALATE_REASONS = [ + "Orchestrator should have handled this", + "Passing to orchestrator this time", + "Need more info", + "Need recommendations", +] as const; + +/** + * The quick-action bar (#1449): one-tap resolutions with the reason + * attached, writing the existing action vocabulary. Chips disable + * while their verb is pending, so a resolution can't be double-sent. + */ +export function quickBarHtml(objectRef: string, tier: "needs-drew" | "needs-orchestrator", cs: CardState): string { + const chip = ( + verb: DashAction["verb"], + label: string, + hidden: string, + opts: { primary?: boolean; disabled?: boolean; sentLabel?: string } = {}, + ): string => + aformHtml({ + kind: "triage", + verb, + objectRef, + inner: `${hidden}`, + }).replace('class="aform"', 'class="aform qform"'); + const donePending = pendingVerb(cs, "mark-done"); + const dismissPending = pendingVerb(cs, "dismiss"); + const movePending = pendingVerb(cs, "de-escalate") ?? pendingVerb(cs, "escalate"); + const parts: string[] = [ + chip("mark-done", "Already done", "", { + primary: true, + disabled: !!donePending, + sentLabel: "βœ“ Already done Β· sent", + }), + ]; + for (const reason of DISMISS_REASONS) { + parts.push( + chip("dismiss", `Dismiss: ${reason}`, ``, { + disabled: !!dismissPending, + sentLabel: "Dismiss Β· sent", + }), + ); + } + if (tier === "needs-drew") { + for (const reason of DEESCALATE_REASONS) { + parts.push( + chip( + "de-escalate", + reason, + ``, + { disabled: !!movePending, sentLabel: "Sent to orchestrator" }, + ), + ); + } + } + const note = donePending || dismissPending || movePending ? ` ⏳ sent Β· pending` : ""; + return `
Quick actions β€” one tap, reason attached${note}${parts.join("")}
`; +} + function authorSelectHtml(identities: AuthorIdentity[]): string { const options = identities .map( @@ -683,33 +884,47 @@ export function triageActionsHtml( tier: "needs-drew" | "needs-orchestrator", opts: ActionFormOpts, extraForms = "", + cs: CardState = cardState(undefined), ): string { + // #1443: a control whose verb is already pending (or, for + // acknowledge, already in effect) renders disabled β€” repeat clicks + // cannot pile up duplicate pending actions, and the card SAYS so. + const ackPending = pendingVerb(cs, "acknowledge"); + const snoozePending = pendingVerb(cs, "snooze"); + const moveVerb = tier === "needs-drew" ? "de-escalate" : "escalate"; + const movePending = pendingVerb(cs, moveVerb); const move = tier === "needs-drew" ? aformHtml({ kind: "triage", verb: "de-escalate", objectRef, - inner: ``, + inner: ``, }) : aformHtml({ kind: "triage", verb: "escalate", objectRef, - inner: ``, + inner: ``, }); + const ackInner = ackPending + ? `Recorded β€” the fleet applies it on its next pass.` + : cs.acked + ? `You have seen this β€” it stays until a resolving action or a new signal.` + : `Records that you have seen this β€” it stays until a resolving action or a new signal.`; const forms = [ + quickBarHtml(objectRef, tier, cs), aformHtml({ kind: "triage", verb: "acknowledge", objectRef, - inner: `Records that you have seen this β€” it stays until a resolving action or a new signal.`, + inner: ackInner, }), aformHtml({ kind: "triage", verb: "snooze", objectRef, - inner: `${snoozeFieldsHtml()}`, + inner: `${snoozeFieldsHtml()}`, }), move, ].join(""); @@ -741,8 +956,9 @@ export function whyUserBadge(item: TierItem): string { return ` ${esc(WHY_USER_LABELS[item.whyUser])}`; } -function questionFieldHtml(q: TierItemQuestion): string { +function questionFieldHtml(q: TierItemQuestion, answeredValue?: string | string[]): string { const name = `answers:${q.id}`; + const answered = answeredValue !== undefined; let field: string; if (q.type === "single" || q.type === "yesno") { const opts = q.options ?? [ @@ -752,17 +968,28 @@ function questionFieldHtml(q: TierItemQuestion): string { field = `${opts .map( (o) => - ``, + ``, ) .join("")}`; } else if (q.type === "multi") { + const chosen = Array.isArray(answeredValue) ? answeredValue : answeredValue ? [answeredValue] : []; field = `${(q.options ?? []) - .map((o) => ``) + .map( + (o) => + ``, + ) .join("")}`; } else { - field = ``; + field = ``; } - return `
${esc(q.prompt)}${q.required ? "" : ` (optional)`}
${field}
Needed: ${esc(q.covers)}
`; + // #1451: answered state rides the card β€” a partial submit records + // what it covered and the still-open required questions say so. + const state = answered + ? ` βœ“ answered: ${esc(Array.isArray(answeredValue) ? answeredValue.join(", ") : (answeredValue ?? ""))}` + : q.required + ? ` still needed` + : ""; + return `
${esc(q.prompt)}${q.required ? "" : ` (optional)`}${state}
${field}
Needed: ${esc(q.covers)}
`; } /** The latest applied reject-proposal on an item, when one exists β€” @@ -856,27 +1083,39 @@ export function needsUserBodyHtml(item: TierItem, actions: DashAction[] | undefi * form, a free-text answer when the item offers neither, delegation * mode controls, proposal approve/reject, and dismiss (#1291). */ -export function needsUserFormsHtml(item: TierItem, objectRef: string, now = Date.now()): string { +export function needsUserFormsHtml( + item: TierItem, + objectRef: string, + now = Date.now(), + cs: CardState = cardState(undefined), +): string { const forms: string[] = []; for (const opt of item.options ?? []) { + const picked = cs.answeredOptionId === opt.id; forms.push( aformHtml({ kind: "triage", verb: "answer", objectRef, - inner: `${ + inner: `${ opt.description ? `${esc(opt.description)}` : "" }${opt.effect ? `Effect: ${esc(opt.effect)}` : ""}`, }), ); } if (item.questions?.length) { + const remaining = item.questions.filter((q) => q.required && !cs.answered.has(q.id)); + const allDone = remaining.length === 0 && item.questions.some((q) => cs.answered.has(q.id)); forms.push( aformHtml({ kind: "triage", verb: "answer", objectRef, - inner: `${item.questions.map((q) => questionFieldHtml(q)).join("")}Required questions are enforced when this posts β€” an incomplete survey comes back with a legible error, nothing is recorded.`, + inner: `${item.questions.map((q) => questionFieldHtml(q, cs.answered.get(q.id))).join("")}${ + allDone + ? "All required questions are answered β€” the answers are recorded and pending with the orchestrator." + : `Answer any subset and submit (#1451): answered questions are recorded, and the card keeps showing what remains${remaining.length ? ` β€” still needed: ${esc(remaining.map((q) => q.id).join(", "))}` : ""}.` + }`, }), ); } @@ -922,13 +1161,13 @@ export function needsUserFormsHtml(item: TierItem, objectRef: string, now = Date kind: "triage", verb: "approve-proposal", objectRef, - inner: `${identity}The pass applies it on its next run and reports the application.`, + inner: `${identity}The pass applies it on its next run and reports the application.`, }), aformHtml({ kind: "triage", verb: "reject-proposal", objectRef, - inner: `${identity}`, + inner: `${identity}`, }), ); } @@ -1113,12 +1352,11 @@ function stripHtml(items: Map, links: BoardItem["links"]): strin // --- Board view ----------------------------------------------------------- -export function renderBoard( +/** The board's card grid alone (#1444 fragment payload). */ +export function renderBoardBody( board: BoardItem[], items: Map, - provenance: Provenance, counts?: Map, - detail?: ProvenanceDetail, act?: { actionsByObject?: Map; poolByRef?: Map; @@ -1178,9 +1416,25 @@ export function renderBoard( return `

${heading}

${cards}
`; }) .join(""); + return `
${bodies}
`; +} + +/** The board page (#1444): full server render. */ +export function renderBoard( + board: BoardItem[], + items: Map, + provenance: Provenance, + counts?: Map, + detail?: ProvenanceDetail, + act?: { + actionsByObject?: Map; + poolByRef?: Map; + identities?: AuthorIdentity[]; + }, +): string { return layout( "Cross-repo WIP board", - `

Cross-repo WIP board

What is being worked on now is the in-flight lane: synthetic entries from the orchestrator's lined-up tasks (the fleet feed's orchestration section), not Kaneo cards. The other columns are the curated Kaneo board across the four repos, including its completion history β€” on their own they are a record of finished and in-review work, not a live WIP list. Each Kaneo card's execution strip is derived from its linked issues/PRs: implementing β†’ review β†’ merged.

${bodies}
`, + `

Cross-repo WIP board

What is being worked on now is the in-flight lane: synthetic entries from the orchestrator's lined-up tasks (the fleet feed's orchestration section), not Kaneo cards. The other columns are the curated Kaneo board across the four repos, including its completion history β€” on their own they are a record of finished and in-review work, not a live WIP list. Each Kaneo card's execution strip is derived from its linked issues/PRs: implementing β†’ review β†’ merged.

${renderBoardBody(board, items, counts, act)}`, provenance, "/", act?.identities ? ACTION_SCRIPT : "", @@ -1188,6 +1442,19 @@ export function renderBoard( ); } +/** The Datastar shell for / (#1444): heading + intro paint at once; + * the board itself streams in from /frag/board. */ +export function renderBoardShell(provenance: Provenance, detail?: ProvenanceDetail): string { + return layout( + "Cross-repo WIP board", + `

Cross-repo WIP board

What is being worked on now is the in-flight lane: synthetic entries from the orchestrator's lined-up tasks (the fleet feed's orchestration section), not Kaneo cards.

Loading the board…
`, + provenance, + "/", + ACTION_SCRIPT, + detail ? freshnessChips(detail, ["board", "items", "orchestration"]) : "", + ); +} + // --- Roadmap view ---------------------------------------------------------- const GRAINS: [RoadmapGrain, string][] = [ @@ -1679,7 +1946,12 @@ function sessionCard( children: Map, depth = 0, counts?: Map, - act?: { actionsByObject?: Map; identities?: AuthorIdentity[] }, + act?: { + actionsByObject?: Map; + identities?: AuthorIdentity[]; + commentsByObject?: Map; + commentOpts?: CommentFormOpts; + }, ): string { const src = SESSION_SOURCE_LABELS[sourceOf(e)]; const sub = @@ -1709,16 +1981,24 @@ function sessionCard( const objectRef = sessionObjectRef(e.sessionId); const own = act?.actionsByObject?.get(objectRef); const badges = actionBadgesHtml(own); + const cs = cardState(own); let controls = ""; if (act?.identities) { const sessionBox = sessionActionsHtml(e.sessionId, sourceOf(e), { identities: act.identities }); const triageBox = e.tier === "needs-drew" || e.tier === "needs-orchestrator" - ? triageActionsHtml(objectRef, e.tier, { identities: act.identities }) + ? triageActionsHtml(objectRef, e.tier, { identities: act.identities }, "", cs) : ""; controls = `${sessionBox}${triageBox}`; } - return `
${esc(e.title ?? e.sessionId)} ${esc(src)} ${esc(STATE_LABELS[e.state])}${tierBadge}${sub}${cmt}${badges}
${esc(e.sessionId)} Β· ${esc(e.directory ?? "β€”")}${e.branch ? ` Β· ${esc(e.branch)}` : ""} Β· ${esc(e.model ?? "β€”")}${e.provider ? ` / ${esc(e.provider)}` : ""} Β· last activity ${fmtDate(e.lastActivityAt)} Β· ${esc(e.messageCount ?? "β€”")} msgs${e.outcome ? ` Β· outcome: ${esc(e.outcome)}` : ""}
${esc(evidence)}${reason}${orch}${controls}${kidsHtml}
`; + // #1445/#1446: inline detail (state + full action history) and the + // per-card comment box ride the session card too. + const detail = `
Details & history
Session
${esc(e.sessionId)}
State
${esc(STATE_LABELS[e.state] ?? e.state)}
Last activity
${esc(fmtDate(e.lastActivityAt))}
Ref
${esc(objectRef)}
${actionHistoryHtml(own)}
`; + const commentBox = + act?.identities && act.commentOpts + ? cardCommentHtml(objectRef, undefined, act.commentsByObject?.get(objectRef), act.commentOpts) + : ""; + return `
${esc(e.title ?? e.sessionId)} ${esc(src)} ${esc(STATE_LABELS[e.state])}${tierBadge}${sub}${cmt}${badges}
${esc(e.sessionId)} Β· ${esc(e.directory ?? "β€”")}${e.branch ? ` Β· ${esc(e.branch)}` : ""} Β· ${esc(e.model ?? "β€”")}${e.provider ? ` / ${esc(e.provider)}` : ""} Β· last activity ${fmtDate(e.lastActivityAt)} Β· ${esc(e.messageCount ?? "β€”")} msgs${e.outcome ? ` Β· outcome: ${esc(e.outcome)}` : ""}
${esc(evidence)}${reason}${orch}${controls}${detail}${commentBox}${kidsHtml}
`; } /** A #899 tier item that is not a live session β€” a decision, task, or gap. */ @@ -1726,7 +2006,13 @@ function tierItemCard( item: TierItem, whyLabel: string, counts?: Map, - act?: { actions?: DashAction[]; identities?: AuthorIdentity[]; disabledReason?: string }, + act?: { + actions?: DashAction[]; + identities?: AuthorIdentity[]; + disabledReason?: string; + comments?: DashComment[]; + commentOpts?: CommentFormOpts; + }, ): string { const blocked = item.blockedBy?.length ? `
Blocked by: ${item.blockedBy @@ -1746,8 +2032,9 @@ function tierItemCard( // options / survey / delegation / dismiss forms in the actbox. const isUserTier = whyLabel === "Why you"; const objectRef = tierItemObjectRef(item); + const cs = cardState(act?.actions); const extBody = isUserTier ? needsUserBodyHtml(item, act?.actions) : ""; - const extForms = isUserTier ? needsUserFormsHtml(item, objectRef) : ""; + const extForms = isUserTier ? needsUserFormsHtml(item, objectRef, Date.now(), cs) : ""; // #1152: the triage control set. Section-derived items disable with // the reason when the tier source is absent/invalid (#1139 state) β€” // the item may not exist in the publisher's current view. @@ -1760,9 +2047,121 @@ function tierItemCard( ...(act.disabledReason ? { disabledReason: act.disabledReason } : {}), }, extForms, + cs, ) : ""; - return `
${esc(item.source)} ${esc(item.kind)}${isUserTier ? whyUserBadge(item) : ""} ${esc(item.title)}${cmt}${badges}
${esc(whyLabel)}: ${esc(item.reason)}${question}${blocked}${action}${extBody}${ref}${controls}
`; + // #1445: the title itself links to the GitHub issue when the card + // carries a gh: ref, and every card expands inline to its full + // detail β€” source, state, since/lastSeenAt, horizon, blockedBy, + // the question payload, and the recorded action history. + const titleHtml = item.ref ? `${esc(item.title)}` : esc(item.title); + const questionPayload = item.questions?.length + ? `
Questions
${item.questions + .map( + (q) => + `${esc(q.prompt)} (covers: ${esc(q.covers)}${q.required ? "" : "; optional"})`, + ) + .join("
")}
` + : item.question + ? `
Question
β€œ${esc(item.question)}”
` + : ""; + const detail = `
Details & history
Source
${esc(item.source)} Β· ${esc(item.kind)}${item.state ? ` Β· state ${esc(item.state)}` : ""}
Since
${esc(fmtDate(item.since))}
Last seen
${esc(fmtDate(item.lastSeenAt))}
${item.horizon ? `
Horizon
${esc(item.horizon)}
` : ""}
Ref
${esc(objectRef)}${item.ref ? ` Β· ${esc(item.ref)}` : ""}
${item.blockedBy?.length ? `
Blocked by
${item.blockedBy.map((d) => esc(`${d.task} (${d.status}${d.workerLabel ? `, ${d.workerLabel}` : ""})`)).join("; ")}
` : ""}${questionPayload}
${actionHistoryHtml(act?.actions)}
`; + const commentBox = + act?.identities && act.commentOpts ? cardCommentHtml(objectRef, item.ref, act.comments, act.commentOpts) : ""; + return `
${esc(item.source)} ${esc(item.kind)}${isUserTier ? whyUserBadge(item) : ""} ${titleHtml}${cmt}${badges}
${esc(whyLabel)}: ${esc(item.reason)}${question}${blocked}${action}${extBody}${ref}${controls}${detail}${commentBox}
`; +} + +export interface AttentionAct { + actionsByObject?: Map; + identities?: AuthorIdentity[]; + commentsByObject?: Map; + commentOpts?: CommentFormOpts; + /** #1456: the effective Needs-you card order + its pending state. */ + needsOrder?: NeedsOrder; + needsOrderPending?: boolean; +} + +interface StripEntry { + objectRef: string; + title?: string; + cs: CardState; +} + +/** One suppressed card in a strip (#1443/#1450): what happened, when it + * lifts, and the way back β€” Unsnooze for a snooze (a superseding + * snooze at "now"), Restore for a dismiss / mark-done (a restore + * action superseding the suppressor). */ +function stripCardHtml(entry: StripEntry, identities: AuthorIdentity[] | undefined): string { + const sup = entry.cs.suppressed!; + const refLink = `${entry.title ? esc(entry.title) : `${esc(entry.objectRef)}`}`; + if (sup.kind === "snoozed") { + const a = sup.action; + const stateLine = + a.state === "new" + ? `⏳ sent Β· pending β€” snooze until ${esc(fmtDate(sup.until))}` + : `applied by ${esc(a.appliedByRun ?? "a fleet run")} β€” snoozed until ${esc(fmtDate(sup.until))}`; + const unsnooze = + identities !== undefined + ? actboxHtml( + { identities }, + aformHtml({ + kind: "triage", + verb: "snooze", + objectRef: entry.objectRef, + supersedes: a.id, + inner: ``, + }), + ) + : ""; + return `
πŸ’€ ${refLink} snoozed until ${esc(fmtDate(sup.until))}
${stateLine}${a.resultNote ? ` β€” ${esc(a.resultNote)}` : ""}${unsnooze}
`; + } + const a = sup.action; + const label = sup.kind === "done" ? "βœ“ marked done by you" : "dismissed by you"; + const stateLine = + a.state === "new" + ? "⏳ sent Β· pending" + : a.state === "applied" + ? `applied by ${esc(a.appliedByRun ?? "a fleet run")}` + : a.state; + const restore = + identities !== undefined + ? actboxHtml( + { identities }, + aformHtml({ + kind: "triage", + verb: "restore", + objectRef: entry.objectRef, + supersedes: a.id, + inner: `Records a restore that supersedes the ${sup.kind === "done" ? "mark-done" : "dismiss"} β€” the card returns with its history intact.`, + }), + ) + : ""; + return `
${refLink} ${label}
${stateLine}${a.payload.reason ? ` β€” reason: ${esc(a.payload.reason)}` : ""}${a.resultNote ? ` Β· ${esc(a.resultNote)}` : ""} Β· ${esc(relTime(a.createdAt))}${restore}
`; +} + +const HORIZON_RANK: Record = { today: 0, "3d": 1, week: 2, month: 3, quarter: 4 }; + +/** #1456: the order control for the Needs-you list β€” a preference + * action; the render applies the saved order immediately. */ +function needsOrderHtml(act: AttentionAct | undefined): string { + if (!act?.identities) return ""; + const order = act.needsOrder ?? "urgency"; + const labels: Record = { + urgency: "Urgency (orchestrator's order)", + newest: "Newest first", + oldest: "Oldest first", + deadline: "Deadline (horizon)", + }; + const options = (Object.keys(labels) as NeedsOrder[]) + .map((o) => ``) + .join(""); + const form = aformHtml({ + kind: "preference", + verb: "set-needs-order", + objectRef: NEEDS_ORDER_OBJECT_REF, + inner: `${act.needsOrderPending ? `⏳ change pending β€” the orchestrator's canonical order follows on its next pass` : ""}`, + }); + return `
Needs-you list order: ${esc(labels[order])}${actboxHtml({ identities: act.identities }, form)}
`; } export function renderAttention( @@ -1771,12 +2170,35 @@ export function renderAttention( provenance: Provenance, counts?: Map, detail?: ProvenanceDetail, - act?: { actionsByObject?: Map; identities?: AuthorIdentity[] }, + act?: AttentionAct, ): string { + const sections = attentionSections(view, coverage, counts, act); + return layout( + "Needs you", + `

Needs you

The NEEDS USER queue is an intake the orchestrator works first β€” it resolves what it can and escalates only what genuinely requires the user, each escalated item with its reason. Everything else the fleet can work is the orchestrator's own queue. Finished runs and stale items expire out (2 h after a run finishes, 24 h at the latest). Machine-first: /api/attention.json Β· /api/coverage.json.

+${sections.header}${sections.queues}${sections.sessions}`, + provenance, + "/attention", + act?.identities ? ACTION_SCRIPT + COMMENT_SCRIPT : "", + detail ? freshnessChips(detail, ["orchestration", "attention", "registry"]) : "", + ); +} + +/** + * The attention page in three independently loadable sections + * (#1444): header (banner / chips / coverage / standing default), + * queues (Needs User + Needs Orchestrator + the snoozed & hidden + * strips), sessions. The full page assembles them; the shell serves + * them as Datastar fragments from /frag/attention/*. + */ +export function attentionSections( + view: AttentionView, + coverage: SourceCoverage[], + counts?: Map, + act?: AttentionAct, +): { header: string; queues: string; sessions: string } { const children = sessionChildren(view.all); const roots = sessionRoots(view.all); - const drewTotal = view.drew.length + view.drewExtra.length; - const orchTotal = view.orchestrator.length + view.orchestratorExtra.length; // #1139: the tier source's state decides what the counts may claim. // Absent/invalid β†’ the orchestrator's published queues are NOT // reflected here, so the banner says so and the headings render @@ -1796,9 +2218,6 @@ export function renderAttention( ts.present && ts.runId ? ` Β· section ${esc(ts.runId)} Β· ${esc(ts.generatedAt ? feedAgeText(ts.generatedAt) : "")}` : ""; - const drewCount = ts.present ? String(drewTotal) : "unknown"; - const orchCount = ts.present ? String(orchTotal) : "unknown"; - const chips = ``; // #1152: section-derived items disable their controls whenever the // tier source is not live β€” stale items come from the publisher's // last section and may no longer exist in its current view (absent/ @@ -1808,11 +2227,111 @@ export function renderAttention( ts.state !== "live" ? `the tier source is ${ts.state}, so this item cannot be confirmed against the orchestrator's current published queues` : undefined; - const tierAct = (item: TierItem) => ({ - actions: act?.actionsByObject?.get(tierItemObjectRef(item)), - identities: act?.identities, - ...(sectionDisabledReason ? { disabledReason: sectionDisabledReason } : {}), - }); + const tierAct = (item: TierItem) => { + const objectRef = tierItemObjectRef(item); + return { + actions: act?.actionsByObject?.get(objectRef), + identities: act?.identities, + ...(sectionDisabledReason ? { disabledReason: sectionDisabledReason } : {}), + comments: act?.commentsByObject?.get(objectRef), + commentOpts: act?.commentOpts, + }; + }; + const sessionAct = act + ? { + actionsByObject: act.actionsByObject, + identities: act.identities, + commentsByObject: act.commentsByObject, + commentOpts: act.commentOpts, + } + : undefined; + + // #1443/#1449/#1450: partition every queue entry by its render-time + // effective state. A suppressed entry (active snooze, dismiss, or + // mark-done β€” pending counts, exactly like applied) leaves its list + // NOW and lands in the matching strip with its way back; the counts + // below are the VISIBLE counts, so acting on a card visibly moves + // the numbers. + const now = Date.now(); + const snoozedList: StripEntry[] = []; + const hiddenList: StripEntry[] = []; + const inViewRefs = new Set(); + const partition = ( + objectRef: string, + title: string | null | undefined, + actions: DashAction[] | undefined, + ): CardState => { + inViewRefs.add(objectRef); + const cs = cardState(actions, now); + if (cs.suppressed) { + (cs.suppressed.kind === "snoozed" ? snoozedList : hiddenList).push({ objectRef, title: title ?? undefined, cs }); + } + return cs; + }; + interface QueuedCard { + html: string; + sinceMs: number; + seenMs: number; + rank: number; + } + const drewCardsList: QueuedCard[] = []; + for (const e of view.drew) { + const objectRef = sessionObjectRef(e.sessionId); + const cs = partition(objectRef, e.title ?? e.sessionId, act?.actionsByObject?.get(objectRef)); + if (cs.suppressed) continue; + drewCardsList.push({ + html: sessionCard(e, children, 0, counts, sessionAct), + sinceMs: Date.parse(e.lastActivityAt ?? "") || 0, + seenMs: Date.parse(e.lastActivityAt ?? "") || 0, + rank: 5, + }); + } + for (const item of view.drewExtra) { + const objectRef = tierItemObjectRef(item); + const cs = partition(objectRef, item.title, act?.actionsByObject?.get(objectRef)); + if (cs.suppressed) continue; + drewCardsList.push({ + html: tierItemCard(item, "Why you", counts, tierAct(item)), + sinceMs: Date.parse(item.since) || 0, + seenMs: Date.parse(item.lastSeenAt) || 0, + rank: item.horizon ? (HORIZON_RANK[item.horizon] ?? 5) : 5, + }); + } + // #1456: the saved card order applies at render. "urgency" is the + // published order (no sort); the rest sort the visible list. + const order = act?.needsOrder ?? "urgency"; + if (order === "newest") drewCardsList.sort((a, b) => b.seenMs - a.seenMs); + else if (order === "oldest") drewCardsList.sort((a, b) => a.sinceMs - b.sinceMs); + else if (order === "deadline") drewCardsList.sort((a, b) => a.rank - b.rank || b.seenMs - a.seenMs); + const orchCardsList: string[] = []; + for (const e of view.orchestrator) { + const objectRef = sessionObjectRef(e.sessionId); + const cs = partition(objectRef, e.title ?? e.sessionId, act?.actionsByObject?.get(objectRef)); + if (cs.suppressed) continue; + orchCardsList.push(sessionCard(e, children, 0, counts, sessionAct)); + } + for (const item of view.orchestratorExtra) { + const objectRef = tierItemObjectRef(item); + const cs = partition(objectRef, item.title, act?.actionsByObject?.get(objectRef)); + if (cs.suppressed) continue; + orchCardsList.push(tierItemCard(item, "Why the fleet", counts, tierAct(item))); + } + // Store-only suppressed refs: items the publisher no longer lists + // (their dismissal was applied and they left the tiers) stay visible + // β€” and restorable β€” here, never silently gone (#1450). + for (const [objectRef, actions] of act?.actionsByObject?.entries() ?? []) { + if (inViewRefs.has(objectRef)) continue; + const cs = cardState(actions, now); + if (cs.suppressed) { + (cs.suppressed.kind === "snoozed" ? snoozedList : hiddenList).push({ objectRef, cs }); + } + } + + const drewVisible = drewCardsList.length; + const orchVisible = orchCardsList.length; + const drewCount = ts.present ? String(drewVisible) : "unknown"; + const orchCount = ts.present ? String(orchVisible) : "unknown"; + const chips = ``; // #1290/#1291: the standing delegation-default toggle β€” a dashboard // preference, so it renders whenever the action surface is up; its // state comes from the preference records in the store. @@ -1821,77 +2340,71 @@ export function renderAttention( identities: act.identities, }) : ""; + const header = `${tierBanner}${chips} +${coverageHtml(coverage)} +${delegationDefault}`; const drewCards = - [ - ...view.drew.map((e) => sessionCard(e, children, 0, counts, act)), - ...view.drewExtra.map((i) => tierItemCard(i, "Why you", counts, tierAct(i))), - ].join("") || + drewCardsList.map((c) => c.html).join("") || (ts.present ? `

Nothing in the user queue right now.

` : `

Unknown β€” the tier source is missing, so this queue cannot be reported.

`); const orchCards = - [ - ...view.orchestrator.map((e) => sessionCard(e, children, 0, counts, act)), - ...view.orchestratorExtra.map((i) => tierItemCard(i, "Why the fleet", counts, tierAct(i))), - ].join("") || + orchCardsList.join("") || (ts.present ? `

The fleet's queue is empty.

` : `

Unknown β€” the tier source is missing, so this queue cannot be reported.

`); - // The snoozed strip: an applied snooze makes the pass omit the item - // from the tiers, so the suppression is rendered HERE, from the - // actions store β€” visible, never silent (design Cluster 3). - const now = Date.now(); - const snoozedEntries = [...(act?.actionsByObject?.entries() ?? [])] - .map(([objectRef, actions]) => ({ objectRef, snooze: latestInFamily(actions, "snooze") })) - .filter((x) => x.snooze?.state === "applied" && x.snooze.payload.until && Date.parse(x.snooze.payload.until) > now); - const snoozedStrip = snoozedEntries.length - ? `

Snoozed by you (${snoozedEntries.length})

These items are out of the queues until their snooze expires β€” the orchestration pass omits them, and they resurface on their own. Unsnoozing records a superseding action.

${snoozedEntries - .map(({ objectRef, snooze }) => { - const unsnooze = - act?.identities && snooze - ? actboxHtml( - { identities: act.identities }, - aformHtml({ - kind: "triage", - verb: "snooze", - objectRef, - supersedes: snooze.id, - inner: ``, - }), - ) - : ""; - return `
πŸ’€ ${esc(objectRef)} snoozed until ${esc(fmtDate(snooze!.payload.until))}
applied by ${esc(snooze!.appliedByRun ?? "a fleet run")}${snooze!.resultNote ? ` β€” ${esc(snooze!.resultNote)}` : ""}${unsnooze}
`; - }) - .join("")}` + const snoozedStrip = snoozedList.length + ? `

Snoozed by you (${snoozedList.length})

These items are out of the queues until their snooze expires β€” the orchestration pass omits them, and they resurface on their own. Unsnoozing records a superseding action.

${snoozedList.map((e) => stripCardHtml(e, act?.identities)).join("")}` + : ""; + const hiddenStrip = hiddenList.length + ? `
Dismissed / done by you (${hiddenList.length}) β€” hidden from the queues; restore any of them to re-review or add a note${hiddenList.map((e) => stripCardHtml(e, act?.identities)).join("")}
` : ""; + const queues = `${needsOrderHtml(act)}

Needs User (${drewCount})${sectionStamp}

${drewCards} +${snoozedStrip}${hiddenStrip}

Needs Orchestrator (${orchCount})${sectionStamp}

The orchestration job (#899) reviews this queue and pushes work back into motion; it escalates to the user queue only what truly needs the user.

${orchCards}`; const sessionCards = roots.length - ? roots.map((e) => sessionCard(e, children, 0, counts, act)).join("") + ? roots.map((e) => sessionCard(e, children, 0, counts, sessionAct)).join("") : `

No current sessions.

`; + const sessions = `

All sessions (${roots.length})

Every current session with its source and state; sub-sessions collapse under their parent.

${sessionCards} +${view.expiredCount ? `

${view.expiredCount} finished or stale ${view.expiredCount === 1 ? "entry" : "entries"} expired out of this view.

` : ""}`; + return { header, queues, sessions }; +} + +/** Wrap one attention section as a Datastar fragment container: the + * shell's placeholder and the fragment payload share this shape, so + * a refresh re-patches the container with itself (attrs included). */ +export function attentionFragment(section: "header" | "queues" | "sessions", innerHtml: string): string { + return `
${innerHtml}
`; +} + +/** + * The Datastar shell for /attention (#1444): nav + headings paint + * immediately; the three heavy sections stream in as fragments. + * Without JS, a meta refresh lands on the full server render. + */ +export function renderAttentionShell(provenance: Provenance, detail?: ProvenanceDetail): string { + const skel = (label: string) => `
Loading ${label}…
`; + const body = `

Needs you

Loading the Needs User and Needs Orchestrator queues…

+${attentionFragment("header", skel("queue status"))} +${attentionFragment("queues", skel("the queues"))} +${attentionFragment("sessions", skel("sessions"))}`; return layout( "Needs you", - `

Needs you

The NEEDS USER queue is an intake the orchestrator works first β€” it resolves what it can and escalates only what genuinely requires the user, each escalated item with its reason. Everything else the fleet can work is the orchestrator's own queue. Finished runs and stale items expire out (2 h after a run finishes, 24 h at the latest). Machine-first: /api/attention.json Β· /api/coverage.json.

-${tierBanner}${chips} -${coverageHtml(coverage)} -${delegationDefault}

Needs User (${drewCount})${sectionStamp}

${drewCards} -${snoozedStrip}

Needs Orchestrator (${orchCount})${sectionStamp}

The orchestration job (#899) reviews this queue and pushes work back into motion; it escalates to the user queue only what truly needs the user.

${orchCards} -

All sessions (${roots.length})

Every current session with its source and state; sub-sessions collapse under their parent.

${sessionCards} -${view.expiredCount ? `

${view.expiredCount} finished or stale ${view.expiredCount === 1 ? "entry" : "entries"} expired out of this view.

` : ""}`, + body, provenance, "/attention", - act?.identities ? ACTION_SCRIPT : "", + ACTION_SCRIPT + COMMENT_SCRIPT, detail ? freshnessChips(detail, ["orchestration", "attention", "registry"]) : "", ); } // --- Today view (slice 2, #898 Β§4) ------------------------------------------- -export function renderToday( +/** The today page's body alone (#1444 fragment payload). */ +export function renderTodayBody( today: TodayView, attention: AttentionView, quota: QuotaView, coverage: SourceCoverage[], - provenance: Provenance, - detail?: ProvenanceDetail, ): string { const walled = quota.pools.filter((p) => p.state === "walled"); const alerts: string[] = []; @@ -1951,12 +2464,36 @@ export function renderToday( }) .join("") : `

No projects to measure yet.

`; - return layout( - "Today", - `

Today

${provenanceLine}${alerts.join("")} + return `${provenanceLine}${alerts.join("")}

Top objectives

${objectives}

Project momentum

${momentum} -${actions}${coverageHtml(coverage)}`, +${actions}${coverageHtml(coverage)}`; +} + +/** The today page (#1444): full server render. */ +export function renderToday( + today: TodayView, + attention: AttentionView, + quota: QuotaView, + coverage: SourceCoverage[], + provenance: Provenance, + detail?: ProvenanceDetail, +): string { + return layout( + "Today", + `

Today

${renderTodayBody(today, attention, quota, coverage)}`, + provenance, + "/today", + "", + detail ? freshnessChips(detail, ["orchestration", "quota", "attention"]) : "", + ); +} + +/** The Datastar shell for /today (#1444). */ +export function renderTodayShell(provenance: Provenance, detail?: ProvenanceDetail): string { + return layout( + "Today", + `

Today

Loading today…
`, provenance, "/today", "", diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 9f59d8a085..341cb5193a 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -8,7 +8,7 @@ // apply actions; the dashboard only records them. import { stat } from "node:fs/promises"; import { ActionsStore, validateNewAction } from "./actions.ts"; -import { checkActionAgainstItem, effectiveStandingAuto, findTierItem } from "./tier-items.ts"; +import { checkActionAgainstItem, effectiveNeedsOrder, effectiveStandingAuto, findTierItem } from "./tier-items.ts"; import { CommentsStore, validateNewComment } from "./comments.ts"; import { loadConfig } from "./config.ts"; import { loadFeed } from "./feed.ts"; @@ -26,10 +26,15 @@ import { } from "./project-config.ts"; import { identitiesFromRecords } from "./registry.ts"; import { + attentionFragment, + attentionSections, ghObjectRef, renderAa, renderAttention, + renderAttentionShell, renderBoard, + renderBoardBody, + renderBoardShell, renderDiscuss, renderDns, renderHealth, @@ -43,6 +48,8 @@ import { renderServiceDetail, renderSessions, renderToday, + renderTodayBody, + renderTodayShell, type CommentFormOpts, } from "./render.ts"; import type { Source } from "./source.ts"; @@ -233,6 +240,66 @@ async function attentionContext() { return { view: buildAttention(feed, summary, Date.now(), diagnosis), coverage }; } +/** + * One Datastar patch-elements event (#1444). The fragment root + * carries its own id + data-on-load attributes, so "outer" mode + * replaces the shell's placeholder with a self-refreshing container. + */ +function ssePatch(selector: string, elementHtml: string): string { + const lines = elementHtml + .split("\n") + .map((l) => `data: elements ${l}`) + .join("\n"); + return `event: datastar-patch-elements\ndata: mode outer\ndata: selector ${selector}\n${lines}\n\n`; +} + +function sseResponse(body: string): Response { + return new Response(body, { + headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" }, + }); +} + +/** The render inputs the board page and its fragment share. */ +async function boardRender() { + const { board, items } = await boardContext(); + const [pool, formOpts, actionsByObject, counts] = await Promise.all([ + source.projects().catch(() => []), + commentFormOpts(), + actionsStore.byObject(), + commentsStore.counts(), + ]); + const act = { + actionsByObject, + poolByRef: new Map(pool.map((p) => [p.ref, p])), + identities: formOpts.identities, + }; + return { board, items, counts, act }; +} + +/** The render inputs the attention page and its fragments share: + * the view, the action/comment stores grouped by object, and the + * effective Needs-you order preference (#1456). */ +async function attentionRender() { + const { view, coverage } = await attentionContext(); + const [formOpts, actionsByObject, commentsByObject, counts, allActions] = await Promise.all([ + commentFormOpts(), + actionsStore.byObject(), + commentsStore.byObject(), + commentsStore.counts(), + actionsStore.all(), + ]); + const order = effectiveNeedsOrder(allActions); + const act = { + actionsByObject, + identities: formOpts.identities, + commentsByObject, + commentOpts: formOpts, + needsOrder: order.order, + needsOrderPending: order.pending, + }; + return { view, coverage, counts, act }; +} + async function todayContext() { const [{ board, items }, { rows }, { view, coverage }, quota, summary] = await Promise.all([ boardContext(), @@ -366,25 +433,32 @@ async function handler(req: Request): Promise { } if (path === "/" || path === "/board") { - const { board, items } = await boardContext(); - const [pool, formOpts, actionsByObject] = await Promise.all([ - source.projects().catch(() => []), - commentFormOpts(), - actionsStore.byObject(), - ]); - return html( - renderBoard(board, items, prov(), await commentsStore.counts(), provDetail(), { - actionsByObject, - poolByRef: new Map(pool.map((p) => [p.ref, p])), - identities: formOpts.identities, - }), - ); + // #1444: the board is the heaviest page β€” shell first, board as a + // fragment. ?full=1 (and the /board alias) keep the full render. + if (path === "/" && url.searchParams.get("full") !== "1") { + return html(renderBoardShell(prov(), provDetail())); + } + const { board, items, counts, act } = await boardRender(); + return html(renderBoard(board, items, prov(), counts, provDetail(), act)); + } + if (path === "/frag/board") { + const { board, items, counts, act } = await boardRender(); + const wrapped = `
${renderBoardBody(board, items, counts, act)}
`; + return sseResponse(ssePatch("#board-main", wrapped)); } if (path === "/today") { + if (url.searchParams.get("full") !== "1") { + return html(renderTodayShell(prov(), provDetail())); + } const { today, view, coverage, quota } = await todayContext(); return html(renderToday(today, view, quota, coverage, prov(), provDetail())); } + if (path === "/frag/today") { + const { today, view, coverage, quota } = await todayContext(); + const wrapped = `
${renderTodayBody(today, view, quota, coverage)}
`; + return sseResponse(ssePatch("#today-main", wrapped)); + } if (path === "/roadmap") { const { rows, items } = await roadmapContext(); @@ -409,14 +483,29 @@ async function handler(req: Request): Promise { } if (path === "/attention") { - const { view, coverage } = await attentionContext(); - const [formOpts, actionsByObject] = await Promise.all([commentFormOpts(), actionsStore.byObject()]); - return html( - renderAttention(view, coverage, prov(), await commentsStore.counts(), provDetail(), { - actionsByObject, - identities: formOpts.identities, - }), - ); + // #1444: shell first; header/queues/sessions stream in as + // fragments. ?full=1 keeps the full server render (no-JS path). + if (url.searchParams.get("full") !== "1") { + return html(renderAttentionShell(prov(), provDetail())); + } + const { view, coverage, counts, act } = await attentionRender(); + return html(renderAttention(view, coverage, prov(), counts, provDetail(), act)); + } + const attnFragMatch = /^\/frag\/attention\/(header|queues|sessions)$/.exec(path); + if (attnFragMatch) { + const section = attnFragMatch[1] as "header" | "queues" | "sessions"; + const { view, coverage, counts, act } = await attentionRender(); + const sections = attentionSections(view, coverage, counts, act); + return sseResponse(ssePatch(`#attn-${section}`, attentionFragment(section, sections[section]))); + } + if (path === "/assets/datastar.js") { + // The vendored Datastar bundle (#1444) β€” a static asset, never a + // service worker; /sw.js keeps serving the kill switch. + const file = Bun.file(new URL("./assets/datastar.js", import.meta.url)); + if (!(await file.exists())) return json({ error: "asset missing" }, 404); + return new Response(file, { + headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=3600" }, + }); } if (path === "/dns") { diff --git a/pm-stack/aggregator/src/tier-items.ts b/pm-stack/aggregator/src/tier-items.ts index e943a9134c..4d793195fd 100644 --- a/pm-stack/aggregator/src/tier-items.ts +++ b/pm-stack/aggregator/src/tier-items.ts @@ -275,6 +275,32 @@ export function effectiveStandingAuto(records: DashAction[]): { }; } +/** The Needs-you card order preference (#1456): persisted as a + * `preference` action (verb set-needs-order) on this object ref. */ +export const NEEDS_ORDER_OBJECT_REF = "needs-user-order"; +export type NeedsOrder = "urgency" | "newest" | "oldest" | "deadline"; +export const NEEDS_ORDERS: readonly NeedsOrder[] = ["urgency", "newest", "oldest", "deadline"]; + +/** The effective Needs-you card order from the preference records: + * the latest non-superseded record (pending or applied) wins; before + * any exists, the orchestrator's published order ("urgency") applies. + * Mirrors effectiveStandingAuto. */ +export function effectiveNeedsOrder(records: DashAction[]): { order: NeedsOrder; pending: boolean } { + const prefs = records + .filter( + (r) => + r.kind === "preference" && + r.verb === "set-needs-order" && + (r.state === "new" || r.state === "applied") && + typeof r.payload?.needsOrder === "string" && + (NEEDS_ORDERS as readonly string[]).includes(r.payload.needsOrder), + ) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + const latest = prefs[0]; + if (!latest) return { order: "urgency", pending: false }; + return { order: latest.payload!.needsOrder as NeedsOrder, pending: latest.state === "new" }; +} + /** #1293: a proposal-ready delegation past its TTL is expired β€” it * renders as expired and the item is decidable again. */ export function proposalExpired(d: TierItemDelegation | undefined, nowMs: number): boolean { @@ -330,9 +356,11 @@ export function checkActionAgainstItem(input: NewAction, item: TierItem | undefi return `answers for "${q.id}" must be chosen from its options`; } } - const answered = new Set(p.answers.map((a) => a.questionId)); - const missing = qs.filter((q) => q.required && !answered.has(q.id)).map((q) => q.id); - if (missing.length) return `missing required answers: ${missing.join(", ")}`; + // #1451 (Drew, 2026-10-27): partial survey submits are allowed β€” + // the card merges answers across submits and shows which required + // questions remain open. Membership and value checks above still + // reject anything the item never asked. (Before #1451 this point + // rejected a submit missing required answers outright.) } else if (p.optionId) { if (!item) return "this item is no longer on the published Needs User tier β€” refresh and try again"; if (!(item.options ?? []).some((o) => o.id === p.optionId)) diff --git a/pm-stack/aggregator/test/boot.test.ts b/pm-stack/aggregator/test/boot.test.ts index d0bac5273d..35a1efa68b 100644 --- a/pm-stack/aggregator/test/boot.test.ts +++ b/pm-stack/aggregator/test/boot.test.ts @@ -74,16 +74,40 @@ describe("server boots from fixtures", () => { expect(quota.includes("Usage & billing")).toBe(true); // the hub retitle (design 2026-10-25 Β§1.1) expect(attention.includes("Needs you")).toBe(true); expect(attention.includes("Needs User")).toBe(true); + expect(attention.includes("amd-6.raptor-pumpkinseed.ts.net")).toBe(true); + // #1444: /attention is a Datastar shell β€” the tier content streams + // in from the fragment endpoints. The honesty assertions (#1139) + // now run against the header fragment that carries them. + expect(attention.includes("/assets/datastar.js")).toBe(true); + expect(attention.includes("data-on-load=\"@get('/frag/attention/header')\"")).toBe(true); + const header = await (await fetch(`http://127.0.0.1:${port}/frag/attention/header`)).text(); // Fixtures carry no orchestration section, so the tier honesty // banner renders and the tier counts are "unknown", never 0 (#1139). - expect(attention.includes("Tier source missing")).toBe(true); - expect(attention.includes("Needs User (unknown)")).toBe(true); - expect(attention.includes("Session coverage")).toBe(true); - expect(attention.includes("amd-6.raptor-pumpkinseed.ts.net")).toBe(true); + expect(header.includes("Tier source missing")).toBe(true); + expect(header.includes("Needs User (unknown)")).toBe(true); + expect(header.includes("Session coverage")).toBe(true); + // The no-JS full render still carries the same content inline. + const full = await (await fetch(`http://127.0.0.1:${port}/attention?full=1`)).text(); + expect(full.includes("Tier source missing")).toBe(true); + expect(full.includes("Needs User (unknown)")).toBe(true); + }); + + test("datastar asset + shell fragments serve (#1444)", async () => { + const asset = await fetch(`http://127.0.0.1:${port}/assets/datastar.js`); + expect(asset.status).toBe(200); + expect(asset.headers.get("content-type")).toContain("javascript"); + expect(await asset.text()).toContain("Datastar"); + const board = await (await fetch(`http://127.0.0.1:${port}/frag/board`)).text(); + expect(board).toContain("datastar-patch-elements"); + expect(board).toContain('id="board-main"'); + const queues = await (await fetch(`http://127.0.0.1:${port}/frag/attention/queues`)).text(); + expect(queues).toContain('id="attn-queues"'); + expect(queues).toContain('id="drew"'); }); test("today page + slice-2 JSON endpoints (today, coverage, horizons)", async () => { - const today = await (await fetch(`http://127.0.0.1:${port}/today`)).text(); + // #1444: /today is a shell; its body streams from /frag/today. + const today = await (await fetch(`http://127.0.0.1:${port}/frag/today`)).text(); expect(today.includes("Top objectives")).toBe(true); expect(today.includes("Project momentum")).toBe(true); const todayJson = (await (await fetch(`http://127.0.0.1:${port}/api/today.json`)).json()) as { diff --git a/pm-stack/aggregator/test/dashboard-overhaul.test.ts b/pm-stack/aggregator/test/dashboard-overhaul.test.ts new file mode 100644 index 0000000000..b323a6d659 --- /dev/null +++ b/pm-stack/aggregator/test/dashboard-overhaul.test.ts @@ -0,0 +1,303 @@ +// Epic #1442 (issues #1443/#1444/#1445/#1446/#1449/#1450/#1451/ +// #1456): the dashboard reflects its own actions store at render β€” +// clicks land visibly, suppressed cards move to their strips with a +// way back, cards expand to their detail + history, carry a comment +// box and one-tap resolutions, surveys accumulate partial answers, +// and the Needs-you order is a saved preference. +import { describe, expect, test } from "bun:test"; +import { validateNewAction, type DashAction } from "../src/actions.ts"; +import { cardState } from "../src/card-state.ts"; +import { buildAttention } from "../src/derive.ts"; +import type { OrchestrationSection, TierItem } from "../src/model.ts"; +import { STANDING_IDENTITIES } from "../src/registry.ts"; +import { attentionSections, renderAttention } from "../src/render.ts"; +import { fixtureSource } from "../src/sources/fixtures.ts"; +import { effectiveNeedsOrder } from "../src/tier-items.ts"; + +const NOW = Date.now(); +const iso = (ms: number) => new Date(ms).toISOString(); +const drew = { kind: "drew" as const, id: "drew", label: "Drew" }; +const identities = STANDING_IDENTITIES.map((i) => ({ ...i })); + +const BASE: TierItem = { + id: "goal_plaid", + kind: "task", + title: "Link the Citi accounts in Plaid", + source: "tracked", + reason: "Only the user can complete the bank sign-in.", + since: iso(NOW - 86_400_000), + lastSeenAt: iso(NOW - 3_600_000), +}; + +const mkAction = (over: Partial): DashAction => ({ + id: "da-x", + clientToken: "ct-x", + kind: "triage", + verb: "acknowledge", + objectRef: "orch:goal_plaid", + payload: {}, + author: drew, + createdAt: iso(NOW - 600_000), + state: "new", + ...over, +}); + +function section(items: TierItem[]): OrchestrationSection { + return { + version: 1, + generatedAt: iso(NOW), + runId: "orch-test", + provenance: { sources: ["fixture"] }, + tiers: { needsDrew: items, needsOrchestrator: [] }, + dependencies: [], + goals: [], + actions: [], + }; +} + +async function page(items: TierItem[], actionsByObject = new Map(), actExtra = {}) { + const src = fixtureSource(); + const view = buildAttention([], section(items), NOW); + return renderAttention(view, await src.coverage(), src.provenance(), undefined, undefined, { + identities, + actionsByObject, + commentOpts: { identities }, + ...actExtra, + }); +} + +describe("action boundary additions (#1449/#1450/#1456)", () => { + const base = { + clientToken: "ct-overhaul-1", + kind: "triage" as const, + objectRef: "orch:goal_plaid", + author: drew, + payload: {}, + }; + test("mark-done validates with no required payload", () => { + expect(validateNewAction({ ...base, verb: "mark-done" }).ok).toBe(true); + }); + test("restore requires supersedes", () => { + const bad = validateNewAction({ ...base, verb: "restore" }); + expect(bad.ok).toBe(false); + if (!bad.ok) expect(bad.error).toContain("restore requires supersedes"); + expect(validateNewAction({ ...base, verb: "restore", supersedes: "da-1" }).ok).toBe(true); + }); + test("set-needs-order requires a valid needsOrder", () => { + const bad = validateNewAction({ ...base, kind: "preference", verb: "set-needs-order" }); + expect(bad.ok).toBe(false); + const bogus = validateNewAction({ + ...base, + kind: "preference", + verb: "set-needs-order", + payload: { needsOrder: "random" }, + }); + expect(bogus.ok).toBe(false); + expect( + validateNewAction({ ...base, kind: "preference", verb: "set-needs-order", payload: { needsOrder: "newest" } }).ok, + ).toBe(true); + }); +}); + +describe("card-state derivation (#1443/#1450)", () => { + test("a PENDING snooze already suppresses β€” the click lands before the consumer runs", () => { + const cs = cardState([mkAction({ verb: "snooze", payload: { until: iso(NOW + 3_600_000) } })], NOW); + expect(cs.suppressed?.kind).toBe("snoozed"); + }); + test("an expired snooze does not suppress", () => { + const cs = cardState( + [mkAction({ verb: "snooze", state: "applied", payload: { until: iso(NOW - 3_600_000) } })], + NOW, + ); + expect(cs.suppressed).toBeNull(); + }); + test("dismiss and mark-done suppress; a consumer rejection lifts the suppression", () => { + expect(cardState([mkAction({ verb: "dismiss", payload: { reason: "Duplicate" } })], NOW).suppressed?.kind).toBe( + "dismissed", + ); + expect(cardState([mkAction({ verb: "mark-done" })], NOW).suppressed?.kind).toBe("done"); + expect( + cardState([mkAction({ verb: "dismiss", state: "rejected", payload: { reason: "Duplicate" } })], NOW).suppressed, + ).toBeNull(); + }); + test("restore cancels even an APPLIED dismiss; the item is back with its history", () => { + const dismiss = mkAction({ id: "da-dismiss", verb: "dismiss", state: "applied", payload: { reason: "x" } }); + const restore = mkAction({ id: "da-restore", verb: "restore", supersedes: "da-dismiss", createdAt: iso(NOW) }); + const cs = cardState([dismiss, restore], NOW); + expect(cs.suppressed).toBeNull(); + expect(cs.pending.map((a) => a.verb)).toContain("restore"); + }); + test("survey answers merge across submits, latest per question wins (#1451)", () => { + const a1 = mkAction({ + verb: "answer", + payload: { answers: [{ questionId: "q1", value: "a" }] }, + }); + const a2 = mkAction({ + id: "da-y", + verb: "answer", + createdAt: iso(NOW), + payload: { + answers: [ + { questionId: "q2", value: "b" }, + { questionId: "q1", value: "c" }, + ], + }, + }); + const cs = cardState([a1, a2], NOW); + expect(cs.answered.get("q1")).toBe("c"); + expect(cs.answered.get("q2")).toBe("b"); + }); +}); + +describe("render-time suppression + strips (#1443/#1450)", () => { + test("a pending snooze moves the card out of Needs User into the Snoozed strip, count drops", async () => { + const snooze = mkAction({ verb: "snooze", payload: { until: iso(NOW + 86_400_000) } }); + const html = await page([BASE], new Map([["orch:goal_plaid", [snooze]]])); + expect(html).toContain("Needs User (0)"); + expect(html).toContain("Nothing in the user queue right now."); + expect(html).toContain("Snoozed by you (1)"); + expect(html).toContain("Link the Citi accounts in Plaid"); + expect(html).toContain("⏳ sent Β· pending"); + expect(html).toContain("Unsnooze now"); + }); + test("a dismissed card lands in the hidden strip with a restore form naming the dismiss", async () => { + const dismiss = mkAction({ id: "da-d1", verb: "dismiss", payload: { reason: "Already handled" } }); + const html = await page([BASE], new Map([["orch:goal_plaid", [dismiss]]])); + expect(html).toContain("Dismissed / done by you (1)"); + expect(html).toContain('data-verb="restore"'); + expect(html).toContain('data-supersedes="da-d1"'); + expect(html).toContain("Already handled"); + }); + test("a dismissed ref no longer published at all still shows in the strip (#1450)", async () => { + const dismiss = mkAction({ + id: "da-d2", + objectRef: "orch:gone_item", + verb: "dismiss", + state: "applied", + payload: { reason: "Duplicate" }, + }); + const html = await page([BASE], new Map([["orch:gone_item", [dismiss]]])); + expect(html).toContain("Dismissed / done by you (1)"); + expect(html).toContain("orch:gone_item"); + expect(html).toContain('data-verb="restore"'); + // the visible card is untouched + expect(html).toContain("Needs User (1)"); + }); + test("an acknowledged card renders quiet with its ack state", async () => { + const ack = mkAction({ verb: "acknowledge", state: "applied" }); + const html = await page([BASE], new Map([["orch:goal_plaid", [ack]]])); + expect(html).toContain('class="card acked"'); + expect(html).toContain("βœ“ Acknowledged"); + }); +}); + +describe("quick actions, detail, comments (#1449/#1445/#1446)", () => { + test("the quick bar carries one-tap resolutions with preset whys", async () => { + const html = await page([BASE]); + expect(html).toContain("Already done"); + expect(html).toContain('data-verb="mark-done"'); + expect(html).toContain("Dismiss: Already handled"); + expect(html).toContain("Orchestrator should have handled this"); + expect(html).toContain("Need more info"); + expect(html).toContain("Need recommendations"); + }); + test("the card expands inline: source, since, last seen, question payload, action history", async () => { + const item: TierItem = { + ...BASE, + questions: [ + { + id: "more-institutions", + prompt: "More institutions to link?", + type: "text", + required: true, + covers: "whether Plaid is done", + }, + ], + }; + const answer = mkAction({ + verb: "answer", + state: "applied", + payload: { answers: [{ questionId: "more-institutions", value: "none" }] }, + }); + const html = await page([item], new Map([["orch:goal_plaid", [answer]]])); + expect(html).toContain("Details & history"); + expect(html).toContain("Last seen"); + expect(html).toContain("More institutions to link?"); + expect(html).toContain("covers: whether Plaid is done"); + expect(html).toContain("βœ“ answered: none"); + }); + test("the comment box offers the public-post checkbox only with a gh: ref", async () => { + const withRef: TierItem = { ...BASE, id: "x1", ref: "developing-today/code#2001" }; + const htmlRef = await page([withRef]); + expect(htmlRef).toContain("Also post publicly to the GitHub issue (developing-today/code#2001)"); + expect(htmlRef).toContain('data-ghref="developing-today/code#2001"'); + const htmlBare = await page([BASE]); + expect(htmlBare).toContain("the comment stays internal"); + expect(htmlBare).not.toContain("data-ghref="); + }); + test("a gh: card title links to the GitHub issue", async () => { + const withRef: TierItem = { ...BASE, id: "x1", ref: "developing-today/code#2001" }; + const html = await page([withRef]); + expect(html).toContain( + 'Link the Citi accounts in Plaid', + ); + }); +}); + +describe("multi-question partial state (#1451)", () => { + test("one answered + one open required question: both states show on the card", async () => { + const item: TierItem = { + ...BASE, + questions: [ + { id: "q1", prompt: "First?", type: "text", required: true, covers: "one" }, + { id: "q2", prompt: "Second?", type: "text", required: true, covers: "two" }, + ], + }; + const partial = mkAction({ verb: "answer", payload: { answers: [{ questionId: "q1", value: "yes" }] } }); + const html = await page([item], new Map([["orch:goal_plaid", [partial]]])); + expect(html).toContain("βœ“ answered: yes"); + expect(html).toContain("still needed"); + expect(html).toContain("still needed: q2"); + }); +}); + +describe("needs-you order (#1456)", () => { + test("effectiveNeedsOrder: default urgency; latest record wins; pending flags", () => { + expect(effectiveNeedsOrder([])).toEqual({ order: "urgency", pending: false }); + const pref = mkAction({ + kind: "preference", + verb: "set-needs-order", + objectRef: "needs-user-order", + payload: { needsOrder: "newest" }, + }); + expect(effectiveNeedsOrder([pref])).toEqual({ order: "newest", pending: true }); + }); + test("the order control renders and newest-first reorders the list at render", async () => { + const older: TierItem = { ...BASE, id: "older", title: "Older card", lastSeenAt: iso(NOW - 86_400_000) }; + const newer: TierItem = { ...BASE, id: "newer", title: "Newer card", lastSeenAt: iso(NOW - 60_000) }; + const src = fixtureSource(); + const view = buildAttention([], section([older, newer]), NOW); + const html = renderAttention(view, await src.coverage(), src.provenance(), undefined, undefined, { + identities, + actionsByObject: new Map(), + needsOrder: "newest", + }); + expect(html).toContain('data-verb="set-needs-order"'); + expect(html.indexOf("Newer card")).toBeLessThan(html.indexOf("Older card")); + }); +}); + +describe("attention sections (#1444)", () => { + test("the page splits into header / queues / sessions that reassemble", async () => { + const src = fixtureSource(); + const view = buildAttention([], section([BASE]), NOW); + const sections = attentionSections(view, await src.coverage(), undefined, { + identities, + actionsByObject: new Map(), + }); + expect(sections.queues).toContain('id="drew"'); + expect(sections.queues).toContain("Link the Citi accounts in Plaid"); + expect(sections.header).toContain("Needs User (1)"); + expect(sections.sessions).toContain('id="sessions"'); + }); +}); diff --git a/pm-stack/aggregator/test/needs-user.test.ts b/pm-stack/aggregator/test/needs-user.test.ts index 516d9ddc68..dee025a7fd 100644 --- a/pm-stack/aggregator/test/needs-user.test.ts +++ b/pm-stack/aggregator/test/needs-user.test.ts @@ -313,13 +313,10 @@ describe("POST-boundary checks against the published item (#1291/#1293)", () => expect(checkActionAgainstItem(actionInput({ payload: { optionId: "csv" } }), item, NOW)).toBeNull(); }); - test("survey answers: unknown ids and missing required answers are legible 400s", () => { + test("survey answers: unknown ids and bad values are legible 400s; partial submits are accepted (#1451)", () => { expect( checkActionAgainstItem(actionInput({ payload: { answers: [{ questionId: "nope", value: "x" }] } }), item, NOW), ).toContain('unknown question id "nope"'); - expect( - checkActionAgainstItem(actionInput({ payload: { answers: [{ questionId: "notes", value: "hi" }] } }), item, NOW), - ).toContain("missing required answers: audience"); expect( checkActionAgainstItem( actionInput({ payload: { answers: [{ questionId: "audience", value: "bogus" }] } }), @@ -327,6 +324,13 @@ describe("POST-boundary checks against the published item (#1291/#1293)", () => NOW, ), ).toContain("must be one of its options"); + // #1451 (Drew, 2026-10-27): a partial submit β€” only the optional + // question answered β€” is recorded, not rejected; the card keeps + // showing the required remainder. (Pre-#1451 this was the + // "missing required answers: audience" 400.) + expect( + checkActionAgainstItem(actionInput({ payload: { answers: [{ questionId: "notes", value: "hi" }] } }), item, NOW), + ).toBeNull(); expect( checkActionAgainstItem( actionInput({ payload: { answers: [{ questionId: "audience", value: "internal" }] } }),