pi-odd-worktree 3.9.2 → 3.11.0

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -40
  3. package/extensions/odd-worktree-tools.ts +1028 -17
  4. package/lib/gh-issues.js +65 -10
  5. package/lib/gh-prs.js +2011 -0
  6. package/lib/issue-preview.js +70 -4
  7. package/lib/issues-cache-store.js +4 -1
  8. package/lib/issues-section.js +346 -23
  9. package/lib/issues-view.js +116 -5
  10. package/lib/pr-preview.js +353 -0
  11. package/lib/prs-rail-store.js +317 -0
  12. package/lib/prs-view.js +2896 -0
  13. package/lib/user-prompt-card.js +477 -0
  14. package/package.json +1 -1
  15. package/tools/files-bridge.test.js +2 -2
  16. package/tools/files-command.test.js +1 -1
  17. package/tools/fixtures/gh-pr-connection-page.json +84 -0
  18. package/tools/fixtures/gh-pr-metadata.json +29 -0
  19. package/tools/fixtures/gh-pr-rail.json +61 -0
  20. package/tools/fixtures/gh-pr-search-page.json +82 -0
  21. package/tools/fixtures/gh-pr-view.json +159 -0
  22. package/tools/gh-issues.test.js +4 -2
  23. package/tools/gh-prs.test.js +1828 -0
  24. package/tools/issue-preview.test.js +119 -0
  25. package/tools/issues-cache-store.test.js +2 -2
  26. package/tools/issues-command.test.js +10 -3
  27. package/tools/issues-open-guard.test.js +15 -0
  28. package/tools/issues-section.test.js +618 -9
  29. package/tools/issues-view.test.js +297 -0
  30. package/tools/package-surface.test.js +21 -5
  31. package/tools/pr-preview.test.js +281 -0
  32. package/tools/prs-command.test.js +1280 -0
  33. package/tools/prs-rail-store.test.js +343 -0
  34. package/tools/prs-t10-safety.test.js +326 -0
  35. package/tools/prs-t12-safety.test.js +348 -0
  36. package/tools/prs-t13-independent.test.js +378 -0
  37. package/tools/prs-t14-safety.test.js +340 -0
  38. package/tools/prs-t15-independent.test.js +259 -0
  39. package/tools/prs-t18-safety.test.js +217 -0
  40. package/tools/prs-t7-safety.test.js +127 -0
  41. package/tools/prs-view.test.js +1462 -0
  42. package/tools/user-prompt-card.test.js +963 -0
@@ -0,0 +1,378 @@
1
+ 'use strict';
2
+ // T13 independent probes: public GH runner, pane keys and rail seams. No real writes.
3
+ const test = require('node:test');
4
+ const assert = require('node:assert/strict');
5
+ const { createPrsClient, setGhRunner } = require('../lib/gh-prs');
6
+ const { createPrsView } = require('../lib/prs-view');
7
+ const { createIssuesView } = require('../lib/issues-view');
8
+ const { createIssuesSection } = require('../lib/issues-section');
9
+ const { createPrsRailStore } = require('../lib/prs-rail-store');
10
+ const fs = require('node:fs/promises');
11
+ const os = require('node:os');
12
+ const path = require('node:path');
13
+ const tick = () => new Promise(setImmediate);
14
+ function deferred() { let resolve; const promise = new Promise((r) => { resolve = r; }); return { promise, resolve }; }
15
+ const ok = (doc) => ({ status: 0, stdout: JSON.stringify(doc) });
16
+ const prNum = 64;
17
+ const methods = { merge: true, rebase: true };
18
+ const allCaps = { canClosePullRequests: true, canMerge: true, canEditLabels: true, canCreateLabels: true, canEditAssignees: true, canEditLinkedIssues: true };
19
+ const writeCalls = [
20
+ ['close', (c, o) => c.closePullRequest(prNum, o)],
21
+ ['merge', (c, o) => c.mergePullRequest(prNum, { method: 'merge', subject: 'subject', body: '' }, o)],
22
+ ['labels', (c, o) => c.editLabels(prNum, { add: ['support'] }, o)],
23
+ ['assignees', (c, o) => c.editAssignees(prNum, { add: ['pat'] }, o)],
24
+ ['linked', (c, o) => c.editLinkedIssues(prNum, { add: [915] }, o)],
25
+ ['create label', (c, o) => c.createLabel({ name: 'support' }, o)],
26
+ ];
27
+ function client(t, fixture = {}) {
28
+ const calls = [], writes = [];
29
+ const run = async (_bin, argv, opts) => {
30
+ const env = opts.env || {};
31
+ const target = env.GH_REPO || (fixture.defaultRepo && fixture.defaultRepo()) || 'github.com/amber/widget';
32
+ const call = { argv, target, host: env.GH_HOST };
33
+ calls.push(call);
34
+ switch (argv.slice(0, 2).join(' ')) {
35
+ case 'repo view': return ok({ nameWithOwner: target.split('/').slice(-2).join('/') });
36
+ case 'api graphql': {
37
+ assert.match(argv[3], /^query=query\b/, 'write GraphQL must never fall through as a read');
38
+ const pullRequest = fixture.gone ? null : {
39
+ ...(fixture.noDraft ? {} : { isDraft: false }),
40
+ ...(fixture.noState ? {} : { state: fixture.state || 'OPEN' }),
41
+ closingIssuesReferences: { nodes: [] },
42
+ };
43
+ fixture.onRole?.(call);
44
+ return ok({ data: { repository: { viewerPermission: fixture.role || 'WRITE', mergeCommitAllowed: true, pullRequest }, viewer: { login: 'pat' } } });
45
+ }
46
+ // The body read answers the pull request STATE with the body (S2/T18).
47
+ case 'pr view': return ok({ body: fixture.body ?? 'Summary\n', state: 'OPEN' });
48
+ default: writes.push(call); return ok({});
49
+ }
50
+ };
51
+ setGhRunner(run);
52
+ t.after(() => setGhRunner(null));
53
+ return { c: createPrsClient(fixture.options), run, writes, calls };
54
+ }
55
+ const opts = {scope:'github.com/amber/widget'};
56
+ // D27 replaced the Markdown reader: a line the panel wrote carries this marker
57
+ // and is the only line a removal may delete, so every removal fixture below
58
+ // names the panel's own declaration.
59
+ const MARK = '<!-- odd-worktree:linked -->';
60
+ const UNREADABLE = 'the pull request body ends inside an unclosed code fence or comment';
61
+ async function removeBody(t, prefix, eol = '\n', fixture = {}) {
62
+ const expected = `${prefix}${eol}${eol}footer${eol}`;
63
+ const body = `${prefix}${eol}${eol}Closes #915 ${MARK}${eol}footer${eol}`;
64
+ const { c, writes } = client(t, { ...fixture, body });
65
+ const result = await c.editLinkedIssues(prNum, { remove: [915] }, opts);
66
+ assert.equal(result.ok, true);
67
+ assert.deepEqual(writes.map(w => w.argv), [['pr', 'edit', '64', '--body', expected]]);
68
+ }
69
+
70
+ test('D4: fence character/length and unrelated bytes', t => removeBody(t, '````md\n```\n~~~\nCloses #915\n````'));
71
+ for (const [name, lines, eol] of [
72
+ ['unordered', ['- item', ' ```txt', ' Closes #915', ' ```']],
73
+ ['ordered', ['10. item', ' ~~~txt', ' Closes #915', ' ~~~']],
74
+ ['deep mixed', ['- top', ' 10. inner', ' - third', ' ```txt', ' Closes #915', ' ```']],
75
+ ['tab-indented list continuation', ['- item', '\t```txt', '\tCloses #915', '\t```']],
76
+ ['blockquote', ['> intro', '>', '> ```txt', '> Closes #915', '> ```']],
77
+ ['CRLF list', ['10. item', ' ```txt', ' Closes #915', ' ```'], '\r\n'],
78
+ ]) test(`D16: ${name}, remove the panel's own declaration only`, t => removeBody(t, lines.join(eol || '\n'), eol));
79
+ for (const remove of [[], [915]]) test(`D16: open to EOF, add + remove=${remove.length}`, async t => {
80
+ const body = 'Closes #915\r\n\r\n````text\r\nCloses #915';
81
+ const {c,writes} = client(t,{body});
82
+ assert.deepEqual(await c.editLinkedIssues(prNum,{add:[916],remove},opts), {ok:false,error:UNREADABLE});
83
+ assert.deepEqual(writes, []);
84
+ });
85
+ test('D16: open to EOF is refused, so a removal never edits half a body', async t => {
86
+ // D27: the run total is odd, so the body cannot be read safely and NOTHING is
87
+ // written — the previous rule removed the real line and left the fence open.
88
+ const body = 'Closes #915\r\n\r\n````text\r\nCloses #915';
89
+ const {c,writes} = client(t,{body});
90
+ assert.deepEqual(await c.editLinkedIssues(prNum,{remove:[915]},opts),{ok:false,error:UNREADABLE});
91
+ assert.deepEqual(writes, []);
92
+ });
93
+ test('D16/T18: a fence opened on a list-marker line cannot be paired line by line, so the edit refuses', async t => {
94
+ // D27/T18 pairs a fence run by character and length: only a run that STARTS a
95
+ // line opens or closes one. Here the closing-looking ` ``` ` starts a line
96
+ // with no fence open, so it opens one that nothing closes and the whole edit
97
+ // is refused — which is what keeps the example, and the panel's own line
98
+ // beside it, byte for byte. The old run COUNT accepted this body and rewrote
99
+ // it; the count was the defect.
100
+ const body = `- \`\`\`text\n Closes #915\n \`\`\`\n\nCloses #915 ${MARK}\nfooter\n`;
101
+ const { c, writes } = client(t, { body });
102
+ assert.deepEqual(await c.editLinkedIssues(prNum, { remove: [915] }, opts), { ok: false, error: UNREADABLE });
103
+ assert.deepEqual(writes, []);
104
+ });
105
+ test('NEW: a fence structure with three runs is refused, never resumed', async t => {
106
+ const {c,writes} = client(t,{body:`- item\n \`\`\`txt\n \`\`\`\n Closes #915 ${MARK}\n \`\`\`\n`});
107
+ assert.deepEqual(await c.editLinkedIssues(prNum,{remove:[915]},opts),{ok:false,error:UNREADABLE});
108
+ assert.deepEqual(writes, []);
109
+ });
110
+ test('NEW: an unclosed list fence is refused; the body is never half-read', async t => {
111
+ const prefix = '10. item\n ```txt\n example\n';
112
+ const {c,writes} = client(t,{body:`${prefix}\nCloses #915 ${MARK}\n`});
113
+ assert.deepEqual(await c.editLinkedIssues(prNum,{remove:[915]},opts),{ok:false,error:UNREADABLE});
114
+ assert.deepEqual(writes, []);
115
+ });
116
+
117
+ for (const [name, call] of writeCalls) test(`D19: ${name} uses enterprise GH_REPO for every child`, async t => {
118
+ const host = 'github.company.example/amber/widget';
119
+ const { c, calls, writes } = client(t);
120
+ assert.equal((await call(c, {env: {GH_REPO:host}})).ok, true);
121
+ assert.equal(writes.length, 1);
122
+ assert.ok(calls.some(x => x.argv[1] === 'graphql'));
123
+ assert.deepEqual([...new Set(calls.map(x => x.target))], [host]);
124
+ });
125
+ test('D13: checkout resolver runs once; every read/write uses the first pin', async t => {
126
+ let resolutions = 0;
127
+ const {c,writes,calls}=client(t,{options:{issues:{checkoutRepoScope:async () => ({ok:true,identity:++resolutions===1?'github.com/amber/widget':'github.com/copper/widget'})}}});
128
+ assert.equal((await c.closePullRequest(prNum,{cwd:process.cwd()})).ok,true);
129
+ assert.equal(resolutions,1);
130
+ assert.equal(writes.length,1);
131
+ assert.deepEqual([...new Set(calls.map(x=>x.target))],['github.com/amber/widget']);
132
+ });
133
+ test('NEW: ambient repository chosen by gh cannot change between authorization and close', async t => {
134
+ let current = 'github.com/amber/widget';
135
+ const {c,writes,calls}=client(t,{defaultRepo:()=>current,onRole:()=>{current='github.com/copper/widget';}});
136
+ const result=await c.closePullRequest(prNum);
137
+ assert.equal(calls.find(x=>x.argv[1]==='graphql').target,'github.com/amber/widget');
138
+ if (result.ok) assert.equal(writes[0].target,'github.com/amber/widget');
139
+ else assert.deepEqual(writes,[]);
140
+ });
141
+ test('D2 and D14: READ refuses all six gated writes, WRITE permits label creation', async t => {
142
+ const fixture={role:'READ'};
143
+ const {c,writes}=client(t,fixture);
144
+ for (const [name,call] of writeCalls) assert.match((await call(c,opts)).error,/permission/i,name);
145
+ assert.deepEqual(writes,[]);
146
+ fixture.role='WRITE';
147
+ assert.equal((await c.createLabel({name:'support'},opts)).ok,true);
148
+ assert.deepEqual(writes.map(x=>x.argv),[['label','create','support']]);
149
+ });
150
+ test('D5: missing draft, blank subject and explicitly blank body', async t => {
151
+ const f={noDraft:true}; const {c,writes}=client(t,f);
152
+ assert.deepEqual(await c.mergePullRequest(prNum,{method:'merge'},opts),{ok:false,error:'pull request metadata is unavailable: the draft state is missing'});
153
+ f.noDraft=false;
154
+ assert.deepEqual(await c.mergePullRequest(prNum,{method:'merge',subject:''},opts),{ok:false,error:'the merge commit message must not be empty'});
155
+ assert.deepEqual(writes,[]);
156
+ assert.equal((await writeCalls[1][1](c,opts)).ok,true);
157
+ assert.deepEqual(writes[0].argv,['pr','merge','64','--merge','--subject','subject','--body','']);
158
+ });
159
+ const unavailable = {close:'closed',merge:'merged',linked:'its linked issues cannot be edited'};
160
+ const notOpen = name => `pull request #64 is not open; ${name==='linked'?unavailable.linked:`it cannot be ${unavailable[name]}`}`;
161
+ for (const state of ['MERGED','CLOSED','gone','missing state']) test(`D20 client: ${state} cannot close, merge or edit links`, async t => {
162
+ const {c,writes}=client(t,{state,gone:state==='gone',noState:state==='missing state'});
163
+ for (const [name,call] of writeCalls.filter(([n])=>n in unavailable)) {
164
+ const error=state==='gone'&&name==='merge'?'pull request metadata is unavailable':notOpen(name);
165
+ assert.deepEqual(await call(c,opts),{ok:false,error},name);
166
+ }
167
+ assert.deepEqual(writes,[]);
168
+ });
169
+
170
+ const row = (number, state='open') => ({number,title:`Ticket-${number}`,author:'someone-else',state});
171
+ const detail = (number, props = {}) => ({ok:true,pullRequest:{...row(number),body:'Summary',isDraft:false,mergeMethods:methods,mergeDefaults:{merge:{subject:'Subject',body:'Details'}},linkedIssues:[915],...props},permissions:props.permissions||allCaps});
172
+ const page = rows => ({ok:true,rows,hasMore:false,totalCount:rows.length});
173
+ const keys = (v,...inputs)=>inputs.forEach(x=>v.handleInput(x));
174
+ const display = (v,width=130)=>v.render(width).join('\n');
175
+ async function panel(extra={}) {
176
+ const hold=deferred(), writes=[], reads=[], others=Array.from({length:30},(_,i)=>row(100+i));
177
+ let mine=0;
178
+ let read=(n)=>detail(n);
179
+ const actions=Object.fromEntries(['close','merge','commentPullRequest','editLinkedIssues','editLabels','editAssignees'].map(name=>[name,(...args)=>{writes.push([name,...args]);return {ok:true};}]));
180
+ const v=createPrsView({rowsAvailable:()=>19,
181
+ loadPullRequestPage:({bucketId})=>bucketId==='mine'&&++mine===2?hold.promise:page([row(prNum),...others]),
182
+ loadPullRequest:(n,opt)=>{reads.push([n,opt]);return read(n,opt);},
183
+ labels:[{name:'support'}], loadAssignees:()=>({ok:true,users:[{login:'pat'}]}),actions,...extra});
184
+ await tick();
185
+ return {v,hold,writes,reads,others,changeRead:fn=>{read=fn;}};
186
+ }
187
+ const workflow = {
188
+ close:{enter:['x'],save:['enter'],title:'Confirm close #64',seam:'close',fail:/pull requests cannot be closed: this repository permission is missing/},
189
+ merge:{enter:['m'],save:['ctrl+s'],title:'Confirm merge #64',seam:'merge',fail:/pull requests cannot be merged: this repository permission is missing/},
190
+ comment:{enter:['c','h','i'],save:['ctrl+s'],title:'Comment on #64',seam:'commentPullRequest'},
191
+ linked:{enter:['i','space'],save:['ctrl+s'],title:'Linked issues',seam:'editLinkedIssues',fail:/linked issues cannot be edited: this repository permission is missing/},
192
+ };
193
+ for (const [name,w] of Object.entries(workflow)) for (const present of [true,false]) test(`D${name==='comment'?18:name==='linked'?20:17}: ${name}, held reload ${present?'moves':'removes'} target`,async()=>{
194
+ const {v,hold,writes,others}=await panel();
195
+ keys(v,'r',...w.enter);
196
+ hold.resolve(page(present?[...others,row(prNum)]:others)); await tick();
197
+ const frame=display(v);
198
+ assert.ok(frame.includes(w.title),frame);
199
+ if(name!=='linked') assert.equal(frame.includes('▸ Ticket-64'),present,frame);
200
+ keys(v,...w.save);await tick();
201
+ assert.deepEqual(writes.map(x=>x.slice(0,2)),[[w.seam,64]]);
202
+ if(name==='linked') assert.deepEqual(writes[0][2],{add:[],remove:[915]});
203
+ });
204
+ for(const name of ['close','merge','linked']) for(const which of ['permission removed','merged','gone']) test(`D20 view: ${name}, ${which} while step is open`,async()=>{
205
+ const w=workflow[name];const {v,hold,writes,reads,others,changeRead}=await panel();
206
+ keys(v,'r',...w.enter);
207
+ changeRead(n=>n!==64?detail(n):which==='gone'?{ok:false,error:'gone'}:detail(n,which==='merged'?{state:'merged'}:{permissions:{}}));
208
+ hold.resolve(page(which==='permission removed'?[...others,row(64)]:others));await tick();
209
+ const start=reads.length;
210
+ keys(v,...w.save);await tick();
211
+ assert.deepEqual(writes,[]);
212
+ assert.ok(reads.slice(start).some(([n,o])=>n===64&&o?.refresh));
213
+ assert.match(display(v),which==='permission removed'?w.fail:new RegExp(notOpen(name)));
214
+ });
215
+ for(const name of ['close','merge','linked']) test(`NEW: ${name} must not use superseded positive detail after newer reload revokes it`,async()=>{
216
+ const w=workflow[name];const {v,hold,writes,others,changeRead}=await panel();
217
+ const first=deferred(),newer=deferred();let read=0;
218
+ keys(v,'r',...w.enter);
219
+ changeRead((n)=>n!==64?detail(n):++read===1?first.promise:newer.promise);
220
+ keys(v,...w.save);
221
+ hold.resolve(page([row(64),...others]));await tick();
222
+ newer.resolve(detail(64,{permissions:{}}));await tick();
223
+ first.resolve(detail(64));await tick();
224
+ assert.deepEqual(writes,[]);
225
+ assert.match(display(v),w.fail);
226
+ });
227
+ for(const [key,seam] of [['l','editLabels'],['a','editAssignees']]) for(const reordered of [false,true]) test(`D3: ${seam} permission revocation during ${reordered?'reordering':'same-row'} reload`,async()=>{
228
+ const {v,hold,writes,others,changeRead}=await panel();keys(v,'r',key); await tick(); keys(v,'space');
229
+ changeRead(n=>detail(n,n===64?{permissions:{}}:{}));
230
+ hold.resolve(page(reordered?[...others,row(64)]:[row(64),...others]));await tick();
231
+ keys(v,'ctrl+s');await tick();
232
+ assert.deepEqual(writes,[]);
233
+ });
234
+ test('D6 and D12: j/k edit merge text; rebase hides text fields and sends no text',async()=>{
235
+ const {v,writes}=await panel();keys(v,'m','tab','j','k','tab','j','k','ctrl+s');await tick();
236
+ assert.deepEqual(writes,[['merge',64,{method:'merge',subject:'Subjectjk',body:'Detailsjk'}]]);
237
+ const view=(await panel());keys(view.v,'m','right');
238
+ assert.match(display(view.v),/Confirm merge #64/);assert.doesNotMatch(display(view.v),/Commit message:|Description:/);
239
+ keys(view.v,'ctrl+s');await tick();assert.deepEqual(view.writes,[['merge',64,{method:'rebase'}]]);
240
+ });
241
+ test('D7: numbered open outside every bucket stays on a merged PR and allows comments only',async()=>{
242
+ const reads=[],writes=[];
243
+ const v=createPrsView({initialPullRequest:713,loadPullRequestPage:()=>page([row(72)]),loadPullRequest:n=>{reads.push(n);return detail(n,n===713?{state:'merged'}:{});},actions:{commentPullRequest:(...a)=>{writes.push(a);return {ok:true};},close:()=>assert.fail('unexpected write')}});
244
+ await tick();assert.ok(reads.includes(713));assert.match(display(v),/#713 Ticket-713/);
245
+ keys(v,'x');assert.equal(v.state.mode,'list');keys(v,'c','z','ctrl+s');await tick();assert.deepEqual(writes,[[713,'z']]);
246
+ });
247
+
248
+ // `gh 2.104.0 api graphql` uses the selected API hostname (GH_HOST or
249
+ // --hostname), NOT the host part of GH_REPO, unlike `gh pr view 64 --json body`.
250
+ for (const [name, call] of writeCalls) test(`D19: ${name} GraphQL read selects the enterprise API host`, async t => {
251
+ const host = 'github.company.example';
252
+ const {c,calls} = client(t);
253
+ const result = await call(c,{env:{GH_REPO:`${host}/amber/widget`}});
254
+ assert.equal(result.ok,true);
255
+ const lookup = calls.find(x => x.argv[1]==='graphql');
256
+ const i = lookup.argv.indexOf('--hostname');
257
+ const selectedByArg = lookup.argv.find(x=>x.startsWith('--hostname='))?.split('=')[1];
258
+ assert.equal((i<0?selectedByArg:lookup.argv[i+1]) || lookup.host || 'github.com',host);
259
+ });
260
+
261
+ test('S1: review, involved and all return to the previous scoped bucket', async()=>{
262
+ const seen=[];
263
+ const v=createPrsView({loadPullRequestPage: ({bucketId})=>{seen.push(bucketId);return page([row(64)]);}});
264
+ await tick();
265
+ for(const label of ['My Pull Request','Needs My Review','Involved']) assert.match(display(v),new RegExp(label));
266
+ keys(v,'tab');await tick();keys(v,'tab');await tick();keys(v,'g');await tick();
267
+ assert.match(display(v),/▸ All \(1\)/);keys(v,'g');await tick();
268
+ assert.match(display(v),/▸ Involved/);assert.deepEqual(seen,['mine','review','involved','all']);
269
+ });
270
+ test('S3: summary, local search/scroll and web opener',()=>{
271
+ const opened=[];
272
+ const pr={...detail(64).pullRequest,labels:[{name:'support'}],assignees:['pat'],reviewers:[{login:'kai',state:'APPROVED'}],createdAt:'2025-01-01',updatedAt:'2025-01-02',changedFiles:3,additions:20,deletions:9,commits:2,checks:{state:'FAILURE',total:3,passed:2,failed:1,pending:0,failing:['lint']}};
273
+ const v=createPrsView({rowsAvailable:()=>24,pages:[{label:'My Pull Request',rows:[pr,row(65)]}],loadPullRequest:n=>n===64?{ok:true,pullRequest:pr}:detail(n),actions:{openBrowser:(n)=>opened.push(n)}});
274
+ const frame=display(v);
275
+ for(const pattern of [/someone-else/,/kai/,/#915/,/created.*updated/,/support/,/3 files changed.*\+20.*-9/,/2 commits/,/3 checks/,/lint/]) assert.match(frame,pattern);
276
+ keys(v,'o','/','6','5','enter','pagedown','o');
277
+ assert.deepEqual(opened,[64,65]);assert.match(display(v),/Ticket-65/);
278
+ });
279
+
280
+ test('S4/S5, D8/D9/D15: independent store reload, repaint notifications, exact count and review click',async()=>{
281
+ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'t13-rail-'));
282
+ const identity='github.com/amber/widget';const mine=Array.from({length:50},(_,i)=>({number:i+101,linkedIssues:[]}));
283
+ const review=[mine[0]];
284
+ assert.equal(await createPrsRailStore({dir}).save(identity,{mine,review,counts:{mine:52,review:1},syncedAt:11}),true);
285
+ const freshStore=createPrsRailStore({dir});
286
+ const live=deferred(), hydration=deferred(), queued=[], frames=[], clicks=[];let loading=0;
287
+ const rail=createIssuesSection({now:()=>11,schedule:fn=>queued.push(fn),onRefreshed:()=>frames.push(rail.section.meta()),
288
+ load:()=>({ok:true,identity,issues:[{number:70,title:'linked issue',pullRequestNumber:101},{number:71,title:'unlinked issue'}]}),
289
+ loadPullRequests:()=>{loading++;return live.promise;},hydratePullRequests:()=>hydration.promise, open:(...a)=>clicks.push(a)});
290
+ assert.equal(rail.section.rowLabel,'github');assert.equal(rail.section.placement,'end');
291
+ await rail.refresh();assert.equal(rail.section.meta(),'2 issues');assert.equal(loading,0);
292
+ const read=queued.shift()();assert.equal(loading,1);
293
+ hydration.resolve(await freshStore.load(identity));await tick();
294
+ assert.equal(rail.section.meta(),'2 issues · 52 pr');assert.equal(frames.at(-1),'2 issues · 52 pr');
295
+ const clicked=rail.section.lines()[0].onClick();while(queued.length) queued.shift()();await clicked;
296
+ assert.deepEqual(clicks,[[70,{pullRequest:101,pullRequestBucket:'review'}]]);
297
+ live.resolve({ok:true,mine,review,counts:{mine:54,review:1}});await read;
298
+ assert.equal(rail.section.meta(),'2 issues · 54 pr');assert.deepEqual(frames,['2 issues','2 issues · 52 pr','2 issues · 54 pr']);
299
+ rail.dispose();
300
+ });
301
+
302
+ function clickNumber(v, frame, title, needle, width=130) {
303
+ const y=frame.findIndex(s=>s.includes(title));assert.ok(y>=0,frame.join('\n'));
304
+ const x=frame[y].indexOf(needle,frame[y].indexOf(title));assert.ok(x>=0,frame[y]);
305
+ assert.equal(v.handleMouse({type:'click',button:'left',x,y,width,height:frame.length})?.handled,true,frame[y]);
306
+ }
307
+ test('S6/S7: independent hit ranges and Enter on both panels',()=>{
308
+ const calls=[];const actions={openLinked:arg=>calls.push(arg),insert:text=>calls.push(text)};
309
+ const v=createPrsView({pages:[{label:'Mine',rows:[row(64)]}],loadPullRequest:()=>detail(64,{linkedIssues:[915,916]}),actions,done:()=>calls.push('closed PR')});
310
+ const issue={number:71,title:'Other issue',state:'open',linkedPullRequests:[91,92]};
311
+ const w=createIssuesView({issues:[issue],loadIssue:()=>({ok:true,issue}),actions,done:()=>calls.push('closed ISSUE')});
312
+ const p=v.render(130);clickNumber(v,p,'linked issues:','#915');clickNumber(v,p,'linked issues:','#916');keys(v,'enter');
313
+ const q=w.render(130);clickNumber(w,q,'linked PRs:','#91');clickNumber(w,q,'linked PRs:','#92');keys(w,'enter');
314
+ assert.deepEqual(calls,[{kind:'issue',number:915},{kind:'issue',number:916},'PR #64','closed PR',{kind:'pullRequest',number:91},{kind:'pullRequest',number:92},'ISSUE #71','closed ISSUE']);
315
+ });
316
+
317
+ test('D10/S5: registered /prs refuses moved repo; session_start does not await its held gh gate',async t=>{
318
+ const {LIB_DIR,stubbedSource,defaultBridge,BRIDGE_SLOT,withGhPath}=require('./fixtures/load-extension');
319
+ const {pathToFileURL}=require('node:url');
320
+ const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'t13-ext-'));
321
+ const file=path.join(tmp,'ext.mjs');await fs.writeFile(file,stubbedSource());
322
+ const original={lib:process.env.GENTLE_WORKTREE_LIB_DIR,repo:process.env.GH_REPO,bridge:globalThis[BRIDGE_SLOT]};
323
+ t.after(()=>{for(const [key, value] of [['GENTLE_WORKTREE_LIB_DIR',original.lib],['GH_REPO',original.repo]]){
324
+ if(value===undefined)delete process.env[key];else process.env[key]=value;
325
+ } if(original.bridge===undefined)delete globalThis[BRIDGE_SLOT];else globalThis[BRIDGE_SLOT]=original.bridge;});
326
+ process.env.GENTLE_WORKTREE_LIB_DIR=LIB_DIR;
327
+ process.env.GH_REPO='github.com/amber/widget';globalThis[BRIDGE_SLOT]=defaultBridge().api;
328
+ const commands=new Map(), hooks=[], writes=[];
329
+ const mod=await withGhPath('present',async()=>{
330
+ const api=await import(pathToFileURL(file).href);
331
+ api.default({registerCommand:(n,s)=>commands.set(n,s),registerTool:()=>{},on:(n,h)=>hooks.push([n,h])});return api;
332
+ });
333
+ const issues=mod.libModule('gh-issues.js');const git=mod.libModule('worktree-git.js');
334
+ const restore={repoIdentity:git.repoIdentityAsync,status:issues.cachedGhStatus,runner:issues.runGh};
335
+ t.after(()=>{git.repoIdentityAsync=restore.repoIdentity;issues.cachedGhStatus=restore.status;issues.runGh=restore.runner;});
336
+ git.repoIdentityAsync=async()=>({root:tmp});
337
+ const gate=deferred();let gateReads=0;
338
+ issues.cachedGhStatus=()=>{gateReads++;return gate.promise;};
339
+ issues.runGh=async (argv)=>{
340
+ switch(argv.slice(0,2).join(' ')) {
341
+ case 'api graphql': {
342
+ if (argv[3].includes('search(')) return ok({data:{search:{edges:[{cursor:'edge-64',node:row(64,'OPEN')}],pageInfo:{hasNextPage:false},issueCount:1}}});
343
+ return ok({data:{repository:{viewerPermission:'WRITE',pullRequest:{state:'OPEN',isDraft:false}}}});
344
+ }
345
+ case 'pr view': return ok({...row(64,'OPEN'),isDraft:false});
346
+ default: writes.push(argv);return ok({});
347
+ }
348
+ };
349
+ mod.setIssuesTuiLoader(async()=>({}));let pane;
350
+ const ctx={cwd:tmp,ui:{notify:(text)=>assert.fail(text),custom:(factory)=>{pane=factory({terminal:{rows:24}},null,null,()=>{});}}};
351
+ // The session hook must finish with its gate held. This does not wait for it.
352
+ const startup=hooks.filter(([n])=>n==='session_start').map(([,fn])=>fn({},ctx));
353
+ let settled=false;Promise.all(startup).then(()=>{settled=true;});await tick();
354
+ assert.ok(settled);assert.equal(gateReads,1);gate.resolve({ok:true});await tick();
355
+ await commands.get('prs').handler('',ctx);await tick();assert.ok(pane);
356
+ process.env.GH_REPO='github.com/copper/widget';
357
+ keys(pane,'x','enter');await tick();
358
+ assert.match(display(pane,180),/the checkout's repository changed since this pull request list loaded \(now github\.com\/copper\/widget instead of github\.com\/amber\/widget\); reopen \/prs/);
359
+ assert.deepEqual(writes,[]);
360
+ });
361
+
362
+ test('D14: downgrade create-only permission during a same-row reload refuses a new-label save', async()=>{
363
+ const {v,hold,writes,others,changeRead}=await panel();
364
+ keys(v,'r','l','n','N','e','w','enter');
365
+ changeRead(n=>detail(n,{permissions:{...allCaps,canCreateLabels:false}}));
366
+ hold.resolve(page([row(64),...others]));await tick();
367
+ keys(v,'ctrl+s');await tick();
368
+ assert.deepEqual(writes,[]);
369
+ assert.match(display(v),/new labels cannot be created: this repository permission is missing/);
370
+ });
371
+
372
+ test('D17: merge must still visibly name the captured number when the row disappears in a short frame',async()=>{
373
+ const {v,hold,writes,others}=await panel({rowsAvailable:()=>12});
374
+ keys(v,'r','m');hold.resolve(page(others));await tick();
375
+ const rendered=display(v);keys(v,'ctrl+s');await tick();
376
+ assert.deepEqual(writes.map(x=>x.slice(0,2)),[['merge',64]]);
377
+ assert.match(rendered,/Confirm merge #64/);
378
+ });