opencode-forgekeeper 6.3.1 → 6.4.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/dist/gui-experimental.cjs +72 -72
- package/dist/index.js +1016 -107
- package/dist/tui.js +258 -65
- package/package.json +1 -1
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("solid-js/web"),
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const d=require("solid-js/web"),le=require("@opencode/plugin/gui"),A=require("solid-js"),Tt=require("solid-js/store");require("node:child_process");const Mr=require("node:crypto");function Re(e){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;try{const t=String(e);if(t!=="[object Object]")return t}catch{}try{const t=JSON.stringify(e);if(typeof t=="string")return t}catch{}return"Unknown error"}try{return String(e)}catch{return"Unknown error"}}const qr=new Set(["SUCCESS","FAILED","CANCELED","CANCELLED","SKIPPED","MANUAL"]),Lr=e=>!!e&&(e.running??!qr.has(e.status)),jr=e=>e?.failedJobsComplete===!1&&!e.failedJobs?.length&&e.status==="FAILED",er=e=>!!e?.failedJobs?.length||jr(e);class J extends Error{constructor(t,r){super(r),this.kind=t}kind}function Or(e){return e.approvers?e.approvers:e.forge==="gitlab"&&e.duoReviewState==="APPROVED"?[{username:"GitLabDuo",bot:!0,automated:!0}]:[]}const tr=e=>e.approvalsComplete!==!1&&e.reviewersComplete!==!1;function Ur(e){return e.state==="opened"&&!e.draft?e.changesRequested:!1}const Ce=e=>e?"yes":"no",Fe=e=>e.toLowerCase().replace(/_/g," ");function rr(e){return e.length>2?`awaiting ${e.length} reviewers`:`awaiting ${e.map(t=>`@${t}`).join(", ")}`}const nr=e=>/(^|\.)gitlab\./.test(e);function Je(e,t,r){let n;try{n=new URL(t)}catch{return}if(!["https:","http:"].includes(n.protocol))return;const o=n.pathname.match(r);if(!o)return;let a;try{a=decodeURIComponent(o[1])}catch{return}return{forge:e,host:n.host.toLowerCase(),project:a,iid:o[2]}}const or=e=>Je("gitlab",e,/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/);function sr(e){const t=Je("github",e,/^\/([^/]+\/[^/]+)\/pull\/([1-9]\d*)\/?$/);return t&&!nr(t.host)?t:void 0}function Br(e){return e.forge==="gitlab"?e.duoReviewState==="REVIEW_STARTED":e.copilotReview?.requested===!0}function ir(e){if(e.state!=="opened"||e.draft||e.autoMergeEnabled===!0||e.mergeTrainIndex!=null)return!1;if(!(!e.conflictsKnown||!tr(e)||e.autoMergeEnabled!==!1)){if(!$t(e)||e.conflicts||e.changesRequested||e.duoReviewState==="REVIEW_STARTED"||ar(e)||er(e.pipeline)||e.pipeline?.status==="FAILED")return!1;if(!(!e.threadsComplete||e.unresolvedThreads>0&&e.discussionResolutionRequired!==!1)&&e.mergeStatus)return e.mergeStatus==="MERGEABLE"||e.mergeStatus==="CI_STILL_RUNNING"&&Lr(e.pipeline)}}function wt(e){const t=ir(e);if(t===!1)return"none";if(t!==void 0){if(e.autoMergeAvailable===!0)return"auto-merge";if(e.mergeStatus==="MERGEABLE"){if(e.canMerge===!0)return"merge";if(e.canMerge===!1)return"maintainer-merge"}if(e.autoMergeAvailable===!1)return"none"}}function Fr(e){const t=wt(e);if(t!==void 0)return t!=="none"}function Gr(e){return e.forge==="gitlab"?wt(e):void 0}function bt(e){switch(e){case"NEED_REBASE":return"rebase";case"JIRA_ASSOCIATION_MISSING":return"jira";case"EXTERNAL_STATUS_CHECKS":return"status-checks";case"BLOCKED_STATUS":return"blocked";default:return}}function Ge(e){return e.mergeStatus==="DISCUSSIONS_NOT_RESOLVED"||e.discussionResolutionRequired===!0&&e.unresolvedThreads>0}function Hr(e){return Ge(e)?"Auto-merge: set (blocked by unresolved threads)":bt(e.mergeStatus)&&e.mergeStatus?`Auto-merge: set (blocked: ${Fe(e.mergeStatus)})`:"Auto-merge: set"}function Wr(e){switch(e){case"rebase":return{text:"needs rebase",tone:"warning",optional:!0};case"jira":return{text:"missing Jira issue",tone:"warning",optional:!0};case"status-checks":return{text:"status checks pending",tone:"warning",optional:!0};case"blocked":return{text:"merge blocked",tone:"warning",optional:!0};default:return}}function He(e){return(e.missingRules?.length??0)>0||(e.approvalsLeft??0)>0||e.mergeStatus==="NOT_APPROVED"}function $t(e){return He(e)?!1:e.approvalRequirementsSatisfied??(e.approved&&e.awaitingReviewers.length===0)}function zr(e){return e.forge==="gitlab"?$t(e):e.approved&&e.awaitingReviewers.length===0}function ar(e){return Ge(e)?"threads":bt(e.mergeStatus)}function Mt(e){return!e.conflicts&&e.pipeline?.status!=="FAILED"}function Vr(e){return!!e.autoMergeEnabled&&!He(e)&&(e.approvalRequirementsSatisfied===!0||e.mergeStatus==="MERGEABLE")}function Qr(e){const t=e.approvalsLeft??0;if(t<=0||e.approvalRequirementsSatisfied===!0)return;const r=Or(e).filter(n=>!n.bot).length;return{text:r?`${r} approval${r===1?"":"s"} · ${t} more needed`:`${t} approval${t===1?"":"s"} needed`,compact:r?`${r} ✓ +${t}`:`+${t}`,tone:"muted",optional:!0}}function Kr(e){const t=e.awaitingReviewers.length?{text:rr(e.awaitingReviewers),tone:"muted"}:void 0;if(t&&!$t(e)||e.draft||e.changesRequested===!0)return t;const r=bt(e.mergeStatus);if(Mt(e)){if(e.mergeTrainIndex!=null)return{text:`merge train #${e.mergeTrainIndex+1}`,tone:"muted",optional:!0};if(Vr(e))return Ge(e)||r?{text:"auto-merge blocked",compact:"auto-merge ⛔",tone:"warning",optional:!0}:t??{text:"auto-merge set",tone:"success",optional:!0}}if(e.approved||e.approvalRequirementsSatisfied===!0)return Mt(e)&&!He(e)?Ge(e)?{text:"merge blocked",tone:"warning",optional:!0}:Wr(r)??t:t;const o=(e.missingRules??[]).find(a=>a.type==="CODE_OWNER"||a.type==="REGULAR");if(o)return{text:o.type==="CODE_OWNER"?"needs a code owner":"needs an approver",tone:"warning",optional:!0};if(e.reviewersComplete&&He(e))return{text:"needs a reviewer",tone:"muted",optional:!0}}function Jr(e){const t=Qr(e),r=Kr(e);return[...t?[t]:[],...e.changesRequested===!0?[{text:"changes requested",tone:"warning",essential:!0}]:[],...e.approved&&!e.awaitingReviewers.length?[{text:"approved",tone:"success"}]:[],...r?[r]:[]]}function Yr(e){return e.discussionResolutionRequired===!1?"none":e.unresolvedThreads>0?e.discussionResolutionRequired===!0?"threads":void 0:e.threadsComplete?"none":void 0}function Xr(e){return e.state!=="opened"||e.draft?"none":!tr(e)||!e.conflictsKnown||Br(e)?void 0:!zr(e)||e.conflicts||Ur(e)===!0||er(e.pipeline)||e.pipeline?.status==="FAILED"?"none":(e.forge==="gitlab"?ar(e):void 0)??Yr(e)}function lr(e){const t=Xr(e);return t==="none"?void 0:t}function yt(e,t={}){if(lr(e)==="threads"){const r=e.forge==="gitlab"&&e.autoMergeEnabled===!1&&e.mergeTrainIndex==null,n=r?"Resolve the blocking threads, then select Set to auto-merge in GitLab when available.":"Resolve the blocking threads.",o=t.canReviewThreads?" In /forge-feedback, select the merge-blocked item and choose Review blocking threads.":"";return{text:r?"resolve threads → Set to auto-merge":"resolve threads",compact:r?"threads → auto-merge":"resolve threads",tone:"warning",essential:!0,detail:`${n}${o}`}}switch(Gr(e)){case"auto-merge":return{text:"Set to auto-merge",tone:"warning",essential:!0,url:e.url,detail:"Open the merge request in GitLab and select Set to auto-merge."};case"merge":return{text:"ready to merge",tone:"warning",essential:!0,url:e.url,detail:"Open the merge request in GitLab and select Merge."};case"maintainer-merge":return{text:"ready for maintainer merge",compact:"needs maintainer merge",tone:"warning",essential:!0,url:e.url,detail:"All merge requirements are met, but your account does not have permission to merge. Ask a maintainer to merge it."};default:return}}function ur(e){return e.map(t=>{const r=Date.parse(t.updatedAt??"");return{request:t,updatedAt:Number.isNaN(r)?Number.MIN_SAFE_INTEGER:r}}).sort((t,r)=>r.updatedAt-t.updatedAt).map(({request:t})=>t)}const T=e=>e,ie=e=>async(t,r,n)=>await e(t,r,n),qe=50,We=30;async function ze(e,t){const r=[],n=new Set;let o;for(let a=0;a<e;a++){const s=await t(o);if(!s)break;r.push(...s.nodes);const l=s.pageInfo;if(!l)break;if(!l.hasNextPage)return{nodes:r,complete:!0};const i=l.endCursor;if(!i||n.has(i))break;n.add(i),o=i}return{nodes:r,complete:!1}}const cr="pageInfo { hasNextPage endCursor } nodes { resolvable resolved }",we=100,Zr=10,en="pageInfo { hasNextPage } nodes { id name allowFailure webPath stage { name } }",tn=new Set(["CHECKING","UNCHECKED","PREPARING"]),qt="CANNOT_BE_MERGED_RECHECK",dr=e=>`pageInfo { hasNextPage endCursor } nodes { id type username bot mergeRequestInteraction { reviewState approved${e?" approvedAt":""} } }`,pr="pageInfo { hasNextPage endCursor } nodes { id username bot }",fr=(e,t)=>`
|
|
2
2
|
iid title webUrl state draft conflicts approved mergeStatusEnum detailedMergeStatus diffHeadSha updatedAt targetBranch sourceBranch
|
|
3
3
|
autoMergeEnabled
|
|
4
4
|
${t?`
|
|
5
5
|
approvalsRequired approvalsLeft mergeTrainCar { index }
|
|
6
6
|
approvalState { rules { name type approvalsRequired approved eligibleApprovers { username type bot } } }
|
|
7
7
|
`:""}
|
|
8
|
-
approvedBy(first: ${we}) { ${
|
|
8
|
+
approvedBy(first: ${we}) { ${pr} }
|
|
9
9
|
sourceProject { fullPath }
|
|
10
10
|
targetProject { fullPath }
|
|
11
11
|
author { id username }
|
|
12
12
|
headPipeline {
|
|
13
13
|
id status path detailedStatus { label }
|
|
14
|
-
jobs(statuses: [FAILED], retried: false, first: ${
|
|
14
|
+
jobs(statuses: [FAILED], retried: false, first: ${Zr}) { ${en} }
|
|
15
15
|
}
|
|
16
|
-
reviewers(first: ${we}) { ${
|
|
17
|
-
discussions(first: ${we}) { ${
|
|
18
|
-
`;function
|
|
16
|
+
reviewers(first: ${we}) { ${dr(e)} }
|
|
17
|
+
discussions(first: ${we}) { ${cr} }
|
|
18
|
+
`;function rn(e,t=!0,r=!0){const n=fr(t,r),o=Array.from({length:e},(s,l)=>`$p${l}: ID!`).join(", "),a=Array.from({length:e},(s,l)=>`p${l}: project(fullPath: $p${l}) {
|
|
19
19
|
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { ${n} } }
|
|
20
20
|
}`).join(`
|
|
21
|
-
`);return
|
|
21
|
+
`);return T(`query($branch: String!, ${o}) {
|
|
22
22
|
${a}
|
|
23
|
-
}`)}function
|
|
24
|
-
`);return
|
|
23
|
+
}`)}function nn(e,t=!0,r=!0){const n=fr(t,r),o=Array.from({length:e},(s,l)=>`$p${l}: ID!`).join(", "),a=Array.from({length:e},(s,l)=>`p${l}: project(fullPath: $p${l}) { mergeRequest(iid: $iid) { ${n} } }`).join(`
|
|
24
|
+
`);return T(`query($iid: String!, ${o}) {
|
|
25
25
|
${a}
|
|
26
|
-
}`)}const
|
|
26
|
+
}`)}const on=T(`query($project: ID!, $iid: String!, $after: String) {
|
|
27
27
|
project(fullPath: $project) {
|
|
28
|
-
mergeRequest(iid: $iid) { discussions(first: ${we}, after: $after) { ${
|
|
28
|
+
mergeRequest(iid: $iid) { discussions(first: ${we}, after: $after) { ${cr} } }
|
|
29
29
|
}
|
|
30
|
-
}`),
|
|
30
|
+
}`),sn=e=>T(`query($project: ID!, $iid: String!, $after: String) {
|
|
31
31
|
project(fullPath: $project) {
|
|
32
|
-
mergeRequest(iid: $iid) { reviewers(first: ${we}, after: $after) { ${
|
|
32
|
+
mergeRequest(iid: $iid) { reviewers(first: ${we}, after: $after) { ${dr(e)} } }
|
|
33
33
|
}
|
|
34
|
-
}`),
|
|
34
|
+
}`),an=T(`query($project: ID!, $iid: String!, $after: String) {
|
|
35
35
|
project(fullPath: $project) {
|
|
36
|
-
mergeRequest(iid: $iid) { approvedBy(first: ${we}, after: $after) { ${
|
|
36
|
+
mergeRequest(iid: $iid) { approvedBy(first: ${we}, after: $after) { ${pr} } }
|
|
37
37
|
}
|
|
38
|
-
}`),
|
|
38
|
+
}`),ln=T(`query($project: ID!, $iid: String!, $after: String) {
|
|
39
39
|
project(fullPath: $project) {
|
|
40
40
|
mergeRequest(iid: $iid) {
|
|
41
41
|
state
|
|
@@ -48,7 +48,7 @@ ${a}
|
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
|
-
}`),
|
|
51
|
+
}`),un=T(`
|
|
52
52
|
query($note: NoteID!, $after: String) {
|
|
53
53
|
note(id: $note) {
|
|
54
54
|
discussion {
|
|
@@ -61,13 +61,13 @@ ${a}
|
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
`),
|
|
65
|
-
`)[0])}const
|
|
64
|
+
`),cn=T("query { currentUser { id username } }"),dn=e=>/(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState).*?(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*?(?:approvalsRequired|approvalsLeft|mergeTrainCar|approvalState)|Field ['"]index['"] doesn't exist on type ['"]MergeTrainCar['"]/i.test(e instanceof Error?e.message:String(e)),pn=e=>/approvedAt.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*approvedAt/i.test(e instanceof Error?e.message:String(e));function _e(e,t){const r=e.trim().replace(/^glab:\s*/,"")||`glab exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new J("missing-glab","glab is not installed"):/\b401\b|unauthori[sz]ed|not logged in|authenticate|invalid token|token.*expired/i.test(r)?new J("auth","GitLab authentication failed. Run `glab auth status`."):/\b429\b|rate limit|too many requests/i.test(r)?new J("rate-limit","GitLab rate limit reached"):new J("request",r.split(`
|
|
65
|
+
`)[0])}const Lt=e=>e.nodes.filter(t=>t.resolvable&&!t.resolved).length;function fn(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 gn(e,t){return!t.id||!t.jobs?{}:{id:t.id,failedJobs:fn(e,t.jobs.nodes),failedJobsComplete:!t.jobs.pageInfo?.hasNextPage}}const ut=(e,t,r)=>e?.type==="DUO_CODE_REVIEW_BOT"||r===!0&&t?.toLowerCase()==="gitlabduo";function ct(e,t){const r=t.username.toLowerCase(),n=e.findIndex(a=>t.id&&a.id?a.id===t.id:a.username.toLowerCase()===r&&(!t.id||!a.id));if(n<0){e.push(t);return}const o=e[n];e[n]={...o,...t,...o.id||t.id?{id:t.id??o.id}:{},...o.bot||t.bot?{bot:!0}:{},...o.automated||t.automated?{automated:!0}:{},...o.reviewID||t.reviewID?{reviewID:t.reviewID??o.reviewID}:{}}}function hn(e,t){const r=new Map,n=new Map;for(const s of e)s.id&&r.set(s.id,s),s.username&&n.set(s.username.toLowerCase(),s);const o=s=>{const l=s?.mergeRequestInteraction?.reviewState;return!!l&&l!=="APPROVED"},a=[];for(const s of e){const l=s.mergeRequestInteraction;if(!(l?.reviewState==="APPROVED"||!l?.reviewState&&l?.approved===!0))continue;const u=ut(s,s.username,s.bot),h=s.username??(u?"GitLabDuo":void 0);if(!h)continue;const y=s.bot===!0||u;ct(a,{...s.id?{id:s.id}:{},username:h,...y?{bot:!0}:{},...u?{automated:!0}:{},...l?.approvedAt?{reviewID:l.approvedAt}:{}})}for(const s of t){const l=(s.id?r.get(s.id):void 0)??(s.username?n.get(s.username.toLowerCase()):void 0);if(o(l))continue;const i=ut(l,s.username??l?.username,s.bot??l?.bot),u=s.username??l?.username??(i?"GitLabDuo":void 0);if(!u)continue;const h=s.bot===!0||l?.bot===!0||i;ct(a,{...s.id||l?.id?{id:s.id??l?.id??void 0}:{},username:u,...h?{bot:!0}:{},...i?{automated:!0}:{}})}return a}function mn(e,t){let r=!1,n=!0,o=!0;const a=[];for(const i of e){const u=i.mergeRequestInteraction?.reviewState;if(!u){n=!1;continue}if(u!=="REQUESTED_CHANGES")continue;r=!0;const h=ut(i,i.username,i.bot),y=i.username??(h?"GitLabDuo":void 0);if(!y){o=!1;continue}const w=i.bot===!0||h;ct(a,{...i.id?{id:i.id}:{},username:y,...w?{bot:!0}:{},...h?{automated:!0}:{}})}const s=t&&n&&o;let l;return r?l=!0:t&&n&&(l=!1),{...l===void 0?{}:{changesRequested:l},...a.length>0||s?{changeRequesters:a}:{},changeRequestersComplete:s}}function vn(e,t={}){const r=ie(e),n=t.unsupportedApprovedAt??new Set,o=t.unsupportedExtendedStatus??new Set;async function a(f,c,b){if(n.has(f))return r(f,c(!1),b);try{return await r(f,c(!0),b)}catch(p){if(!pn(p))throw p;return n.add(f),r(f,c(!1),b)}}async function s(f,c,b){const p=S=>a(f,v=>c(v,S),b);if(o.has(f))return p(!1);try{return await p(!0)}catch(S){if(!dn(S))throw S;return o.add(f),p(!1)}}async function l(f,c){return c.detailedMergeStatus==="DISCUSSIONS_NOT_RESOLVED"?!0:(await r(f,T("query($project: ID!) { project(fullPath: $project) { onlyAllowMergeIfAllDiscussionsAreResolved } }"),{project:c.targetProject.fullPath}).catch(()=>{}))?.project?.onlyAllowMergeIfAllDiscussionsAreResolved??void 0}async function i(f,c){let b=Lt(c.discussions),p=c.discussions.pageInfo,S=1;for(;p.hasNextPage&&p.endCursor&&S<qe;){const C=(await r(f,on,{project:c.targetProject.fullPath,iid:c.iid,after:p.endCursor})).project?.mergeRequest?.discussions;if(!C)break;b+=Lt(C),p=C.pageInfo,S++}return{count:b,complete:!p.hasNextPage}}async function u(f,c){if(!c.reviewers?.pageInfo)return{nodes:[...c.reviewers?.nodes??[]],complete:!1};const b=[...c.reviewers.nodes];let p=c.reviewers.pageInfo,S=1;for(;p.hasNextPage&&p.endCursor&&S<qe;){const C=(await a(f,D=>sn(D),{project:c.targetProject.fullPath,iid:c.iid,after:p.endCursor})).project?.mergeRequest?.reviewers;if(!C?.pageInfo)return{nodes:b,complete:!1};b.push(...C.nodes),p=C.pageInfo,S++}return{nodes:b,complete:!p.hasNextPage}}async function h(f,c){if(!c.approvedBy?.pageInfo)return{nodes:[...c.approvedBy?.nodes??[]],complete:!1};const b=[...c.approvedBy.nodes];let p=c.approvedBy.pageInfo,S=1;for(;p.hasNextPage&&p.endCursor&&S<qe;){const C=(await r(f,an,{project:c.targetProject.fullPath,iid:c.iid,after:p.endCursor})).project?.mergeRequest?.approvedBy;if(!C?.pageInfo)return{nodes:b,complete:!1};b.push(...C.nodes),p=C.pageInfo,S++}return{nodes:b,complete:!p.hasNextPage}}async function y(f,c){const[b,p,S]=await Promise.all([i(f,c),u(f,c),h(f,c)]),v=c.headPipeline,C=b.count>0?await l(f,c):void 0,D=S.nodes.some(B=>B.bot!==!0),_=p.nodes.filter(B=>B.bot!==!0&&B.username&&B.mergeRequestInteraction?.approved!==!0),H=_.filter(B=>B.mergeRequestInteraction?.reviewState!=="REQUESTED_CHANGES"),O=H.map(B=>B.username),Q=H.map(B=>({...B.id?{id:B.id}:{},username:B.username})),ae=hn(p.nodes,S.nodes),Ze=new Set([...S.nodes,...ae].flatMap(({username:B})=>B?[B.toLowerCase()]:[])),te=(c.approvalState?.rules??[]).flatMap(B=>{if(B.approvalsRequired==null||B.approvalsRequired<=0||B.approved!==!1)return[];const re=(B.eligibleApprovers??[]).filter(({username:X,bot:ke})=>!ke&&!Ze.has(X.toLowerCase())),ye=new Set(re.map(({username:X})=>X.toLowerCase())),Ie=re.filter(({type:X})=>X==="HUMAN"),Te=new Set(Ie.map(({username:X})=>X.toLowerCase())),et=_.map(X=>X.username).filter(X=>ye.has(X.toLowerCase())).sort((X,ke)=>Number(Te.has(ke.toLowerCase()))-Number(Te.has(X.toLowerCase()))),fe=Ie.length?Ie:re;return[{name:B.name??"Unnamed approval rule",type:B.type??void 0,required:B.approvalsRequired,eligibleReviewers:et,eligible:fe.slice(0,2).map(({username:X})=>X),eligibleCount:fe.length}]}),K={forge:"gitlab",iid:c.iid,title:c.title,url:c.webUrl,state:c.state.toLowerCase(),draft:c.draft,conflicts:c.conflicts||c.mergeStatusEnum===qt,conflictsKnown:c.mergeStatusEnum!==qt&&!tn.has(c.detailedMergeStatus??""),approved:c.approved===!0&&D&&_.length===0,hasApprovals:D,approvalRequirementsSatisfied:c.approved,discussionResolutionRequired:C,approvalsRequired:c.approvalsRequired??void 0,approvalsLeft:c.approvalsLeft??void 0,missingRules:te,autoMergeEnabled:c.autoMergeEnabled,mergeTrainIndex:c.mergeTrainCar?.index,awaitingReviewers:O,pendingHumanReviewers:Q,reviewersComplete:p.complete,...mn(p.nodes,p.complete),approvalsComplete:p.complete&&S.complete,reviewerIDs:p.nodes.flatMap(B=>B.id??[]),approvers:ae,mergeStatus:c.detailedMergeStatus??void 0,targetProject:c.targetProject.fullPath,targetBranch:c.targetBranch,...c.sourceProject?{sourceProject:c.sourceProject.fullPath}:{},sourceBranch:c.sourceBranch,headSha:c.diffHeadSha??void 0,...c.author?.id?{authorID:c.author.id}:{},...c.author?.username?{authorUsername:c.author.username}:{},updatedAt:c.updatedAt??void 0,pipeline:v?{status:v.status,label:v.detailedStatus?.label??v.status.toLowerCase().replace(/_/g," "),url:v.path?`https://${f}${v.path}`:void 0,...gn(f,v)}:void 0,unresolvedThreads:b.count,threadsComplete:b.complete,duoReviewState:p.nodes.find(B=>B.type==="DUO_CODE_REVIEW_BOT")?.mergeRequestInteraction?.reviewState??void 0};if(ir(K)===!0&&K.headSha){const re=(await r(f,T(`query($project: ID!, $iid: String!) {
|
|
66
66
|
project(fullPath: $project) { mergeRequest(iid: $iid) {
|
|
67
67
|
diffHeadSha autoMergeEnabled detailedMergeStatus userPermissions { canMerge }
|
|
68
68
|
availableAutoMergeStrategies
|
|
69
69
|
} }
|
|
70
|
-
}`),{project:
|
|
70
|
+
}`),{project:K.targetProject,iid:K.iid}).catch(()=>{}))?.project?.mergeRequest;re?.diffHeadSha===K.headSha&&re.autoMergeEnabled===!1&&re.detailedMergeStatus===K.mergeStatus&&(typeof re.userPermissions?.canMerge=="boolean"&&(K.canMerge=re.userPermissions.canMerge),re.userPermissions?.canMerge===!1?K.autoMergeAvailable=!1:re.userPermissions?.canMerge===!0&&Array.isArray(re.availableAutoMergeStrategies)&&(K.autoMergeAvailable=re.availableAutoMergeStrategies.length>0))}return K}async function w(f,{id:c,anchor:b}){if(!b)return;let p=!1,S=!1;const v=await ze(10,async _=>{const O=(await r(f.host,un,{note:b,..._?{after:_}:{}})).note?.discussion,Q=O?.noteable?.webUrl&&or(O.noteable.webUrl);if(S=!!(O?.id===c&&Q&&Q.host===f.host&&Q.project===f.project&&Q.iid===f.iid),!(!S||!O))return p=O.resolved,p||!O.resolvable?void 0:O.notes});if(!S)return;if(p)return"resolved";const C=[];let D=!v.complete;for(const _ of v.nodes)if(!_.system){if(!_.id||!_.author?.username||typeof _.body!="string"){D=!0;continue}C.push({id:_.id.slice(_.id.lastIndexOf("/")+1),url:_.url??void 0,authorID:_.author.id,username:_.author.username,bot:_.author.bot===!0,body:_.body,createdAt:_.createdAt??void 0,path:_.position?.newPath??_.position?.oldPath??void 0,line:_.position?.newLine??_.position?.oldLine??void 0})}return{id:c,anchor:b,notes:C,url:C.find(_=>_.url)?.url,incomplete:D||C.length===0}}async function R(f){const c=await ze(qe,async S=>(await r(f.host,ln,{project:f.project,iid:f.iid,...S?{after:S}:{}})).project?.mergeRequest?.discussions),b=[],p=c.nodes.filter(({id:S,resolvable:v,resolved:C})=>S&&v&&!C);for(const S of p.slice(0,We)){const v=S.notes?.nodes[0]?.id?.match(/^gid:\/\/gitlab\/\w+\/(\d+)$/)?.[1],C=v?`gid://gitlab/Note/${v}`:void 0,D=await w(f,{id:S.id,anchor:C}).catch(()=>{});D!=="resolved"&&b.push(D??{id:S.id,notes:[],incomplete:!0})}return{complete:c.complete&&p.length<=We,discussions:b}}async function k(f,c){if(f.length===0)return;const b=f[0].host,p={iid:c};f.forEach((v,C)=>p[`p${C}`]=v.path);const S=await s(b,(v,C)=>nn(f.length,v,C),p);for(let v=0;v<f.length;v++){const C=S[`p${v}`]?.mergeRequest;if(C)return y(b,C)}}async function I(f,c,b){if(c.length===0)return[];const p={branch:b};c.forEach((H,O)=>p[`p${O}`]=H.path);const S=await s(f.host,(H,O)=>rn(c.length,H,O),p),v=f.path.toLowerCase(),C=new Set,D=[];return c.forEach((H,O)=>{for(const Q of S[`p${O}`]?.mergeRequests?.nodes??[]){if(Q.sourceProject?.fullPath.toLowerCase()!==v)continue;const ae=`${Q.targetProject.fullPath}!${Q.iid}`;C.has(ae)||(C.add(ae),D.push(Q))}}),(await Promise.all(D.map(H=>y(f.host,H)))).sort((H,O)=>(O.updatedAt??"").localeCompare(H.updatedAt??""))}async function $(f){const b=(await r(f,cn,{})).currentUser;if(!(!b?.id&&!b?.username))return{...b.id?{id:b.id}:{},...b.username?{username:b.username}:{}}}return{forge:"gitlab",fetchRequest:f=>k([{host:f.host,path:f.project}],f.iid),fetchByProjects:k,fetchByBranch:I,unresolvedDiscussions:R,discussion:w,viewer:$}}const Ve="copilot-pull-request-reviewer[bot]",he=50,jt=e=>`number title url state isDraft mergeable reviewDecision headRefOid headRefName
|
|
71
71
|
${e?"autoMergeRequest { enabledAt }":""}
|
|
72
72
|
headRepository { nameWithOwner } baseRepository { nameWithOwner } baseRefName updatedAt
|
|
73
73
|
author { login ... on User { id } ... on Bot { id } }
|
|
@@ -75,12 +75,12 @@ ${a}
|
|
|
75
75
|
reviewRequests(first:100) { nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } } pageInfo { hasNextPage endCursor } }
|
|
76
76
|
latestReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } }
|
|
77
77
|
latestOpinionatedReviews(first:100) { nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } } pageInfo { hasNextPage endCursor } }
|
|
78
|
-
copilotReviews: reviews(last:1, author:"${
|
|
78
|
+
copilotReviews: reviews(last:1, author:"${Ve}", states:[COMMENTED,CHANGES_REQUESTED,APPROVED,DISMISSED]) { nodes { id state comments { totalCount } author { __typename login ... on Bot { id } ... on User { id } } } }
|
|
79
79
|
commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100) {
|
|
80
80
|
nodes { __typename ... on CheckRun { id name status conclusion detailsUrl startedAt checkSuite { createdAt app { id } workflowRun { workflow { id } } } } ... on StatusContext { id context state targetUrl } }
|
|
81
81
|
pageInfo { hasNextPage endCursor }
|
|
82
|
-
} } } } }`,
|
|
83
|
-
`)[0])}const
|
|
82
|
+
} } } } }`,wn=e=>/autoMergeRequest.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*autoMergeRequest/i.test(e instanceof Error?e.message:String(e)),bn=T("query { viewer { id login } }");function Ot(e,t){const r=e.trim()||`gh exited with code ${t}`;return/ENOENT|command not found/i.test(r)?new J("missing-gh","gh is not installed"):/401|unauthori[sz]ed|authenticate|not logged|token.*expired/i.test(r)?new J("auth","GitHub authentication failed. Run `gh auth status`."):/429|rate limit|too many requests/i.test(r)?new J("rate-limit","GitHub rate limit reached"):new J("request",r.split(`
|
|
83
|
+
`)[0])}const $n=["FAILURE","ERROR","TIMED_OUT","ACTION_REQUIRED","STARTUP_FAILURE"],yn=["SUCCESS","NEUTRAL","SKIPPED","FAILURE","TIMED_OUT","CANCELLED","ACTION_REQUIRED","STARTUP_FAILURE","STALE"],Sn=["SUCCESS","FAILURE","ERROR","PENDING","EXPECTED"],Ut=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]),dt=e=>Date.parse(e.checkSuite?.createdAt??""),Bt=(e,t)=>dt(e)>dt(t);function Rn(e,t,r,n){const o=new Map;for(const I of e){const $=dt(I),f=Ut(I);if(!f||!Number.isFinite($))continue;const c=o.get(f);(!c||Bt(I,c))&&o.set(f,I)}e=e.filter(I=>{const $=Ut(I),f=$&&o.get($);return!f||!Bt(f,I)});const a=I=>`${I} check${I===1?"":"s"}`,s=e.filter(I=>I.conclusion==="CANCELLED").length,l=e.filter(I=>I.conclusion==="STALE").length,i=[...s?[`${a(s)} cancelled`]:[],...l?[`${a(l)} stale`]:[]],u=e.filter(I=>$n.includes(I.conclusion??I.state??"")),h=u.length,y=n?{id:n,failedJobs:u.flatMap(I=>{const $=I.name??I.context,f=I.detailsUrl??I.targetUrl;return $?[{...I.id?{id:I.id}:{},name:$,...f?{url:f}:{}}]:[]}),failedJobsComplete:t}:{},w=e.filter(I=>I.status?I.status!=="COMPLETED":["PENDING","EXPECTED"].includes(I.state??"")).length,R=e.some(I=>I.status==="COMPLETED"?!yn.includes(I.conclusion??""):!I.status&&!Sn.includes(I.state??""));return h?{status:"FAILED",label:[`${a(h)} failed`,...i,...w?[`${a(w)} pending`]:[]].join(", ")+(t?"":" (partial)"),url:r,...y,running:w>0}:w||!t||R?{status:"PENDING",label:[...i,w?`${a(w)} pending`:"unknown"].join(", ")+(t?"":" (partial)"),url:r,...y}:s||l?{status:"CANCELLED",label:i.join(", "),url:r,...y}:{status:"SUCCESS",label:[["SUCCESS","passed"],["SKIPPED","skipped"],["NEUTRAL","neutral"]].flatMap(([I,$])=>{const f=e.filter(c=>(c.conclusion??c.state)===I).length;return f?[`${a(f)} ${$}`]:[]}).join(", ")||"0 checks",url:r,...y}}const St=e=>/^copilot-pull-request-reviewer(\[bot\])?$/i.test(e??""),pt=e=>e?.__typename==="Bot"&&St(e.login);function be(e,t){return t==="Bot"&&!e.endsWith("[bot]")?`${e}[bot]`:e}function Cn(e){const t=e.reviewRequests.nodes.some(n=>pt(n.requestedReviewer)),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}:{}}}function gr(e){const t=new Set,r=new Set,n=new Set,o=(a,s)=>`${a??"Unknown"}:${be(s,a).toLowerCase()}`;for(const a of e.nodes){const s=a.requestedReviewer;if(s?.id&&t.add(s.id),s?.login){const l=o(s.__typename,s.login);n.add(l),s.id||r.add(l)}}return(a,s,l)=>{const i=o(s,l);return a?t.has(a)||r.has(i):n.has(i)}}function In(e,t,r){const n=gr(t),o=new Map,a=i=>{const u=`${i.bot?"bot":"user"}:${i.username.toLowerCase()}`,h=o.get(u);if(!h){o.set(u,i);return}o.set(u,{...h,...i,...h.id||i.id?{id:i.id??h.id}:{},...h.bot||i.bot?{bot:!0}:{},...h.automated||i.automated?{automated:!0}:{},...h.reviewID||i.reviewID?{reviewID:i.reviewID??h.reviewID}:{}})};for(const i of r){if(i?.state!=="APPROVED"||!i.author?.login)continue;const{id:u,login:h,__typename:y}=i.author;if(n(u,y,h))continue;const w=y==="Bot",R=w&&St(h),k=R?Ve:be(h,y);a({...u?{id:u}:{},username:k,...w?{bot:!0}:{},...R?{automated:!0}:{},...i.id?{reviewID:i.id}:{}})}const s=e.copilotReviews?.nodes?.find(i=>i),l=t.nodes.some(i=>pt(i.requestedReviewer));return s?.state==="APPROVED"&&pt(s.author)&&!l&&a({...s.author?.id?{id:s.author.id}:{},username:Ve,bot:!0,automated:!0,...s.id?{reviewID:s.id}:{}}),[...o.values()]}function kn(e,t){if(!e.pageInfo||e.pageInfo.hasNextPage)return{changeRequestersComplete:!1};const r=gr(e),n=[],o=new Map;let a=t.complete;for(const s of t.nodes){if(s?.state!=="CHANGES_REQUESTED")continue;const l=s.author;if(!l?.login||!s.id){a=!1;continue}if(r(l.id,l.__typename,l.login))continue;n.push(s.id);const i=l.__typename==="Bot",u=i&&St(l.login),h=u?Ve:be(l.login,l.__typename),y=l.id?`id:${l.id}`:`${i?"bot":"user"}:${h.toLowerCase()}`;o.set(y,{...l.id?{id:l.id}:{},username:h,...i?{bot:!0}:{},...u?{automated:!0}:{},reviewID:s.id})}return n.length?{changesRequested:!0,changeReviewIDs:n,changeRequesters:[...o.values()],changeRequestersComplete:a}:a?{changesRequested:!1,changeRequesters:[],changeRequestersComplete:!0}:{changeRequestersComplete:!1}}function En(e,t={}){const r=ie(e),n=t.unsupportedAutoMerge??new Set;async function o($,f,c){if(n.has($))return r($,f(!1),c);try{return await r($,f(!0),c)}catch(b){if(!wn(b))throw b;return n.add($),r($,f(!1),c)}}async function a($,f){const[c,b]=f.baseRepository.nameWithOwner.split("/");let p,S=!1;for(let v=0;v<he;v++){const D=(await r($,T(`query($owner:String!,$repo:String!,$branch:String!,$after:String) {
|
|
84
84
|
repository(owner:$owner,name:$repo) {
|
|
85
85
|
ref(qualifiedName:$branch) {
|
|
86
86
|
branchProtectionRule { requiresConversationResolution }
|
|
@@ -90,27 +90,27 @@ ${a}
|
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
-
}`),{owner:c,repo:b,branch:`refs/heads/${f.baseRefName}`,...p?{after:p}:{}}).catch(()=>{}))?.repository?.ref;if(D?.branchProtectionRule?.requiresConversationResolution)return!0;const _=D?.rules;if(!_?.pageInfo)return;for(const
|
|
93
|
+
}`),{owner:c,repo:b,branch:`refs/heads/${f.baseRefName}`,...p?{after:p}:{}}).catch(()=>{}))?.repository?.ref;if(D?.branchProtectionRule?.requiresConversationResolution)return!0;const _=D?.rules;if(!_?.pageInfo)return;for(const O of _.nodes){if(O.type!=="PULL_REQUEST")continue;const Q=O.parameters?.requiredReviewThreadResolution,ae=O.repositoryRuleset?.enforcement;if(ae==="ACTIVE"&&Q===!0)return!0;(!ae||Q===void 0)&&(S=!0)}if(!_.pageInfo.hasNextPage)return S?void 0:!1;const H=_.pageInfo.endCursor;if(!H||H===p)return;p=H}}async function s($,f){const[c,b]=f.baseRepository.nameWithOwner.split("/"),p=[...f.reviewThreads.nodes];let S=f.reviewThreads.pageInfo;for(let v=1;S?.hasNextPage&&S.endCursor&&v<he;v++){const D=(await r($,T(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
94
94
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
95
95
|
reviewThreads(first:100,after:$after) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
|
|
96
|
-
} } }`),{owner:c,repo:b,number:f.number,after:
|
|
96
|
+
} } }`),{owner:c,repo:b,number:f.number,after:S.endCursor})).repository?.pullRequest?.reviewThreads;if(!D)break;p.push(...D.nodes),S=D.pageInfo}return{unresolved:p.filter(v=>!v.isResolved).length,complete:!S?.hasNextPage}}async function l($,f){const[c,b]=f.baseRepository.nameWithOwner.split("/"),p=f.commits.nodes[0]?.commit.statusCheckRollup?.contexts,S=[...p?.nodes??[]];let v=p?.pageInfo;for(let C=1;v?.hasNextPage&&v.endCursor&&C<he;C++){const _=(await r($,T(`query($owner:String!,$repo:String!,$oid:GitObjectID!,$after:String!) {
|
|
97
97
|
repository(owner:$owner,name:$repo) { object(oid:$oid) { ... on Commit { statusCheckRollup {
|
|
98
98
|
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 } }
|
|
99
|
-
} } } } }`),{owner:c,repo:b,oid:f.headRefOid,after:
|
|
99
|
+
} } } } }`),{owner:c,repo:b,oid:f.headRefOid,after:v.endCursor})).repository?.object?.statusCheckRollup?.contexts;if(!_)break;S.push(..._.nodes),v=_.pageInfo}return{nodes:S,complete:!v?.hasNextPage}}async function i($,f){const c=[...f.reviewRequests.nodes];let b=f.reviewRequests.pageInfo;for(let p=1;b?.hasNextPage&&p<he;p++){if(!b.endCursor)return{nodes:c,pageInfo:{hasNextPage:!0}};const[S,v]=f.baseRepository.nameWithOwner.split("/"),D=(await r($,T(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
100
100
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
101
101
|
reviewRequests(first:100,after:$after) {
|
|
102
102
|
nodes { requestedReviewer { __typename ... on User { id login } ... on Bot { id login } ... on Team { name } } }
|
|
103
103
|
pageInfo { hasNextPage endCursor }
|
|
104
104
|
}
|
|
105
105
|
} }
|
|
106
|
-
}`),{owner:
|
|
106
|
+
}`),{owner:S,repo:v,number:f.number,after:b.endCursor})).repository?.pullRequest?.reviewRequests;if(!D)return{nodes:c,pageInfo:{hasNextPage:!0}};c.push(...D.nodes),b=D.pageInfo}return{nodes:c,pageInfo:b}}async function u($,f){if(!f.latestOpinionatedReviews?.pageInfo)return{nodes:[...f.latestOpinionatedReviews?.nodes??[]],complete:!1};const c=[...f.latestOpinionatedReviews.nodes];let b=f.latestOpinionatedReviews.pageInfo;for(let p=1;b.hasNextPage&&b.endCursor&&p<he;p++){const[S,v]=f.baseRepository.nameWithOwner.split("/"),D=(await r($,T(`query($owner:String!,$repo:String!,$number:Int!,$after:String!) {
|
|
107
107
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) {
|
|
108
108
|
latestOpinionatedReviews(first:100,after:$after) {
|
|
109
109
|
nodes { id state author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
110
110
|
pageInfo { hasNextPage endCursor }
|
|
111
111
|
}
|
|
112
112
|
} }
|
|
113
|
-
}`),{owner:
|
|
113
|
+
}`),{owner:S,repo:v,number:f.number,after:b.endCursor})).repository?.pullRequest?.latestOpinionatedReviews;if(!D?.pageInfo)return{nodes:c,complete:!1};c.push(...D.nodes),b=D.pageInfo}return{nodes:c,complete:!b.hasNextPage}}async function h($,f){const c=await i($,f),[b,p,S]=await Promise.all([s($,f),l($,f),u($,f)]),v=kn(c,S),C=c.nodes.flatMap(_=>{const H=_.requestedReviewer;if(H?.__typename==="Bot")return[];const O=H?.login||H?.name;return O?[O]:[]}),D=c.nodes.flatMap(_=>{const H=_.requestedReviewer;return H?.__typename!=="User"||!H.login?[]:[{...H.id?{id:H.id}:{},username:H.login}]});return{forge:"github",iid:String(f.number),title:f.title,url:f.url,state:f.state==="OPEN"?"opened":f.state.toLowerCase(),draft:f.isDraft,conflicts:f.mergeable==="CONFLICTING",conflictsKnown:f.mergeable!=="UNKNOWN",approved:f.reviewDecision==="APPROVED"&&C.length===0&&v.changesRequested!==!0,reviewDecision:f.reviewDecision??void 0,...f.autoMergeRequest===void 0?{}:{autoMergeEnabled:f.autoMergeRequest!==null},...v,copilotReview:Cn({...f,reviewRequests:c}),awaitingReviewers:C,pendingHumanReviewers:D,reviewersComplete:!!c.pageInfo&&!c.pageInfo.hasNextPage,approvalsComplete:!!c.pageInfo&&!c.pageInfo.hasNextPage&&S.complete,reviewerIDs:[...new Set([...c.nodes.flatMap(_=>_.requestedReviewer?.__typename==="User"?_.requestedReviewer.id??[]:[]),...[...f.latestReviews?.nodes??[],...S.nodes].flatMap(_=>!_?.author?.__typename||_.author.__typename==="User"?_?.author?.id??[]:[])])],approvers:In(f,c,S.nodes),targetProject:f.baseRepository.nameWithOwner,targetBranch:f.baseRefName,...f.headRepository?{sourceProject:f.headRepository.nameWithOwner}:{},sourceBranch:f.headRefName,headSha:f.headRefOid,...f.author?.id?{authorID:f.author.id}:{},...f.author?.login?{authorUsername:f.author.login}:{},updatedAt:f.updatedAt,pipeline:p.nodes.length||!p.complete?Rn(p.nodes,p.complete,`${f.url}/checks`,f.headRefOid):void 0,unresolvedThreads:b.unresolved,discussionResolutionRequired:b.unresolved>0?await a($,f):void 0,threadsComplete:b.complete}}async function y($,{id:f}){let c;const b=await ze(10,async v=>{const D=(await r($.host,T(`
|
|
114
114
|
query($id:ID!,$after:String) {
|
|
115
115
|
node(id:$id) { ... on PullRequestReviewThread {
|
|
116
116
|
id isResolved path line pullRequest { url }
|
|
@@ -119,7 +119,7 @@ ${a}
|
|
|
119
119
|
nodes { id url body createdAt isMinimized author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } } }
|
|
120
120
|
}
|
|
121
121
|
} }
|
|
122
|
-
}`),{id:f,...
|
|
122
|
+
}`),{id:f,...v?{after:v}:{}})).node,_=D?.pullRequest&&sr(D.pullRequest.url);if(!D||D.id!==f||!_||_.host!==$.host||_.project.toLowerCase()!==$.project.toLowerCase()||_.iid!==$.iid){c=void 0;return}return c=D,c.isResolved?void 0:c.comments});if(!c)return;if(c.isResolved)return"resolved";const p=[];let S=!b.complete;for(const v of b.nodes){const C=v.author;if(!v.id||v.isMinimized||!C?.login||typeof v.body!="string"){S=!0;continue}p.push({id:v.id,url:v.url,authorID:C.id,username:be(C.login,C.__typename),bot:C.__typename==="Bot"||C.login.endsWith("[bot]"),body:v.body,createdAt:v.createdAt,path:c.path??void 0,line:c.line??void 0})}return{id:f,notes:p,url:p.find(v=>v.url)?.url,incomplete:S||p.length===0}}async function w($){const[f,c]=$.project.split("/"),b=Number($.iid);if(!f||!c||!Number.isInteger(b)||b<1)return;const p=await ze(he,async C=>(await r($.host,T(`query($owner:String!,$repo:String!,$number:Int!${C?",$after:String!":""}) {
|
|
123
123
|
repository(owner:$owner,name:$repo) {
|
|
124
124
|
pullRequest(number:$number) {
|
|
125
125
|
reviewThreads(first:100${C?",after:$after":""}) {
|
|
@@ -128,27 +128,27 @@ ${a}
|
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
130
|
}
|
|
131
|
-
}`),{owner:f,repo:c,number:b,...C?{after:C}:{}})).repository?.pullRequest?.reviewThreads),
|
|
132
|
-
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${
|
|
133
|
-
}`),{owner:b,repo:p,number:Number(f)})).repository?.pullRequest;if(
|
|
131
|
+
}`),{owner:f,repo:c,number:b,...C?{after:C}:{}})).repository?.pullRequest?.reviewThreads),S=[],v=p.nodes.filter(({id:C,isResolved:D})=>C&&!D);for(const{id:C}of v.slice(0,We)){const D=await y($,{id:C}).catch(()=>{});D!=="resolved"&&S.push(D??{id:C,notes:[],incomplete:!0})}return{complete:p.complete&&v.length<=We,discussions:S}}async function R($,f){for(const c of $){const[b,p]=c.path.split("/"),v=(await o(c.host,C=>T(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
132
|
+
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { ${jt(C)} } }
|
|
133
|
+
}`),{owner:b,repo:p,number:Number(f)})).repository?.pullRequest;if(v)return h(c.host,v)}}async function k($,f,c){const b=new Map;for(const p of f){const[S,v]=p.path.split("/");let C,D=!1;for(let _=0;_<he;_++){const O=(await o(p.host,Q=>T(`query($owner:String!,$repo:String!,$branch:String!${C?",$after:String!":""}) {
|
|
134
134
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch${C?",after:$after":""}) {
|
|
135
|
-
nodes { ${
|
|
136
|
-
} } }`),{owner:
|
|
137
|
-
`);if(t<1||t>r.length)return;const n=Math.max(1,t-
|
|
138
|
-
`)}const
|
|
135
|
+
nodes { ${jt(Q)} } pageInfo { hasNextPage endCursor }
|
|
136
|
+
} } }`),{owner:S,repo:v,branch:c,...C?{after:C}:{}})).repository?.pullRequests;if(!O)throw new J("request","GitHub repository unavailable");for(const Q of O.nodes)Q.headRepository?.nameWithOwner.toLowerCase()===$.path.toLowerCase()&&(b.has(Q.url)||b.set(Q.url,await h(p.host,Q)));if(!O.pageInfo?.hasNextPage){D=!0;break}if(C=O.pageInfo.endCursor,!C)break}if(!D)throw new J("request","GitHub PR discovery exceeded its pagination limit")}return[...b.values()].sort((p,S)=>(S.updatedAt??"").localeCompare(p.updatedAt??""))}async function I($){const c=(await r($,bn,{})).viewer;if(!(!c?.id&&!c?.login))return{...c.id?{id:c.id}:{},...c.login?{username:c.login}:{}}}return{forge:"github",fetchRequest:$=>R([{host:$.host,path:$.project}],$.iid),fetchByProjects:R,fetchByBranch:k,unresolvedDiscussions:w,discussion:y,viewer:I}}const hr=e=>t=>t.forge===e,_n=e=>e?.match(/^\[[^\]]*\]/)?.[0]??"";function mr(e,t){return _n(e).slice(1,-1).split(/[\s,]+/).flatMap(r=>r.startsWith(t)&&/^[1-9]\d*$/.test(r.slice(t.length))?[r.slice(t.length)]:[])}const Ft=10,An=10,Gt=300,Dn=5,Ht=300;function Pn(e,t){const r=e.split(`
|
|
137
|
+
`);if(t<1||t>r.length)return;const n=Math.max(1,t-Ft),o=Math.min(r.length,t+Ft);return r.slice(n-1,o).map((a,s)=>{const l=n+s,i=a.length>Gt?`${a.slice(0,Gt)}…`:a;return`${l===t?">":" "}${l}: ${i}`}).join(`
|
|
138
|
+
`)}const Ne=100,Qe=20,vr=200,Rt="author { __typename login ... on User { id } ... on Bot { id } ... on Mannequin { id } }",Ct="pageInfo { hasPreviousPage startCursor }",wr=`id url state createdAt publishedAt lastEditedAt isMinimized pullRequestReview { state } ${Rt}`,It=(e,t)=>T(`query($owner: String!, $repo: String!, $number: Int!, $before: String) {
|
|
139
139
|
viewer { id }
|
|
140
140
|
repository(owner: $owner, name: $repo) {
|
|
141
141
|
pullRequest(number: $number) {
|
|
142
|
-
${e}(last: ${
|
|
142
|
+
${e}(last: ${Ne}, before: $before) { ${Ct} nodes { ${t} } }
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
}`),
|
|
145
|
+
}`),Nn=It("comments",`id url createdAt publishedAt lastEditedAt isMinimized ${Rt}`),xn=It("reviews",`id url state body submittedAt lastEditedAt isMinimized ${Rt}`),Tn=It("reviewThreads",`id isResolved comments(last: ${Ne}) { ${Ct} nodes { ${wr} } }`),Mn=T(`query($id: ID!, $before: String) {
|
|
146
146
|
node(id: $id) {
|
|
147
147
|
... on PullRequestReviewThread {
|
|
148
|
-
comments(last: ${
|
|
148
|
+
comments(last: ${Ne}, before: $before) { ${Ct} nodes { ${wr} } }
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
}`),
|
|
151
|
+
}`),qn=new Set(["COMMENTED","CHANGES_REQUESTED"]),kt=(...e)=>{const t=e.find(r=>r);return t?Date.parse(t):NaN},Et=(e,t)=>{const r=e?Date.parse(e):NaN;return Number.isFinite(r)?Math.max(r,t):t};function _t({node:e,postedAt:t,editedAt:r,resolved:n,resolvable:o,discussionID:a}){if(e.isMinimized||!e.author?.id||!Number.isFinite(t)||!Number.isFinite(r))return;const{__typename:s,login:l}=e.author;return{id:e.id,order:t,url:e.url??"",editedAt:r,resolved:n,resolvable:o,bot:s==="Bot"||l.endsWith("[bot]"),authorID:e.author.id,username:be(l,s),...a?{discussionID:a}:{}}}function Ln(e){const t=kt(e.publishedAt,e.createdAt);return _t({node:e,postedAt:t,editedAt:Et(e.lastEditedAt,t),resolved:!1,resolvable:!1})}function jn(e){if(!qn.has(e.state)||!e.body.trim())return;const t=kt(e.submittedAt);return _t({node:e,postedAt:t,editedAt:Et(e.lastEditedAt,t),resolved:!1,resolvable:!1})}function On(e,t,r){if(e.state==="PENDING")return;const n=kt(e.publishedAt,e.createdAt),o=_t({node:e,postedAt:n,editedAt:Et(e.lastEditedAt,n),resolved:t,resolvable:!0,discussionID:r});if(o)return e.pullRequestReview?.state?{...o,reviewState:e.pullRequestReview.state}:o}const Un={pages:Qe,completeAtLimit:!0},Bn={pages:vr,completeAtLimit:!1};async function nt(e,t,r,n,o,a=Un){const s=[];let l,i;const u=h=>({items:s.toReversed().flat(),viewer:l,complete:h});for(let h=0;h<a.pages;h++){const y=i?{...r,before:i}:r,w=await e(t,n,y);l??=w.viewer?.id??void 0;const R=w.repository?.pullRequest?.[o];if(!R)return h===0?{viewer:l,complete:!1}:u(!1);if(s.push(R.nodes),!R.pageInfo.hasPreviousPage)return u(!0);if(i=R.pageInfo.startCursor??void 0,!i)return u(!1)}return u(a.completeAtLimit)}async function Fn(e,t,r){if(!r.comments)return{comments:[],complete:!1};const n=[];let o=r.comments?.pageInfo.hasPreviousPage?r.comments.pageInfo.startCursor??void 0:void 0;if(r.comments?.pageInfo.hasPreviousPage&&!o)return{comments:[],complete:!1};for(let a=1;o&&a<Qe;a++){const l=(await e(t,Mn,{id:r.id,before:o})).node?.comments;if(!l)return{comments:n.toReversed().flat(),complete:!1};if(n.push(l.nodes),o=l.pageInfo.hasPreviousPage?l.pageInfo.startCursor??void 0:void 0,l.pageInfo.hasPreviousPage&&!o)return{comments:n.toReversed().flat(),complete:!1}}return{comments:n.toReversed().flat(),complete:!0}}const Gn=e=>T(`query {
|
|
152
152
|
nodes(ids: ${JSON.stringify(e)}) {
|
|
153
153
|
__typename
|
|
154
154
|
... on IssueComment { id url body author { __typename login ... on User { id } ... on Bot { id } } }
|
|
@@ -159,57 +159,57 @@ ${a}
|
|
|
159
159
|
replyTo { body author { __typename login } }
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
|
-
}`),
|
|
162
|
+
}`),Hn=/^[A-Za-z0-9_=-]+$/,Wt=50;async function Wn(e,t,r){const n=ie(e),o=[],a=r.filter(s=>Hn.test(s));for(let s=0;s<a.length;s+=Wt){const l=await n(t,Gn(a.slice(s,s+Wt)),{});for(const i of l.nodes??[]){if(!i?.id||!i.url||!i.author||i.body===void 0||i.__typename==="PullRequestReview"&&i.state==="APPROVED")continue;const u=i.line??i.originalLine??void 0,h=i.diffHunk?.split(`
|
|
163
163
|
`).slice(-21).join(`
|
|
164
|
-
`),
|
|
164
|
+
`),y=i.replyTo?.author?[{username:be(i.replyTo.author.login,i.replyTo.author.__typename),body:i.replyTo.body}]:[],w=i.author.__typename==="Bot"||i.author.login.endsWith("[bot]");let R;i.__typename==="PullRequestReviewComment"?R=i.pullRequestReview?.state??void 0:i.__typename==="PullRequestReview"&&(R=i.state??void 0),o.push({id:i.id,url:i.url,username:be(i.author.login,i.author.__typename),...i.author.id?{authorID:i.author.id}:{},...w?{bot:!0}:{},...R?{reviewState:R}:{},body:i.body,...i.path?{path:i.path}:{},...u===void 0?{}:{line:u},...i.path&&h?{code:{path:i.path,text:h}}:{},...y.length?{replies:y}:{}})}}return o}async function zn(e,t,r,n){let o=0;const a=ie(async(...$)=>o++>=vr?{}:e(...$)),[s,l]=r.split("/"),i={owner:s,repo:l,number:Number(n)},[u,h,y]=await Promise.all([nt(a,t,i,Nn,"comments"),nt(a,t,i,xn,"reviews"),nt(a,t,i,Tn,"reviewThreads",Bn)]);if(!u.items||!h.items||!y.items)return;const w=u.viewer??h.viewer??y.viewer;let R=y.complete;const k=[];for(const $ of y.items){const f=await Fn(a,t,$);R&&=f.complete;for(const c of[...f.comments,...$.comments?.nodes??[]]){const b=On(c,$.isResolved,$.id);b&&k.push(b)}k.sort((c,b)=>b.order-c.order),k.splice(Ne*Qe)}const I=[...u.items.map(Ln),...h.items.map(jn),...k.sort(($,f)=>$.order-f.order).slice(-Ne*Qe)].flatMap($=>$??[]);return{complete:u.complete&&h.complete&&R&&w!==void 0,viewerID:w,comments:I.sort(($,f)=>$.order-f.order)}}const Vn=[{name:"group",prefixes:["group::"]},{name:"type",prefixes:["maintenance::","bug::","feature::"]}],br=Vn.flatMap(({prefixes:e})=>e),Qn=100,Kn=20,ft=T(`query($project: ID!, $iid: String!, $before: String) {
|
|
165
165
|
currentUser { id }
|
|
166
166
|
project(fullPath: $project) {
|
|
167
167
|
mergeRequest(iid: $iid) {
|
|
168
|
-
notes(last: ${
|
|
168
|
+
notes(last: ${Qn}, before: $before, filter: ONLY_COMMENTS) {
|
|
169
169
|
pageInfo { hasPreviousPage startCursor }
|
|
170
170
|
nodes {
|
|
171
171
|
id url createdAt updatedAt lastEditedAt system
|
|
172
172
|
position { newPath }
|
|
173
|
-
discussion { id resolved }
|
|
173
|
+
discussion { id resolved resolvable }
|
|
174
174
|
author { id username bot }
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
}
|
|
179
|
-
}`),
|
|
179
|
+
}`),Jn=T(String(ft).replace("position { newPath }","position { newPath } duoCreatedSession { id status workflowDefinition }")),Oe=e=>e.slice(e.lastIndexOf("/")+1),Yn=e=>Date.parse(e.lastEditedAt??e.updatedAt??e.createdAt);function Xn(e){const t=Yn(e),r=Oe(e.id);if(e.system||!e.author||!Number.isFinite(t)||!/^\d+$/.test(r))return;const n=e.discussion?.resolvable===void 0?!!e.discussion?.id:e.discussion.resolvable;return{id:r,order:Number(r),url:e.url??"",editedAt:t,resolved:e.discussion?.resolved===!0,resolvable:n,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 Zn(e,t,r,n){const o=ie(e),a=[];let s,l,i=!0;const u=h=>({complete:h&&s!==void 0,viewerID:s,comments:a.toReversed().flat()});for(let h=0;h<Kn;h++){const y={project:r,iid:n};l&&(y.before=l);let w;try{w=await o(t,i?Jn:ft,y)}catch(k){if(!i||!/duoCreatedSession.*(?:doesn't exist|not defined|unknown)|(?:undefinedField|unknown field).*duoCreatedSession/i.test(k instanceof Error?k.message:String(k)))throw k;i=!1,w=await o(t,ft,y)}s??=w.currentUser?.id??void 0;const R=w.project?.mergeRequest?.notes;if(!R)return h===0?void 0:u(!1);if(a.push(R.nodes.flatMap(k=>Xn(k)??[])),!R.pageInfo.hasPreviousPage)return u(!0);if(l=R.pageInfo.startCursor??void 0,!l)return u(!1)}return u(!0)}const zt=10,eo=20,to=/^[0-9a-f]{40}$/;function $r(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 ro(e,t,r,n){const o=ie(e),a=[],s=n.filter(i=>/^\d+$/.test(i));for(let i=0;i<s.length;i+=zt){const u=s.slice(i,i+zt).map((y,w)=>`n${w}: note(id: "gid://gitlab/Note/${y}") { id url body author { id username }
|
|
180
180
|
position { diffRefs { baseSha headSha } newPath newLine oldPath oldLine }
|
|
181
|
-
discussion { resolved notes(first: ${
|
|
182
|
-
`),h=await o(t,
|
|
183
|
-
`),u=await e(t,
|
|
181
|
+
discussion { resolved notes(first: ${eo}) { nodes { id body author { username } } } } }`).join(`
|
|
182
|
+
`),h=await o(t,T(`query { ${u} }`),{});for(const y of Object.values(h))y?.author&&y.url&&a.push(y)}const l=await no(o,t,r,a).catch(()=>new Map);return a.map(i=>{const u=$r(i.position),h=u&&l.get(JSON.stringify([u.sha,u.path])),y=h!==void 0&&u?Pn(h,u.line):void 0,w=i.discussion?.notes?.nodes??[],R=w.findIndex(I=>Oe(I.id)===Oe(i.id)),k=(R>0?w.slice(0,R):[]).flatMap(I=>I.author?[{username:I.author.username,body:I.body}]:[]);return{id:Oe(i.id),url:i.url??"",username:i.author?.username??"",...i.author?.id?{authorID:i.author.id}:{},body:i.body,...typeof i.discussion?.resolved=="boolean"?{resolved:i.discussion.resolved}:{},...u?{path:u.path,line:u.line}:{},...y&&u?{code:{path:u.path,text:y}}:{},...k.length?{replies:k}:{}}})}async function no(e,t,r,n){const o=new Map;let a=0;for(const h of n){const y=$r(h.position);if(!y||!to.test(y.sha))continue;const w=o.get(y.sha)??new Set;!w.has(y.path)&&a>=An||(w.has(y.path)||a++,o.set(y.sha,w.add(y.path)))}const s=new Map;if(!o.size)return s;const l=[...o.keys()],i=l.map((h,y)=>`b${y}: project(fullPath: ${JSON.stringify(r)}) { repository { blobs(paths: ${JSON.stringify([...o.get(h)])}, ref: ${JSON.stringify(h)}) { nodes { path rawTextBlob } } } }`).join(`
|
|
183
|
+
`),u=await e(t,T(`query { ${i} }`),{});return l.forEach((h,y)=>{for(const w of u[`b${y}`]?.repository?.blobs?.nodes??[])w.rawTextBlob!==null&&s.set(JSON.stringify([h,w.path]),w.rawTextBlob)}),s}const oo=100,so=10,io=T(`query($project: ID!, $iid: String!, $before: String) {
|
|
184
184
|
currentUser { id username }
|
|
185
185
|
project(fullPath: $project) {
|
|
186
186
|
mergeRequest(iid: $iid) {
|
|
187
|
-
notes(last: ${
|
|
187
|
+
notes(last: ${oo}, before: $before, filter: ONLY_ACTIVITY) {
|
|
188
188
|
pageInfo { hasPreviousPage startCursor }
|
|
189
189
|
nodes { id url body createdAt system systemNoteMetadata { action } author { id username } }
|
|
190
190
|
}
|
|
191
191
|
}
|
|
192
192
|
}
|
|
193
|
-
}`),
|
|
193
|
+
}`),Vt="requested review from ",ao=/\sand removed (?:review request for|approval)\b/;function yr(e){return e.startsWith(Vt)?[...e.slice(Vt.length).split(ao)[0].matchAll(/@([A-Za-z0-9_][A-Za-z0-9_.-]*)/g)].map(r=>r[1].replace(/\.+$/,"").toLowerCase()):[]}const At=e=>e.slice(e.lastIndexOf("/")+1);function lo(e,t,r){const n=At(e.id),o=Date.parse(e.createdAt),a=e.systemNoteMetadata?.action;if(!(!e.system||a&&a!=="reviewer")&&!(!/^\d+$/.test(n)||!Number.isFinite(o))&&yr(e.body).includes(t.toLowerCase()))return{id:n,order:Number(n),url:e.url??`${r}#note_${n}`,at:o,...e.author?{requester:{id:e.author.id,username:e.author.username}}:{}}}function uo(e,t){const r=At(e.id),n=Date.parse(e.createdAt),o=e.systemNoteMetadata?.action;if(!e.system||o&&o!=="reviewer"||!/^\d+$/.test(r)||!Number.isFinite(n)||e.author?.id!==t)return;const a=yr(e.body);if(a.length)return{order:Number(r),at:n,reviewers:a}}async function co(e,t,r,n,o){const a=ie(e),s=[];let l,i;const u=h=>{const y=s.toReversed().flat(),w=l?y.flatMap(R=>uo(R,l.id)??[]).sort((R,k)=>R.order-k.order):[];return{complete:h&&l!==void 0,...l?{viewerID:l.id}:{},newest:y.reduce((R,k)=>{const I=Number(At(k.id));return Number.isFinite(I)?Math.max(R,I):R},0),requests:l?y.flatMap(R=>lo(R,l.username,o)??[]).sort((R,k)=>R.order-k.order):[],...w.length?{outgoing:w}:{}}};for(let h=0;h<so;h++){const y={project:r,iid:n};i&&(y.before=i);const w=await a(t,io,y);l??=w.currentUser??void 0;const R=w.project?.mergeRequest?.notes;if(!R)return h===0?void 0:u(!1);if(s.push(R.nodes),!R.pageInfo.hasPreviousPage)return u(!0);if(i=R.pageInfo.startCursor??void 0,!i)return u(!1)}return u(!0)}const po=/^\/(.+?)\/-\/(issues|work_items|merge_requests)\/(\d+)(\/diffs)?\/?$/,fo=/^#note_(\d+)$/,go=/https:\/\/[^\s<>()[\]"'`]+/g,ho=/^gid:\/\/gitlab\/[A-Za-z]*Note\/(\d+)$/;function gt(e,t){if(e.length>Ht*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(fo)?.[1],o=r.pathname.match(po);if(!n||!o)return;const[,a,s,l,i]=o;if(i&&s!=="merge_requests"||a.split("/").some(h=>!h||h==="."||h===".."))return;const u=`https://${t}/${a}/-/${s}/${l}#note_${n}`;if(!(u.length>Ht))return{url:u,project:a,resource:s==="merge_requests"?"merge_request":"issue",iid:l,noteID:n}}const Sr=(e,t)=>e.project.toLowerCase()===t.project.toLowerCase()&&e.resource===t.resource&&e.iid===t.iid&&e.noteID===t.noteID;function mo(e,t){const r=new Set(t.map(o=>o.id)),n=[];for(const o of t)for(const[a]of o.body.matchAll(go)){const s=gt(a.replace(/[.,;:!?*_~]+$/,""),e);if(!(!s||r.has(s.noteID))&&!n.some(l=>Sr(l,s))&&(n.push(s),n.length===Dn))return n.map(l=>l.url)}return n.map(o=>o.url)}async function vo(e,t,r){const n=gt(r,t);if(!n||n.url!==r)return;const a=(await ie(e)(t,T("query($id: NoteID!) { note(id: $id) { id url body author { username } } }"),{id:`gid://gitlab/Note/${n.noteID}`})).note;if(!a?.author||!a.url||a.id.match(ho)?.[1]!==n.noteID)return;const s=gt(a.url,t);if(!(!s||!Sr(s,n)))return{url:n.url,username:a.author.username,body:a.body}}const wo=4*6e4;function bo(e){return{...e,comments:e.comments.filter(t=>t.automated?.reviewer==="GitLab Duo"&&t.automated.finding).map(t=>({...t,bot:!1}))}}function $o(e,t){return e.comments.filter(n=>!n.resolved).every(n=>t-n.editedAt>=wo&&(!n.automated?.status||["FINISHED","FAILED","STOPPED"].includes(n.automated.status)))}function yo(e,t,r){const n={Authorization:`Bearer ${t}`,Origin:r},o=new WebSocket(e,{protocols:["actioncable-v1-json"],headers:n}),a=new AbortController;let s=!1,l=!1;const i={send:u=>o.send(u),close:()=>{a.abort(),o.close()},onmessage:null,onerror:null,onclose:null,onresponse:null};return o.onopen=()=>{s=!0},o.onmessage=({data:u})=>i.onmessage?.(String(u)),o.onclose=()=>{l||i.onclose?.()},o.onerror=async()=>{if(a.signal.aborted||l)return;if(s){i.onerror?.();return}l=!0;const u=new URL(e);u.protocol=u.protocol==="wss:"?"https:":"http:";try{const h=await fetch(u,{redirect:"manual",signal:AbortSignal.any([a.signal,AbortSignal.timeout(1e4)]),headers:{...n,Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":Mr.randomBytes(16).toString("base64"),"Sec-WebSocket-Protocol":"actioncable-v1-json"}});try{a.signal.aborted||i.onresponse?.(h.status,h.headers)}finally{await h.body?.cancel()}}catch{a.signal.aborted||i.onerror?.()}},i}class So extends Error{constructor(t){super("Feedback subscription rate limited"),this.retryAt=t}retryAt}function Ro(e,t=Date.now()){const r=Date.parse(e.get("date")??""),n=Number.isFinite(r)?r:t,o=[],a=e.get("retry-after")?.trim();a&&(/^\d+$/.test(a)?o.push(Number(a)*1e3):/^[+-]?[\d.]+$/.test(a)||o.push(Date.parse(a)-n));for(const u of["ratelimit-reset","x-ratelimit-reset"]){const h=e.get(u)?.trim();h&&/^\d+$/.test(h)&&o.push(Number(h)*1e3-n)}const s=e.get("ratelimit-resettime");s&&o.push(Date.parse(s)-n);const l=o.filter(u=>Number.isFinite(u)&&u>=0);if(!l.length)return;const i=t+Math.max(...l);return Number.isSafeInteger(i)?i:void 0}async function Co(e,t,r,n,o,a=yo){const s=new URL(r.url);if(s.protocol!=="https:"||s.username||s.password||s.port)return;const l=s.pathname.match(/^\/(.+)\/-\/merge_requests\/([1-9]\d*)\/?$/);if(!l||o.aborted)return;const i=await e("glab",["config","get","token","--host",s.hostname],t);if(o.aborted)return;if(i.code!==0||!i.stdout.trim())throw new Error("Subscription credentials unavailable");const u=await e("glab",["api",`projects/${encodeURIComponent(decodeURIComponent(l[1]))}/merge_requests/${l[2]}`,"--hostname",s.hostname],t);if(o.aborted)return;if(u.code!==0)throw new Error("Subscription target lookup failed");const h=JSON.parse(u.stdout);if(!Number.isSafeInteger(h.id)||!Number.isSafeInteger(h.project_id))throw new Error("Invalid subscription target");const y=JSON.stringify({channel:"Noteable::NotesChannel",project_id:h.project_id,noteable_type:"MergeRequest",noteable_id:h.id});await new Promise((w,R)=>{const k=a(`wss://${s.host}/-/cable`,i.stdout.trim(),s.origin);let I=!1,$=!1,f,c;const b=()=>{I||(I=!0,clearTimeout(c),o.removeEventListener("abort",b),k.onmessage=null,k.onerror=null,k.onclose=null,k.onresponse=null,k.close(),f?R(f):w())},p=()=>{clearTimeout(c),c=setTimeout(b,$?45e3:15e3)};p(),o.addEventListener("abort",b,{once:!0}),k.onerror=b,k.onclose=b,k.onresponse=(S,v)=>{S===429&&(f=new So(Ro(v)??Date.now()+6e4)),b()},k.onmessage=S=>{if(!I)try{const v=JSON.parse(String(S));if($&&p(),v.type==="welcome"&&k.send(JSON.stringify({command:"subscribe",identifier:y})),v.type==="disconnect"&&b(),v.identifier!==y)return;v.type==="reject_subscription"&&b(),v.type==="confirm_subscription"&&!$&&($=!0,p(),n.connected()),$&&v.message?.event==="updated"&&n.changed()}catch{b()}},o.aborted&&b()})}function Io(e){const t=Array.from({length:e},(n,o)=>`$p${o}: ID!`).join(", "),r=Array.from({length:e},(n,o)=>`p${o}: project(fullPath: $p${o}) {
|
|
194
194
|
mergeRequests(sourceBranches: [$branch], state: opened, first: 20) { nodes { iid updatedAt sourceProject { fullPath } } }
|
|
195
195
|
}`).join(`
|
|
196
|
-
`);return
|
|
196
|
+
`);return T(`query($branch: String!, ${t}) {
|
|
197
197
|
${r}
|
|
198
|
-
}`)}const
|
|
198
|
+
}`)}const ko=T(`query($project: ID!, $iid: String!) {
|
|
199
199
|
project(fullPath: $project) { mergeRequest(iid: $iid) { sourceBranch } }
|
|
200
|
-
}`),
|
|
200
|
+
}`),Rr="searchIn: [TITLE], includeAncestorGroups: true, first: 100",Eo=T(`query($project: ID!, $prefix: String!, $after: String!) {
|
|
201
201
|
project(fullPath: $project) {
|
|
202
|
-
labels(searchTerm: $prefix, ${
|
|
202
|
+
labels(searchTerm: $prefix, ${Rr}, after: $after) {
|
|
203
203
|
nodes { title }
|
|
204
204
|
pageInfo { hasNextPage endCursor }
|
|
205
205
|
}
|
|
206
206
|
}
|
|
207
|
-
}`),
|
|
207
|
+
}`),_o=T(`query($project: ID!, $iid: String!) {
|
|
208
208
|
project(fullPath: $project) {
|
|
209
209
|
activeMilestones: milestones(state: active, includeAncestors: true, first: 1) {
|
|
210
210
|
nodes { title }
|
|
211
211
|
}
|
|
212
|
-
${
|
|
212
|
+
${br.map((e,t)=>`labelPrefix${t}: labels(searchTerm: "${e}", ${Rr}) { nodes { title } pageInfo { hasNextPage endCursor } }`).join(`
|
|
213
213
|
`)}
|
|
214
214
|
workItems(iid: $iid, first: 1) {
|
|
215
215
|
nodes {
|
|
@@ -227,43 +227,43 @@ ${r}
|
|
|
227
227
|
}
|
|
228
228
|
}
|
|
229
229
|
}
|
|
230
|
-
}`);function
|
|
230
|
+
}`);function Ao(e){const t=Array.from({length:e},(n,o)=>`$i${o}: String!`).join(", "),r=Array.from({length:e},(n,o)=>`$i${o}`).join(", ");return T(`query($project: ID!, ${t}) {
|
|
231
231
|
project(fullPath: $project) {
|
|
232
232
|
mergeRequests(iids: [${r}], first: ${e}) {
|
|
233
233
|
nodes { iid title webUrl state targetProject { fullPath } }
|
|
234
234
|
}
|
|
235
235
|
}
|
|
236
|
-
}`)}function
|
|
236
|
+
}`)}function Do(e){const t=Array.from({length:e},(n,o)=>`$i${o}: String!`).join(", "),r=Array.from({length:e},(n,o)=>`$i${o}`).join(", ");return T(`query($project: ID!, ${t}) {
|
|
237
237
|
project(fullPath: $project) {
|
|
238
238
|
workItems(iids: [${r}], first: ${e}) {
|
|
239
239
|
nodes { iid state }
|
|
240
240
|
}
|
|
241
241
|
}
|
|
242
|
-
}`)}const
|
|
242
|
+
}`)}const Po=T(`mutation($project: ID!, $iid: String!) {
|
|
243
243
|
mergeRequestSetDraft(input: { projectPath: $project, iid: $iid, draft: false }) {
|
|
244
244
|
mergeRequest { draft }
|
|
245
245
|
errors
|
|
246
246
|
}
|
|
247
|
-
}`),
|
|
247
|
+
}`),No=T(`mutation($id: DiscussionID!) {
|
|
248
248
|
discussionToggleResolve(input: { id: $id, resolve: true }) {
|
|
249
249
|
discussion { id resolved }
|
|
250
250
|
errors
|
|
251
251
|
}
|
|
252
|
-
}`),
|
|
252
|
+
}`),xo=new Set,To=new Set,Mo=e=>typeof e=="object"&&e!==null&&(!("errors"in e)||Array.isArray(e.errors))&&(!("data"in e)||typeof e.data=="object");function me(e,t){return async(r,n,o)=>{const a=["api","graphql","--hostname",r,"-f",`query=${n}`];for(const[i,u]of Object.entries(o))a.push("-f",`${i}=${u}`);const s=await e("glab",a,t);let l;try{l=JSON.parse(s.stdout)}catch{throw _e(s.stderr,s.code)}if(!Mo(l))throw _e(s.stderr||"Unexpected GitLab response",s.code);if(l.errors?.length)throw _e(String(l.errors[0]?.message??""),s.code);if(s.code!==0)throw _e(s.stderr,s.code);if(!l.data)throw _e("GitLab returned no data",s.code);return l.data}}const pe={kind:"gitlab",noun:"MR",fullNoun:"merge request",ci:"pipeline",recognizes:nr,open:(e,t)=>new jo(me(e,t),xo,To),owns:hr("gitlab"),parseUrl:or,parseIssueUrl:e=>Je("gitlab",e,/^\/(.+)\/-\/(?:issues|work_items)\/([1-9]\d*)\/?$/),reference:e=>`!${e}`,issueReference:e=>`#${e}`,titleReferences:e=>mr(e,"!"),indicators:()=>[],reviewIndicators:Jr,readyToMerge:Fr,readyToMergeState:wt,hasRequestedChanges:e=>e.changesRequested,details(e){const t=e.approvalRequirementsSatisfied===null?"unknown":Ce(e.approvalRequirementsSatisfied),r=[`Human approvals: ${Ce(e.hasApprovals)} · Approval requirements satisfied: ${t}`],n=e.approvalRequirementsSatisfied===!0?[]:e.missingRules??[];for(const o of n.slice(0,2)){const a=(o.eligibleCount??o.eligible.length)-o.eligible.length;let s="";if(o.eligibleReviewers.length)s=`, @${o.eligibleReviewers[0]} can approve`;else if(o.eligible.length){const l=e.awaitingReviewers.length?"ask an eligible approver: ":"ask ",i=a>0?` or ${a} ${a===1?"other":"others"}`:"";s=`, ${l}@${o.eligible.join(", @")}${i}`}r.push(`Still needed: ${o.name} (${o.required} required in total${s})`)}return n.length>2&&r.push(`+${n.length-2} more rules`),e.autoMergeEnabled&&r.push(Hr(e)),e.mergeTrainIndex!=null&&r.push(`Merge train: position ${e.mergeTrainIndex+1}`),e.mergeStatus&&r.push(`Merge status: ${Fe(e.mergeStatus)}`),r},automatedReview:{publishedFeedback:{storageKey:"duo",select:bo,ready:$o},name:"GitLab Duo",status(e){const t=e.duoReviewState;if(t)return{state:Lo(t),label:Fe(t)}}},feedback:{async viewerID(e,t,r){return(await ie(me(e,t))(r,T("query { currentUser { id } }"),{})).currentUser?.id},async reviewerID(e,t,r,n){const o=await ie(me(e,t))(r,T("query($username: String!) { user(username: $username) { id username } }"),{username:n});return o.user?.username.toLowerCase()===n.toLowerCase()?o.user.id:void 0},subscribe:Co,async fetch(e,t,r){const n=pe.parseUrl(r.url);return n?Zn(me(e,t),n.host,n.project,n.iid):void 0},async reviewRequests(e,t,r){const n=pe.parseUrl(r.url);return n?co(me(e,t),n.host,n.project,n.iid,r.url):void 0},async details(e,t,r,n){const o=pe.parseUrl(r.url);return o?ro(me(e,t),o.host,o.project,n):[]},commentID:e=>e.match(/#note_(\d+)$/)?.[1],linkedNotes(e,t){const r=pe.parseUrl(e.url);return r?mo(r.host,t):[]},async linkedNote(e,t,r,n){const o=pe.parseUrl(r.url);return o?vo(me(e,t),o.host,n):void 0}}},qo=new Set(["REVIEWED","REQUESTED_CHANGES"]);function Lo(e){return e==="REVIEW_STARTED"?"running":qo.has(e)?"feedback":"settled"}class jo{traits=pe;graphql;source;constructor(t,r=new Set,n=new Set){this.graphql=ie(t),this.source=vn(t,{unsupportedApprovedAt:r,unsupportedExtendedStatus:n})}findByBranch(t){return this.source.fetchByBranch(t.source,t.targets,t.sourceBranch)}async findNumberByBranch(t){const{source:r,targets:n,sourceBranch:o}=t,a={branch:o};n.forEach((u,h)=>a[`p${h}`]=u.path);const s=await this.graphql(r.host,Io(n.length),a),l=r.path.toLowerCase();return n.flatMap((u,h)=>s[`p${h}`]?.mergeRequests?.nodes??[]).filter(u=>u.sourceProject?.fullPath.toLowerCase()===l).sort((u,h)=>(h.updatedAt??"").localeCompare(u.updatedAt??""))[0]?.iid}async sourceBranch(t){const n=(await this.graphql(t.host,ko,{project:t.project,iid:t.iid})).project?.mergeRequest?.sourceBranch;return typeof n=="string"&&n?n:void 0}async issue(t){const r=await this.graphql(t.host,_o,{project:t.project,iid:t.iid}),n=r.project?.workItems?.nodes[0];if(!n)return;const o=n.widgets,a=o.find(u=>u.milestone)?.milestone?.title,s=o.find(u=>u.status)?.status?.name,l=o.some(u=>u.__typename==="WorkItemWidgetStatus")?n.workItemType?.widgetDefinitions.flatMap(({allowedStatuses:u})=>(u??[]).map(({name:h})=>h))??[]:[],i=(await Promise.all(br.map(async(u,h)=>{let y=r.project?.[`labelPrefix${h}`];for(;y;){if(y.nodes.some(({title:k})=>k.startsWith(u)))return u;const w=y.pageInfo?.endCursor;if(!y.pageInfo?.hasNextPage||!w)break;y=(await this.graphql(t.host,Eo,{project:t.project,prefix:u,after:w})).project?.labels}}))).filter(u=>u!==void 0);return{forge:"gitlab",open:n.state==="OPEN",...s?{status:s}:{},assignees:o.flatMap(u=>u.assignees?.nodes??[]).map(u=>u.username),labels:o.flatMap(u=>u.labels?.nodes??[]).map(u=>u.title),...a?{milestone:a}:{},availableStatuses:l,availableLabelPrefixes:i,hasActiveMilestones:o.some(u=>u.__typename==="WorkItemWidgetMilestone")&&!!r.project?.activeMilestones?.nodes.length}}async requestStates(t,r){const n=[...new Set(r.filter(Boolean))],o=new Map,a=async s=>{if(s.length===0)return;const l={project:t.path};s.forEach((i,u)=>l[`i${u}`]=i);try{const i=await this.graphql(t.host,Ao(s.length),l);for(const u of i.project?.mergeRequests?.nodes??[])!u||!u.iid||!u.state||!u.webUrl||!u.targetProject?.fullPath||o.set(u.iid,{iid:u.iid,title:u.title??"",url:u.webUrl,state:u.state.toLowerCase(),targetProject:u.targetProject.fullPath})}catch(i){if(!(i instanceof J)||i.kind!=="request")throw i;if(s.length===1)return;const u=Math.ceil(s.length/2);await a(s.slice(0,u)),await a(s.slice(u))}};return await a(n),o}async issueStates(t,r){const n=[...new Set(r.filter(Boolean))],o=new Map,a=async s=>{if(s.length===0)return;const l={project:t.path};s.forEach((i,u)=>l[`i${u}`]=i);try{const i=await this.graphql(t.host,Do(s.length),l);for(const u of i.project?.workItems?.nodes??[])!u||!u.iid||u.state!=="OPEN"&&u.state!=="CLOSED"||o.set(u.iid,{iid:u.iid,open:u.state==="OPEN"})}catch(i){if(!(i instanceof J)||i.kind!=="request")throw i;if(s.length===1)return;const u=Math.ceil(s.length/2);await a(s.slice(0,u)),await a(s.slice(u))}};return await a(n),o}async markReady(t,r){await r?.beforeMutate?.();const o=(await this.graphql(t.host,Po,{project:t.project,iid:t.iid})).mergeRequestSetDraft;if(o?.errors?.length)throw new J("request",o.errors[0]);if(!o?.mergeRequest||o.mergeRequest.draft!==!1)throw new J("request","Could not mark the GitLab merge request as ready")}unresolvedDiscussions(t){return this.source.unresolvedDiscussions(t)}discussion(t,r){return this.source.discussion(t,r)}async resolveDiscussion(t,r,n){await n?.beforeMutate?.();const a=(await this.graphql(t.host,No,{id:r})).discussionToggleResolve;if(a?.errors?.length)throw new J("request",a.errors[0]);if(!a?.discussion||a.discussion.resolved!==!0)throw new J("request","Could not resolve the GitLab discussion")}findByNumber(t,r){return this.source.fetchByProjects(t,r)}}function Le(e,t){return async(r,n,o)=>{const a=["api","graphql","--hostname",r,"-f",`query=${n}`];for(const[u,h]of Object.entries(o))a.push(typeof h=="number"?"-F":"-f",`${u}=${h}`);const s=await e("gh",a,t);let l;try{l=JSON.parse(s.stdout)}catch{throw Ot(s.stderr,s.code)}const i=(l.errors??[]).filter(u=>u.type!=="NOT_FOUND");if(!l.data||i.length||s.code!==0&&!l.errors?.length)throw Ot(i[0]?.message??s.stderr,s.code);return l.data}}const Oo=new Set;function Uo(e){const t=Je("github",e,/^\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)\/?$/);return t&&!pe.recognizes(t.host)?t:void 0}const Pe={kind:"github",noun:"PR",fullNoun:"pull request",ci:"checks",recognizes:()=>!1,open:(e,t)=>new Go(Le(e,t),Oo),owns:hr("github"),parseUrl:sr,parseIssueUrl:Uo,reference:e=>`#${e}`,issueReference:e=>`#${e}`,titleReferences:e=>mr(e,"#"),hasRequestedChanges:e=>e.changesRequested===!0||e.reviewDecision==="CHANGES_REQUESTED"?!0:e.changesRequested,indicators:e=>Pe.hasRequestedChanges(e)===!0?[{text:"changes requested",tone:"warning",essential:!0}]:[],details:e=>[`Review decision: ${e.reviewDecision?Fe(e.reviewDecision):"not reported"}`],automatedReview:{name:"GitHub Copilot",status:e=>Fo(e.copilotReview)},feedback:{async viewerID(e,t,r){return(await ie(Le(e,t))(r,T("query { viewer { id } }"),{})).viewer?.id},async reviewerID(e,t,r,n){const o=await e("gh",["api","--hostname",r,`users/${encodeURIComponent(n)}`],t);if(o.code!==0)throw new Error("Could not resolve the GitHub reviewer account");const a=JSON.parse(o.stdout);return a.login?.toLowerCase()===n.toLowerCase()?a.node_id:void 0},async fetch(e,t,r){const n=Pe.parseUrl(r.url);return n?zn(Le(e,t),n.host,n.project,n.iid):void 0},async details(e,t,r,n){const o=Pe.parseUrl(r.url);return o?Wn(Le(e,t),o.host,n):[]}}};function Bo(e,t){return e?"dismissed":t?"commented":"no comments"}function Fo(e){if(!e)return;const t=e.comments>0&&!e.dismissed,r=Bo(e.dismissed,t),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}}class Go{traits=Pe;graphql;source;constructor(t,r=new Set){this.graphql=ie(t),this.source=En(t,{unsupportedAutoMerge:r})}findByNumber(t,r){return this.source.fetchByProjects(t,r)}async findNumberByBranch(t){let r;for(const n of t.targets){const[o,a]=n.path.split("/"),l=(await this.graphql(n.host,T(`query($owner:String!,$repo:String!,$branch:String!) {
|
|
253
253
|
repository(owner:$owner,name:$repo) { pullRequests(first:100,states:OPEN,headRefName:$branch,orderBy:{field:UPDATED_AT,direction:DESC}) {
|
|
254
254
|
nodes { number updatedAt headRepository { nameWithOwner } }
|
|
255
|
-
} } }`),{owner:o,repo:a,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const i of l)i.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(!r||i.updatedAt>r.updatedAt)&&(r=i)}return r?String(r.number):void 0}async sourceBranch(t){const[r,n]=t.project.split("/");return(await this.graphql(t.host,
|
|
255
|
+
} } }`),{owner:o,repo:a,branch:t.sourceBranch})).repository?.pullRequests?.nodes??[];for(const i of l)i.headRepository?.nameWithOwner.toLowerCase()===t.source.path.toLowerCase()&&(!r||i.updatedAt>r.updatedAt)&&(r=i)}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!) {
|
|
256
256
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { headRefName } }
|
|
257
|
-
}`),{owner:r,repo:n,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async issue(t){const[r,n]=t.project.split("/"),o=Number(t.iid);if(!r||!n||!Number.isInteger(o)||o<1)return;const s=(await this.graphql(t.host,
|
|
257
|
+
}`),{owner:r,repo:n,number:Number(t.iid)})).repository?.pullRequest?.headRefName||void 0}async issue(t){const[r,n]=t.project.split("/"),o=Number(t.iid);if(!r||!n||!Number.isInteger(o)||o<1)return;const s=(await this.graphql(t.host,T(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
258
258
|
repository(owner:$owner,name:$repo) { issue(number:$number) { state url } }
|
|
259
|
-
}`),{owner:r,repo:n,number:o})).repository?.issue;if(!(!s||!s.url||s.state!=="OPEN"&&s.state!=="CLOSED"))return{forge:"github",open:s.state==="OPEN",url:s.url}}async requestStates(t,r){const[n,o]=t.path.split("/"),a=[...new Set(r.filter(i=>{const u=Number(i);return Number.isInteger(u)&&u>=1}))];if(!n||!o||a.length===0)return new Map;const s=new Map,l=async i=>{if(i.length===0)return;const u=i.map((
|
|
259
|
+
}`),{owner:r,repo:n,number:o})).repository?.issue;if(!(!s||!s.url||s.state!=="OPEN"&&s.state!=="CLOSED"))return{forge:"github",open:s.state==="OPEN",url:s.url}}async requestStates(t,r){const[n,o]=t.path.split("/"),a=[...new Set(r.filter(i=>{const u=Number(i);return Number.isInteger(u)&&u>=1}))];if(!n||!o||a.length===0)return new Map;const s=new Map,l=async i=>{if(i.length===0)return;const u=i.map((w,R)=>`$n${R}:Int!`).join(","),h=i.map((w,R)=>`pr${R}:pullRequest(number:$n${R}){number title url state baseRepository{nameWithOwner}}`).join(" "),y={owner:n,repo:o};i.forEach((w,R)=>y[`n${R}`]=Number(w));try{const R=(await this.graphql(t.host,T(`query($owner:String!,$repo:String!,${u}){repository(owner:$owner,name:$repo){${h}}}`),y)).repository;if(!R)return;i.forEach((k,I)=>{const $=R[`pr${I}`];!$||!$.url||!$.state||String($.number??k)!==k||s.set(k,{iid:k,title:$.title??"",url:$.url,state:$.state==="OPEN"?"opened":$.state.toLowerCase(),targetProject:$.baseRepository?.nameWithOwner??t.path})})}catch(w){if(!(w instanceof J)||w.kind!=="request")throw w;if(i.length===1)return;const R=Math.ceil(i.length/2);await l(i.slice(0,R)),await l(i.slice(R))}};return await l(a),s}async issueStates(t,r){const[n,o]=t.path.split("/"),a=[...new Set(r.filter(i=>{const u=Number(i);return Number.isInteger(u)&&u>=1}))];if(!n||!o||a.length===0)return new Map;const s=new Map,l=async i=>{if(i.length===0)return;const u=i.map((w,R)=>`$n${R}:Int!`).join(","),h=i.map((w,R)=>`i${R}:issue(number:$n${R}){number state url}`).join(" "),y={owner:n,repo:o};i.forEach((w,R)=>y[`n${R}`]=Number(w));try{const R=(await this.graphql(t.host,T(`query($owner:String!,$repo:String!,${u}){repository(owner:$owner,name:$repo){${h}}}`),y)).repository;if(!R)return;i.forEach((k,I)=>{const $=R[`i${I}`];!$||!$.url||$.state!=="OPEN"&&$.state!=="CLOSED"||String($.number??k)===k&&s.set(k,{iid:k,open:$.state==="OPEN"})})}catch(w){if(!(w instanceof J)||w.kind!=="request")throw w;if(i.length===1)return;const R=Math.ceil(i.length/2);await l(i.slice(0,R)),await l(i.slice(R))}};return await l(a),s}async markReady(t,r){const[n,o]=t.project.split("/"),s=(await this.graphql(t.host,T(`query($owner:String!,$repo:String!,$number:Int!) {
|
|
260
260
|
repository(owner:$owner,name:$repo) { pullRequest(number:$number) { id isDraft state } }
|
|
261
|
-
}`),{owner:n,repo:o,number:Number(t.iid)})).repository?.pullRequest;if(!s?.id)throw new J("request","GitHub pull request not found");if(s.state!=="OPEN")throw new J("request","The GitHub pull request is no longer open");if(!s.isDraft)return;await r?.beforeMutate?.();const i=(await this.graphql(t.host,
|
|
261
|
+
}`),{owner:n,repo:o,number:Number(t.iid)})).repository?.pullRequest;if(!s?.id)throw new J("request","GitHub pull request not found");if(s.state!=="OPEN")throw new J("request","The GitHub pull request is no longer open");if(!s.isDraft)return;await r?.beforeMutate?.();const i=(await this.graphql(t.host,T(`mutation($id:ID!) {
|
|
262
262
|
markPullRequestReadyForReview(input:{pullRequestId:$id}) { pullRequest { id isDraft } }
|
|
263
|
-
}`),{id:s.id})).markPullRequestReadyForReview?.pullRequest;if(!i||i.isDraft)throw new J("request","Could not mark the GitHub pull request as ready")}unresolvedDiscussions(t){return this.source.unresolvedDiscussions(t)}discussion(t,r){return this.source.discussion(t,r)}async resolveDiscussion(t,r,n){await n?.beforeMutate?.();const a=(await this.graphql(t.host,
|
|
263
|
+
}`),{id:s.id})).markPullRequestReadyForReview?.pullRequest;if(!i||i.isDraft)throw new J("request","Could not mark the GitHub pull request as ready")}unresolvedDiscussions(t){return this.source.unresolvedDiscussions(t)}discussion(t,r){return this.source.discussion(t,r)}async resolveDiscussion(t,r,n){await n?.beforeMutate?.();const a=(await this.graphql(t.host,T(`mutation($id:ID!) {
|
|
264
264
|
resolveReviewThread(input:{threadId:$id}) { thread { id isResolved } }
|
|
265
|
-
}`),{id:r})).resolveReviewThread?.thread;if(!a||!a.isResolved)throw new J("request","Could not resolve the GitHub review thread")}findByBranch(t){return this.source.fetchByBranch(t.source,t.targets,t.sourceBranch)}}const be={gitlab:pe,github:De},Sr=Object.keys(be),ce=e=>be[e.forge],Qe=e=>ce(e).reference(e.iid);function Fo(e){const t=new Set;for(const r of e)r&&t.add(r);return t.size===1?[...t][0]:void 0}function _t(e){const t=new Set;for(const r of e)r&&t.add(r);if(t.size!==0)return t.size===1?[...t][0]:"mixed"}function oe(e){switch(e){case"gitlab":case"github":return be[e].noun;default:return"PR/MR"}}function Je(e){switch(e){case"gitlab":case"github":return`${be[e].noun}s`;default:return"PRs/MRs"}}function Go(e){for(const t of Sr){const r=be[t].parseUrl(e);if(r)return r}}function Ho(e){for(const t of Sr){const r=be[t].parseUrl(e);if(r)return{ref:r,issue:!1};const n=be[t].parseIssueUrl(e);if(n)return{ref:n,issue:!0}}}function Ye(e){const t=ce(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const zt={url:{type:"string"},issueUrl:{type:"string"}},Vt={type:"object",properties:{...zt,targets:{type:"array",items:{type:"object",properties:zt,required:["url"],additionalProperties:!1}}},additionalProperties:!1},Le={type:"string"},Rr={type:"string",enum:["gitlab","github"]},gt={type:"object",title:"Snapshot"},ye={type:"object",title:"InboxState"},Wo={type:"object",properties:{enabled:{type:"boolean"},forge:Rr,snapshot:gt},required:["enabled","snapshot"],additionalProperties:!1},zo={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:ye},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:ye},markFeedbackRead:{input:{type:"object",properties:{ids:{type:"array",items:{type:"string"},maxItems:500}},required:["ids"],additionalProperties:!1},output:ye},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:ye},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:ye},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:ye},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:Vt},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:Le},visible:Le},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},forge:Rr,statuses:{type:"object",additionalProperties:gt}},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:Le},required:["key"],additionalProperties:!1},output:Wo},cleanupCandidates:{input:{type:"object",properties:{scanID:{type:"string"}},additionalProperties:!1},output:{type:"object",title:"CleanupScanResult"}},cleanupSessions:{input:{type:"object",properties:{scanID:{type:"string"},allowClientArchive:{type:"boolean"},finalizeArchived:{type:"boolean"},sessionIDs:{type:"array",items:{type:"string"},minItems:1,maxItems:500}},required:["sessionIDs"],additionalProperties:!1},output:{type:"object",title:"CleanupResult"}}},events:{cleanupProgress:{schema:{type:"object",properties:{scanID:{type:"string"},phase:{type:"string",enum:["sessions","targets","verifying","archiving"]},checked:{type:"number"},total:{type:"number"}},required:["phase","checked","total"],additionalProperties:!1}},sessionsCleanedUp:{schema:{type:"object",properties:{sessionIDs:{type:"array",items:{type:"string"}},archive:{type:"boolean"}},required:["sessionIDs"],additionalProperties:!1}},feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...Vt.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:Le,snapshot:gt},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"]},openTab:{type:"boolean"}},required:["message","variant"],additionalProperties:!1}}}},Vo="",Cr=6e4,Qt=(e,t)=>e.directory===t.directory&&e.key===t.key,_e=e=>JSON.stringify([e.directory,e.key]);function Qo(e){const t=e.now??Date.now,r=e.setTimer??((p,y)=>setTimeout(p,y)),n=e.clearTimer??(p=>clearTimeout(p)),o=e.defer??queueMicrotask,a=new Map,s=new Map,l=new Map,i=new Map;let u,h=!1;const S=p=>s.get(p.directory)?.has(p.key)===!0;function v(p,y){const w=_e(p);(y.revision??-1)>=(a.get(w)?.revision??-1)&&a.set(w,y)}function R(p,y){const w=y instanceof Error?y.message:String(y),C={kind:"request",message:`${oe(i.get(p))} status service unavailable: ${w}`,at:t()};for(const D of s.get(p)??[]){const _=_e({directory:p,key:D});a.set(_,{...a.get(_)??{},loading:!1,error:C})}e.onChange()}const E=new Map,I=new Map;function $(p){const y=(E.get(p)??0)+1;E.set(p,y);const w=I.get(p);w!==void 0&&n(w),I.set(p,r(()=>{f(p)},Math.min(Cr,1e3*2**y)))}async function f(p){if(h)return;const y=I.get(p);y!==void 0&&n(y),I.delete(p);const w=[...s.get(p)??[]];try{const C=await e.watch(p,{clientID:e.clientID,keys:w,...u?.directory===p?{visible:u.key}:{}});if(h)return;E.delete(p),l.set(p,C.enabled),C.forge&&i.set(p,C.forge);for(const[D,_]of Object.entries(C.statuses))S({directory:p,key:D})&&v({directory:p,key:D},_);e.onChange()}catch(C){if(h)return;R(p,C),$(p)}}const c=new Set;function b(p){c.has(p)||(c.add(p),o(()=>{c.delete(p),f(p)}))}return{snapshot:p=>a.get(_e(p))??{loading:!1},enabled:p=>l.get(p)??!0,forge:p=>i.get(p),show(p){if(p.key!==Vo)for(const[w,C]of s)w===p.directory||!C.delete(p.key)||(a.delete(_e({directory:w,key:p.key})),u&&Qt(u,{directory:w,key:p.key})&&(u=void 0),b(w));const y=s.get(p.directory)??new Set;s.set(p.directory,y),y.add(p.key),u=p,b(p.directory)},hide(p){u&&Qt(u,p)&&(u=void 0),b(p.directory)},async refresh(p){const y=_e(p);a.set(y,{...a.get(y)??{},loading:!0}),e.onChange();try{const w=await e.refresh(p.directory,p.key);if(h)return;l.set(p.directory,w.enabled),w.forge&&i.set(p.directory,w.forge),v(p,w.snapshot),e.onChange()}catch(w){if(h)return;R(p.directory,w)}},heartbeat(){for(const p of s.keys())f(p)},receive(p,y,w){S({directory:p,key:y})&&(v({directory:p,key:y},w),e.onChange())},hasShown:p=>[...s.values()].some(y=>y.has(p)),dispose(){h=!0;for(const p of I.values())n(p);for(const p of s.keys())e.release(p,e.clientID).catch(()=>{})}}}const Oe=e=>({location:{directory:e}}),Ko=async(e,t)=>await e.feedback({},Oe(t));function Jo(e){let t,r=0;const n=new Map;let o;return{get client(){return t?.client},connect(a){t?.dispose(),t=Xo(a,{...e,clientID:`${e.clientID}:${++r}`});for(const s of n.values())t.client.show(s),t.client.hide(s);o&&t.client.show(o),e.onChange()},show(a){n.set(a.key,a),o=a,t?.client.show(a)},hide(a){o?.key===a.key&&o.directory===a.directory&&(o=void 0),t?.client.hide(a)},dispose(){t?.dispose(),t=void 0}}}function Yo(e){const t=new Map;let r=0;const n=async o=>{const a=(t.get(o)??0)+1;t.set(o,a);const s=r,l=()=>s===r&&t.get(o)===a;try{const i=await e.load(o);l()&&e.changed(o,i)}catch(i){l()&&e.failed(o,i instanceof Error?i.message:String(i))}};return{reload:n,has:o=>t.has(o),refresh:()=>Promise.all([...t.keys()].map(n)),invalidate(){r++}}}function Xo(e,t){const r=e,n=Qo({clientID:t.clientID,watch:async(s,l)=>await r.watch(l,Oe(s)),refresh:async(s,l)=>await r.refresh({key:l},Oe(s)),release:(s,l)=>r.release({clientID:l},Oe(s)),onChange:t.onChange}),o=setInterval(()=>{n.heartbeat(),t.heartbeat?.()},Cr),a=e.events.on("status",s=>{const{directory:l,key:i,snapshot:u}=s.data;n.receive(l,i,u)});return{client:n,dispose(){clearInterval(o),a(),n.dispose()}}}const Zo=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,nt=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),es=e=>e.kind==="review-request",ts=e=>e.kind==="approval",Ir=e=>e.kind==="merge-blocked";function Er(e){return e.canAct!==void 0?e.canAct:e.humanApprovalOnly?!1:ts(e)?e.approverKind!=="human"&&!!e.automationAllowed:Ir(e)?(e.mergeBlocker??"threads")==="threads":!(e.kind&&e.kind!=="ci-failed")}const Ue=e=>Ir(e)&&(e.mergeBlocker??"threads")==="threads"&&Er(e),rs=e=>es(e)?`Requested: ${nt(e.postedAt??e.at)}`:e.postedAt===void 0?`Detected: ${nt(e.at)}`:`Latest comment: ${nt(e.postedAt)}`,ht=(e,t)=>t?e.items.filter(r=>r.sessionID===t):[];function ns(e,t){const r=ht(e,t).filter(n=>!n.read).length;if(r!==0)return`📥 ${r}${e.paused?" (paused)":""}`}function os(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 ss(e){const t=os(e),r=t.filter(o=>o!==e.url),n=e.kind==="ci-failed";return[...r.map((o,a)=>({title:e.kind==="issue-outdated"?"Issue":`${n?"Failed job":"Comment"} ${r.length>1?`${a+1} of ${r.length} `:""}(${n?new URL(o).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(o).hash||"no anchor"})`,description:o,value:o})),...t.includes(e.url)?[{title:`${oe(Ho(e.url)?.ref.forge)} overview`,description:e.url,value:e.url}]:[]]}function Ne(e,t){const r=e?.lookup,n=e?.forge??r?.forge??(r?.kind==="found"?_t([...r.requests.map(o=>o.forge),...(r.failed??[]).map(o=>Go(o.url)?.forge)]):void 0);switch(n){case"gitlab":case"github":return n;case"mixed":return;default:return t}}function kr(e,t){return e.some(r=>r.url===t&&Ue(r))}const is=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function At(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":is.has(e.status)?"warning":"muted":"muted"}const _r=(e,t)=>`${e} ${t}${e===1?"":"s"}`,as=e=>e.charAt(0).toUpperCase()+e.slice(1),ls={success:"CI ✓",error:"CI ✗",warning:"CI …"};function us(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const ot=e=>({text:Qe(e),tone:"muted",url:e.url,essential:!0});function cs(e){const t=At(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:ls[t],tone:t,url:e.pipeline.url}:{text:`no ${ce(e).ci}`,compact:"no CI",tone:t}}function ds(e){const t=Fo(e.map(c=>c.forge)),r=e.length===1?`1 ${oe(t)}`:`${e.length} ${Je(t)}`,n=e.filter(c=>c.state==="opened"),o=[{text:r,tone:"muted",essential:!0}],a=n.filter(c=>Ye(c)?.state==="running").length;a&&o.push({text:`🤖 ${a} reviewing`,compact:`🤖 ${a}`,tone:"warning",essential:!0});const s=n.filter(c=>At(c.pipeline)==="error").length;s&&o.push({text:`${s} CI failed`,compact:`CI ✗ ${s}`,tone:"error"});const l=n.filter(c=>c.conflicts).length;l&&o.push({text:_r(l,"conflict"),tone:"error",essential:!0});const i=n.map(ir),u=i.filter(c=>c==="threads").length,h=i.filter(c=>c&&c!=="threads").length,S=n.map(c=>ce(c).readyToMergeState?.(c)).filter(c=>c!==void 0&&c!=="none"),v=S.filter(c=>c==="merge").length,R=S.filter(c=>c==="maintainer-merge").length,E=S.filter(c=>c==="auto-merge").length;u&&o.push({text:`${u} ${u===1?"needs":"need"} threads resolved`,compact:`${u} resolve threads`,tone:"warning",essential:!0}),v&&o.push({text:`${v} ready to merge`,tone:"warning",essential:!0}),R&&o.push({text:`${R} ${R===1?"needs":"need"} maintainer merge`,tone:"warning",essential:!0}),E&&o.push({text:`${E} ${E===1?"needs":"need"} auto-merge`,tone:"warning",essential:!0}),h&&o.push({text:`${h} merge blocked`,compact:`${h} blocked`,tone:"warning"});const I=n.filter(c=>c.approved&&c.awaitingReviewers.length===0).length;I&&o.push({text:`${I} approved`,tone:"success"});const $=e.filter(c=>c.state==="merged").length;$&&o.push({text:`${$} merged`,tone:"success"});const f=e.length-n.length-$;return f&&o.push({text:`${f} closed`,tone:"muted"}),o}function ps(e,t){const{lookup:r,error:n}=e,o=n?[{text:"stale",tone:"warning",essential:!0}]:[];if(!r||r.kind==="none"||r.requests.length===0){const h=oe(Ne(e,t));return e.targeted&&(n||r?.explicitTarget)?[{text:`${h} status unavailable`,tone:"warning"}]:[]}r.failed?.length&&o.unshift({text:`${r.failed.length} unavailable`,tone:"warning",essential:!0});const a=r.requests;if(r.explicitTarget&&a.length>1)return[...ds(a),...o];if(a.length>1){const h=ce(a[0]).noun;return[...a.map(ot),{text:`${_r(a.length,`open ${h}`)}, run /${h.toLowerCase()}-status`,tone:"warning"},...o]}const[s]=a;if(s.state!=="opened")return[ot(s),{text:s.state,tone:s.state==="merged"?"success":"muted",essential:!0},...o];const l=[ot(s),cs(s)],i=$t(s);if(i&&l.push(i),s.unresolvedThreads>0||!s.threadsComplete){const h=us(s);l.push({text:h,compact:h.replace("unresolved ",""),tone:"warning"})}Ye(s)?.state==="running"&&l.push({text:"🤖 reviewing",compact:"🤖",tone:"warning",essential:!0}),l.push(...ce(s).indicators(s)),s.conflicts&&l.push({text:"conflicts",tone:"error",essential:!0}),s.conflictsKnown||l.push({text:"mergeability unknown",tone:"muted"});const u=ce(s).reviewIndicators;return u?l.push(...u(s)):s.awaitingReviewers.length?l.push({text:er(s.awaitingReviewers),tone:"muted"}):s.approved&&l.push({text:"approved",tone:"success"}),[...l,...o]}const Kt=e=>new Date(e).toLocaleTimeString();function fs(e,t,r){const n=ce(e),o=$t(e,{canReviewThreads:r?kr(r,e.url):!1}),a=[`${Qe(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,...o?[`Next step: ${o.detail}`]:[],`Target: ${e.targetProject} → ${e.targetBranch}`,`${as(n.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${Se(e.draft)} · Conflicts: ${e.conflictsKnown?Se(e.conflicts):"unknown"}`,...n.details(e)],s=Ye(e);return s&&a.push(`${s.name} review: ${s.label}`),e.awaitingReviewers.length&&a.push(`Awaiting review: ${e.awaitingReviewers.map(l=>`@${l}`).join(", ")}`),e.reviewersComplete||a.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&a.push(`Local HEAD differs from the ${n.noun} head commit (unpushed or not fetched)`),a.push(e.url),a}function gs(e,t,r){const{lookup:n,error:o,fetchedAt:a}=e,s=oe(Ne(e,t)),l=[];if(!n)l.push(o?`Could not look up the ${s}.`:"No data yet.");else if(n.kind==="none")l.push(`No ${s} lookup: ${n.reason}.`);else{const{repository:i,sessionTarget:u,requests:h}=n;if(i){const S=i.branch===i.sourceBranch?i.branch:`${i.branch} (pushes to ${i.sourceBranch})`;l.push(`Branch: ${S} in ${i.source.path}`),h.length===0&&l.push("",`No open ${s} for this branch.`)}else u&&l.push(`Session target: ${u}`);for(const{url:S,reason:v}of n.failed??[])l.push(`Unavailable: ${S} (${v})`);for(const S of ar(h))l.push("",...fs(S,i?.head??"",r))}return o&&l.push("",`Last refresh failed at ${Kt(o.at)}: ${o.message}`),a!==void 0&&l.push("",`Last fetched: ${Kt(a)}`),l.join(`
|
|
266
|
-
`)}async function
|
|
265
|
+
}`),{id:r})).resolveReviewThread?.thread;if(!a||!a.isResolved)throw new J("request","Could not resolve the GitHub review thread")}findByBranch(t){return this.source.fetchByBranch(t.source,t.targets,t.sourceBranch)}}const $e={gitlab:pe,github:Pe},Cr=Object.keys($e),ce=e=>$e[e.forge],Ke=e=>ce(e).reference(e.iid);function Ho(e){const t=new Set;for(const r of e)r&&t.add(r);return t.size===1?[...t][0]:void 0}function Dt(e){const t=new Set;for(const r of e)r&&t.add(r);if(t.size!==0)return t.size===1?[...t][0]:"mixed"}function se(e){switch(e){case"gitlab":case"github":return $e[e].noun;default:return"PR/MR"}}function Ye(e){switch(e){case"gitlab":case"github":return`${$e[e].noun}s`;default:return"PRs/MRs"}}function Wo(e){for(const t of Cr){const r=$e[t].parseUrl(e);if(r)return r}}function zo(e){for(const t of Cr){const r=$e[t].parseUrl(e);if(r)return{ref:r,issue:!1};const n=$e[t].parseIssueUrl(e);if(n)return{ref:n,issue:!0}}}function Xe(e){const t=ce(e).automatedReview,r=t?.status(e);return t&&r?{name:t.name,...r}:void 0}const Qt={url:{type:"string"},issueUrl:{type:"string"}},Kt={type:"object",properties:{...Qt,targets:{type:"array",items:{type:"object",properties:Qt,required:["url"],additionalProperties:!1}}},additionalProperties:!1},je={type:"string"},Ir={type:"string",enum:["gitlab","github"]},ht={type:"object",title:"Snapshot"},Se={type:"object",title:"InboxState"},Vo={type:"object",properties:{enabled:{type:"boolean"},forge:Ir,snapshot:ht},required:["enabled","snapshot"],additionalProperties:!1},Qo={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:Se},acknowledgeFeedback:{input:{type:"object",properties:{id:{type:"string"},ids:{type:"array",items:{type:"string"},maxItems:500}},additionalProperties:!1},output:Se},markFeedbackRead:{input:{type:"object",properties:{ids:{type:"array",items:{type:"string"},maxItems:500}},required:["ids"],additionalProperties:!1},output:Se},summarizeFeedback:{input:{type:"object",properties:{id:{type:"string"}},required:["id"],additionalProperties:!1},output:Se},pauseFeedback:{input:{type:"object",properties:{paused:{type:"boolean"}},required:["paused"],additionalProperties:!1},output:Se},actOnFeedback:{input:{type:"object",properties:{id:{type:"string"},retry:{type:"boolean"}},required:["id"],additionalProperties:!1},output:Se},target:{input:{type:"object",properties:{sessionID:{type:"string"}},required:["sessionID"],additionalProperties:!1},output:Kt},watch:{input:{type:"object",properties:{clientID:{type:"string"},keys:{type:"array",items:je},visible:je},required:["clientID","keys"],additionalProperties:!1},output:{type:"object",properties:{enabled:{type:"boolean"},forge:Ir,statuses:{type:"object",additionalProperties:ht}},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:je},required:["key"],additionalProperties:!1},output:Vo},cleanupCandidates:{input:{type:"object",properties:{scanID:{type:"string"}},additionalProperties:!1},output:{type:"object",title:"CleanupScanResult"}},cleanupSessions:{input:{type:"object",properties:{scanID:{type:"string"},allowClientArchive:{type:"boolean"},finalizeArchived:{type:"boolean"},sessionIDs:{type:"array",items:{type:"string"},minItems:1,maxItems:500}},required:["sessionIDs"],additionalProperties:!1},output:{type:"object",title:"CleanupResult"}}},events:{cleanupProgress:{schema:{type:"object",properties:{scanID:{type:"string"},phase:{type:"string",enum:["sessions","targets","verifying","archiving"]},checked:{type:"number"},total:{type:"number"}},required:["phase","checked","total"],additionalProperties:!1}},sessionsCleanedUp:{schema:{type:"object",properties:{sessionIDs:{type:"array",items:{type:"string"}},archive:{type:"boolean"}},required:["sessionIDs"],additionalProperties:!1}},feedbackChanged:{schema:{type:"object",properties:{directory:{type:"string"}},required:["directory"],additionalProperties:!1}},targetChanged:{schema:{type:"object",properties:{sessionID:{type:"string"},...Kt.properties},required:["sessionID"],additionalProperties:!1}},status:{schema:{type:"object",properties:{directory:{type:"string"},key:je,snapshot:ht},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"]},openTab:{type:"boolean"}},required:["message","variant"],additionalProperties:!1}}}},Ko="",kr=6e4,Jt=(e,t)=>e.directory===t.directory&&e.key===t.key,Ae=e=>JSON.stringify([e.directory,e.key]);function Jo(e){const t=e.now??Date.now,r=e.setTimer??((p,S)=>setTimeout(p,S)),n=e.clearTimer??(p=>clearTimeout(p)),o=e.defer??queueMicrotask,a=new Map,s=new Map,l=new Map,i=new Map;let u,h=!1;const y=p=>s.get(p.directory)?.has(p.key)===!0;function w(p,S){const v=Ae(p);(S.revision??-1)>=(a.get(v)?.revision??-1)&&a.set(v,S)}function R(p,S){const v=Re(S),C={kind:"request",message:`${se(i.get(p))} status service unavailable: ${v}`,at:t()};for(const D of s.get(p)??[]){const _=Ae({directory:p,key:D});a.set(_,{...a.get(_)??{},loading:!1,error:C})}e.onChange()}const k=new Map,I=new Map;function $(p){const S=(k.get(p)??0)+1;k.set(p,S);const v=I.get(p);v!==void 0&&n(v),I.set(p,r(()=>{f(p)},Math.min(kr,1e3*2**S)))}async function f(p){if(h)return;const S=I.get(p);S!==void 0&&n(S),I.delete(p);const v=[...s.get(p)??[]];try{const C=await e.watch(p,{clientID:e.clientID,keys:v,...u?.directory===p?{visible:u.key}:{}});if(h)return;k.delete(p),l.set(p,C.enabled),C.forge&&i.set(p,C.forge);for(const[D,_]of Object.entries(C.statuses))y({directory:p,key:D})&&w({directory:p,key:D},_);e.onChange()}catch(C){if(h)return;R(p,C),$(p)}}const c=new Set;function b(p){c.has(p)||(c.add(p),o(()=>{c.delete(p),f(p)}))}return{snapshot:p=>a.get(Ae(p))??{loading:!1},enabled:p=>l.get(p)??!0,forge:p=>i.get(p),show(p){if(p.key!==Ko)for(const[v,C]of s)v===p.directory||!C.delete(p.key)||(a.delete(Ae({directory:v,key:p.key})),u&&Jt(u,{directory:v,key:p.key})&&(u=void 0),b(v));const S=s.get(p.directory)??new Set;s.set(p.directory,S),S.add(p.key),u=p,b(p.directory)},hide(p){u&&Jt(u,p)&&(u=void 0),b(p.directory)},async refresh(p){const S=Ae(p);a.set(S,{...a.get(S)??{},loading:!0}),e.onChange();try{const v=await e.refresh(p.directory,p.key);if(h)return;l.set(p.directory,v.enabled),v.forge&&i.set(p.directory,v.forge),w(p,v.snapshot),e.onChange()}catch(v){if(h)return;R(p.directory,v)}},heartbeat(){for(const p of s.keys())f(p)},receive(p,S,v){y({directory:p,key:S})&&(w({directory:p,key:S},v),e.onChange())},hasShown:p=>[...s.values()].some(S=>S.has(p)),dispose(){h=!0;for(const p of I.values())n(p);for(const p of s.keys())e.release(p,e.clientID).catch(()=>{})}}}const Ue=e=>({location:{directory:e}}),Yo=async(e,t)=>await e.feedback({},Ue(t));function Xo(e){let t,r=0;const n=new Map;let o;return{get client(){return t?.client},connect(a){t?.dispose(),t=es(a,{...e,clientID:`${e.clientID}:${++r}`});for(const s of n.values())t.client.show(s),t.client.hide(s);o&&t.client.show(o),e.onChange()},show(a){n.set(a.key,a),o=a,t?.client.show(a)},hide(a){o?.key===a.key&&o.directory===a.directory&&(o=void 0),t?.client.hide(a)},dispose(){t?.dispose(),t=void 0}}}function Zo(e){const t=new Map;let r=0;const n=async o=>{const a=(t.get(o)??0)+1;t.set(o,a);const s=r,l=()=>s===r&&t.get(o)===a;try{const i=await e.load(o);return l()&&e.changed(o,i),i}catch(i){l()&&e.failed(o,Re(i));return}};return{reload:n,has:o=>t.has(o),refresh:()=>Promise.all([...t.keys()].map(n)),invalidate(){r++}}}function es(e,t){const r=e,n=Jo({clientID:t.clientID,watch:async(s,l)=>await r.watch(l,Ue(s)),refresh:async(s,l)=>await r.refresh({key:l},Ue(s)),release:(s,l)=>r.release({clientID:l},Ue(s)),onChange:t.onChange}),o=setInterval(()=>{n.heartbeat(),t.heartbeat?.()},kr),a=e.events.on("status",s=>{const{directory:l,key:i,snapshot:u}=s.data;n.receive(l,i,u)});return{client:n,dispose(){clearInterval(o),a(),n.dispose()}}}const ts=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,ot=e=>new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(e),rs=e=>e.kind==="review-request",ns=e=>e.kind==="approval",Er=e=>e.kind==="merge-blocked";function _r(e){return e.canAct!==void 0?e.canAct:e.humanApprovalOnly?!1:ns(e)?e.approverKind!=="human"&&!!e.automationAllowed:Er(e)?(e.mergeBlocker??"threads")==="threads":!(e.kind&&e.kind!=="ci-failed")}const Be=e=>Er(e)&&(e.mergeBlocker??"threads")==="threads"&&_r(e),os=e=>rs(e)?`Requested: ${ot(e.postedAt??e.at)}`:e.postedAt===void 0?`Detected: ${ot(e.at)}`:`Latest comment: ${ot(e.postedAt)}`;function ss(e){const t=e.totalThreads===1?"thread":"threads",r=`${e.resolvedThreads} of ${e.totalThreads} ${t} resolved`;if(!e.standaloneComments)return r;const n=e.standaloneComments===1?"comment":"comments";return`${r} · ${e.standaloneComments} ${n}`}function is(e){return[...e].sort((t,r)=>+!!t.waitingForReviewer-+!!r.waitingForReviewer)}const mt=(e,t)=>t?e.items.filter(r=>r.sessionID===t):[];function as(e,t){const r=mt(e,t).filter(n=>!n.read&&!n.waitingForReviewer).length;if(r!==0)return`📥 ${r}${e.paused?" (paused)":""}`}function ls(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 us(e){const t=ls(e),r=t.filter(o=>o!==e.url),n=e.kind==="ci-failed";return[...r.map((o,a)=>({title:e.kind==="issue-outdated"?"Issue":`${n?"Failed job":"Comment"} ${r.length>1?`${a+1} of ${r.length} `:""}(${n?new URL(o).pathname.split("/").filter(Boolean).slice(-2).join("/"):new URL(o).hash||"no anchor"})`,description:o,value:o})),...t.includes(e.url)?[{title:`${se(zo(e.url)?.ref.forge)} overview`,description:e.url,value:e.url}]:[]]}function xe(e,t){const r=e?.lookup,n=e?.forge??r?.forge??(r?.kind==="found"?Dt([...r.requests.map(o=>o.forge),...(r.failed??[]).map(o=>Wo(o.url)?.forge)]):void 0);switch(n){case"gitlab":case"github":return n;case"mixed":return;default:return t}}function Ar(e,t){return e.some(r=>r.url===t&&Be(r))}const cs=new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SCHEDULED","WAITING_FOR_CALLBACK","CANCELING"]);function Pt(e){return e?e.status==="FAILED"?"error":e.status==="SUCCESS"?e.label.includes("warning")?"warning":"success":cs.has(e.status)?"warning":"muted":"muted"}const Dr=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ds=e=>e.charAt(0).toUpperCase()+e.slice(1),ps={success:"CI ✓",error:"CI ✗",warning:"CI …"};function fs(e){return`${e.unresolvedThreads}${e.threadsComplete?"":"+"} unresolved thread${e.unresolvedThreads===1&&e.threadsComplete?"":"s"}`}const st=e=>({text:Ke(e),tone:"muted",url:e.url,essential:!0});function gs(e){const t=Pt(e.pipeline);return e.pipeline?{text:`CI ${e.pipeline.label}`,compact:ps[t],tone:t,url:e.pipeline.url}:{text:`no ${ce(e).ci}`,compact:"no CI",tone:t}}function hs(e){const t=Ho(e.map(c=>c.forge)),r=e.length===1?`1 ${se(t)}`:`${e.length} ${Ye(t)}`,n=e.filter(c=>c.state==="opened"),o=[{text:r,tone:"muted",essential:!0}],a=n.filter(c=>Xe(c)?.state==="running").length;a&&o.push({text:`🤖 ${a} reviewing`,compact:`🤖 ${a}`,tone:"warning",essential:!0});const s=n.filter(c=>Pt(c.pipeline)==="error").length;s&&o.push({text:`${s} CI failed`,compact:`CI ✗ ${s}`,tone:"error"});const l=n.filter(c=>c.conflicts).length;l&&o.push({text:Dr(l,"conflict"),tone:"error",essential:!0});const i=n.map(lr),u=i.filter(c=>c==="threads").length,h=i.filter(c=>c&&c!=="threads").length,y=n.map(c=>ce(c).readyToMergeState?.(c)).filter(c=>c!==void 0&&c!=="none"),w=y.filter(c=>c==="merge").length,R=y.filter(c=>c==="maintainer-merge").length,k=y.filter(c=>c==="auto-merge").length;u&&o.push({text:`${u} ${u===1?"needs":"need"} threads resolved`,compact:`${u} resolve threads`,tone:"warning",essential:!0}),w&&o.push({text:`${w} ready to merge`,tone:"warning",essential:!0}),R&&o.push({text:`${R} ${R===1?"needs":"need"} maintainer merge`,tone:"warning",essential:!0}),k&&o.push({text:`${k} ${k===1?"needs":"need"} auto-merge`,tone:"warning",essential:!0}),h&&o.push({text:`${h} merge blocked`,compact:`${h} blocked`,tone:"warning"});const I=n.filter(c=>c.approved&&c.awaitingReviewers.length===0).length;I&&o.push({text:`${I} approved`,tone:"success"});const $=e.filter(c=>c.state==="merged").length;$&&o.push({text:`${$} merged`,tone:"success"});const f=e.length-n.length-$;return f&&o.push({text:`${f} closed`,tone:"muted"}),o}function ms(e,t){const{lookup:r,error:n}=e,o=n?[{text:"stale",tone:"warning",essential:!0}]:[];if(!r||r.kind==="none"||r.requests.length===0){const h=se(xe(e,t));return e.targeted&&(n||r?.explicitTarget)?[{text:`${h} status unavailable`,tone:"warning"}]:[]}r.failed?.length&&o.unshift({text:`${r.failed.length} unavailable`,tone:"warning",essential:!0});const a=r.requests;if(r.explicitTarget&&a.length>1)return[...hs(a),...o];if(a.length>1){const h=ce(a[0]).noun;return[...a.map(st),{text:`${Dr(a.length,`open ${h}`)}, run /${h.toLowerCase()}-status`,tone:"warning"},...o]}const[s]=a;if(s.state!=="opened")return[st(s),{text:s.state,tone:s.state==="merged"?"success":"muted",essential:!0},...o];const l=[st(s),gs(s)],i=yt(s);if(i&&l.push(i),s.unresolvedThreads>0||!s.threadsComplete){const h=fs(s);l.push({text:h,compact:h.replace("unresolved ",""),tone:"warning"})}Xe(s)?.state==="running"&&l.push({text:"🤖 reviewing",compact:"🤖",tone:"warning",essential:!0}),l.push(...ce(s).indicators(s)),s.conflicts&&l.push({text:"conflicts",tone:"error",essential:!0}),s.conflictsKnown||l.push({text:"mergeability unknown",tone:"muted"});const u=ce(s).reviewIndicators;return u?l.push(...u(s)):s.awaitingReviewers.length?l.push({text:rr(s.awaitingReviewers),tone:"muted"}):s.approved&&l.push({text:"approved",tone:"success"}),[...l,...o]}const Yt=e=>new Date(e).toLocaleTimeString();function vs(e,t,r){const n=ce(e),o=yt(e,{canReviewThreads:r?Ar(r,e.url):!1}),a=[`${Ke(e)} ${e.title}${e.state==="opened"?"":` (${e.state})`}`,...o?[`Next step: ${o.detail}`]:[],`Target: ${e.targetProject} → ${e.targetBranch}`,`${ds(n.ci)}: ${e.pipeline?e.pipeline.label:"none"}${e.pipeline?.url?` (${e.pipeline.url})`:""}`,`Unresolved threads: ${e.unresolvedThreads}${e.threadsComplete?"":"+"}`,`Draft: ${Ce(e.draft)} · Conflicts: ${e.conflictsKnown?Ce(e.conflicts):"unknown"}`,...n.details(e)],s=Xe(e);return s&&a.push(`${s.name} review: ${s.label}`),e.awaitingReviewers.length&&a.push(`Awaiting review: ${e.awaitingReviewers.map(l=>`@${l}`).join(", ")}`),e.reviewersComplete||a.push("Reviewer list is partial"),t&&e.headSha&&t!==e.headSha&&a.push(`Local HEAD differs from the ${n.noun} head commit (unpushed or not fetched)`),a.push(e.url),a}function ws(e,t,r){const{lookup:n,error:o,fetchedAt:a}=e,s=se(xe(e,t)),l=[];if(!n)l.push(o?`Could not look up the ${s}.`:"No data yet.");else if(n.kind==="none")l.push(`No ${s} lookup: ${n.reason}.`);else{const{repository:i,sessionTarget:u,requests:h}=n;if(i){const y=i.branch===i.sourceBranch?i.branch:`${i.branch} (pushes to ${i.sourceBranch})`;l.push(`Branch: ${y} in ${i.source.path}`),h.length===0&&l.push("",`No open ${s} for this branch.`)}else u&&l.push(`Session target: ${u}`);for(const{url:y,reason:w}of n.failed??[])l.push(`Unavailable: ${y} (${w})`);for(const y of ur(h))l.push("",...vs(y,i?.head??"",r))}return o&&l.push("",`Last refresh failed at ${Yt(o.at)}: ${o.message}`),a!==void 0&&l.push("",`Last fetched: ${Yt(a)}`),l.join(`
|
|
266
|
+
`)}async function bs(e,t,r){const n=new Array(e.length);let o=0;const a=async()=>{for(;o<e.length;){const s=o++;n[s]=await r(e[s])}};return await Promise.all(Array.from({length:Math.min(t,e.length)},a)),n}function $s(e){const t=e.lookup;return t?.kind==="found"&&t.explicitTarget===!0&&t.requests.length>0&&!t.failed?.length&&t.requests.every(r=>r.state==="merged")}function vt(e){if(e.lookup?.cleanupReady)return e.lookup.cleanupReady;if(!$s(e)||e.lookup?.kind!=="found")return;const t=e.lookup.requests,r=Dt(t.map(n=>n.forge));return{kind:"merged-requests",reason:t.length===1?`${se(r)} merged`:`All ${Ye(r)} merged`}}function ys(e){const t=e.targets.map(o=>o.reference).join(", "),r=e.reason==="merged-requests"?"merged":"closed",n=t?`${t} ${r}`:r;return e.pendingFeedback<=0?n:`${n} · ${e.pendingFeedback} review update${e.pendingFeedback===1?"":"s"}`}function Ss(e){const r=e.replace(/\/+$/,"").split("/").filter(Boolean);return r[r.length-1]??e}function Xt(e,t="scan",r){const n=Ye(r);if(!e)return t==="cleanup"?"Verifying and archiving sessions…":`Checking sessions for merged ${n} and closed issues…`;const o=e.total>0?` (${e.checked}/${e.total})`:"";switch(e.phase){case"sessions":return`Scanning project sessions…${e.checked>0?` (${e.checked} found)`:""}`;case"targets":return`Checking ${n} and tracked issues…${o}`;case"verifying":return`Verifying target status before archiving…${o}`;case"archiving":return`Archiving sessions…${o}`}}function Rs(e){const t=new Map;for(const r of e)t.set(r.reason,(t.get(r.reason)??0)+1);return[...t.entries()].map(([r,n])=>n===1?r:`${r} (${n} sessions)`).join("; ")}function Cs(e,t,r,n){const o=ms(e,n),a=vt(e),s=!o.length&&a?.kind==="closed-issues";if(!o.length&&!t&&!s)return;const l=se(xe(e,n)),i=o.findIndex(w=>!w.essential||!w.url),u=i<0?o.length:Math.max(1,i),h=e.lookup?.kind==="found"&&e.lookup.requests.length===1?e.lookup.requests[0].awaitingReviewers:void 0,y=[...o.map(w=>w.tone),...s?["success"]:[]];return{icon:"review",label:[...o.map((w,R)=>({segment:w,priority:R<u?-1:Is(w)})).sort((w,R)=>w.priority-R.priority).map(({segment:w})=>ks(w,h)),...s?[`✓ ${a.reason}`]:[],t?.replace(/^(\d+) review updates?/,"📥 $1")].filter(Boolean).join(" · "),tone:Es(y),title:`${l} status`,rows:[...o.map((w,R)=>{let k;return w.tone==="success"||w.tone==="warning"?k=w.tone:w.tone==="error"&&(k="danger"),{id:`segment-${R}`,label:w.text.startsWith("awaiting ")&&h?.length?`awaiting ${h.map(I=>`@${I}`).join(", ")}`:w.text,...w.url?{icon:"outline-arrow-up-right"}:{},...k?{tone:k}:{},...w.url?{run:()=>r.external(w.url)}:{}}}),{id:"details",label:`Show ${l} status`,icon:"status",run:r.status},...t?[{id:"feedback",label:t,icon:"comment",run:r.feedback}]:[],...a&&r.cleanup?[{id:"cleanup",label:`${a.reason} · /forge-cleanup`,icon:"archive",tone:"success",run:r.cleanup}]:[]]}}function Is(e){return e.text==="mergeability unknown"?4:e.tone==="error"?0:/unresolved threads?$/.test(e.text)?1:e.tone==="warning"?2:3}function ks(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 Es(e){if(e.includes("error"))return"danger";if(e.includes("warning"))return"warning";if(e.includes("success"))return"success"}function _s(e,t){const{sessionID:r}=e;r&&!t.hasShown(r)||(r&&e.variant==="info"&&e.openTab!==!1&&t.openTab(r),t.toast({...e.title?{title:e.title}:{},message:e.message,variant:e.variant}))}var As=d.template("<a><b>"),Ds=d.template("<div><span class=fk-label>: "),Ps=d.template("<b>"),Ns=d.template("<div class=fk-warning>Reviewer list is partial"),xs=d.template("<div class=fk-warning>Local HEAD differs from the <!> head commit (unpushed or not fetched)"),Ts=d.template("<div class=fk-card><a><b> </b></a><section></section><section><b>Review and approval"),it=d.template("<div>"),Ms=d.template("<div class=forgekeeper-panel><header><h2> status</h2><div class=fk-actions>"),qs=d.template("<div> status is off."),Ls=d.template("<div class=fk-success><b>✓ </b> — ready to archive with /forge-cleanup."),js=d.template("<div class=fk-muted>No <!> status available."),Os=d.template("<div class=fk-muted>Last fetched: "),Us=d.template("<section>"),Bs=d.template('<div class="fk-warning fk-pre"><b>Unavailable'),Fs=d.template('<div class="fk-error fk-pre"><b>Last refresh failed at '),Gs=d.template("<div class=fk-card><b></b><div class=fk-muted></div><section></section><div class=fk-actions>"),Hs=d.template("<a>"),Ws=d.template("<div class=forgekeeper-panel><header><h2>Review updates"),zs=d.template("<div class=fk-error>Could not load review updates: <!>. Retrying automatically."),at=d.template("<div class=fk-muted>"),Vs=d.template("<div class=fk-cleanup-row><div class=fk-cleanup-main><div class=fk-cleanup-title></div><div class=fk-cleanup-meta>"),Qs=d.template("<div class=fk-warning>"),Ks=d.template("<div class=fk-cleanup-list>"),Js=d.template("<div class=fk-cleanup-dialog>"),Ys=d.template("<div class=fk-cleanup-footer>"),Xs=d.template("<div class=fk-error>"),Zs=d.template("<div class=fk-cleanup-group>");const ei=`
|
|
267
267
|
.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); }
|
|
268
268
|
.forgekeeper-panel header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
269
269
|
.forgekeeper-panel h2 { font-size: 13px; font-weight: 600; margin: 0; }
|
|
@@ -287,7 +287,7 @@ ${r}
|
|
|
287
287
|
.fk-cleanup-title:hover { text-decoration: underline; }
|
|
288
288
|
.fk-cleanup-meta { font-size: 12px; color: var(--v2-text-text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
289
289
|
.fk-cleanup-footer { display: flex; align-items: center; gap: 8px; }
|
|
290
|
-
`,
|
|
291
|
-
${
|
|
292
|
-
${
|
|
293
|
-
${j().message}`,null),Z})()}),d.createComponent(A.Show,{get when(){return k().fetchedAt!==void 0},get children(){var j=qs();return j.firstChild,d.insert(j,()=>new Date(k().fetchedAt).toLocaleTimeString(),null),j}})]})]}}),null),T})()}async function Re(g,m,k){try{await t()[m](k,r(g)),await h(g)}catch(x){e.toast.show({title:x instanceof Error?x.message:String(x),variant:"error"})}}function Ce(g){const m=()=>g.item,k=()=>[m().read?"Read":"Unread",rs(m()),m().automation?`${m().automation.state}${m().automation.reason?`: ${m().automation.reason}`:""}`:void 0].filter(Boolean).join(" · "),x=(P,q={})=>Re(g.directory,P,{id:m().id,...q});return(()=>{var P=Os(),q=P.firstChild,Q=q.nextSibling,L=Q.nextSibling,M=L.nextSibling;return d.insert(q,(()=>{var V=d.memo(()=>!!Ue(m()));return()=>V()?`🚧 ${m().title}`:m().title})()),d.insert(Q,k),d.insert(P,d.createComponent(A.For,{get each(){return m().details??[]},children:V=>(()=>{var T=st();return d.insert(T,V),T})()}),L),d.insert(L,d.createComponent(A.For,{get each(){return ss(m())},children:V=>(()=>{var T=Us();return T.$$click=()=>e.system.openExternal(V.value),d.insert(T,()=>V.title),T})()})),d.insert(M,d.createComponent(te.Button,{size:"small",onClick:()=>{x("summarizeFeedback")},children:"Summarize in session"}),null),d.insert(M,d.createComponent(A.Show,{get when(){return Er(m())},get children(){return[d.createComponent(te.Button,{size:"small",onClick:()=>{x("actOnFeedback")},get children(){return Ue(m())?"Review blocking threads":"Act on feedback"}}),d.createComponent(te.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 x("actOnFeedback",{retry:!0})},children:"Retry"})]}}),null),d.insert(M,d.createComponent(te.Button,{size:"small",onClick:()=>{x("acknowledgeFeedback")},children:"Acknowledge"}),null),d.effect(()=>d.className(q,at(Ue(m())?"warning":void 0))),P})()}function xe(g){const m=()=>E(g.session),k=()=>p(m()),x=A.createMemo(()=>ht(k(),g.session.id));return(()=>{var P=Bs(),q=P.firstChild,Q=q.firstChild;return Q.firstChild,d.insert(Q,()=>k().paused?" (monitoring paused)":"",null),d.insert(q,d.createComponent(te.Button,{size:"small",get disabled(){return!x().some(L=>!L.read)},onClick:()=>{Re(m(),"markFeedbackRead",{ids:x().map(L=>L.id)})},children:"Mark all as read"}),null),d.insert(q,d.createComponent(te.Button,{size:"small",onClick:()=>{Re(m(),"pauseFeedback",{paused:!k().paused})},get children(){return k().paused?"Enable feedback inbox":"Pause monitoring"}}),null),d.insert(P,d.createComponent(A.Show,{get when(){return l[m()]},children:L=>(()=>{var M=Fs(),V=M.firstChild,T=V.nextSibling;return T.nextSibling,d.insert(M,L,T),M})()}),null),d.insert(P,d.createComponent(A.Show,{get when(){return x().length},get fallback(){return d.createComponent(A.Show,{get when(){return!l[m()]},get children(){var L=it();return d.insert(L,()=>a[m()]?"No pending review updates for this session.":"Loading review updates…"),L}})},get children(){return d.createComponent(A.For,{get each(){return x()},children:L=>d.createComponent(Ce,{item:L,get directory(){return m()}})})}}),null),P})()}function Ze(g){const[m,k]=A.createSignal(!0),[x,P]=A.createSignal(),[q,Q]=A.createSignal(),[L,M]=A.createSignal(),[V,T]=A.createSignal({enabled:!0,candidates:[],skippedErrors:0});let X="",ee;const $e=t().events.on("cleanupProgress",O=>{const H=O.data;H.scanID===X&&M(H)});A.onCleanup(()=>{ee?.abort(),$e()});const ue=async()=>{ee?.abort();const O=new AbortController;ee=O;const H=Yt();X=H,M(void 0),k(!0),Q(void 0);try{const K=await t().cleanupCandidates({scanID:H},{...r(g.directory),signal:O.signal});O.signal.aborted||T(K)}catch(K){O.signal.aborted||Q(K instanceof Error?K.message:String(K))}finally{ee===O&&k(!1)}};ue();const U=()=>V().candidates,j=A.createMemo(()=>new Set(e.tabs.list().flatMap(O=>O.session&&R(O.session)?[O.session.id]:[]))),Z=A.createMemo(()=>{const O=U(),H=[...new Set(O.map(ne=>ne.directory))],K=H.length>1;return H.map(ne=>({directory:ne,label:K?vs(ne):void 0,items:O.filter(le=>le.directory===ne)}))}),de=async(O,H)=>{if(x())return;const K=Yt();X=K,M(void 0),P(H);try{const ne=await B(g.directory,O,K,M),le=[...ne?.archived??[],...ne?.alreadyArchived??[]];if(le.length){const et=new Set(le),Ee=U().filter(tt=>!et.has(tt.sessionID));T(tt=>({...tt,candidates:Ee})),Ee.length===0&&g.close()}}finally{P(void 0),M(void 0)}},Te=A.createMemo(()=>c(g.directory)),Dr=A.createMemo(()=>oe(Te())),Pt=A.createMemo(()=>Je(Te())),Pr=()=>m()?Jt(L(),"scan",Te()):V().enabled?`No sessions with all ${Pt()} merged or tracked issues closed.`:`${Dr()} status is off. Enable options.status in opencode.json to use this command.`,Nr=O=>{const H=()=>{const K=[ws(O)];return j().has(O.sessionID)&&K.push("open tab"),K.join(" · ")};return(()=>{var K=Gs(),ne=K.firstChild,le=ne.firstChild,et=le.nextSibling;return le.$$click=()=>{const Ee=_()?.id;Ee&&(g.close(),e.tabs.open({server:Ee,id:O.sessionID},{focus:!0}))},d.insert(le,()=>O.title),d.insert(et,H),d.insert(K,d.createComponent(te.Button,{size:"small",icon:"archive",get busy(){return x()===O.sessionID},get disabled(){return m()||x()!==void 0},onClick:()=>{de([O.sessionID],O.sessionID)},children:"Clean up"}),null),K})()};return d.createComponent(te.Dialog,{title:"Clean up finished sessions",get description(){return`Archive idle sessions whose ${Pt()} have merged or tracked issues have closed, and close their open tabs.`},size:"large",get footer(){return(()=>{var O=Vs();return d.insert(O,d.createComponent(te.Button,{size:"small",icon:"refresh",get busy(){return m()},get disabled(){return x()!==void 0},onClick:()=>{ue()},children:"Refresh"}),null),d.insert(O,d.createComponent(A.Show,{get when(){return U().length>0},get children(){return d.createComponent(te.Button,{size:"small",variant:"contrast",icon:"archive",get busy(){return x()==="all"},get disabled(){return m()||x()!==void 0},onClick:()=>{de(U().map(H=>H.sessionID),"all")},get children(){return`Clean up all (${U().length})`}})}}),null),O})()},get children(){var O=zs();return d.insert(O,d.createComponent(A.Show,{get when(){return q()},children:H=>(()=>{var K=Qs();return d.insert(K,H),K})()}),null),d.insert(O,d.createComponent(A.Show,{get when(){return V().skippedErrors>0},get children(){var H=Hs();return d.insert(H,()=>`Skipped ${V().skippedErrors} session${V().skippedErrors===1?"":"s"} whose target status could not be verified.`),H}}),null),d.insert(O,d.createComponent(A.Show,{get when(){return d.memo(()=>x()!==void 0)()&&L()},get children(){var H=it();return d.insert(H,()=>Jt(L(),"cleanup",Te())),H}}),null),d.insert(O,d.createComponent(A.Show,{get when(){return d.memo(()=>!m())()&&U().length>0},get fallback(){return d.createComponent(A.Show,{get when(){return!q()},get children(){var H=it();return d.insert(H,Pr),H}})},get children(){var H=Ws();return d.insert(H,d.createComponent(A.For,{get each(){return Z()},children:K=>[d.createComponent(A.Show,{get when(){return K.label},children:ne=>(()=>{var le=Ks();return d.insert(le,ne),le})()}),d.createComponent(A.For,{get each(){return K.items},children:ne=>Nr(ne)})]})),H}}),null),O}})}const fe=(g,m)=>({id:g,title:m,closable:"hover"}),Y={github:fe(me,"PR status"),gitlab:fe(me,"MR status"),mixed:fe(me,"PR/MR status")},Ie=g=>{if(!R(g))return Y.mixed;const m=b(I(g));return m?Y[m]:Y.mixed},Ar=fe(Ae,"Review updates");e.add(ae.Panel,{id:me,region:"side",width:420,list:g=>g.open.includes(me)?[Ie(g.session)]:[],render:g=>d.createComponent(re,{get session(){return g.session}})}),e.add(ae.Panel,{id:Ae,region:"side",width:420,list:g=>g.open.includes(Ae)?[Ar]:[],render:g=>d.createComponent(xe,{get session(){return g.session}})});const Dt=()=>{const g=w();return g?b(I(g)):void 0};return e.add(ae.Command,()=>({id:"status",title:`Show ${oe(Dt())} status`,keywords:"PR MR pull request merge request",group:"Forge",slash:{name:"forge-status"},enabled:!!w(),run:()=>{const g=w();if(!g)return;const m=I(g);D(m.directory,b(m))||(v()?.refresh(m),C(me,g))}})),e.add(ae.Command,()=>({id:"feedback",title:"Show pending review feedback",group:"Forge",slash:{name:"forge-feedback"},enabled:!!w(),run:()=>{const g=w();g&&(h(E(g)),C(Ae,g))}})),e.add(ae.Command,()=>({id:"open",title:`Open ${oe(Dt())} in browser`,keywords:"PR MR pull request merge request",group:"Forge",slash:{name:"forge-open"},enabled:!!w(),run:async()=>{const g=w();if(!g)return;const m=I(g);if(D(m.directory,b(m)))return;let k=y(m);if(k.length===0&&(await v()?.refresh(m),k=y(m)),k.length===0){e.toast.show({title:`No ${oe(b(m))} for this session`});return}const x=_t(k.map(q=>q.forge)),P=k.length===1?k[0].url:await e.dialogs.select({title:`Open ${oe(x)}`,options:k.map(q=>({title:`${Qe(q)} ${q.title}`,description:q.targetProject,value:q.url}))});P&&e.system.openExternal(P)}})),e.add(ae.Command,()=>({id:"cleanup",title:"Clean up finished sessions",group:"Forge",slash:{name:"forge-cleanup"},enabled:!!_()&&!!W(),run:()=>ie()})),ae.createKeyed(()=>e.client,()=>{const g=t();u.invalidate(),S.connect(g),u.refresh();const m=[g.events.on("sessionsCleanedUp",k=>{const{sessionIDs:x,archive:P}=k.data;if(G(x),P)for(const q of x)e.client.session.update({sessionID:q,archived:!0}).catch(()=>{})}),g.events.on("feedbackChanged",k=>{const{directory:x}=k.data;u.has(x)&&h(x)}),g.events.on("notice",k=>{const x=k.data;Cs(x,{hasShown:P=>!!v()?.hasShown(P)||!!k.location?.directory&&u.has(k.location.directory),openTab:P=>{const q=_()?.id;q&&e.tabs.open({server:q,id:P})},toast:({title:P,message:q,variant:Q})=>{const L=_()?.id,M=x.sessionID;e.toast.show({title:P??q,...P?{description:q}:{},variant:Q==="error"?"error":"default",...L&&M?{actions:[{label:"Open session",run:()=>e.tabs.open({server:L,id:M},{focus:!0})}]}:{}}),e.attention.notify({title:P??"Forgekeeper",message:q,variant:Q==="error"?"error":"default",...L&&M?{session:{server:L,id:M}}:{},id:`forgekeeper:${M??""}:${P??""}:${q}`})}})})];A.onCleanup(()=>{for(const k of m)k();u.invalidate(),S.dispose()})}),()=>{u.invalidate(),S.dispose()}}});d.delegateEvents(["click"]);exports.default=Zs;
|
|
290
|
+
`,ve="status",De="feedback",ti={items:[],paused:!1};let ri=0;const Zt=()=>`gui-cleanup-${Date.now()}-${++ri}`;function lt(e){switch(e){case"success":return"fk-success";case"warning":return"fk-warning";case"error":return"fk-error";case"muted":return"fk-muted";default:return}}const ni=le.Plugin.define({setup(e){e.add(le.Style,ei);const t=()=>e.client.rpc(Qo),r=g=>({location:{directory:g}}),[n,o]=A.createSignal(0),[a,s]=Tt.createStore({}),[l,i]=Tt.createStore({}),u=Zo({load:g=>Yo(t(),g),changed:(g,m)=>{s(g,m),i(g,void 0)},failed:(g,m)=>i(g,m)}),h=u.reload,y=Xo({clientID:ts(),onChange:()=>o(g=>g+1),heartbeat:()=>{u.refresh()}}),w=()=>y.client,R=g=>g.server.builtin,k=g=>g.location?.directory??g.directory,I=g=>({directory:k(g),key:g.id}),$=g=>(n(),w()?.snapshot(g)??{loading:!1}),f=g=>(n(),w()?.enabled(g)??!0),c=g=>(n(),w()?.forge(g)),b=g=>xe($(g),c(g.directory)),p=g=>a[g]??ti,S=g=>{const m=$(g).lookup;return m?.kind==="found"?m.requests:[]},v=()=>{const g=e.sessions.current();return g&&R(g)?g:void 0};le.createKeyed(()=>{const g=v();return g?JSON.stringify([k(g),g.id]):void 0},g=>{const[m,E]=JSON.parse(g),M={directory:m,key:E};y.show(M),h(m),A.onCleanup(()=>y.hide(M))});const C=(g,m=v())=>{m&&e.layout.open(`${e.id}:${g}`,m,{tab:"select"})},D=(g,m=c(g))=>f(g)?!1:(e.toast.show({title:`${se(m)} status is off in the plugin's options (status: false)`}),!0),_=()=>e.servers.list().map(g=>e.servers.get(g)).find(g=>g?.builtin);function H(g){if(!g.length)return;const m=new Set(g);for(const E of e.tabs.list())E.session&&R(E.session)&&m.has(E.session.id)&&e.tabs.close(E.key)}async function O(g,m,E,M){try{const N=[],q=[],z=[];for(let P=0;P<m.length;P+=500){const G=m.slice(P,P+500),x=await t().cleanupSessions({sessionIDs:G,...E?{scanID:E}:{},allowClientArchive:!0},r(g));N.push(...x.archived),q.push(...x.alreadyArchived),z.push(...x.failed);const V=x.needsClientArchive??[];if(V.length>0){let Z=0;const ge=V.length;M?.({phase:"archiving",checked:0,total:ge});const ne=[];if(await bs(V,8,async j=>{try{await e.client.session.update({sessionID:j,archived:!0}),ne.push(j)}catch(U){z.push({sessionID:j,reason:Re(U)})}finally{Z++,M?.({phase:"archiving",checked:Z,total:ge})}}),ne.length>0){const j=await t().cleanupSessions({sessionIDs:ne,...E?{scanID:E}:{},finalizeArchived:!0},r(g));N.push(...j.archived),q.push(...j.alreadyArchived),z.push(...j.failed)}}}const F={archived:N,alreadyArchived:q,failed:z};if(H([...F.archived,...F.alreadyArchived]),F.archived.length>0){const P=F.archived.length;e.toast.show({title:P===1?"Archived 1 session and closed its tab.":`Archived ${P} sessions and closed their tabs.`})}else if(F.alreadyArchived.length>0&&F.failed.length===0){const P=F.alreadyArchived.length;e.toast.show({title:P===1?"Session was already archived.":`${P} sessions were already archived.`})}return F.failed.length>0&&e.toast.show({title:Rs(F.failed),variant:"error"}),F}catch(N){e.toast.show({title:Re(N),variant:"error"});return}}const Q=g=>g??(v()?k(v()):void 0)??e.tabs.list().find(m=>m.session&&R(m.session)&&m.session.location?.directory)?.session?.location?.directory;function ae(g){const m=Q(g);if(!m){e.toast.show({title:"Open a project session to run /forge-cleanup."});return}D(m)||e.dialogs.open(E=>d.createComponent(et,{directory:m,get close(){return E.close}}))}e.add(le.ComposerPill,{id:"status",show:g=>Ze(g.session)});function Ze(g){if(!R(g))return;const m=I(g);if(!f(m.directory))return;const E=as(p(m.directory),g.id);return Cs($(m),E,{external:M=>e.system.openExternal(M),status:()=>C(ve,g),feedback:()=>C(De,g),cleanup:()=>ae(m.directory)},c(m.directory))}const te=e.ui;e.add(le.Slot,{at:"session.header",render:g=>{const m=()=>{if(!R(g.session))return;const E=I(g.session);if(f(E.directory))return vt($(E))};return d.createComponent(A.Show,{get when(){return m()},children:E=>d.createComponent(te.Button,{size:"small",variant:"ghost",icon:"archive",onClick:()=>ae(k(g.session)),get children(){return d.memo(()=>!!g.compact)()?"Clean up":`${E().reason} · /forge-cleanup`}})})}});function K(g){return(()=>{var m=Ds(),E=m.firstChild,M=E.firstChild;return d.insert(E,()=>g.label,M),d.insert(m,d.createComponent(A.Show,{get when(){return g.url},get fallback(){return(()=>{var N=Ps();return d.insert(N,()=>g.value),d.effect(()=>d.className(N,lt(g.tone))),N})()},get children(){var N=As(),q=N.firstChild;return N.$$click=()=>e.system.openExternal(g.url),d.insert(q,()=>g.value),d.effect(()=>d.className(N,lt(g.tone))),N}}),null),m})()}function B(g){const m=()=>g.request,E=()=>ce(m()),M=()=>Xe(m());return(()=>{var N=Ts(),q=N.firstChild,z=q.firstChild,F=z.firstChild,P=q.nextSibling,G=P.nextSibling;return G.firstChild,q.$$click=()=>e.system.openExternal(m().url),d.insert(z,()=>Ke(m()),F),d.insert(z,()=>m().title,null),d.insert(N,d.createComponent(A.Show,{get when(){return yt(m(),{canReviewThreads:g.canReviewThreads})},children:x=>d.createComponent(K,{label:"Next step",get value(){return x().detail},get tone(){return x().tone},get url(){return x().url}})}),P),d.insert(P,d.createComponent(K,{label:"State",get value(){return m().state},get tone(){return m().state==="merged"?"success":void 0}}),null),d.insert(P,d.createComponent(K,{label:"Target",get value(){return`${m().targetProject} → ${m().targetBranch}`}}),null),d.insert(P,d.createComponent(K,{get label(){return E().ci.charAt(0).toUpperCase()+E().ci.slice(1)},get value(){return m().pipeline?.label??"none"},get tone(){return Pt(m().pipeline)},get url(){return m().pipeline?.url}}),null),d.insert(P,d.createComponent(K,{label:"Unresolved threads",get value(){return`${m().unresolvedThreads}${m().threadsComplete?"":"+"}`},get tone(){return m().unresolvedThreads||!m().threadsComplete?"warning":void 0}}),null),d.insert(P,d.createComponent(K,{label:"Draft",get value(){return Ce(m().draft)},get tone(){return m().draft?"warning":void 0}}),null),d.insert(P,d.createComponent(K,{label:"Conflicts",get value(){return d.memo(()=>!!m().conflictsKnown)()?Ce(m().conflicts):"unknown"},get tone(){return m().conflicts?"error":void 0}}),null),d.insert(G,d.createComponent(A.For,{get each(){return E().details(m())},children:x=>{const V=x.indexOf(": ");return V<0?(()=>{var Z=it();return d.insert(Z,x),Z})():d.createComponent(K,{get label(){return x.slice(0,V)},get value(){return x.slice(V+2)}})}}),null),d.insert(G,d.createComponent(A.Show,{get when(){return M()},children:x=>d.createComponent(K,{get label(){return`${x().name} review`},get value(){return x().label},get tone(){return x().state==="running"?"warning":void 0}})}),null),d.insert(G,d.createComponent(A.Show,{get when(){return m().awaitingReviewers.length},get children(){return d.createComponent(K,{label:"Awaiting review",get value(){return m().awaitingReviewers.map(x=>`@${x}`).join(", ")}})}}),null),d.insert(N,d.createComponent(A.Show,{get when(){return!m().reviewersComplete},get children(){return Ns()}}),null),d.insert(N,d.createComponent(A.Show,{get when(){return d.memo(()=>!!(g.head&&m().headSha))()&&g.head!==m().headSha},get children(){var x=xs(),V=x.firstChild,Z=V.nextSibling;return Z.nextSibling,d.insert(x,()=>E().noun,Z),x}}),null),N})()}function re(g){const m=A.createMemo(()=>I(g.session),void 0,{equals:(x,V)=>x.directory===V.directory&&x.key===V.key}),E=A.createMemo(()=>$(m())),M=A.createMemo(()=>mt(p(m().directory),g.session.id)),N=A.createMemo(()=>xe(E(),c(m().directory))),q=A.createMemo(()=>se(N())),z=A.createMemo(()=>vt(E())),[F,P]=A.createSignal(!1),G=()=>{const x=E().lookup;return x?.kind==="found"?x:void 0};return(()=>{var x=Ms(),V=x.firstChild,Z=V.firstChild,ge=Z.firstChild,ne=Z.nextSibling;return d.insert(Z,q,ge),d.insert(ne,d.createComponent(A.Show,{get when(){return z()},get children(){return d.createComponent(te.Button,{size:"small",icon:"archive",get busy(){return F()},onClick:async()=>{if(!F()){P(!0);try{await O(m().directory,[g.session.id])}finally{P(!1)}}},children:"Clean up session"})}}),null),d.insert(ne,d.createComponent(te.Button,{size:"small",icon:"refresh",get busy(){return E().loading},onClick:()=>{w()?.refresh(m())},children:"Refresh"}),null),d.insert(x,d.createComponent(A.Show,{get when(){return f(m().directory)},get fallback(){return(()=>{var j=qs(),U=j.firstChild;return d.insert(j,q,U),j})()},get children(){return[d.createComponent(A.Show,{get when(){return z()},children:j=>(()=>{var U=Ls(),ee=U.firstChild;return ee.firstChild,d.insert(ee,()=>j().reason,null),U})()}),d.createComponent(A.Show,{get when(){return G()},get fallback(){return(()=>{var j=it();return d.insert(j,()=>ws(E(),c(m().directory),M())),d.effect(()=>d.className(j,`fk-pre ${E().error?"fk-error":"fk-muted"}`)),j})()},children:j=>[d.createComponent(A.Show,{get when(){return j().repository},children:U=>(()=>{var ee=Us();return d.insert(ee,d.createComponent(K,{label:"Repository",get value(){return U().source.path}}),null),d.insert(ee,d.createComponent(K,{label:"Branch",get value(){return d.memo(()=>U().branch===U().sourceBranch)()?U().branch:`${U().branch} (pushes to ${U().sourceBranch})`}}),null),ee})()}),d.createComponent(A.Show,{get when(){return d.memo(()=>!j().repository)()&&j().sessionTarget},get children(){return d.createComponent(K,{label:"Session target",get value(){return j().sessionTarget}})}}),d.createComponent(A.For,{get each(){return j().failed??[]},children:U=>(()=>{var ee=Bs();return ee.firstChild,d.insert(ee,()=>`
|
|
291
|
+
${U.url}
|
|
292
|
+
${U.reason}`,null),ee})()}),d.createComponent(A.Show,{get when(){return j().requests.length===0},get children(){var U=js(),ee=U.firstChild,de=ee.nextSibling;return de.nextSibling,d.insert(U,q,de),U}}),d.createComponent(A.For,{get each(){return ur(j().requests)},children:U=>d.createComponent(B,{request:U,get head(){return j().repository?.head},get canReviewThreads(){return Ar(M(),U.url)}})}),d.createComponent(A.Show,{get when(){return E().error},children:U=>(()=>{var ee=Fs(),de=ee.firstChild;return de.firstChild,d.insert(de,()=>new Date(U().at).toLocaleTimeString(),null),d.insert(ee,()=>`
|
|
293
|
+
${U().message}`,null),ee})()}),d.createComponent(A.Show,{get when(){return E().fetchedAt!==void 0},get children(){var U=Os();return U.firstChild,d.insert(U,()=>new Date(E().fetchedAt).toLocaleTimeString(),null),U}})]})]}}),null),x})()}async function ye(g,m,E){try{await t()[m](E,r(g)),await h(g)}catch(M){e.toast.show({title:Re(M),variant:"error"})}}function Ie(g){const m=()=>g.item,E=()=>[m().waitingForReviewer?"Waiting for reviewer":void 0,m().read?"Read":"Unread",m().progress?ss(m().progress):void 0,os(m()),m().automation?`${m().automation.state}${m().automation.reason?`: ${m().automation.reason}`:""}`:void 0].filter(Boolean).join(" · "),M=(N,q={})=>ye(g.directory,N,{id:m().id,...q});return(()=>{var N=Gs(),q=N.firstChild,z=q.nextSibling,F=z.nextSibling,P=F.nextSibling;return d.insert(q,(()=>{var G=d.memo(()=>!!Be(m()));return()=>G()?`🚧 ${m().title}`:m().title})()),d.insert(z,E),d.insert(N,d.createComponent(A.For,{get each(){return m().details??[]},children:G=>(()=>{var x=it();return d.insert(x,G),x})()}),F),d.insert(F,d.createComponent(A.For,{get each(){return us(m())},children:G=>(()=>{var x=Hs();return x.$$click=()=>e.system.openExternal(G.value),d.insert(x,()=>G.title),x})()})),d.insert(P,d.createComponent(te.Button,{size:"small",onClick:()=>{M("summarizeFeedback")},children:"Summarize in session"}),null),d.insert(P,d.createComponent(A.Show,{get when(){return _r(m())},get children(){return[d.createComponent(te.Button,{size:"small",onClick:()=>{M("actOnFeedback")},get children(){return Be(m())?"Review blocking threads":"Act on feedback"}}),d.createComponent(te.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 M("actOnFeedback",{retry:!0})},children:"Retry"})]}}),null),d.insert(P,d.createComponent(te.Button,{size:"small",onClick:()=>{M("acknowledgeFeedback")},children:"Acknowledge"}),null),d.effect(()=>d.className(q,lt(Be(m())?"warning":void 0))),N})()}function Te(g){const m=()=>k(g.session),E=()=>p(m()),M=A.createMemo(()=>is(mt(E(),g.session.id))),N=A.createMemo(()=>M().filter(q=>q.read));return(()=>{var q=Ws(),z=q.firstChild,F=z.firstChild;return F.firstChild,d.insert(F,()=>E().paused?" (monitoring paused)":"",null),d.insert(z,d.createComponent(te.Button,{size:"small",get disabled(){return!M().some(P=>!P.read)},onClick:()=>{ye(m(),"markFeedbackRead",{ids:M().map(P=>P.id)})},children:"Mark all as read"}),null),d.insert(z,d.createComponent(A.Show,{get when(){return N().length>0},get children(){return d.createComponent(te.Button,{size:"small",onClick:async()=>{const P=N(),G=P.map(ne=>ne.id),x=P.filter(ne=>ne.automation?.state==="queued"||ne.automation?.state==="running").length,V=`${G.length} read update${G.length===1?"":"s"}`,Z=x>0?`This removes ${V} from the inbox, including ${x} with queued or running automation.`:`This removes ${V} from the inbox.`;await e.dialogs.confirm({title:`Acknowledge ${V}?`,description:Z,confirm:`Acknowledge read (${G.length})`,danger:x>0})&&await ye(m(),"acknowledgeFeedback",{ids:G})},get children(){return`Acknowledge read (${N().length})`}})}}),null),d.insert(z,d.createComponent(te.Button,{size:"small",onClick:()=>{ye(m(),"pauseFeedback",{paused:!E().paused})},get children(){return E().paused?"Enable feedback inbox":"Pause monitoring"}}),null),d.insert(q,d.createComponent(A.Show,{get when(){return l[m()]},children:P=>(()=>{var G=zs(),x=G.firstChild,V=x.nextSibling;return V.nextSibling,d.insert(G,P,V),G})()}),null),d.insert(q,d.createComponent(A.Show,{get when(){return M().length},get fallback(){return d.createComponent(A.Show,{get when(){return!l[m()]},get children(){var P=at();return d.insert(P,()=>a[m()]?"No pending review updates for this session.":"Loading review updates…"),P}})},get children(){return d.createComponent(A.For,{get each(){return M()},children:P=>d.createComponent(Ie,{item:P,get directory(){return m()}})})}}),null),q})()}function et(g){const[m,E]=A.createSignal(!0),[M,N]=A.createSignal(),[q,z]=A.createSignal(),[F,P]=A.createSignal(),[G,x]=A.createSignal({enabled:!0,candidates:[],skippedErrors:0});let V="",Z;const ge=t().events.on("cleanupProgress",L=>{const W=L.data;W.scanID===V&&P(W)});A.onCleanup(()=>{Z?.abort(),ge()});const ne=async()=>{Z?.abort();const L=new AbortController;Z=L;const W=Zt();V=W,P(void 0),E(!0),z(void 0);try{const Y=await t().cleanupCandidates({scanID:W},{...r(g.directory),signal:L.signal});L.signal.aborted||x(Y)}catch(Y){L.signal.aborted||z(Re(Y))}finally{Z===L&&E(!1)}};ne();const j=()=>G().candidates,U=A.createMemo(()=>new Set(e.tabs.list().flatMap(L=>L.session&&R(L.session)?[L.session.id]:[]))),ee=A.createMemo(()=>{const L=j(),W=[...new Set(L.map(oe=>oe.directory))],Y=W.length>1;return W.map(oe=>({directory:oe,label:Y?Ss(oe):void 0,items:L.filter(ue=>ue.directory===oe)}))}),de=async(L,W)=>{if(M())return;const Y=Zt();V=Y,P(void 0),N(W);try{const oe=await O(g.directory,L,Y,P),ue=[...oe?.archived??[],...oe?.alreadyArchived??[]];if(ue.length){const tt=new Set(ue),Ee=j().filter(rt=>!tt.has(rt.sessionID));x(rt=>({...rt,candidates:Ee})),Ee.length===0&&g.close()}}finally{N(void 0),P(void 0)}},Me=A.createMemo(()=>c(g.directory)),Nr=A.createMemo(()=>se(Me())),xt=A.createMemo(()=>Ye(Me())),xr=()=>m()?Xt(F(),"scan",Me()):G().enabled?`No sessions with all ${xt()} merged or tracked issues closed.`:`${Nr()} status is off. Enable options.status in opencode.json to use this command.`,Tr=L=>{const W=()=>{const Y=[ys(L)];return U().has(L.sessionID)&&Y.push("open tab"),Y.join(" · ")};return(()=>{var Y=Vs(),oe=Y.firstChild,ue=oe.firstChild,tt=ue.nextSibling;return ue.$$click=()=>{const Ee=_()?.id;Ee&&(g.close(),e.tabs.open({server:Ee,id:L.sessionID},{focus:!0}))},d.insert(ue,()=>L.title),d.insert(tt,W),d.insert(Y,d.createComponent(te.Button,{size:"small",icon:"archive",get busy(){return M()===L.sessionID},get disabled(){return m()||M()!==void 0},onClick:()=>{de([L.sessionID],L.sessionID)},children:"Clean up"}),null),Y})()};return d.createComponent(te.Dialog,{title:"Clean up finished sessions",get description(){return`Archive idle sessions whose ${xt()} have merged or tracked issues have closed, and close their open tabs.`},size:"large",get footer(){return(()=>{var L=Ys();return d.insert(L,d.createComponent(te.Button,{size:"small",icon:"refresh",get busy(){return m()},get disabled(){return M()!==void 0},onClick:()=>{ne()},children:"Refresh"}),null),d.insert(L,d.createComponent(A.Show,{get when(){return j().length>0},get children(){return d.createComponent(te.Button,{size:"small",variant:"contrast",icon:"archive",get busy(){return M()==="all"},get disabled(){return m()||M()!==void 0},onClick:()=>{de(j().map(W=>W.sessionID),"all")},get children(){return`Clean up all (${j().length})`}})}}),null),L})()},get children(){var L=Js();return d.insert(L,d.createComponent(A.Show,{get when(){return q()},children:W=>(()=>{var Y=Xs();return d.insert(Y,W),Y})()}),null),d.insert(L,d.createComponent(A.Show,{get when(){return G().skippedErrors>0},get children(){var W=Qs();return d.insert(W,()=>`Skipped ${G().skippedErrors} session${G().skippedErrors===1?"":"s"} whose target status could not be verified.`),W}}),null),d.insert(L,d.createComponent(A.Show,{get when(){return d.memo(()=>M()!==void 0)()&&F()},get children(){var W=at();return d.insert(W,()=>Xt(F(),"cleanup",Me())),W}}),null),d.insert(L,d.createComponent(A.Show,{get when(){return d.memo(()=>!m())()&&j().length>0},get fallback(){return d.createComponent(A.Show,{get when(){return!q()},get children(){var W=at();return d.insert(W,xr),W}})},get children(){var W=Ks();return d.insert(W,d.createComponent(A.For,{get each(){return ee()},children:Y=>[d.createComponent(A.Show,{get when(){return Y.label},children:oe=>(()=>{var ue=Zs();return d.insert(ue,oe),ue})()}),d.createComponent(A.For,{get each(){return Y.items},children:oe=>Tr(oe)})]})),W}}),null),L}})}const fe=(g,m)=>({id:g,title:m,closable:"hover"}),X={github:fe(ve,"PR status"),gitlab:fe(ve,"MR status"),mixed:fe(ve,"PR/MR status")},ke=g=>{if(!R(g))return X.mixed;const m=b(I(g));return m?X[m]:X.mixed},Pr=fe(De,"Review updates");e.add(le.Panel,{id:ve,region:"side",width:420,list:g=>g.open.includes(ve)?[ke(g.session)]:[],render:g=>d.createComponent(re,{get session(){return g.session}})}),e.add(le.Panel,{id:De,region:"side",width:420,list:g=>g.open.includes(De)?[Pr]:[],render:g=>d.createComponent(Te,{get session(){return g.session}})});const Nt=()=>{const g=v();return g?b(I(g)):void 0};return e.add(le.Command,()=>({id:"status",title:`Show ${se(Nt())} status`,keywords:"PR MR pull request merge request",group:"Forge",slash:{name:"forge-status"},enabled:!!v(),run:()=>{const g=v();if(!g)return;const m=I(g);D(m.directory,b(m))||(w()?.refresh(m),C(ve,g))}})),e.add(le.Command,()=>({id:"feedback",title:"Show pending review feedback",group:"Forge",slash:{name:"forge-feedback"},enabled:!!v(),run:()=>{const g=v();g&&(h(k(g)),C(De,g))}})),e.add(le.Command,()=>({id:"open",title:`Open ${se(Nt())} in browser`,keywords:"PR MR pull request merge request",group:"Forge",slash:{name:"forge-open"},enabled:!!v(),run:async()=>{const g=v();if(!g)return;const m=I(g);if(D(m.directory,b(m)))return;let E=S(m);if(E.length===0&&(await w()?.refresh(m),E=S(m)),E.length===0){e.toast.show({title:`No ${se(b(m))} for this session`});return}const M=Dt(E.map(q=>q.forge)),N=E.length===1?E[0].url:await e.dialogs.select({title:`Open ${se(M)}`,options:E.map(q=>({title:`${Ke(q)} ${q.title}`,description:q.targetProject,value:q.url}))});N&&e.system.openExternal(N)}})),e.add(le.Command,()=>({id:"cleanup",title:"Clean up finished sessions",group:"Forge",slash:{name:"forge-cleanup"},enabled:!!_()&&!!Q(),run:()=>ae()})),le.createKeyed(()=>e.client,()=>{const g=t();u.invalidate(),y.connect(g),u.refresh();const m=[g.events.on("sessionsCleanedUp",E=>{const{sessionIDs:M,archive:N}=E.data;if(H(M),N)for(const q of M)e.client.session.update({sessionID:q,archived:!0}).catch(()=>{})}),g.events.on("feedbackChanged",E=>{const{directory:M}=E.data;u.has(M)&&h(M)}),g.events.on("notice",E=>{const M=E.data;_s(M,{hasShown:N=>!!w()?.hasShown(N)||!!E.location?.directory&&u.has(E.location.directory),openTab:N=>{const q=_()?.id;q&&e.tabs.open({server:q,id:N})},toast:({title:N,message:q,variant:z})=>{const F=_()?.id,P=M.sessionID;e.toast.show({title:N??q,...N?{description:q}:{},variant:z==="error"?"error":"default",...F&&P?{actions:[{label:"Open session",run:()=>e.tabs.open({server:F,id:P},{focus:!0})}]}:{}}),e.attention.notify({title:N??"Forgekeeper",message:q,variant:z==="error"?"error":"default",...F&&P?{session:{server:F,id:P}}:{},id:`forgekeeper:${P??""}:${N??""}:${q}`})}})})];A.onCleanup(()=>{for(const E of m)E();u.invalidate(),y.dispose()})}),()=>{u.invalidate(),y.dispose()}}});d.delegateEvents(["click"]);exports.default=ni;
|