opencode-forgekeeper 5.0.1 β 5.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/gui-experimental.cjs +39 -39
- package/dist/index.js +688 -581
- package/dist/tui.js +72 -69
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -38,8 +38,9 @@ For example, a session working on issue `#12` and MR `!45` gets a title prefix s
|
|
|
38
38
|
`[#12, !45]`. Several targets produce `[!101, !102]`, or `[!101, !102, !103, +3]` for a larger set.
|
|
39
39
|
Your own title text is preserved.
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
Run `/forge-detach` to clear all explicit targets without a model call. To remove only specific
|
|
42
|
+
targets, pass their full URLs separated by spaces. After you remove the last target,
|
|
43
|
+
Forgekeeper follows the checked-out branch and its open PR/MR again. Default branches
|
|
43
44
|
get no branch-based prefix. Child sessions aren't renamed.
|
|
44
45
|
|
|
45
46
|
See the reference for [target rules](https://github.com/pedropombeiro/opencode-plugins/blob/main/packages/forgekeeper/docs/reference.md#session-targets) and
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("solid-js/web"),
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("solid-js/web"),F=require("@opencode/plugin/gui"),N=require("solid-js"),Ne=require("solid-js/store"),ht=require("node:crypto"),Ke=e=>t=>t.forge===e,mt=e=>e?.match(/^\[[^\]]*\]/)?.[0]??"";function Ve(e,t){return mt(e).slice(1,-1).split(/[\s,]+/).flatMap(r=>r.startsWith(t)&&/^[1-9]\d*$/.test(r.slice(t.length))?[r.slice(t.length)]:[])}function me(e,t,r){let n;try{n=new URL(t)}catch{return}if(!["https:","http:"].includes(n.protocol))return;const s=n.pathname.match(r);if(s)return{forge:e,host:n.hostname.toLowerCase(),project:decodeURIComponent(s[1]),iid:s[2]}}const J=e=>e?"yes":"no",ge=e=>e.toLowerCase().replace(/_/g," ");class O extends Error{constructor(t,r){super(r),this.kind=t}kind}const T=e=>e,j=e=>async(t,r,n)=>await e(t,r,n),Ae=10,gt=10,De=300,wt=5,Te=300;function bt(e,t){const r=e.split(`
|
|
2
2
|
`);if(t<1||t>r.length)return;const n=Math.max(1,t-Ae),s=Math.min(r.length,t+Ae);return r.slice(n-1,s).map((o,a)=>{const i=n+a,c=o.length>De?`${o.slice(0,De)}β¦`:o;return`${i===t?">":" "}${i}: ${c}`}).join(`
|
|
3
|
-
`)}const ee=100,ie=20,Ye=200,ye="author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } }",Se="pageInfo { hasPreviousPage startCursor }",Xe=`id url state createdAt publishedAt lastEditedAt isMinimized ${ye}`,Re=(e,t)=>
|
|
3
|
+
`)}const ee=100,ie=20,Ye=200,ye="author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } }",Se="pageInfo { hasPreviousPage startCursor }",Xe=`id url state createdAt publishedAt lastEditedAt isMinimized ${ye}`,Re=(e,t)=>T(`query($owner: String!, $repo: String!, $number: Int!, $before: String) {
|
|
4
4
|
viewer { id }
|
|
5
5
|
repository(owner: $owner, name: $repo) {
|
|
6
6
|
pullRequest(number: $number) {
|
|
7
7
|
${e}(last: ${ee}, before: $before) { ${Se} nodes { ${t} } }
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
}`),
|
|
10
|
+
}`),vt=Re("comments",`id url createdAt publishedAt lastEditedAt isMinimized ${ye}`),$t=Re("reviews",`id url state body submittedAt lastEditedAt isMinimized ${ye}`),yt=Re("reviewThreads",`id isResolved comments(last: ${ee}) { ${Se} nodes { ${Xe} } }`),St=T(`query($id: ID!, $before: String) {
|
|
11
11
|
node(id: $id) {
|
|
12
12
|
... on PullRequestReviewThread {
|
|
13
13
|
comments(last: ${ee}, before: $before) { ${Se} nodes { ${Xe} } }
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
-
}`),
|
|
16
|
+
}`),Rt=new Set(["COMMENTED","CHANGES_REQUESTED","APPROVED"]),Ce=(...e)=>{const t=e.find(r=>r);return t?Date.parse(t):NaN},ke=(e,t)=>{const r=e?Date.parse(e):NaN;return Number.isFinite(r)?Math.max(r,t):t};function Ee({node:e,postedAt:t,editedAt:r,resolved:n}){if(e.isMinimized||!e.author?.id||!Number.isFinite(t)||!Number.isFinite(r))return;const{__typename:s,login:o}=e.author;return{id:e.id,order:t,url:e.url??"",editedAt:r,resolved:n,bot:s==="Bot"||o.endsWith("[bot]"),authorID:e.author.id,username:o}}function Ct(e){const t=Ce(e.publishedAt,e.createdAt);return Ee({node:e,postedAt:t,editedAt:ke(e.lastEditedAt,t),resolved:!1})}function kt(e){if(!Rt.has(e.state)||!e.body.trim())return;const t=Ce(e.submittedAt);return Ee({node:e,postedAt:t,editedAt:ke(e.lastEditedAt,t),resolved:!1})}function Et(e,t){if(e.state==="PENDING")return;const r=Ce(e.publishedAt,e.createdAt);return Ee({node:e,postedAt:r,editedAt:ke(e.lastEditedAt,r),resolved:t})}const It={pages:ie,completeAtLimit:!0},Pt={pages:Ye,completeAtLimit:!1};async function de(e,t,r,n,s,o=It){const a=[];let i,c;const u=f=>({items:a.toReversed().flat(),viewer:i,complete:f});for(let f=0;f<o.pages;f++){const m=c?{...r,before:c}:r,g=await e(t,n,m);i??=g.viewer?.id??void 0;const y=g.repository?.pullRequest?.[s];if(!y)return f===0?{viewer:i,complete:!1}:u(!1);if(a.push(y.nodes),!y.pageInfo.hasPreviousPage)return u(!0);if(c=y.pageInfo.startCursor??void 0,!c)return u(!1)}return u(o.completeAtLimit)}async function _t(e,t,r){if(!r.comments)return{comments:[],complete:!1};const n=[];let s=r.comments?.pageInfo.hasPreviousPage?r.comments.pageInfo.startCursor??void 0:void 0;if(r.comments?.pageInfo.hasPreviousPage&&!s)return{comments:[],complete:!1};for(let o=1;s&&o<ie;o++){const i=(await e(t,St,{id:r.id,before:s})).node?.comments;if(!i)return{comments:n.toReversed().flat(),complete:!1};if(n.push(i.nodes),s=i.pageInfo.hasPreviousPage?i.pageInfo.startCursor??void 0:void 0,i.pageInfo.hasPreviousPage&&!s)return{comments:n.toReversed().flat(),complete:!1}}return{comments:n.toReversed().flat(),complete:!0}}const Nt=e=>T(`query {
|
|
17
17
|
nodes(ids: ${JSON.stringify(e)}) {
|
|
18
18
|
__typename
|
|
19
19
|
... on IssueComment { id url body author { login ... on User { id } ... on Bot { id } } }
|
|
@@ -23,13 +23,13 @@
|
|
|
23
23
|
replyTo { body author { login } }
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
-
}`),
|
|
26
|
+
}`),At=/^[A-Za-z0-9_=-]+$/,qe=50;async function Dt(e,t,r){const n=j(e),s=[],o=r.filter(a=>At.test(a));for(let a=0;a<o.length;a+=qe){const i=await n(t,Nt(o.slice(a,a+qe)),{});for(const c of i.nodes??[]){if(!c?.id||!c.url||!c.author||c.body===void 0)continue;const u=c.line??c.originalLine??void 0,f=c.diffHunk?.split(`
|
|
27
27
|
`).slice(-21).join(`
|
|
28
|
-
`),m=c.replyTo?.author?[{username:c.replyTo.author.login,body:c.replyTo.body}]:[];s.push({id:c.id,url:c.url,username:c.author.login,...c.author.id?{authorID:c.author.id}:{},body:c.body,...c.path?{path:c.path}:{},...u!==void 0?{line:u}:{},...c.path&&f?{code:{path:c.path,text:f}}:{},...m.length?{replies:m}:{}})}}return s}async function
|
|
28
|
+
`),m=c.replyTo?.author?[{username:c.replyTo.author.login,body:c.replyTo.body}]:[];s.push({id:c.id,url:c.url,username:c.author.login,...c.author.id?{authorID:c.author.id}:{},body:c.body,...c.path?{path:c.path}:{},...u!==void 0?{line:u}:{},...c.path&&f?{code:{path:c.path,text:f}}:{},...m.length?{replies:m}:{}})}}return s}async function Tt(e,t,r,n){let s=0;const o=j(async(...C)=>s++>=Ye?{}:e(...C)),[a,i]=r.split("/"),c={owner:a,repo:i,number:Number(n)},[u,f,m]=await Promise.all([de(o,t,c,vt,"comments"),de(o,t,c,$t,"reviews"),de(o,t,c,yt,"reviewThreads",Pt)]);if(!u.items||!f.items||!m.items)return;const g=u.viewer??f.viewer??m.viewer;let y=m.complete;const v=[];for(const C of m.items){const I=await _t(o,t,C);y&&=I.complete;for(const q of[...I.comments,...C.comments?.nodes??[]]){const p=Et(q,C.isResolved);p&&v.push(p)}v.sort((q,p)=>p.order-q.order),v.splice(ee*ie)}const w=[...u.items.map(Ct),...f.items.map(kt),...v.sort((C,I)=>C.order-I.order).slice(-ee*ie)].flatMap(C=>C??[]);return{complete:u.complete&&f.complete&&y&&g!==void 0,viewerID:g,comments:w.sort((C,I)=>C.order-I.order)}}const qt=100,xt=20,we=T(`query($project: ID!, $iid: String!, $before: String) {
|
|
29
29
|
currentUser { id }
|
|
30
30
|
project(fullPath: $project) {
|
|
31
31
|
mergeRequest(iid: $iid) {
|
|
32
|
-
notes(last: ${
|
|
32
|
+
notes(last: ${qt}, before: $before, filter: ONLY_COMMENTS) {
|
|
33
33
|
pageInfo { hasPreviousPage startCursor }
|
|
34
34
|
nodes {
|
|
35
35
|
id url createdAt updatedAt lastEditedAt system
|
|
@@ -40,21 +40,21 @@
|
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
|
-
}`),
|
|
43
|
+
}`),Lt=T(String(we).replace("position { newPath }","position { newPath } duoCreatedSession { id status workflowDefinition }")),se=e=>e.slice(e.lastIndexOf("/")+1),Ot=e=>Date.parse(e.lastEditedAt??e.updatedAt??e.createdAt);function Ut(e){const t=Ot(e),r=se(e.id);if(!(e.system||!e.author||!Number.isFinite(t)||!/^\d+$/.test(r)))return{id:r,order:Number(r),url:e.url??"",editedAt:t,resolved:e.discussion?.resolved===!0,bot:e.author.bot,authorID:e.author.id,username:e.author.username,...e.discussion?.id?{discussionID:e.discussion.id}:{},...e.author.bot&&e.author.username.toLowerCase()==="gitlabduo"?{automated:{reviewer:"GitLab Duo",finding:!!e.position,...e.duoCreatedSession?.workflowDefinition==="code_review/v1"?{runID:e.duoCreatedSession.id,status:e.duoCreatedSession.status}:{}}}:{}}}async function Mt(e,t,r,n){const s=j(e),o=[];let a,i,c=!0;const u=f=>({complete:f&&a!==void 0,viewerID:a,comments:o.toReversed().flat()});for(let f=0;f<xt;f++){const m={project:r,iid:n};i&&(m.before=i);let g;try{g=await s(t,c?Lt:we,m)}catch(v){if(!c||!/duoCreatedSession.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*duoCreatedSession/i.test(v instanceof Error?v.message:String(v)))throw v;c=!1,g=await s(t,we,m)}a??=g.currentUser?.id??void 0;const y=g.project?.mergeRequest?.notes;if(!y)return f===0?void 0:u(!1);if(o.push(y.nodes.flatMap(v=>Ut(v)??[])),!y.pageInfo.hasPreviousPage)return u(!0);if(i=y.pageInfo.startCursor??void 0,!i)return u(!1)}return u(!0)}const xe=25,jt=20,Ft=/^[0-9a-f]{40}$/;function Ze(e){const t=e?.diffRefs;if(t){if(e.newLine&&e.newPath)return{sha:t.headSha,path:e.newPath,line:e.newLine};if(e.oldLine&&e.oldPath)return{sha:t.baseSha,path:e.oldPath,line:e.oldLine}}}async function Bt(e,t,r,n){const s=j(e),o=[],a=n.filter(c=>/^\d+$/.test(c));for(let c=0;c<a.length;c+=xe){const u=a.slice(c,c+xe).map((m,g)=>`n${g}: note(id: "gid://gitlab/Note/${m}") { id url body author { id username }
|
|
44
44
|
position { diffRefs { baseSha headSha } newPath newLine oldPath oldLine }
|
|
45
|
-
discussion { resolved notes(first: ${
|
|
46
|
-
`),f=await s(t,
|
|
47
|
-
`),u=await e(t,
|
|
45
|
+
discussion { resolved notes(first: ${jt}) { nodes { id body author { username } } } } }`).join(`
|
|
46
|
+
`),f=await s(t,T(`query { ${u} }`),{});for(const m of Object.values(f))m?.author&&m.url&&o.push(m)}const i=await Gt(s,t,r,o).catch(()=>new Map);return o.map(c=>{const u=Ze(c.position),f=u&&i.get(JSON.stringify([u.sha,u.path])),m=f!==void 0&&u?bt(f,u.line):void 0,g=c.discussion?.notes?.nodes??[],y=g.findIndex(w=>se(w.id)===se(c.id)),v=(y>0?g.slice(0,y):[]).flatMap(w=>w.author?[{username:w.author.username,body:w.body}]:[]);return{id:se(c.id),url:c.url??"",username:c.author?.username??"",...c.author?.id?{authorID:c.author.id}:{},body:c.body,...typeof c.discussion?.resolved=="boolean"?{resolved:c.discussion.resolved}:{},...u?{path:u.path,line:u.line}:{},...m&&u?{code:{path:u.path,text:m}}:{},...v.length?{replies:v}:{}}})}async function Gt(e,t,r,n){const s=new Map;let o=0;for(const f of n){const m=Ze(f.position);if(!m||!Ft.test(m.sha))continue;const g=s.get(m.sha)??new Set;!g.has(m.path)&&o>=gt||(g.has(m.path)||o++,s.set(m.sha,g.add(m.path)))}const a=new Map;if(!s.size)return a;const i=[...s.keys()],c=i.map((f,m)=>`b${m}: project(fullPath: ${JSON.stringify(r)}) { repository { blobs(paths: ${JSON.stringify([...s.get(f)])}, ref: ${JSON.stringify(f)}) { nodes { path rawTextBlob } } } }`).join(`
|
|
47
|
+
`),u=await e(t,T(`query { ${c} }`),{});return i.forEach((f,m)=>{for(const g of u[`b${m}`]?.repository?.blobs?.nodes??[])g.rawTextBlob!==null&&a.set(JSON.stringify([f,g.path]),g.rawTextBlob)}),a}const Ht=100,zt=10,Wt=T(`query($project: ID!, $iid: String!, $before: String) {
|
|
48
48
|
currentUser { id username }
|
|
49
49
|
project(fullPath: $project) {
|
|
50
50
|
mergeRequest(iid: $iid) {
|
|
51
|
-
notes(last: ${
|
|
51
|
+
notes(last: ${Ht}, before: $before, filter: ONLY_ACTIVITY) {
|
|
52
52
|
pageInfo { hasPreviousPage startCursor }
|
|
53
53
|
nodes { id url body createdAt system systemNoteMetadata { action } author { id username } }
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
}`),Le="requested review from ",
|
|
57
|
+
}`),Le="requested review from ",Jt=/\sand removed (?:review request for|approval)\b/;function Qt(e){return e.startsWith(Le)?[...e.slice(Le.length).split(Jt)[0].matchAll(/@([A-Za-z0-9_][A-Za-z0-9_.-]*)/g)].map(r=>r[1].replace(/\.+$/,"").toLowerCase()):[]}const et=e=>e.slice(e.lastIndexOf("/")+1);function Kt(e,t,r){const n=et(e.id),s=Date.parse(e.createdAt),o=e.systemNoteMetadata?.action;if(!(!e.system||o&&o!=="reviewer")&&!(!/^\d+$/.test(n)||!Number.isFinite(s))&&Qt(e.body).includes(t.toLowerCase()))return{id:n,order:Number(n),url:e.url??`${r}#note_${n}`,at:s,...e.author?{requester:{id:e.author.id,username:e.author.username}}:{}}}async function Vt(e,t,r,n,s){const o=j(e),a=[];let i,c;const u=f=>{const m=a.toReversed().flat();return{complete:f&&i!==void 0,...i?{viewerID:i.id}:{},newest:m.reduce((g,y)=>{const v=Number(et(y.id));return Number.isFinite(v)?Math.max(g,v):g},0),requests:i?m.flatMap(g=>Kt(g,i.username,s)??[]).sort((g,y)=>g.order-y.order):[]}};for(let f=0;f<zt;f++){const m={project:r,iid:n};c&&(m.before=c);const g=await o(t,Wt,m);i??=g.currentUser??void 0;const y=g.project?.mergeRequest?.notes;if(!y)return f===0?void 0:u(!1);if(a.push(y.nodes),!y.pageInfo.hasPreviousPage)return u(!0);if(c=y.pageInfo.startCursor??void 0,!c)return u(!1)}return u(!0)}const Yt=/^\/(.+?)\/-\/(issues|work_items|merge_requests)\/(\d+)(\/diffs)?\/?$/,Xt=/^#note_(\d+)$/,Zt=/https:\/\/[^\s<>()[\]"'`]+/g,er=/^gid:\/\/gitlab\/[A-Za-z]*Note\/(\d+)$/;function be(e,t){if(e.length>Te*2)return;let r;try{r=new URL(e)}catch{return}if(r.protocol!=="https:"||r.hostname.toLowerCase()!==t||r.port||r.username||r.password)return;const n=r.hash.match(Xt)?.[1],s=r.pathname.match(Yt);if(!n||!s)return;const[,o,a,i,c]=s;if(c&&a!=="merge_requests"||o.split("/").some(f=>!f||f==="."||f===".."))return;const u=`https://${t}/${o}/-/${a}/${i}#note_${n}`;if(!(u.length>Te))return{url:u,project:o,resource:a==="merge_requests"?"merge_request":"issue",iid:i,noteID:n}}const tt=(e,t)=>e.project.toLowerCase()===t.project.toLowerCase()&&e.resource===t.resource&&e.iid===t.iid&&e.noteID===t.noteID;function tr(e,t){const r=new Set(t.map(s=>s.id)),n=[];for(const s of t)for(const[o]of s.body.matchAll(Zt)){const a=be(o.replace(/[.,;:!?*_~]+$/,""),e);if(!(!a||r.has(a.noteID))&&!n.some(i=>tt(i,a))&&(n.push(a),n.length===wt))return n.map(i=>i.url)}return n.map(s=>s.url)}async function rr(e,t,r){const n=be(r,t);if(!n||n.url!==r)return;const o=(await j(e)(t,T("query($id: NoteID!) { note(id: $id) { id url body author { username } } }"),{id:`gid://gitlab/Note/${n.noteID}`})).note;if(!o?.author||!o.url||o.id.match(er)?.[1]!==n.noteID)return;const a=be(o.url,t);if(!(!a||!tt(a,n)))return{url:n.url,username:o.author.username,body:o.body}}const nr=4*6e4;function sr(e){return{...e,comments:e.comments.filter(t=>t.automated?.reviewer==="GitLab Duo"&&t.automated.finding).map(t=>({...t,bot:!1}))}}function or(e,t){return e.comments.filter(n=>!n.resolved).every(n=>t-n.editedAt>=nr&&(!n.automated?.status||["FINISHED","FAILED","STOPPED"].includes(n.automated.status)))}function ir(e,t,r){const n={Authorization:`Bearer ${t}`,Origin:r},s=new WebSocket(e,{protocols:["actioncable-v1-json"],headers:n}),o=new AbortController;let a=!1,i=!1;const c={send:u=>s.send(u),close:()=>{o.abort(),s.close()},onmessage:null,onerror:null,onclose:null,onresponse:null};return s.onopen=()=>{a=!0},s.onmessage=({data:u})=>c.onmessage?.(String(u)),s.onclose=()=>{i||c.onclose?.()},s.onerror=async()=>{if(o.signal.aborted||i)return;if(a){c.onerror?.();return}i=!0;const u=new URL(e);u.protocol=u.protocol==="wss:"?"https:":"http:";try{const f=await fetch(u,{redirect:"manual",signal:AbortSignal.any([o.signal,AbortSignal.timeout(1e4)]),headers:{...n,Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":ht.randomBytes(16).toString("base64"),"Sec-WebSocket-Protocol":"actioncable-v1-json"}});try{o.signal.aborted||c.onresponse?.(f.status,f.headers)}finally{await f.body?.cancel()}}catch{o.signal.aborted||c.onerror?.()}},c}class ar extends Error{constructor(t){super("Feedback subscription rate limited"),this.retryAt=t}retryAt}function cr(e,t=Date.now()){const r=Date.parse(e.get("date")??""),n=Number.isFinite(r)?r:t,s=[],o=e.get("retry-after")?.trim();o&&(/^\d+$/.test(o)?s.push(Number(o)*1e3):/^[+-]?[\d.]+$/.test(o)||s.push(Date.parse(o)-n));for(const u of["ratelimit-reset","x-ratelimit-reset"]){const f=e.get(u)?.trim();f&&/^\d+$/.test(f)&&s.push(Number(f)*1e3-n)}const a=e.get("ratelimit-resettime");a&&s.push(Date.parse(a)-n);const i=s.filter(u=>Number.isFinite(u)&&u>=0);if(!i.length)return;const c=t+Math.max(...i);return Number.isSafeInteger(c)?c:void 0}async function lr(e,t,r,n,s,o=ir){const a=new URL(r.url);if(a.protocol!=="https:"||a.username||a.password||a.port)return;const i=a.pathname.match(/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/);if(!i||s.aborted)return;const c=await e("glab",["config","get","token","--host",a.hostname],t);if(s.aborted)return;if(c.code!==0||!c.stdout.trim())throw new Error("Subscription credentials unavailable");const u=await e("glab",["api",`projects/${encodeURIComponent(decodeURIComponent(i[1]))}/merge_requests/${i[2]}`,"--hostname",a.hostname],t);if(s.aborted)return;if(u.code!==0)throw new Error("Subscription target lookup failed");const f=JSON.parse(u.stdout);if(!Number.isSafeInteger(f.id)||!Number.isSafeInteger(f.project_id))throw new Error("Invalid subscription target");const m=JSON.stringify({channel:"Noteable::NotesChannel",project_id:f.project_id,noteable_type:"MergeRequest",noteable_id:f.id});await new Promise((g,y)=>{const v=o(`wss://${a.host}/-/cable`,c.stdout.trim(),a.origin);let w=!1,C=!1,I,q;const p=()=>{w||(w=!0,clearTimeout(q),s.removeEventListener("abort",p),v.onmessage=null,v.onerror=null,v.onclose=null,v.onresponse=null,v.close(),I?y(I):g())},R=()=>{clearTimeout(q),q=setTimeout(p,C?45e3:15e3)};R(),s.addEventListener("abort",p,{once:!0}),v.onerror=p,v.onclose=p,v.onresponse=(P,x)=>{P===429&&(I=new ar(cr(x)??Date.now()+6e4)),p()},v.onmessage=P=>{if(!w)try{const x=JSON.parse(String(P));if(C&&R(),x.type==="welcome"&&v.send(JSON.stringify({command:"subscribe",identifier:m})),x.type==="disconnect"&&p(),x.identifier!==m)return;x.type==="reject_subscription"&&p(),x.type==="confirm_subscription"&&!C&&(C=!0,R(),n.connected()),C&&x.message?.event==="updated"&&n.changed()}catch{p()}},s.aborted&&p()})}const rt="pageInfo { hasNextPage endCursor } nodes { resolvable resolved }",nt=100,ur=50,dr=10,pr="pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }",fr=new Set(["CHECKING","UNCHECKED","PREPARING"]),Oe="CANNOT_BE_MERGED_RECHECK",st=`
|
|
58
58
|
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
59
59
|
approvedBy(first: 100) { nodes { id bot } }
|
|
60
60
|
sourceProject { fullPath }
|
|
@@ -62,66 +62,66 @@
|
|
|
62
62
|
author { id }
|
|
63
63
|
headPipeline {
|
|
64
64
|
id status path detailedStatus { label }
|
|
65
|
-
jobs(statuses: [FAILED], retried: false, first: ${
|
|
65
|
+
jobs(statuses: [FAILED], retried: false, first: ${dr}) { ${pr} }
|
|
66
66
|
}
|
|
67
67
|
reviewers(first: 100) { nodes { id type username bot mergeRequestInteraction { reviewState approved } } }
|
|
68
68
|
discussions(first: ${nt}) { ${rt} }
|
|
69
|
-
`;function
|
|
69
|
+
`;function hr(e){const t=Array.from({length:e},(n,s)=>`$p${s}: ID!`).join(", "),r=Array.from({length:e},(n,s)=>`p${s}: project(fullPath: $p${s}) {
|
|
70
70
|
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${st} } }
|
|
71
71
|
}`).join(`
|
|
72
|
-
`);return
|
|
72
|
+
`);return T(`query($branch: String!, ${t}) {
|
|
73
73
|
${r}
|
|
74
|
-
}`)}function
|
|
75
|
-
`);return
|
|
74
|
+
}`)}function mr(e){const t=Array.from({length:e},(n,s)=>`$p${s}: ID!`).join(", "),r=Array.from({length:e},(n,s)=>`p${s}: project(fullPath: $p${s}) { mergeRequest(iid: $iid) { ${st} } }`).join(`
|
|
75
|
+
`);return T(`query($iid: String!, ${t}) {
|
|
76
76
|
${r}
|
|
77
|
-
}`)}function
|
|
77
|
+
}`)}function gr(e){const t=Array.from({length:e},(n,s)=>`$p${s}: ID!`).join(", "),r=Array.from({length:e},(n,s)=>`p${s}: project(fullPath: $p${s}) {
|
|
78
78
|
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { iid updatedAt sourceProject { fullPath } } }
|
|
79
79
|
}`).join(`
|
|
80
|
-
`);return
|
|
80
|
+
`);return T(`query($branch: String!, ${t}) {
|
|
81
81
|
${r}
|
|
82
|
-
}`)}const
|
|
82
|
+
}`)}const wr=T(`query($project: ID!, $iid: String!) {
|
|
83
83
|
project(fullPath: $project) { mergeRequest(iid: $iid) { sourceBranch } }
|
|
84
|
-
}`),
|
|
84
|
+
}`),br=T(`query($project: ID!, $iid: String!, $after: String) {
|
|
85
85
|
project(fullPath: $project) {
|
|
86
86
|
mergeRequest(iid: $iid) { discussions(first: ${nt}, after: $after) { ${rt} } }
|
|
87
87
|
}
|
|
88
|
-
}`);function V(e,t){const r=e.trim().replace(/^glab:\s*/,"")||`glab exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new
|
|
89
|
-
`)[0])}const
|
|
88
|
+
}`);function V(e,t){const r=e.trim().replace(/^glab:\s*/,"")||`glab exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new O("missing-glab","glab is not installed"):/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(r)?new O("auth","GitLab authentication failed. Run `glab auth status`."):/\b429\b|rate limit|too many requests/i.test(r)?new O("rate-limit","GitLab rate limit reached"):new O("request",r.split(`
|
|
89
|
+
`)[0])}const vr=e=>typeof e=="object"&&e!==null&&(!("errors"in e)||Array.isArray(e.errors))&&(!("data"in e)||typeof e.data=="object");function H(e,t){return async(r,n,s)=>{const o=["api","graphql","--hostname",r,"-f",`query=${n}`];for(const[c,u]of Object.entries(s))o.push("-f",`${c}=${u}`);const a=await e("glab",o,t);let i;try{i=JSON.parse(a.stdout)}catch{throw V(a.stderr,a.code)}if(!vr(i))throw V(a.stderr||"Unexpected GitLab response",a.code);if(i.errors?.length)throw V(String(i.errors[0]?.message??""),a.code);if(a.code!==0)throw V(a.stderr,a.code);if(!i.data)throw V("GitLab returned no data",a.code);return i.data}}const Ue=e=>e.nodes.filter(t=>t.resolvable&&!t.resolved).length,B={kind:"gitlab",noun:"MR",ci:"pipeline",recognizes:e=>/(^|\.)gitlab\./.test(e),open:(e,t)=>new Cr(H(e,t)),owns:Ke("gitlab"),parseUrl:e=>me("gitlab",e,/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/),parseIssueUrl:e=>me("gitlab",e,/^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),reference:e=>`!${e}`,issueReference:e=>`#${e}`,titleReferences:e=>Ve(e,"!"),indicators:()=>[],details(e){const t=e.approvalRequirementsSatisfied===null?"unknown":J(e.approvalRequirementsSatisfied),r=[`Human approvals: ${J(e.hasApprovals)} Β· Approval requirements satisfied: ${t}`];return e.mergeStatus&&r.push(`Merge status: ${ge(e.mergeStatus)}`),r},automatedReview:{publishedFeedback:{storageKey:"duo",select:sr,ready:or},name:"GitLab Duo",status(e){const t=e.duoReviewState;if(t)return{state:Rr(t),label:ge(t)}}},feedback:{async viewerID(e,t,r){return(await j(H(e,t))(r,T("query { currentUser { id } }"),{})).currentUser?.id},async reviewerID(e,t,r,n){const s=await j(H(e,t))(r,T("query($username: String!) { user(username: $username) { id username } }"),{username:n});return s.user?.username.toLowerCase()===n.toLowerCase()?s.user.id:void 0},subscribe:lr,async fetch(e,t,r){const n=B.parseUrl(r.url);return n?Mt(H(e,t),n.host,n.project,n.iid):void 0},async reviewRequests(e,t,r){const n=B.parseUrl(r.url);return n?Vt(H(e,t),n.host,n.project,n.iid,r.url):void 0},async details(e,t,r,n){const s=B.parseUrl(r.url);return s?Bt(H(e,t),s.host,s.project,n):[]},commentID:e=>e.match(/#note_(\d+)$/)?.[1],linkedNotes(e,t){const r=B.parseUrl(e.url);return r?tr(r.host,t):[]},async linkedNote(e,t,r,n){const s=B.parseUrl(r.url);return s?rr(H(e,t),s.host,n):void 0}}},$r=new Set(["REVIEWED","REQUESTED_CHANGES"]);function yr(e,t){return!t.id||!t.jobs?{}:{id:t.id,failedJobs:Sr(e,t.jobs.nodes),failedJobsComplete:!t.jobs.pageInfo?.hasNextPage}}function Sr(e,t){return t.flatMap(r=>!r.allowFailure&&r.name?[{...r.id?{id:r.id}:{},name:r.name,...r.webPath?{url:`https://${e}${r.webPath}`}:{},...r.stage?.name?{stage:r.stage.name}:{}}]:[])}function Rr(e){return e==="REVIEW_STARTED"?"running":$r.has(e)?"feedback":"settled"}class Cr{traits=B;graphql;constructor(t){this.graphql=j(t)}async findByBranch(t){const{source:r,targets:n,sourceBranch:s}=t,o={branch:s};n.forEach((m,g)=>o[`p${g}`]=m.path);const a=await this.graphql(r.host,hr(n.length),o),i=r.path.toLowerCase(),c=new Set,u=[];return n.forEach((m,g)=>{for(const y of a[`p${g}`]?.mergeRequests?.nodes??[]){if(y.sourceProject?.fullPath.toLowerCase()!==i)continue;const v=`${y.targetProject.fullPath}!${y.iid}`;c.has(v)||(c.add(v),u.push(y))}}),(await Promise.all(u.map(m=>this.normalize(r.host,m)))).sort((m,g)=>(g.updatedAt??"").localeCompare(m.updatedAt??""))}async findNumberByBranch(t){const{source:r,targets:n,sourceBranch:s}=t,o={branch:s};n.forEach((u,f)=>o[`p${f}`]=u.path);const a=await this.graphql(r.host,gr(n.length),o),i=r.path.toLowerCase();return n.flatMap((u,f)=>a[`p${f}`]?.mergeRequests?.nodes??[]).filter(u=>u.sourceProject?.fullPath.toLowerCase()===i).sort((u,f)=>(f.updatedAt??"").localeCompare(u.updatedAt??""))[0]?.iid}async sourceBranch(t){const n=(await this.graphql(t.host,wr,{project:t.project,iid:t.iid})).project?.mergeRequest?.sourceBranch;return typeof n=="string"&&n?n:void 0}async findByNumber(t,r){if(t.length===0)return;const n=t[0].host,s={iid:r};t.forEach((a,i)=>s[`p${i}`]=a.path);const o=await this.graphql(n,mr(t.length),s);for(let a=0;a<t.length;a++){const i=o[`p${a}`]?.mergeRequest;if(i)return this.normalize(n,i)}}async unresolvedThreads(t,r){let n=Ue(r.discussions),s=r.discussions.pageInfo,o=1;for(;s.hasNextPage&&s.endCursor&&o<ur;){const i=(await this.graphql(t,br,{project:r.targetProject.fullPath,iid:r.iid,after:s.endCursor})).project?.mergeRequest?.discussions;if(!i)break;n+=Ue(i),s=i.pageInfo,o++}return{count:n,complete:!s.hasNextPage}}async normalize(t,r){const n=await this.unresolvedThreads(t,r),s=r.headPipeline,o=(r.approvedBy?.nodes??[]).some(i=>i.bot!==!0),a=(r.reviewers?.nodes??[]).filter(i=>i.bot!==!0&&i.username&&i.mergeRequestInteraction?.approved!==!0).map(i=>i.username);return{forge:"gitlab",iid:r.iid,title:r.title,url:r.webUrl,state:r.state.toLowerCase(),draft:r.draft,conflicts:r.conflicts||r.mergeStatusEnum===Oe,conflictsKnown:r.mergeStatusEnum!==Oe&&!fr.has(r.detailedMergeStatus??""),approved:r.approved===!0&&o&&a.length===0,hasApprovals:o,approvalRequirementsSatisfied:r.approved,awaitingReviewers:a,reviewersComplete:!0,reviewerIDs:(r.reviewers?.nodes??[]).flatMap(i=>i.id??[]),mergeStatus:r.detailedMergeStatus??void 0,targetProject:r.targetProject.fullPath,targetBranch:r.targetBranch,...r.sourceProject?{sourceProject:r.sourceProject.fullPath}:{},sourceBranch:r.sourceBranch,headSha:r.diffHeadSha??void 0,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt??void 0,pipeline:s?{status:s.status,label:s.detailedStatus?.label??s.status.toLowerCase().replace(/_/g," "),url:s.path?`https://${t}${s.path}`:void 0,...yr(t,s)}:void 0,unresolvedThreads:n.count,threadsComplete:n.complete,duoReviewState:r.reviewers?.nodes.find(i=>i.type==="DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState??void 0}}}const kr="copilot-pull-request-reviewer[bot]",Me=`number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
90
90
|
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
91
91
|
author { ... on User { id } ... on Bot { id } }
|
|
92
92
|
reviewThreads(first:100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
93
93
|
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
94
94
|
latestReviews(first:100) { nodes { author { ... on User { id } } } }
|
|
95
|
-
copilotReviews: reviews(last:1, author:"${
|
|
95
|
+
copilotReviews: reviews(last:1, author:"${kr}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } } }
|
|
96
96
|
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
97
97
|
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
98
98
|
pageInfo { hasNextPage endCursor }
|
|
99
|
-
} } } } }`,te=50;function re(e,t){return async(r,n,s)=>{const o=["api","graphql","--hostname",r,"-f",`query=${n}`];for(const[u,f]of Object.entries(s))o.push(typeof f=="number"?"-F":"-f",`${u}=${f}`);const a=await e("gh",o,t);let i;try{i=JSON.parse(a.stdout)}catch{throw je(a.stderr,a.code)}const c=(i.errors??[]).filter(u=>u.type!=="NOT_FOUND");if(!i.data||c.length||a.code!==0&&!i.errors?.length)throw je(c[0]?.message??a.stderr,a.code);return i.data}}function je(e,t){const r=e.trim()||`gh exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new
|
|
100
|
-
`)[0])}const
|
|
99
|
+
} } } } }`,te=50;function re(e,t){return async(r,n,s)=>{const o=["api","graphql","--hostname",r,"-f",`query=${n}`];for(const[u,f]of Object.entries(s))o.push(typeof f=="number"?"-F":"-f",`${u}=${f}`);const a=await e("gh",o,t);let i;try{i=JSON.parse(a.stdout)}catch{throw je(a.stderr,a.code)}const c=(i.errors??[]).filter(u=>u.type!=="NOT_FOUND");if(!i.data||c.length||a.code!==0&&!i.errors?.length)throw je(c[0]?.message??a.stderr,a.code);return i.data}}function je(e,t){const r=e.trim()||`gh exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new O("missing-gh","gh is not installed"):/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(r)?new O("auth","GitHub authentication failed. Run `gh auth status`."):/429|rate limit|too many requests/i.test(r)?new O("rate-limit","GitHub rate limit reached"):new O("request",r.split(`
|
|
100
|
+
`)[0])}const Er=["FAILURE","ERROR","TIMED_OUT","ACTION_REQUIRED","STARTUP_FAILURE"],Ir=["SUCCESS","NEUTRAL","SKIPPED","FAILURE","TIMED_OUT","CANCELLED","ACTION_REQUIRED","STARTUP_FAILURE","STALE"],Pr=["SUCCESS","FAILURE","ERROR","PENDING","EXPECTED"],Fe=e=>e.__typename==="CheckRun"&&e.name&&e.checkSuite?.app?.id&&e.checkSuite.workflowRun?.workflow?.id&&JSON.stringify([e.checkSuite.app.id,e.checkSuite.workflowRun?.workflow?.id,e.name]),ve=e=>Date.parse(e.checkSuite?.createdAt??""),Be=(e,t)=>ve(e)>ve(t);function _r(e,t,r,n){const s=new Map;for(const w of e){const C=ve(w),I=Fe(w);if(!I||!Number.isFinite(C))continue;const q=s.get(I);(!q||Be(w,q))&&s.set(I,w)}e=e.filter(w=>{const C=Fe(w),I=C&&s.get(C);return!I||!Be(I,w)});const o=w=>`${w} check${w===1?"":"s"}`,a=e.filter(w=>w.conclusion==="CANCELLED").length,i=e.filter(w=>w.conclusion==="STALE").length,c=[...a?[`${o(a)} cancelled`]:[],...i?[`${o(i)} stale`]:[]],u=e.filter(w=>Er.includes(w.conclusion??w.state??"")),f=u.length,m=n?{id:n,failedJobs:u.flatMap(w=>{const C=w.name??w.context,I=w.detailsUrl??w.targetUrl;return C?[{...w.id?{id:w.id}:{},name:C,...I?{url:I}:{}}]:[]}),failedJobsComplete:t}:{},g=e.filter(w=>w.status?w.status!=="COMPLETED":["PENDING","EXPECTED"].includes(w.state??"")).length,y=e.some(w=>w.status==="COMPLETED"?!Ir.includes(w.conclusion??""):!w.status&&!Pr.includes(w.state??""));return f?{status:"FAILED",label:[`${o(f)} failed`,...c,...g?[`${o(g)} pending`]:[]].join(", ")+(t?"":" (partial)"),url:r,...m,running:g>0}:g||!t||y?{status:"PENDING",label:[...c,g?`${o(g)} pending`:"unknown"].join(", ")+(t?"":" (partial)"),url:r,...m}:a||i?{status:"CANCELLED",label:c.join(", "),url:r,...m}:{status:"SUCCESS",label:[["SUCCESS","passed"],["SKIPPED","skipped"],["NEUTRAL","neutral"]].flatMap(([w,C])=>{const I=e.filter(q=>(q.conclusion??q.state)===w).length;return I?[`${o(I)} ${C}`]:[]}).join(", ")||"0 checks",url:r,...m}}function Ge(e,t){const r=me("github",e,t);return r&&!B.recognizes(r.host)?r:void 0}const ae={kind:"github",noun:"PR",ci:"checks",recognizes:()=>!1,open:(e,t)=>new Tr(re(e,t)),owns:Ke("github"),parseUrl:e=>Ge(e,/^\/([^/]+\/[^/]+)\/pull\/([1-9]\d*)\/?$/),parseIssueUrl:e=>Ge(e,/^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/),reference:e=>`#${e}`,issueReference:e=>`#${e}`,titleReferences:e=>Ve(e,"#"),indicators:e=>e.reviewDecision==="CHANGES_REQUESTED"?[{text:"changes requested",tone:"warning",essential:!0}]:[],details:e=>[`Review decision: ${e.reviewDecision?ge(e.reviewDecision):"not reported"}`],automatedReview:{name:"GitHub Copilot",status:e=>Nr(e.copilotReview)},feedback:{async viewerID(e,t,r){return(await j(re(e,t))(r,T("query { viewer { id } }"),{})).viewer?.id},async reviewerID(e,t,r,n){const s=await e("gh",["api","--hostname",r,`users/${encodeURIComponent(n)}`],t);if(s.code!==0)throw new Error("Could not resolve the GitHub reviewer account");const o=JSON.parse(s.stdout);return o.login?.toLowerCase()===n.toLowerCase()?o.node_id:void 0},async fetch(e,t,r){const n=ae.parseUrl(r.url);return n?Tt(re(e,t),n.host,n.project,n.iid):void 0},async details(e,t,r,n){const s=ae.parseUrl(r.url);return s?Dt(re(e,t),s.host,n):[]}}};function Nr(e){if(!e)return;const t=e.comments>0&&!e.dismissed,r=e.dismissed?"dismissed":t?"commented":"no comments",n=e.reviewID?{id:e.reviewID,feedback:t,label:r}:void 0;if(e.requested)return{state:"running",label:"reviewing",completed:n};if(n)return{state:t?"feedback":"settled",label:r,completed:n}}const Ar=e=>/^copilot-pull-request-reviewer(\[bot\])?$/i.test(e??"");function Dr(e){const t=e.reviewRequests.nodes.some(n=>Ar(n.requestedReviewer?.login)),r=e.copilotReviews?.nodes?.find(n=>n);if(!(!t&&!r))return{requested:t,reviewID:r?.id,comments:r?.comments.totalCount??0,...r?.state==="DISMISSED"?{dismissed:!0}:{}}}class Tr{traits=ae;graphql;constructor(t){this.graphql=j(t)}async findByNumber(t,r){for(const n of t){const[s,o]=n.path.split("/"),i=(await this.graphql(n.host,T(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
101
101
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${Me} } }
|
|
102
|
-
}`),{owner:s,repo:o,number:Number(r)})).repository?.pullRequest;if(i)return this.normalize(n.host,i)}}async findNumberByBranch(t){let r;for(const n of t.targets){const[s,o]=n.path.split("/"),i=(await this.graphql(n.host,
|
|
102
|
+
}`),{owner:s,repo:o,number:Number(r)})).repository?.pullRequest;if(i)return this.normalize(n.host,i)}}async findNumberByBranch(t){let r;for(const n of t.targets){const[s,o]=n.path.split("/"),i=(await this.graphql(n.host,T(`query($owner:String!,$repo:String!,$branch:String!) {
|
|
103
103
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch,orderBy:{field:UPDATED_AT,direction:DESC}) {
|
|
104
104
|
nodes { number updatedAt headRepository { nameWithOwner } }
|
|
105
|
-
} } }`),{owner:s,repo:o,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const c of i)c.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(!r||c.updatedAt>r.updatedAt)&&(r=c)}return r?String(r.number):void 0}async sourceBranch(t){const[r,n]=t.project.split("/");return(await this.graphql(t.host,
|
|
105
|
+
} } }`),{owner:s,repo:o,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const c of i)c.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(!r||c.updatedAt>r.updatedAt)&&(r=c)}return r?String(r.number):void 0}async sourceBranch(t){const[r,n]=t.project.split("/");return(await this.graphql(t.host,T(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
106
106
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { headRefName } }
|
|
107
|
-
}`),{owner:r,repo:n,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async findByBranch(t){const r=new Map;for(const n of t.targets){const[s,o]=n.path.split("/");let a,i=!1;for(let c=0;c<te;c++){const f=(await this.graphql(n.host,
|
|
107
|
+
}`),{owner:r,repo:n,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async findByBranch(t){const r=new Map;for(const n of t.targets){const[s,o]=n.path.split("/");let a,i=!1;for(let c=0;c<te;c++){const f=(await this.graphql(n.host,T(`query($owner:String!,$repo:String!,$branch:String!${a?",$after:String!":""}) {
|
|
108
108
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${a?",after:$after":""}) {
|
|
109
109
|
nodes { ${Me} } pageInfo { hasNextPage endCursor }
|
|
110
|
-
} } }`),{owner:s,repo:o,branch:t.sourceBranch,...a?{after:a}:{}})).repository?.pullRequests;if(!f)throw new
|
|
110
|
+
} } }`),{owner:s,repo:o,branch:t.sourceBranch,...a?{after:a}:{}})).repository?.pullRequests;if(!f)throw new O("request","GitHub repository unavailable");for(const m of f.nodes)m.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(r.has(m.url)||r.set(m.url,await this.normalize(n.host,m)));if(!f.pageInfo?.hasNextPage){i=!0;break}if(a=f.pageInfo.endCursor,!a)break}if(!i)throw new O("request","GitHub PR discovery exceeded its pagination limit")}return[...r.values()].sort((n,s)=>(s.updatedAt??"").localeCompare(n.updatedAt??""))}async threads(t,r){const[n,s]=r.baseRepository.nameWithOwner.split("/"),o=[...r.reviewThreads.nodes];let a=r.reviewThreads.pageInfo;for(let i=1;a?.hasNextPage&&a.endCursor&&i<te;i++){const u=(await this.graphql(t,T(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
111
111
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
112
112
|
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
113
|
-
} } }`),{owner:n,repo:s,number:r.number,after:a.endCursor})).repository?.pullRequest?.reviewThreads;if(!u)break;o.push(...u.nodes),a=u.pageInfo}return{unresolved:o.filter(i=>!i.isResolved).length,complete:!a?.hasNextPage}}async contexts(t,r){const[n,s]=r.baseRepository.nameWithOwner.split("/"),o=r.commits.nodes[0]?.commit.statusCheckRollup?.contexts,a=[...o?.nodes??[]];let i=o?.pageInfo;for(let c=1;i?.hasNextPage&&i.endCursor&&c<te;c++){const f=(await this.graphql(t,
|
|
113
|
+
} } }`),{owner:n,repo:s,number:r.number,after:a.endCursor})).repository?.pullRequest?.reviewThreads;if(!u)break;o.push(...u.nodes),a=u.pageInfo}return{unresolved:o.filter(i=>!i.isResolved).length,complete:!a?.hasNextPage}}async contexts(t,r){const[n,s]=r.baseRepository.nameWithOwner.split("/"),o=r.commits.nodes[0]?.commit.statusCheckRollup?.contexts,a=[...o?.nodes??[]];let i=o?.pageInfo;for(let c=1;i?.hasNextPage&&i.endCursor&&c<te;c++){const f=(await this.graphql(t,T(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
114
114
|
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
115
115
|
contexts(first:100,after:$after) { nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } } pageInfo { hasNextPage endCursor } }
|
|
116
|
-
} } } } }`),{owner:n,repo:s,oid:r.headRefOid,after:i.endCursor})).repository?.object?.statusCheckRollup?.contexts;if(!f)break;a.push(...f.nodes),i=f.pageInfo}return{nodes:a,complete:!i?.hasNextPage}}async reviewers(t,r){const n=[...r.reviewRequests.nodes];let s=r.reviewRequests.pageInfo;for(let o=1;s?.hasNextPage&&o<te;o++){if(!s.endCursor)throw new
|
|
116
|
+
} } } } }`),{owner:n,repo:s,oid:r.headRefOid,after:i.endCursor})).repository?.object?.statusCheckRollup?.contexts;if(!f)break;a.push(...f.nodes),i=f.pageInfo}return{nodes:a,complete:!i?.hasNextPage}}async reviewers(t,r){const n=[...r.reviewRequests.nodes];let s=r.reviewRequests.pageInfo;for(let o=1;s?.hasNextPage&&o<te;o++){if(!s.endCursor)throw new O("request","GitHub reviewer pagination cursor missing");const[a,i]=r.baseRepository.nameWithOwner.split("/"),u=(await this.graphql(t,T(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
117
117
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
118
118
|
reviewRequests(first:100,after:$after) {
|
|
119
119
|
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { login } ... on Team { name } } }
|
|
120
120
|
pageInfo { hasNextPage endCursor }
|
|
121
121
|
}
|
|
122
122
|
} }
|
|
123
|
-
}`),{owner:a,repo:i,number:r.number,after:s.endCursor})).repository?.pullRequest?.reviewRequests;if(!u)throw new U("request","GitHub reviewers unavailable");n.push(...u.nodes),s=u.pageInfo}if(s?.hasNextPage)throw new U("request","GitHub reviewers exceeded the pagination limit");return{nodes:n,pageInfo:s}}async normalize(t,r){const n=await this.reviewers(t,r),[s,o]=[await this.threads(t,r),await this.contexts(t,r)];return{forge:"github",iid:String(r.number),title:r.title,url:r.url,state:r.state==="OPEN"?"opened":r.state.toLowerCase(),draft:r.isDraft,conflicts:r.mergeable==="CONFLICTING",conflictsKnown:r.mergeable!=="UNKNOWN",approved:r.reviewDecision==="APPROVED",reviewDecision:r.reviewDecision??void 0,copilotReview:Ar({...r,reviewRequests:n}),awaitingReviewers:n.nodes.flatMap(a=>{const i=a.requestedReviewer;return i?.__typename==="Bot"?[]:i?.login?[i.login]:i?.name?[i.name]:[]}),reviewersComplete:!n.pageInfo?.hasNextPage,reviewerIDs:[...new Set([...n.nodes.flatMap(a=>a.requestedReviewer?.__typename==="User"?a.requestedReviewer.id??[]:[]),...(r.latestReviews?.nodes??[]).flatMap(a=>a?.author?.id??[])])],targetProject:r.baseRepository.nameWithOwner,targetBranch:r.baseRefName,...r.headRepository?{sourceProject:r.headRepository.nameWithOwner}:{},sourceBranch:r.headRefName,headSha:r.headRefOid,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt,pipeline:o.nodes.length||!o.complete?Pr(o.nodes,o.complete,`${r.url}/checks`,r.headRefOid):void 0,unresolvedThreads:s.unresolved,threadsComplete:s.complete}}}const Tr={gitlab:F,github:ae},G=e=>Tr[e.forge],ce=e=>G(e).reference(e.iid);function le(e){const t=G(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const He={url:{type:"string"},issueUrl:{type:"string"}},ze={type:"object",properties:{...He,targets:{type:"array",items:{type:"object",properties:He,required:["url"],additionalProperties:!1}}},additionalProperties:!1},ne={type:"string"},$e={type:"object",title:"Snapshot"},W={type:"object",title:"InboxState"},qr={type:"object",properties:{enabled:{type:"boolean"},snapshot:$e},required:["enabled","snapshot"],additionalProperties:!1},xr={id:"opencode-forgekeeper",methods:{monitoringStatus:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:{type:"object",title:"MonitoringStatus"}},feedback:{input:{type:"object",additionalProperties:!1},output:W},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:W},markFeedbackRead:{input:{type:"object",properties:{ids:{type:"array",items:{type:"string"},maxItems:500}},required:["ids"],additionalProperties:!1},output:W},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:W},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:W},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:W},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:ze},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:ne},visible:ne},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},statuses:{type:"object",additionalProperties:$e}},required:["enabled","statuses"],additionalProperties:!1}},release:{input:{type:"object",properties:{clientID:{type:"string"}},required:["clientID"],additionalProperties:!1},output:{type:"object",additionalProperties:!1}},refresh:{input:{type:"object",properties:{key:ne},required:["key"],additionalProperties:!1},output:qr}},events:{feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...ze.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:ne,snapshot:$e},required:["directory","key","snapshot"],additionalProperties:!1}},notice:{schema:{type:"object",properties:{sessionID:{type:"string"},title:{type:"string"},message:{type:"string"},variant:{type:"string",enum:["info","error"]}},required:["message","variant"],additionalProperties:!1}}}},Lr="",ot=6e4,We=(e,t)=>e.directory===t.directory&&e.key===t.key,Y=e=>JSON.stringify([e.directory,e.key]);function Or(e){const t=e.now??Date.now,r=e.setTimer??((p,S)=>setTimeout(p,S)),n=e.clearTimer??(p=>clearTimeout(p)),s=e.defer??queueMicrotask,o=new Map,a=new Map,i=new Map;let c,u=!1;const f=p=>a.get(p.directory)?.has(p.key)===!0;function m(p,S){const _=Y(p);(S.revision??-1)>=(o.get(_)?.revision??-1)&&o.set(_,S)}function g(p,S){const x={kind:"request",message:`PR/MR status service unavailable: ${S instanceof Error?S.message:String(S)}`,at:t()};for(const z of a.get(p)??[]){const O=Y({directory:p,key:z});o.set(O,{...o.get(O)??{},loading:!1,error:x})}e.onChange()}const y=new Map,$=new Map;function w(p){const S=(y.get(p)??0)+1;y.set(p,S);const _=$.get(p);_!==void 0&&n(_),$.set(p,r(()=>{R(p)},Math.min(ot,1e3*2**S)))}async function R(p){if(u)return;const S=$.get(p);S!==void 0&&n(S),$.delete(p);const _=[...a.get(p)??[]];try{const x=await e.watch(p,{clientID:e.clientID,keys:_,...c?.directory===p?{visible:c.key}:{}});if(u)return;y.delete(p),i.set(p,x.enabled);for(const[z,O]of Object.entries(x.statuses))f({directory:p,key:z})&&m({directory:p,key:z},O);e.onChange()}catch(x){if(u)return;g(p,x),w(p)}}const P=new Set;function q(p){P.has(p)||(P.add(p),s(()=>{P.delete(p),R(p)}))}return{snapshot:p=>o.get(Y(p))??{loading:!1},enabled:p=>i.get(p)??!0,show(p){if(p.key!==Lr)for(const[_,x]of a)_===p.directory||!x.delete(p.key)||(o.delete(Y({directory:_,key:p.key})),c&&We(c,{directory:_,key:p.key})&&(c=void 0),q(_));const S=a.get(p.directory)??new Set;a.set(p.directory,S),S.add(p.key),c=p,q(p.directory)},hide(p){c&&We(c,p)&&(c=void 0),q(p.directory)},async refresh(p){const S=Y(p);o.set(S,{...o.get(S)??{},loading:!0}),e.onChange();try{const _=await e.refresh(p.directory,p.key);if(u)return;i.set(p.directory,_.enabled),m(p,_.snapshot),e.onChange()}catch(_){if(u)return;g(p.directory,_)}},heartbeat(){for(const p of a.keys())R(p)},receive(p,S,_){f({directory:p,key:S})&&(m({directory:p,key:S},_),e.onChange())},hasShown:p=>[...a.values()].some(S=>S.has(p)),dispose(){u=!0;for(const p of $.values())n(p);for(const p of a.keys())e.release(p,e.clientID).catch(()=>{})}}}const oe=e=>({location:{directory:e}}),Ur=async(e,t)=>await e.feedback({},oe(t));function Mr(e){let t,r=0;const n=new Map;let s;return{get client(){return t?.client},connect(o){t?.dispose(),t=Br(o,{...e,clientID:`${e.clientID}:${++r}`});for(const a of n.values())t.client.show(a),t.client.hide(a);s&&t.client.show(s),e.onChange()},show(o){n.set(o.key,o),s=o,t?.client.show(o)},hide(o){s?.key===o.key&&s.directory===o.directory&&(s=void 0),t?.client.hide(o)},dispose(){t?.dispose(),t=void 0}}}function jr(e){const t=new Map;let r=0;const n=async s=>{const o=(t.get(s)??0)+1;t.set(s,o);const a=r,i=()=>a===r&&t.get(s)===o;try{const c=await e.load(s);i()&&e.changed(s,c)}catch(c){i()&&e.failed(s,c instanceof Error?c.message:String(c))}};return{reload:n,has:s=>t.has(s),refresh:()=>Promise.all([...t.keys()].map(n)),invalidate(){r++}}}function Br(e,t){const r=e,n=Or({clientID:t.clientID,watch:async(a,i)=>await r.watch(i,oe(a)),refresh:async(a,i)=>await r.refresh({key:i},oe(a)),release:(a,i)=>r.release({clientID:i},oe(a)),onChange:t.onChange}),s=setInterval(()=>{n.heartbeat(),t.heartbeat?.()},ot),o=e.events.on("status",a=>{const{directory:i,key:c,snapshot:u}=a.data;n.receive(i,c,u)});return{client:n,dispose(){clearInterval(s),o(),n.dispose()}}}const Fr=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,pe=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),Gr=e=>e.kind==="review-request",Hr=e=>Gr(e)?`Requested: ${pe(e.postedAt??e.at)}`:e.postedAt!==void 0?`Latest comment: ${pe(e.postedAt)}`:`Detected: ${pe(e.at)}`;function zr(e,t){const r=e.items.filter(n=>n.sessionID===t&&!n.read).length;if(!(!t||r===0))return`${r} review update${r===1?"":"s"}${e.paused?" (paused)":""}`}function Wr(e){return[...new Set([e.url,...e.links])].filter(t=>{try{const r=new URL(t);return r.protocol==="https:"&&r.origin===new URL(e.url).origin&&!r.username&&!r.password}catch{return!1}})}function Jr(e){const t=Wr(e),r=t.filter(s=>s!==e.url),n=e.kind==="ci-failed";return[...r.map((s,o)=>({title:`${n?"Failed job":"Comment"} ${r.length>1?`${o+1} of ${r.length} `:""}(${n?new URL(s).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(s).hash||"no anchor"})`,description:s,value:s})),...t.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const Qr=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Ie(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":Qr.has(e.status)?"warning":"muted":"muted"}const it=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Kr=e=>e.charAt(0).toUpperCase()+e.slice(1),Vr={success:"CI β",error:"CI β",warning:"CI β¦"};function Yr(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}function Xr(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const fe=e=>({text:ce(e),tone:"muted",url:e.url,essential:!0});function Zr(e){const t=Ie(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:Vr[t],tone:t,url:e.pipeline.url}:{text:`no ${G(e).ci}`,compact:"no CI",tone:t}}function en(e){const t=new Set(e.map(g=>G(g).noun)),r=t.size===1?[...t][0]:"PR/MR",n=e.length===1?`1 ${r}`:`${e.length} ${r==="PR/MR"?"PRs/MRs":`${r}s`}`,s=e.filter(g=>g.state==="opened"),o=[{text:n,tone:"muted",essential:!0}],a=s.filter(g=>le(g)?.state==="running").length;a&&o.push({text:`π€ ${a} reviewing`,compact:`π€ ${a}`,tone:"warning",essential:!0});const i=s.filter(g=>Ie(g.pipeline)==="error").length;i&&o.push({text:`${i} CI failed`,compact:`CI β ${i}`,tone:"error"});const c=s.filter(g=>g.conflicts).length;c&&o.push({text:it(c,"conflict"),tone:"error",essential:!0});const u=s.filter(g=>g.approved&&g.awaitingReviewers.length===0).length;u&&o.push({text:`${u} approved`,tone:"success"});const f=e.filter(g=>g.state==="merged").length;f&&o.push({text:`${f} merged`,tone:"success"});const m=e.length-s.length-f;return m&&o.push({text:`${m} closed`,tone:"muted"}),o}function tn(e){const{lookup:t,error:r}=e,n=r?[{text:"stale",tone:"warning",essential:!0}]:[];if(!t||t.kind==="none"||t.requests.length===0)return e.targeted&&(r||t?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];t.failed?.length&&n.unshift({text:`${t.failed.length} unavailable`,tone:"warning",essential:!0});const s=t.requests;if(t.explicitTarget&&s.length>1)return[...en(s),...n];if(s.length>1){const i=G(s[0]).noun;return[...s.map(fe),{text:`${it(s.length,`open ${i}`)}, run /${i.toLowerCase()}-status`,tone:"warning"},...n]}const[o]=s;if(o.state!=="opened")return[fe(o),{text:o.state,tone:o.state==="merged"?"success":"muted",essential:!0},...n];const a=[fe(o),Zr(o)];if(o.unresolvedThreads>0||!o.threadsComplete){const i=Xr(o);a.push({text:i,compact:i.replace("unresolved ",""),tone:"warning"})}return le(o)?.state==="running"&&a.push({text:"π€ reviewing",compact:"π€",tone:"warning",essential:!0}),a.push(...G(o).indicators(o)),o.conflicts&&a.push({text:"conflicts",tone:"error",essential:!0}),o.conflictsKnown||a.push({text:"mergeability unknown",tone:"muted"}),o.awaitingReviewers.length?a.push({text:Yr(o.awaitingReviewers),tone:"muted"}):o.approved&&a.push({text:"approved",tone:"success"}),[...a,...n]}const Je=e=>new Date(e).toLocaleTimeString();function rn(e,t){const r=G(e),n=[`${ce(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} β ${e.targetBranch}`,`${Kr(r.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${J(e.draft)} Β· Conflicts: ${e.conflictsKnown?J(e.conflicts):"unknown"}`,...r.details(e)],s=le(e);return s&&n.push(`${s.name} review: ${s.label}`),e.awaitingReviewers.length&&n.push(`Awaiting review: ${e.awaitingReviewers.map(o=>`@${o}`).join(", ")}`),e.reviewersComplete||n.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&n.push(`Local HEAD differs from the ${r.noun} head commit (unpushed or not fetched)`),n.push(e.url),n}function nn(e){const{lookup:t,error:r,fetchedAt:n}=e,s=[];if(!t)s.push(r?"Could not look up the PR/MR.":"No data yet.");else if(t.kind==="none")s.push(`No PR/MR lookup: ${t.reason}.`);else{const{repository:o,sessionTarget:a,requests:i}=t;if(o){const c=o.branch===o.sourceBranch?o.branch:`${o.branch} (pushes to ${o.sourceBranch})`;s.push(`Branch: ${c} in ${o.source.path}`),i.length===0&&s.push("","No open PR/MR for this branch.")}else a&&s.push(`Session target: ${a}`);for(const{url:c,reason:u}of t.failed??[])s.push(`Unavailable: ${c} (${u})`);for(const c of i)s.push("",...rn(c,o?.head??""))}return r&&s.push("",`Last refresh failed at ${Je(r.at)}: ${r.message}`),n!==void 0&&s.push("",`Last fetched: ${Je(n)}`),s.join(`
|
|
124
|
-
`)}function
|
|
123
|
+
}`),{owner:a,repo:i,number:r.number,after:s.endCursor})).repository?.pullRequest?.reviewRequests;if(!u)throw new O("request","GitHub reviewers unavailable");n.push(...u.nodes),s=u.pageInfo}if(s?.hasNextPage)throw new O("request","GitHub reviewers exceeded the pagination limit");return{nodes:n,pageInfo:s}}async normalize(t,r){const n=await this.reviewers(t,r),[s,o]=[await this.threads(t,r),await this.contexts(t,r)];return{forge:"github",iid:String(r.number),title:r.title,url:r.url,state:r.state==="OPEN"?"opened":r.state.toLowerCase(),draft:r.isDraft,conflicts:r.mergeable==="CONFLICTING",conflictsKnown:r.mergeable!=="UNKNOWN",approved:r.reviewDecision==="APPROVED",reviewDecision:r.reviewDecision??void 0,copilotReview:Dr({...r,reviewRequests:n}),awaitingReviewers:n.nodes.flatMap(a=>{const i=a.requestedReviewer;return i?.__typename==="Bot"?[]:i?.login?[i.login]:i?.name?[i.name]:[]}),reviewersComplete:!n.pageInfo?.hasNextPage,reviewerIDs:[...new Set([...n.nodes.flatMap(a=>a.requestedReviewer?.__typename==="User"?a.requestedReviewer.id??[]:[]),...(r.latestReviews?.nodes??[]).flatMap(a=>a?.author?.id??[])])],targetProject:r.baseRepository.nameWithOwner,targetBranch:r.baseRefName,...r.headRepository?{sourceProject:r.headRepository.nameWithOwner}:{},sourceBranch:r.headRefName,headSha:r.headRefOid,...r.author?.id?{authorID:r.author.id}:{},updatedAt:r.updatedAt,pipeline:o.nodes.length||!o.complete?_r(o.nodes,o.complete,`${r.url}/checks`,r.headRefOid):void 0,unresolvedThreads:s.unresolved,threadsComplete:s.complete}}}const qr={gitlab:B,github:ae},G=e=>qr[e.forge],ce=e=>G(e).reference(e.iid);function le(e){const t=G(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const He={url:{type:"string"},issueUrl:{type:"string"}},ze={type:"object",properties:{...He,targets:{type:"array",items:{type:"object",properties:He,required:["url"],additionalProperties:!1}}},additionalProperties:!1},ne={type:"string"},$e={type:"object",title:"Snapshot"},W={type:"object",title:"InboxState"},xr={type:"object",properties:{enabled:{type:"boolean"},snapshot:$e},required:["enabled","snapshot"],additionalProperties:!1},Lr={id:"opencode-forgekeeper",methods:{monitoringStatus:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:{type:"object",title:"MonitoringStatus"}},feedback:{input:{type:"object",additionalProperties:!1},output:W},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:W},markFeedbackRead:{input:{type:"object",properties:{ids:{type:"array",items:{type:"string"},maxItems:500}},required:["ids"],additionalProperties:!1},output:W},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:W},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:W},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:W},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:ze},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:ne},visible:ne},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},statuses:{type:"object",additionalProperties:$e}},required:["enabled","statuses"],additionalProperties:!1}},release:{input:{type:"object",properties:{clientID:{type:"string"}},required:["clientID"],additionalProperties:!1},output:{type:"object",additionalProperties:!1}},refresh:{input:{type:"object",properties:{key:ne},required:["key"],additionalProperties:!1},output:xr}},events:{feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...ze.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:ne,snapshot:$e},required:["directory","key","snapshot"],additionalProperties:!1}},notice:{schema:{type:"object",properties:{sessionID:{type:"string"},title:{type:"string"},message:{type:"string"},variant:{type:"string",enum:["info","error"]}},required:["message","variant"],additionalProperties:!1}}}},Or="",ot=6e4,We=(e,t)=>e.directory===t.directory&&e.key===t.key,Y=e=>JSON.stringify([e.directory,e.key]);function Ur(e){const t=e.now??Date.now,r=e.setTimer??((p,R)=>setTimeout(p,R)),n=e.clearTimer??(p=>clearTimeout(p)),s=e.defer??queueMicrotask,o=new Map,a=new Map,i=new Map;let c,u=!1;const f=p=>a.get(p.directory)?.has(p.key)===!0;function m(p,R){const P=Y(p);(R.revision??-1)>=(o.get(P)?.revision??-1)&&o.set(P,R)}function g(p,R){const x={kind:"request",message:`PR/MR status service unavailable: ${R instanceof Error?R.message:String(R)}`,at:t()};for(const z of a.get(p)??[]){const U=Y({directory:p,key:z});o.set(U,{...o.get(U)??{},loading:!1,error:x})}e.onChange()}const y=new Map,v=new Map;function w(p){const R=(y.get(p)??0)+1;y.set(p,R);const P=v.get(p);P!==void 0&&n(P),v.set(p,r(()=>{C(p)},Math.min(ot,1e3*2**R)))}async function C(p){if(u)return;const R=v.get(p);R!==void 0&&n(R),v.delete(p);const P=[...a.get(p)??[]];try{const x=await e.watch(p,{clientID:e.clientID,keys:P,...c?.directory===p?{visible:c.key}:{}});if(u)return;y.delete(p),i.set(p,x.enabled);for(const[z,U]of Object.entries(x.statuses))f({directory:p,key:z})&&m({directory:p,key:z},U);e.onChange()}catch(x){if(u)return;g(p,x),w(p)}}const I=new Set;function q(p){I.has(p)||(I.add(p),s(()=>{I.delete(p),C(p)}))}return{snapshot:p=>o.get(Y(p))??{loading:!1},enabled:p=>i.get(p)??!0,show(p){if(p.key!==Or)for(const[P,x]of a)P===p.directory||!x.delete(p.key)||(o.delete(Y({directory:P,key:p.key})),c&&We(c,{directory:P,key:p.key})&&(c=void 0),q(P));const R=a.get(p.directory)??new Set;a.set(p.directory,R),R.add(p.key),c=p,q(p.directory)},hide(p){c&&We(c,p)&&(c=void 0),q(p.directory)},async refresh(p){const R=Y(p);o.set(R,{...o.get(R)??{},loading:!0}),e.onChange();try{const P=await e.refresh(p.directory,p.key);if(u)return;i.set(p.directory,P.enabled),m(p,P.snapshot),e.onChange()}catch(P){if(u)return;g(p.directory,P)}},heartbeat(){for(const p of a.keys())C(p)},receive(p,R,P){f({directory:p,key:R})&&(m({directory:p,key:R},P),e.onChange())},hasShown:p=>[...a.values()].some(R=>R.has(p)),dispose(){u=!0;for(const p of v.values())n(p);for(const p of a.keys())e.release(p,e.clientID).catch(()=>{})}}}const oe=e=>({location:{directory:e}}),Mr=async(e,t)=>await e.feedback({},oe(t));function jr(e){let t,r=0;const n=new Map;let s;return{get client(){return t?.client},connect(o){t?.dispose(),t=Br(o,{...e,clientID:`${e.clientID}:${++r}`});for(const a of n.values())t.client.show(a),t.client.hide(a);s&&t.client.show(s),e.onChange()},show(o){n.set(o.key,o),s=o,t?.client.show(o)},hide(o){s?.key===o.key&&s.directory===o.directory&&(s=void 0),t?.client.hide(o)},dispose(){t?.dispose(),t=void 0}}}function Fr(e){const t=new Map;let r=0;const n=async s=>{const o=(t.get(s)??0)+1;t.set(s,o);const a=r,i=()=>a===r&&t.get(s)===o;try{const c=await e.load(s);i()&&e.changed(s,c)}catch(c){i()&&e.failed(s,c instanceof Error?c.message:String(c))}};return{reload:n,has:s=>t.has(s),refresh:()=>Promise.all([...t.keys()].map(n)),invalidate(){r++}}}function Br(e,t){const r=e,n=Ur({clientID:t.clientID,watch:async(a,i)=>await r.watch(i,oe(a)),refresh:async(a,i)=>await r.refresh({key:i},oe(a)),release:(a,i)=>r.release({clientID:i},oe(a)),onChange:t.onChange}),s=setInterval(()=>{n.heartbeat(),t.heartbeat?.()},ot),o=e.events.on("status",a=>{const{directory:i,key:c,snapshot:u}=a.data;n.receive(i,c,u)});return{client:n,dispose(){clearInterval(s),o(),n.dispose()}}}const Gr=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,pe=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),Hr=e=>e.kind==="review-request",zr=e=>Hr(e)?`Requested: ${pe(e.postedAt??e.at)}`:e.postedAt!==void 0?`Latest comment: ${pe(e.postedAt)}`:`Detected: ${pe(e.at)}`,it=(e,t)=>t?e.items.filter(r=>r.sessionID===t):[];function Wr(e,t){const r=it(e,t).filter(n=>!n.read).length;if(r!==0)return`${r} review update${r===1?"":"s"}${e.paused?" (paused)":""}`}function Jr(e){return[...new Set([e.url,...e.links])].filter(t=>{try{const r=new URL(t);return r.protocol==="https:"&&r.origin===new URL(e.url).origin&&!r.username&&!r.password}catch{return!1}})}function Qr(e){const t=Jr(e),r=t.filter(s=>s!==e.url),n=e.kind==="ci-failed";return[...r.map((s,o)=>({title:`${n?"Failed job":"Comment"} ${r.length>1?`${o+1} of ${r.length} `:""}(${n?new URL(s).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(s).hash||"no anchor"})`,description:s,value:s})),...t.includes(e.url)?[{title:"PR/MR overview",description:e.url,value:e.url}]:[]]}const Kr=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Ie(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":Kr.has(e.status)?"warning":"muted":"muted"}const at=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Vr=e=>e.charAt(0).toUpperCase()+e.slice(1),Yr={success:"CI β",error:"CI β",warning:"CI β¦"};function Xr(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}function Zr(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const fe=e=>({text:ce(e),tone:"muted",url:e.url,essential:!0});function en(e){const t=Ie(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:Yr[t],tone:t,url:e.pipeline.url}:{text:`no ${G(e).ci}`,compact:"no CI",tone:t}}function tn(e){const t=new Set(e.map(g=>G(g).noun)),r=t.size===1?[...t][0]:"PR/MR",n=e.length===1?`1 ${r}`:`${e.length} ${r==="PR/MR"?"PRs/MRs":`${r}s`}`,s=e.filter(g=>g.state==="opened"),o=[{text:n,tone:"muted",essential:!0}],a=s.filter(g=>le(g)?.state==="running").length;a&&o.push({text:`π€ ${a} reviewing`,compact:`π€ ${a}`,tone:"warning",essential:!0});const i=s.filter(g=>Ie(g.pipeline)==="error").length;i&&o.push({text:`${i} CI failed`,compact:`CI β ${i}`,tone:"error"});const c=s.filter(g=>g.conflicts).length;c&&o.push({text:at(c,"conflict"),tone:"error",essential:!0});const u=s.filter(g=>g.approved&&g.awaitingReviewers.length===0).length;u&&o.push({text:`${u} approved`,tone:"success"});const f=e.filter(g=>g.state==="merged").length;f&&o.push({text:`${f} merged`,tone:"success"});const m=e.length-s.length-f;return m&&o.push({text:`${m} closed`,tone:"muted"}),o}function rn(e){const{lookup:t,error:r}=e,n=r?[{text:"stale",tone:"warning",essential:!0}]:[];if(!t||t.kind==="none"||t.requests.length===0)return e.targeted&&(r||t?.explicitTarget)?[{text:"PR/MR status unavailable",tone:"warning"}]:[];t.failed?.length&&n.unshift({text:`${t.failed.length} unavailable`,tone:"warning",essential:!0});const s=t.requests;if(t.explicitTarget&&s.length>1)return[...tn(s),...n];if(s.length>1){const i=G(s[0]).noun;return[...s.map(fe),{text:`${at(s.length,`open ${i}`)}, run /${i.toLowerCase()}-status`,tone:"warning"},...n]}const[o]=s;if(o.state!=="opened")return[fe(o),{text:o.state,tone:o.state==="merged"?"success":"muted",essential:!0},...n];const a=[fe(o),en(o)];if(o.unresolvedThreads>0||!o.threadsComplete){const i=Zr(o);a.push({text:i,compact:i.replace("unresolved ",""),tone:"warning"})}return le(o)?.state==="running"&&a.push({text:"π€ reviewing",compact:"π€",tone:"warning",essential:!0}),a.push(...G(o).indicators(o)),o.conflicts&&a.push({text:"conflicts",tone:"error",essential:!0}),o.conflictsKnown||a.push({text:"mergeability unknown",tone:"muted"}),o.awaitingReviewers.length?a.push({text:Xr(o.awaitingReviewers),tone:"muted"}):o.approved&&a.push({text:"approved",tone:"success"}),[...a,...n]}const Je=e=>new Date(e).toLocaleTimeString();function nn(e,t){const r=G(e),n=[`${ce(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,`Target: ${e.targetProject} β ${e.targetBranch}`,`${Vr(r.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${J(e.draft)} Β· Conflicts: ${e.conflictsKnown?J(e.conflicts):"unknown"}`,...r.details(e)],s=le(e);return s&&n.push(`${s.name} review: ${s.label}`),e.awaitingReviewers.length&&n.push(`Awaiting review: ${e.awaitingReviewers.map(o=>`@${o}`).join(", ")}`),e.reviewersComplete||n.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&n.push(`Local HEAD differs from the ${r.noun} head commit (unpushed or not fetched)`),n.push(e.url),n}function sn(e){const{lookup:t,error:r,fetchedAt:n}=e,s=[];if(!t)s.push(r?"Could not look up the PR/MR.":"No data yet.");else if(t.kind==="none")s.push(`No PR/MR lookup: ${t.reason}.`);else{const{repository:o,sessionTarget:a,requests:i}=t;if(o){const c=o.branch===o.sourceBranch?o.branch:`${o.branch} (pushes to ${o.sourceBranch})`;s.push(`Branch: ${c} in ${o.source.path}`),i.length===0&&s.push("","No open PR/MR for this branch.")}else a&&s.push(`Session target: ${a}`);for(const{url:c,reason:u}of t.failed??[])s.push(`Unavailable: ${c} (${u})`);for(const c of i)s.push("",...nn(c,o?.head??""))}return r&&s.push("",`Last refresh failed at ${Je(r.at)}: ${r.message}`),n!==void 0&&s.push("",`Last fetched: ${Je(n)}`),s.join(`
|
|
124
|
+
`)}function on(e,t,r){const n=rn(e);if(!n.length&&!t)return;const s=n.findIndex(i=>!i.essential||!i.url),o=s<0?n.length:Math.max(1,s),a=e.lookup?.kind==="found"&&e.lookup.requests.length===1?e.lookup.requests[0].awaitingReviewers:void 0;return{icon:"review",label:[...n.map((i,c)=>({segment:i,priority:c<o?-1:an(i)})).sort((i,c)=>i.priority-c.priority).map(({segment:i})=>cn(i,a)),t?.replace(/^(\d+) review updates?/,"β» $1")].filter(Boolean).join(" Β· "),tone:ln(n.map(i=>i.tone)),title:"PR/MR status",rows:[...n.map((i,c)=>({id:`segment-${c}`,label:i.text.startsWith("awaiting ")&&a?.length?`awaiting ${a.map(u=>`@${u}`).join(", ")}`:i.text,...i.url?{icon:"outline-arrow-up-right"}:{},...i.tone==="success"||i.tone==="warning"?{tone:i.tone}:i.tone==="error"?{tone:"danger"}:{},...i.url?{run:()=>r.external(i.url)}:{}})),{id:"details",label:"Show PR/MR status",icon:"status",run:r.status},...t?[{id:"feedback",label:t,icon:"comment",run:r.feedback}]:[]]}}function an(e){return e.text==="mergeability unknown"?4:e.tone==="error"?0:/unresolved threads?$/.test(e.text)?1:e.tone==="warning"?2:3}function cn(e,t){const r=e.text.match(/^(\d+\+?) unresolved threads?$/);return r?`π¬ ${r[1]}`:e.text.startsWith("awaiting ")&&t?.length?`β· @${t[0]}${t.length>1?` +${t.length-1}`:""}`:e.text==="approved"?"β approved":e.compact?.startsWith("CI ")?e.compact.replace(/^CI ([βββ¦])/,"$1 CI"):e.compact??e.text}function ln(e){if(e.includes("error"))return"danger";if(e.includes("warning"))return"warning";if(e.includes("success"))return"success"}function un(e,t){const{sessionID:r}=e;r&&!t.hasShown(r)||(r&&e.variant==="info"&&t.openTab(r),t.toast({...e.title?{title:e.title}:{},message:e.message,variant:e.variant}))}var dn=l.template("<a><b>"),pn=l.template("<div><span class=fk-label>: "),fn=l.template("<b>"),hn=l.template("<div class=fk-warning>Reviewer list is partial"),mn=l.template("<div class=fk-warning>Local HEAD differs from the <!> head commit (unpushed or not fetched)"),gn=l.template("<div class=fk-card><a><b> </b></a><section></section><section><b>Review and approval"),he=l.template("<div>"),wn=l.template("<div class=forgekeeper-panel><header><h2>PR/MR status"),bn=l.template("<div>PR/MR status is off."),vn=l.template("<div class=fk-muted>No PR/MR status available."),$n=l.template("<div class=fk-muted>Last fetched: "),yn=l.template("<section>"),Sn=l.template('<div class="fk-warning fk-pre"><b>Unavailable'),Rn=l.template('<div class="fk-error fk-pre"><b>Last refresh failed at '),Cn=l.template("<div class=fk-card><b></b><div class=fk-muted></div><section></section><div class=fk-actions>"),kn=l.template("<a>"),En=l.template("<div class=forgekeeper-panel><header><h2>Review updates"),In=l.template("<div class=fk-error>Could not load review updates: <!>. Retrying automatically."),Pn=l.template("<div class=fk-muted>");const _n=`
|
|
125
125
|
.forgekeeper-panel { display: flex; flex-direction: column; gap: 12px; padding: 12px 16px; overflow-y: auto; height: 100%; font-size: 13px; line-height: 1.5; color: var(--v2-text-text-base); }
|
|
126
126
|
.forgekeeper-panel header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
127
127
|
.forgekeeper-panel h2 { font-size: 13px; font-weight: 600; margin: 0; }
|
|
@@ -135,7 +135,7 @@ ${r}
|
|
|
135
135
|
.forgekeeper-panel .fk-error { color: var(--v2-state-fg-danger); }
|
|
136
136
|
.forgekeeper-panel a { color: var(--v2-text-text-accent); cursor: pointer; text-decoration: underline; }
|
|
137
137
|
.forgekeeper-panel .fk-pre { white-space: pre-wrap; }
|
|
138
|
-
`,X="status",Z="feedback",
|
|
139
|
-
${
|
|
140
|
-
${
|
|
141
|
-
${
|
|
138
|
+
`,X="status",Z="feedback",Nn={items:[],paused:!1},Qe=e=>e==="success"?"fk-success":e==="warning"?"fk-warning":e==="error"?"fk-error":e==="muted"?"fk-muted":void 0,An=F.Plugin.define({setup(e){e.add(F.Style,_n);const t=()=>e.client.rpc(Lr),r=d=>({location:{directory:d}}),[n,s]=N.createSignal(0),[o,a]=Ne.createStore({}),[i,c]=Ne.createStore({}),u=Fr({load:d=>Mr(t(),d),changed:(d,h)=>{a(d,h),c(d,void 0)},failed:(d,h)=>c(d,h)}),f=u.reload,m=jr({clientID:Gr(),onChange:()=>s(d=>d+1),heartbeat:()=>{u.refresh()}}),g=()=>m.client,y=d=>d.server.builtin,v=d=>d.location?.directory??d.directory,w=d=>({directory:v(d),key:d.id}),C=d=>(n(),g()?.snapshot(d)??{loading:!1}),I=d=>(n(),g()?.enabled(d)??!0),q=d=>o[d]??Nn,p=d=>{const h=C(d).lookup;return h?.kind==="found"?h.requests:[]},R=()=>{const d=e.sessions.current();return d&&y(d)?d:void 0};F.createKeyed(()=>{const d=R();return d?JSON.stringify([v(d),d.id]):void 0},d=>{const[h,$]=JSON.parse(d),E={directory:h,key:$};m.show(E),f(h),N.onCleanup(()=>m.hide(E))});const P=(d,h=R())=>{h&&e.layout.open(`${e.id}:${d}`,h,{tab:"select"})},x=d=>I(d)?!1:(e.toast.show({title:"PR/MR status is off in the plugin's options (status: false)"}),!0);e.add(F.ComposerPill,{id:"status",show:d=>z(d.session)});function z(d){if(!y(d))return;const h=w(d);if(!I(h.directory))return;const $=Wr(q(h.directory),d.id);return on(C(h),$,{external:E=>e.system.openExternal(E),status:()=>P(X,d),feedback:()=>P(Z,d)})}const U=e.ui;function M(d){return(()=>{var h=pn(),$=h.firstChild,E=$.firstChild;return l.insert($,()=>d.label,E),l.insert(h,l.createComponent(N.Show,{get when(){return d.url},get fallback(){return(()=>{var b=fn();return l.insert(b,()=>d.value),l.effect(()=>l.className(b,Qe(d.tone))),b})()},get children(){var b=dn(),_=b.firstChild;return b.$$click=()=>e.system.openExternal(d.url),l.insert(_,()=>d.value),l.effect(()=>l.className(b,Qe(d.tone))),b}}),null),h})()}function ct(d){const h=()=>d.request,$=()=>G(h()),E=()=>le(h());return(()=>{var b=gn(),_=b.firstChild,A=_.firstChild,S=A.firstChild,k=_.nextSibling,L=k.nextSibling;return L.firstChild,_.$$click=()=>e.system.openExternal(h().url),l.insert(A,()=>ce(h()),S),l.insert(A,()=>h().title,null),l.insert(k,l.createComponent(M,{label:"State",get value(){return h().state},get tone(){return h().state==="merged"?"success":void 0}}),null),l.insert(k,l.createComponent(M,{label:"Target",get value(){return`${h().targetProject} β ${h().targetBranch}`}}),null),l.insert(k,l.createComponent(M,{get label(){return $().ci.charAt(0).toUpperCase()+$().ci.slice(1)},get value(){return h().pipeline?.label??"none"},get tone(){return Ie(h().pipeline)},get url(){return h().pipeline?.url}}),null),l.insert(k,l.createComponent(M,{label:"Unresolved threads",get value(){return`${h().unresolvedThreads}${h().threadsComplete?"":"+"}`},get tone(){return h().unresolvedThreads||!h().threadsComplete?"warning":void 0}}),null),l.insert(k,l.createComponent(M,{label:"Draft",get value(){return J(h().draft)},get tone(){return h().draft?"warning":void 0}}),null),l.insert(k,l.createComponent(M,{label:"Conflicts",get value(){return l.memo(()=>!!h().conflictsKnown)()?J(h().conflicts):"unknown"},get tone(){return h().conflicts?"error":void 0}}),null),l.insert(L,l.createComponent(N.For,{get each(){return $().details(h())},children:D=>{const Q=D.indexOf(": ");return Q<0?(()=>{var K=he();return l.insert(K,D),K})():l.createComponent(M,{get label(){return D.slice(0,Q)},get value(){return D.slice(Q+2)}})}}),null),l.insert(L,l.createComponent(N.Show,{get when(){return E()},children:D=>l.createComponent(M,{get label(){return`${D().name} review`},get value(){return D().label},get tone(){return D().state==="running"?"warning":void 0}})}),null),l.insert(L,l.createComponent(N.Show,{get when(){return h().awaitingReviewers.length},get children(){return l.createComponent(M,{label:"Awaiting review",get value(){return h().awaitingReviewers.map(D=>`@${D}`).join(", ")}})}}),null),l.insert(b,l.createComponent(N.Show,{get when(){return!h().reviewersComplete},get children(){return hn()}}),null),l.insert(b,l.createComponent(N.Show,{get when(){return l.memo(()=>!!(d.head&&h().headSha))()&&d.head!==h().headSha},get children(){var D=mn(),Q=D.firstChild,K=Q.nextSibling;return K.nextSibling,l.insert(D,()=>$().noun,K),D}}),null),b})()}function lt(d){const h=N.createMemo(()=>w(d.session),void 0,{equals:(b,_)=>b.directory===_.directory&&b.key===_.key}),$=N.createMemo(()=>C(h())),E=()=>{const b=$().lookup;return b?.kind==="found"?b:void 0};return(()=>{var b=wn(),_=b.firstChild;return _.firstChild,l.insert(_,l.createComponent(U.Button,{size:"small",icon:"refresh",get busy(){return $().loading},onClick:()=>{g()?.refresh(h())},children:"Refresh"}),null),l.insert(b,l.createComponent(N.Show,{get when(){return I(h().directory)},get fallback(){return bn()},get children(){return l.createComponent(N.Show,{get when(){return E()},get fallback(){return(()=>{var A=he();return l.insert(A,()=>sn($())),l.effect(()=>l.className(A,`fk-pre ${$().error?"fk-error":"fk-muted"}`)),A})()},children:A=>[l.createComponent(N.Show,{get when(){return A().repository},children:S=>(()=>{var k=yn();return l.insert(k,l.createComponent(M,{label:"Repository",get value(){return S().source.path}}),null),l.insert(k,l.createComponent(M,{label:"Branch",get value(){return l.memo(()=>S().branch===S().sourceBranch)()?S().branch:`${S().branch} (pushes to ${S().sourceBranch})`}}),null),k})()}),l.createComponent(N.Show,{get when(){return l.memo(()=>!A().repository)()&&A().sessionTarget},get children(){return l.createComponent(M,{label:"Session target",get value(){return A().sessionTarget}})}}),l.createComponent(N.For,{get each(){return A().failed??[]},children:S=>(()=>{var k=Sn();return k.firstChild,l.insert(k,()=>`
|
|
139
|
+
${S.url}
|
|
140
|
+
${S.reason}`,null),k})()}),l.createComponent(N.Show,{get when(){return A().requests.length===0},get children(){return vn()}}),l.createComponent(N.For,{get each(){return A().requests},children:S=>l.createComponent(ct,{request:S,get head(){return A().repository?.head}})}),l.createComponent(N.Show,{get when(){return $().error},children:S=>(()=>{var k=Rn(),L=k.firstChild;return L.firstChild,l.insert(L,()=>new Date(S().at).toLocaleTimeString(),null),l.insert(k,()=>`
|
|
141
|
+
${S().message}`,null),k})()}),l.createComponent(N.Show,{get when(){return $().fetchedAt!==void 0},get children(){var S=$n();return S.firstChild,l.insert(S,()=>new Date($().fetchedAt).toLocaleTimeString(),null),S}})]})}}),null),b})()}async function ue(d,h,$){try{await t()[h]($,r(d)),await f(d)}catch(E){e.toast.show({title:E instanceof Error?E.message:String(E),variant:"error"})}}function ut(d){const h=()=>d.item,$=()=>[h().read?"Read":"Unread",zr(h()),h().automation?`${h().automation.state}${h().automation.reason?`: ${h().automation.reason}`:""}`:void 0].filter(Boolean).join(" Β· "),E=(b,_={})=>ue(d.directory,b,{id:h().id,..._});return(()=>{var b=Cn(),_=b.firstChild,A=_.nextSibling,S=A.nextSibling,k=S.nextSibling;return l.insert(_,()=>h().title),l.insert(A,$),l.insert(b,l.createComponent(N.For,{get each(){return h().details??[]},children:L=>(()=>{var D=he();return l.insert(D,L),D})()}),S),l.insert(S,l.createComponent(N.For,{get each(){return Qr(h())},children:L=>(()=>{var D=kn();return D.$$click=()=>e.system.openExternal(L.value),l.insert(D,()=>L.title),D})()})),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:()=>{E("summarizeFeedback")},children:"Summarize in session"}),null),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:()=>{E("actOnFeedback")},children:"Act on feedback"}),null),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:async()=>{await e.dialogs.confirm({title:"Retry feedback work?",description:"Retry may repeat earlier changes. Inspect the session first.",confirm:"Retry",danger:!0})&&await E("actOnFeedback",{retry:!0})},children:"Retry"}),null),l.insert(k,l.createComponent(U.Button,{size:"small",onClick:()=>{E("acknowledgeFeedback")},children:"Acknowledge"}),null),b})()}function dt(d){const h=()=>v(d.session),$=()=>q(h()),E=N.createMemo(()=>it($(),d.session.id));return(()=>{var b=En(),_=b.firstChild,A=_.firstChild;return A.firstChild,l.insert(A,()=>$().paused?" (monitoring paused)":"",null),l.insert(_,l.createComponent(U.Button,{size:"small",get disabled(){return!E().some(S=>!S.read)},onClick:()=>{ue(h(),"markFeedbackRead",{ids:E().map(S=>S.id)})},children:"Mark all as read"}),null),l.insert(_,l.createComponent(U.Button,{size:"small",onClick:()=>{ue(h(),"pauseFeedback",{paused:!$().paused})},get children(){return $().paused?"Enable feedback inbox":"Pause monitoring"}}),null),l.insert(b,l.createComponent(N.Show,{get when(){return i[h()]},children:S=>(()=>{var k=In(),L=k.firstChild,D=L.nextSibling;return D.nextSibling,l.insert(k,S,D),k})()}),null),l.insert(b,l.createComponent(N.Show,{get when(){return E().length},get fallback(){return l.createComponent(N.Show,{get when(){return!i[h()]},get children(){var S=Pn();return l.insert(S,()=>o[h()]?"No pending review updates for this session.":"Loading review updatesβ¦"),S}})},get children(){return l.createComponent(N.For,{get each(){return E()},children:S=>l.createComponent(ut,{item:S,get directory(){return h()}})})}}),null),b})()}const Pe=(d,h)=>({id:d,title:h,closable:"hover"}),pt=Pe(X,"PR/MR status"),ft=Pe(Z,"Review updates");e.add(F.Panel,{id:X,region:"side",width:420,list:d=>d.open.includes(X)?[pt]:[],render:d=>l.createComponent(lt,{get session(){return d.session}})}),e.add(F.Panel,{id:Z,region:"side",width:420,list:d=>d.open.includes(Z)?[ft]:[],render:d=>l.createComponent(dt,{get session(){return d.session}})}),e.add(F.Command,()=>({id:"status",title:"Show PR/MR status",group:"Forge",slash:{name:"forge-status"},enabled:!!R(),run:()=>{const d=R();!d||x(v(d))||(g()?.refresh(w(d)),P(X,d))}})),e.add(F.Command,()=>({id:"feedback",title:"Show pending review feedback",group:"Forge",slash:{name:"forge-feedback"},enabled:!!R(),run:()=>{const d=R();d&&(f(v(d)),P(Z,d))}})),e.add(F.Command,()=>({id:"open",title:"Open PR/MR in browser",group:"Forge",slash:{name:"forge-open"},enabled:!!R(),run:async()=>{const d=R();if(!d||x(v(d)))return;const h=w(d);let $=p(h);if($.length===0&&(await g()?.refresh(h),$=p(h)),$.length===0){e.toast.show({title:"No PR/MR for this session or branch"});return}const E=$.length===1?$[0].url:await e.dialogs.select({title:"Open PR/MR",options:$.map(b=>({title:`${ce(b)} ${b.title}`,description:b.targetProject,value:b.url}))});E&&e.system.openExternal(E)}}));const _e=()=>e.servers.list().map(d=>e.servers.get(d)).find(d=>d?.builtin);return F.createKeyed(()=>e.client,()=>{const d=t();u.invalidate(),m.connect(d),u.refresh();const h=[d.events.on("feedbackChanged",$=>{const{directory:E}=$.data;u.has(E)&&f(E)}),d.events.on("notice",$=>{const E=$.data;un(E,{hasShown:b=>!!g()?.hasShown(b)||!!$.location?.directory&&u.has($.location.directory),openTab:b=>{const _=_e()?.id;_&&e.tabs.open({server:_,id:b})},toast:({title:b,message:_,variant:A})=>{const S=_e()?.id,k=E.sessionID;e.toast.show({title:b??_,...b?{description:_}:{},variant:A==="error"?"error":"default",...S&&k?{actions:[{label:"Open session",run:()=>e.tabs.open({server:S,id:k},{focus:!0})}]}:{}}),e.attention.notify({title:b??"Forgekeeper",message:_,variant:A==="error"?"error":"default",...S&&k?{session:{server:S,id:k}}:{},id:`forgekeeper:${k??""}:${b??""}:${_}`})}})})];N.onCleanup(()=>{for(const $ of h)$();u.invalidate(),m.dispose()})}),()=>{u.invalidate(),m.dispose()}}});l.delegateEvents(["click"]);exports.default=An;
|