@bevel-software/platform-core-frontend 0.21.0 → 0.23.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 (72) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +140 -0
  4. package/src/lib/api.ts +49 -0
  5. package/src/modules/access/__tests__/ManageAccessDialog.request.test.tsx +376 -0
  6. package/src/modules/access/api.ts +6 -4
  7. package/src/modules/access/components/AccessRequestControl.tsx +155 -0
  8. package/src/modules/{library → access}/components/AccessRequestsBanner.tsx +62 -24
  9. package/src/modules/access/components/ManageAccessDialog.tsx +81 -4
  10. package/src/modules/access/hooks/useAccessRequests.ts +183 -0
  11. package/src/modules/access/requests.api.ts +121 -0
  12. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +89 -1
  13. package/src/modules/admin/components/UserAccountsPage.tsx +93 -5
  14. package/src/modules/auth/components/LoginScreen.tsx +8 -0
  15. package/src/modules/auth/services/account.api.ts +26 -3
  16. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +171 -38
  17. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +34 -19
  18. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +173 -6
  19. package/src/modules/change-requests/components/BranchFilePreview.tsx +7 -1
  20. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +155 -98
  21. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +89 -10
  22. package/src/modules/git/__tests__/HistoryVersionPreview.test.tsx +479 -0
  23. package/src/modules/git/components/FileHistoryPanel.tsx +52 -65
  24. package/src/modules/git/components/HistoryVersionPreview.tsx +410 -0
  25. package/src/modules/layout/__tests__/ReadOnlyBanner.test.tsx +157 -0
  26. package/src/modules/layout/components/ReadOnlyBanner.tsx +96 -0
  27. package/src/modules/library/__tests__/SkillPage.test.tsx +15 -0
  28. package/src/modules/library/__tests__/ToolPage.test.tsx +15 -1
  29. package/src/modules/library/__tests__/title-row-actions.ts +53 -1
  30. package/src/modules/library/components/PluginJoinRequests.tsx +2 -2
  31. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  32. package/src/modules/library/components/tool-page/ToolPage.tsx +11 -1
  33. package/src/modules/library/hooks/useJoinRequests.ts +26 -101
  34. package/src/modules/pr/services/pr-merge.api.ts +10 -2
  35. package/src/modules/settings/components/DeploymentPage.tsx +22 -0
  36. package/src/modules/settings/components/__tests__/DeploymentPage.test.tsx +72 -4
  37. package/src/modules/setup/__tests__/setup.first-run.test.tsx +276 -0
  38. package/src/modules/setup/__tests__/setup.github.test.tsx +416 -0
  39. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +275 -0
  40. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +296 -0
  41. package/src/modules/setup/__tests__/setup.repository.test.tsx +463 -0
  42. package/src/modules/setup/__tests__/setup.test.tsx +13 -17
  43. package/src/modules/setup/components/GitHubRepositoryPanel.tsx +369 -0
  44. package/src/modules/setup/components/SetupGate.tsx +1 -0
  45. package/src/modules/setup/components/SetupScreen.tsx +608 -41
  46. package/src/modules/setup/services/setup.api.ts +171 -3
  47. package/src/modules/setup/utils/kept-draft.ts +86 -0
  48. package/src/modules/workspace/components/FileExplorer.tsx +140 -12
  49. package/src/modules/workspace/components/FileViewer.tsx +11 -1
  50. package/src/modules/workspace/components/TreeActionConfirm.tsx +5 -7
  51. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +603 -29
  52. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +23 -6
  53. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +41 -8
  54. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +20 -5
  55. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +39 -16
  56. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +27 -7
  57. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +20 -5
  58. package/src/modules/workspace/components/renderers/RetryReadButton.tsx +37 -0
  59. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +20 -5
  60. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +186 -7
  61. package/src/modules/workspace/components/renderers/__tests__/readPane.test.tsx +59 -0
  62. package/src/modules/workspace/components/renderers/htmlSandbox.ts +80 -20
  63. package/src/modules/workspace/components/renderers/index.ts +6 -1
  64. package/src/modules/workspace/components/renderers/readPane.ts +22 -0
  65. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +50 -9
  66. package/src/modules/workspace/components/renderers/useReadRetry.ts +27 -0
  67. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +79 -0
  68. package/src/modules/workspace/routing/kb-routes.ts +25 -10
  69. package/src/modules/workspace/services/workspace.api.ts +22 -1
  70. package/src/shared/components/SlotBoundary.tsx +51 -0
  71. package/src/shared/markdown/__tests__/hrefs.test.ts +111 -0
  72. package/src/shared/markdown/hrefs.ts +80 -4
@@ -11,9 +11,18 @@ import type { FileApprovalState, PullRequestSummary } from '@bevel-software/plat
11
11
  * outside engineering knows what `main` is, and nobody should have to press a
12
12
  * button to get a proposal that merges cleanly back into shape.
13
13
  *
14
+ * What it does NOT do any more is make the reader wait. The update runs
15
+ * behind the files, which are on screen from the first render; only Approve
16
+ * and Apply — the two verbs the merge can change the answer to — wait for it.
17
+ * And it only runs at all when the target changed a file THIS request also
18
+ * changes (`needsUpdate`), not merely when the two branches have diverged
19
+ * (`behind`), which on a live knowledge base is true again within minutes of
20
+ * every update.
21
+ *
14
22
  * What these pin: the automatic update for the three viewers who may run it,
15
- * silence for the one who may not, the conflict path, once-per-open, and the
16
- * guard that no state of this dialog ever prints the default branch name.
23
+ * silence for the one who may not, silence for a target that moved elsewhere,
24
+ * the files being readable throughout, the conflict path, once-per-open, and
25
+ * the guard that no state of this dialog ever prints the default branch name.
17
26
  */
18
27
 
19
28
  const detailMock = vi.hoisted(() => ({ fetchPrDetail: vi.fn() }));
@@ -102,12 +111,17 @@ function detail(over: Record<string, unknown> = {}) {
102
111
  viewerCanCancel: false,
103
112
  mergeBaseSha: FORK,
104
113
  behind: true,
114
+ // The two are separate answers, and only this one makes the dialog act.
115
+ // A test that wants "diverged, but not in this request's files" sets
116
+ // `needsUpdate: false` and leaves `behind` alone.
117
+ needsUpdate: true,
118
+ updatedPaths: ['Sales/deal.yaml'],
105
119
  viewerCanUpdate: true,
106
120
  ...over,
107
121
  };
108
122
  }
109
123
 
110
- const RUNNING = 'Bringing this up to date with what everyone sees…';
124
+ const RUNNING = 'Checking against the latest version…';
111
125
  const DONE = 'Brought up to date with what everyone sees.';
112
126
  const READER_NOTICE =
113
127
  'What everyone sees has changed since this was proposed. Its author, or someone who can apply it, brings it up to date by opening it.';
@@ -121,7 +135,11 @@ const conflict = () =>
121
135
 
122
136
  beforeEach(() => {
123
137
  detailMock.fetchPrDetail.mockReset();
124
- mergeApi.refreshChangeRequestFromTarget.mockReset().mockResolvedValue({});
138
+ // The Update's own answer IS the fresh detail — the dialog takes it as one
139
+ // and does not read the detail again.
140
+ mergeApi.refreshChangeRequestFromTarget
141
+ .mockReset()
142
+ .mockResolvedValue(detail({ behind: false, needsUpdate: false }));
125
143
  filesApi.readFileAtForkPoint
126
144
  .mockReset()
127
145
  .mockImplementation(async (_n: number, sha: string) => ({ content: BEFORE, forkSha: sha }));
@@ -149,9 +167,10 @@ const MAY_UPDATE: [string, Record<string, unknown>][] = [
149
167
 
150
168
  describe('ChangeRequestDialog: a stale request brings itself up to date', () => {
151
169
  it.each(MAY_UPDATE)('updates itself on open for %s — no button, no confirmation', async (_who, over) => {
152
- detailMock.fetchPrDetail
153
- .mockResolvedValueOnce(detail(over))
154
- .mockResolvedValue(detail({ ...over, behind: false }));
170
+ mergeApi.refreshChangeRequestFromTarget.mockResolvedValue(
171
+ detail({ ...over, behind: false, needsUpdate: false }),
172
+ );
173
+ detailMock.fetchPrDetail.mockResolvedValue(detail(over));
155
174
 
156
175
  const { container } = render(
157
176
  <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
@@ -167,32 +186,117 @@ describe('ChangeRequestDialog: a stale request brings itself up to date', () =>
167
186
  expect(screen.queryByRole('alert')).not.toBeInTheDocument();
168
187
  });
169
188
 
170
- it('shows the status line and NO file content while the update runs', async () => {
189
+ it('shows the files AT ONCE while the update runs, with the note above them', async () => {
190
+ // The ticket, in one test. The proposal is readable from the first
191
+ // render; the note says a check is happening; nobody waits out a merge to
192
+ // see what was proposed.
171
193
  let land: (v: unknown) => void = () => {};
172
194
  mergeApi.refreshChangeRequestFromTarget.mockImplementation(
173
195
  () => new Promise((resolve) => (land = resolve)),
174
196
  );
175
- detailMock.fetchPrDetail
176
- .mockResolvedValueOnce(detail())
177
- .mockResolvedValue(detail({ behind: false }));
197
+ // A viewer whose authority covers the request, so Apply is on screen to
198
+ // be held in the first place.
199
+ const canApply = { approvals: [{ ...approval, inMergeGate: true, viewerCanApprove: true }] };
200
+ detailMock.fetchPrDetail.mockResolvedValue(detail(canApply));
178
201
 
179
202
  const { container } = render(
180
203
  <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
181
204
  );
182
205
 
183
206
  expect(await screen.findByText(RUNNING)).toBeInTheDocument();
184
- // Not the pre-update text, and not a diff of it: the proposal on screen
185
- // must never be the one against text that has already moved.
186
- expect(container.textContent).not.toContain('price: 120');
187
- expect(container.querySelector('ins')).toBeNull();
188
- expect(filesApi.readFileOnBranch).not.toHaveBeenCalled();
189
- expect(filesApi.readFileAtForkPoint).not.toHaveBeenCalled();
190
- expect(screen.queryByRole('button', { name: 'Apply changes' })).not.toBeInTheDocument();
191
-
192
- land({});
207
+ // The files are read and drawn, not withheld.
208
+ await waitFor(() => expect(container.querySelector('ins')?.textContent).toBe('price: 120'));
209
+ expect(filesApi.readFileOnBranch).toHaveBeenCalledWith(CR.branch, 'Sales/deal.yaml');
210
+ expect(filesApi.readFileAtForkPoint).toHaveBeenCalled();
211
+
212
+ // What DOES wait is the verdict: the merge can move the text these two
213
+ // verbs would act on, so both are on screen and both are held.
214
+ const apply = screen.getByRole('button', { name: /Apply changes|Bypass approval and apply/ });
215
+ expect(apply).toBeDisabled();
216
+ expect(screen.getByRole('button', { name: /Approve this file/ })).toBeDisabled();
217
+
218
+ land(detail({ ...canApply, behind: false, needsUpdate: false }));
193
219
  expect(await screen.findByText(DONE)).toBeInTheDocument();
194
220
  expect(screen.queryByText(RUNNING)).not.toBeInTheDocument();
221
+ await waitFor(() =>
222
+ expect(
223
+ screen.getByRole('button', { name: /Apply changes|Bypass approval and apply/ }),
224
+ ).toBeEnabled(),
225
+ );
226
+ });
227
+
228
+ it('does NOT update when the target moved in files this request does not change', async () => {
229
+ // The everyday case on a live knowledge base: somebody saved something
230
+ // else. The request is `behind`, and nothing about it has gone stale.
231
+ detailMock.fetchPrDetail.mockResolvedValue(detail({ behind: true, needsUpdate: false }));
232
+
233
+ const { container } = render(
234
+ <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
235
+ );
236
+
237
+ await waitFor(() => expect(container.querySelector('ins')?.textContent).toBe('price: 120'));
238
+ expect(mergeApi.refreshChangeRequestFromTarget).not.toHaveBeenCalled();
239
+ expect(screen.queryByText(RUNNING)).not.toBeInTheDocument();
240
+ expect(screen.queryByText(DONE)).not.toBeInTheDocument();
241
+ expect(screen.queryByText(READER_NOTICE)).not.toBeInTheDocument();
242
+ });
243
+
244
+ it('re-opened with nothing changed, it runs no update and says nothing about one', async () => {
245
+ // Opening the same request a second time, with no change to the shared
246
+ // version and none to the request in between.
247
+ detailMock.fetchPrDetail.mockResolvedValue(detail({ behind: false, needsUpdate: false }));
248
+
249
+ const first = render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
250
+ await waitFor(() => expect(first.container.querySelector('ins')).not.toBeNull());
251
+ first.unmount();
252
+
253
+ const { container } = render(
254
+ <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
255
+ );
195
256
  await waitFor(() => expect(container.querySelector('ins')?.textContent).toBe('price: 120'));
257
+ expect(mergeApi.refreshChangeRequestFromTarget).not.toHaveBeenCalled();
258
+ expect(screen.queryByText(RUNNING)).not.toBeInTheDocument();
259
+ expect(screen.queryByText(DONE)).not.toBeInTheDocument();
260
+ });
261
+
262
+ it('after the update, only the files the update changed are read again', async () => {
263
+ // `updatedPaths` is git's own answer to "what did this merge move". A
264
+ // dialog that forgot everything would blank the pane the reader is
265
+ // mid-sentence in and re-read the whole request to replace one file.
266
+ detailMock.fetchPrDetail.mockResolvedValue(
267
+ detail({
268
+ files: [
269
+ { path: 'Sales/deal.yaml', status: 'modified' as const, additions: 1, deletions: 1, isBinary: false, sha: '', rawUrl: '' },
270
+ { path: 'Sales/untouched.yaml', status: 'modified' as const, additions: 1, deletions: 1, isBinary: false, sha: '', rawUrl: '' },
271
+ ],
272
+ }),
273
+ );
274
+ mergeApi.refreshChangeRequestFromTarget.mockResolvedValue(
275
+ detail({ behind: false, needsUpdate: false, updatedPaths: ['Sales/deal.yaml'] }),
276
+ );
277
+
278
+ render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
279
+ expect(await screen.findByText(DONE)).toBeInTheDocument();
280
+
281
+ await waitFor(() =>
282
+ expect(
283
+ filesApi.readFileOnBranch.mock.calls.filter((c) => c[1] === 'Sales/deal.yaml').length,
284
+ ).toBe(2),
285
+ );
286
+ // The file the merge did not touch keeps the copy already on screen.
287
+ expect(
288
+ filesApi.readFileOnBranch.mock.calls.filter((c) => c[1] === 'Sales/untouched.yaml').length,
289
+ ).toBeLessThanOrEqual(1);
290
+ });
291
+
292
+ it('takes the update\'s own answer as the fresh detail — no second detail read', async () => {
293
+ // One detail read after the merge, on the server. A dialog that re-fetched
294
+ // here would make the server build a second one saying the same thing.
295
+ detailMock.fetchPrDetail.mockResolvedValue(detail());
296
+ render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
297
+
298
+ expect(await screen.findByText(DONE)).toBeInTheDocument();
299
+ expect(detailMock.fetchPrDetail).toHaveBeenCalledTimes(1);
196
300
  });
197
301
 
198
302
  it('never runs for a viewer who may not update it — they get the plain-words notice, no button', async () => {
@@ -208,7 +312,9 @@ describe('ChangeRequestDialog: a stale request brings itself up to date', () =>
208
312
  });
209
313
 
210
314
  it('never runs on a request that is no longer open', async () => {
211
- detailMock.fetchPrDetail.mockResolvedValue(detail({ state: 'merged', behind: true }));
315
+ detailMock.fetchPrDetail.mockResolvedValue(
316
+ detail({ state: 'merged', behind: true, needsUpdate: false }),
317
+ );
212
318
  render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
213
319
 
214
320
  await waitFor(() => expect(screen.getByText(/1 file/)).toBeInTheDocument());
@@ -218,7 +324,7 @@ describe('ChangeRequestDialog: a stale request brings itself up to date', () =>
218
324
  });
219
325
 
220
326
  it('says nothing at all about updating when the request is already up to date', async () => {
221
- detailMock.fetchPrDetail.mockResolvedValue(detail({ behind: false }));
327
+ detailMock.fetchPrDetail.mockResolvedValue(detail({ behind: false, needsUpdate: false }));
222
328
  render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
223
329
 
224
330
  await waitFor(() => expect(screen.getByText(/1 file/)).toBeInTheDocument());
@@ -250,18 +356,16 @@ describe('ChangeRequestDialog: a stale request brings itself up to date', () =>
250
356
  expect(mergeApi.refreshChangeRequestFromTarget).toHaveBeenCalledTimes(1);
251
357
  });
252
358
 
253
- it('opened ABOUT a file, it reads nothing until the update has settled', async () => {
359
+ it('opened ABOUT a file, it reads that file while the update runs', async () => {
254
360
  // A dialog opened from a file surface knows its selection before the
255
- // detail arrives (`initialPath`). That must not become a read: until the
256
- // detail says whether this request is behind, the branch copy it would
257
- // fetch is the one the update is about to replace.
361
+ // detail arrives (`initialPath`). It still waits for the DETAIL — the
362
+ // pane cannot draw a diff before the fork point is named — but not for
363
+ // the update: that is the wait this ticket removed.
258
364
  let land: (v: unknown) => void = () => {};
259
365
  mergeApi.refreshChangeRequestFromTarget.mockImplementation(
260
366
  () => new Promise((resolve) => (land = resolve)),
261
367
  );
262
- detailMock.fetchPrDetail
263
- .mockResolvedValueOnce(detail())
264
- .mockResolvedValue(detail({ behind: false }));
368
+ detailMock.fetchPrDetail.mockResolvedValue(detail());
265
369
 
266
370
  render(
267
371
  <ChangeRequestDialog
@@ -273,24 +377,29 @@ describe('ChangeRequestDialog: a stale request brings itself up to date', () =>
273
377
  );
274
378
 
275
379
  expect(await screen.findByText(RUNNING)).toBeInTheDocument();
276
- expect(filesApi.readFileOnBranch).not.toHaveBeenCalled();
277
- expect(filesApi.readFileAtForkPoint).not.toHaveBeenCalled();
380
+ await waitFor(() =>
381
+ expect(filesApi.readFileOnBranch).toHaveBeenCalledWith(CR.branch, 'Sales/deal.yaml'),
382
+ );
383
+ expect(filesApi.readFileAtForkPoint).toHaveBeenCalled();
278
384
 
279
- land({});
385
+ land(detail({ behind: false, needsUpdate: false }));
280
386
  expect(await screen.findByText(DONE)).toBeInTheDocument();
281
- // And afterwards it reads the file it was opened about — against the head
282
- // the merge left.
387
+ // Read again afterwards, against the head the merge left — the file is on
388
+ // `updatedPaths`.
283
389
  await waitFor(() =>
284
- expect(filesApi.readFileOnBranch).toHaveBeenCalledWith(CR.branch, 'Sales/deal.yaml'),
390
+ expect(
391
+ filesApi.readFileOnBranch.mock.calls.filter((c) => c[1] === 'Sales/deal.yaml').length,
392
+ ).toBe(2),
285
393
  );
286
394
  });
287
395
 
288
396
  it('two people opening the same stale request at once: the second finds nothing to merge, and neither sees an error', async () => {
289
397
  // The server answers an already-merged update with a plain, successful
290
398
  // detail — nothing merged, nothing to report.
291
- detailMock.fetchPrDetail
292
- .mockResolvedValueOnce(detail())
293
- .mockResolvedValue(detail({ behind: false }));
399
+ detailMock.fetchPrDetail.mockResolvedValue(detail());
400
+ mergeApi.refreshChangeRequestFromTarget.mockResolvedValue(
401
+ detail({ behind: false, needsUpdate: false, updatedPaths: [] }),
402
+ );
294
403
  render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
295
404
 
296
405
  expect(await screen.findByText(DONE)).toBeInTheDocument();
@@ -327,6 +436,23 @@ describe('ChangeRequestDialog: an update that cannot be combined', () => {
327
436
  expect(detailMock.fetchPrDetail).toHaveBeenCalledTimes(1);
328
437
  });
329
438
 
439
+ it('reports the conflict the background update found, with the files still on screen', async () => {
440
+ // The update now runs behind the files, so a conflict arrives over a
441
+ // dialog the reader is already reading. It is reported exactly as before.
442
+ mergeApi.refreshChangeRequestFromTarget.mockRejectedValue(conflict());
443
+ detailMock.fetchPrDetail.mockResolvedValue(detail());
444
+ const { container } = render(
445
+ <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
446
+ );
447
+
448
+ const banner = await screen.findByRole('alert');
449
+ expect(banner.textContent).toContain("the two can't be combined automatically");
450
+ expect(screen.getByText(/Fastest fix: ask your agent to resolve it/)).toBeInTheDocument();
451
+ // The request is still readable: the conflict is news about applying it,
452
+ // not a reason to take the proposal off the screen.
453
+ expect(container.textContent).toContain('deal.yaml');
454
+ });
455
+
330
456
  it('any other refusal is reported as itself, without the conflict help', async () => {
331
457
  mergeApi.refreshChangeRequestFromTarget.mockRejectedValue(
332
458
  new GitApiError(403, 'Only the author of this change request, or someone who may apply it, can update it.'),
@@ -381,6 +507,13 @@ describe('ChangeRequestDialog: never names the default branch to a business user
381
507
  expect(prose(c)).not.toMatch(NAMES_TARGET);
382
508
  });
383
509
 
510
+ it('when the target moved on but this request needs nothing', async () => {
511
+ const c = await rendered({ behind: true, needsUpdate: false }, () =>
512
+ screen.findByText(/1 file/),
513
+ );
514
+ expect(prose(c)).not.toMatch(NAMES_TARGET);
515
+ });
516
+
384
517
  it('when the update conflicts', async () => {
385
518
  mergeApi.refreshChangeRequestFromTarget.mockRejectedValue(conflict());
386
519
  const c = await rendered({}, () => screen.findByRole('alert'));
@@ -94,6 +94,8 @@ function detail(over: Record<string, unknown> = {}) {
94
94
  viewerCanCancel: false,
95
95
  mergeBaseSha: FORK,
96
96
  behind: true,
97
+ needsUpdate: true,
98
+ updatedPaths: ['Sales/deal.yaml'],
97
99
  viewerCanUpdate: true,
98
100
  ...over,
99
101
  };
@@ -133,7 +135,7 @@ describe('ChangeRequestDialog: diff from the fork point', () => {
133
135
  });
134
136
 
135
137
  it('a request that is up to date reads its files straight away, against its own fork point', async () => {
136
- detailMock.fetchPrDetail.mockResolvedValue(detail({ behind: false }));
138
+ detailMock.fetchPrDetail.mockResolvedValue(detail({ behind: false, needsUpdate: false }));
137
139
  const { container } = render(
138
140
  <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
139
141
  );
@@ -148,9 +150,15 @@ describe('ChangeRequestDialog: diff from the fork point', () => {
148
150
 
149
151
  describe('ChangeRequestDialog: the files after the request brings itself up to date', () => {
150
152
  it("re-reads the open file against the fresh fork point, and still marks only the author's line", async () => {
151
- detailMock.fetchPrDetail
152
- .mockResolvedValueOnce(detail())
153
- .mockResolvedValue(detail({ behind: false, mergeBaseSha: MERGED_FORK }));
153
+ // The merge moves the fork point, so the file the reader is looking at is
154
+ // read a second time — against the commit the merge left. The FIRST read,
155
+ // at the old fork point, is not a mistake: it is what puts the proposal on
156
+ // screen immediately, and it describes what the author started from
157
+ // exactly as truthfully until the merge lands.
158
+ detailMock.fetchPrDetail.mockResolvedValue(detail());
159
+ mergeApi.refreshChangeRequestFromTarget.mockResolvedValue(
160
+ detail({ behind: false, needsUpdate: false, mergeBaseSha: MERGED_FORK }),
161
+ );
154
162
  // After the merge the branch carries Bob's line too, and the fork point is
155
163
  // the target tip it was merged from.
156
164
  filesApi.readFileOnBranch.mockImplementation(async () => 'price: 120\nstatus: signed\n');
@@ -158,36 +166,43 @@ describe('ChangeRequestDialog: the files after the request brings itself up to d
158
166
  content: TARGET_TIP,
159
167
  forkSha: sha,
160
168
  }));
161
- mergeApi.refreshChangeRequestFromTarget.mockResolvedValue({});
162
169
 
163
170
  const { container } = render(
164
171
  <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
165
172
  );
166
173
 
167
174
  await waitFor(() => expect(mergeApi.refreshChangeRequestFromTarget).toHaveBeenCalledWith(21));
175
+ await waitFor(() =>
176
+ expect(filesApi.readFileAtForkPoint).toHaveBeenCalledWith(21, MERGED_FORK, 'Sales/deal.yaml'),
177
+ );
168
178
  await waitFor(() => expect(container.querySelector('ins')).not.toBeNull());
169
- expect(detailMock.fetchPrDetail).toHaveBeenLastCalledWith(21, { fresh: true });
170
- expect(filesApi.readFileAtForkPoint).toHaveBeenCalledWith(21, MERGED_FORK, 'Sales/deal.yaml');
171
- // NEVER against the fork point the update replaced: a read fired before
172
- // the merge would diff the proposal against a commit that no longer
173
- // describes what the author started from.
174
- expect(filesApi.readFileAtForkPoint).not.toHaveBeenCalledWith(21, FORK, 'Sales/deal.yaml');
179
+ // The update's own answer is the fresh detail; there is no second read.
180
+ expect(detailMock.fetchPrDetail).toHaveBeenCalledTimes(1);
181
+ // The proposal is still the author's line alone, read against the fork
182
+ // point the merge left.
175
183
  expect([...container.querySelectorAll('del')].map((n) => n.textContent)).toEqual(['price: 100']);
176
184
  expect([...container.querySelectorAll('ins')].map((n) => n.textContent)).toEqual(['price: 120']);
177
185
  await waitFor(() => expect(screen.queryByText('Loading…')).not.toBeInTheDocument());
178
186
  });
179
187
 
180
- it('an update that lands but cannot be reloaded says so, and still reads the open file', async () => {
181
- detailMock.fetchPrDetail.mockResolvedValueOnce(detail()).mockRejectedValue(new Error('503'));
182
- mergeApi.refreshChangeRequestFromTarget.mockResolvedValue({});
183
- filesApi.readFileOnBranch.mockImplementation(async () => 'price: 125\nstatus: draft\n');
188
+ it('shows the file against the OLD fork point before the update lands', async () => {
189
+ // What the reader gets for free now: the diff, immediately, while the
190
+ // merge runs behind it.
191
+ let land: (v: unknown) => void = () => {};
192
+ mergeApi.refreshChangeRequestFromTarget.mockImplementation(
193
+ () => new Promise((resolve) => (land = resolve)),
194
+ );
195
+ detailMock.fetchPrDetail.mockResolvedValue(detail());
196
+
184
197
  const { container } = render(
185
198
  <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
186
199
  );
187
200
 
188
- expect(
189
- await screen.findByText(/Updated, but couldn't reload this change request/),
190
- ).toBeInTheDocument();
191
- await waitFor(() => expect(container.querySelector('ins')?.textContent).toBe('price: 125'));
201
+ await waitFor(() => expect(container.querySelector('ins')?.textContent).toBe('price: 120'));
202
+ expect(filesApi.readFileAtForkPoint).toHaveBeenCalledWith(21, FORK, 'Sales/deal.yaml');
203
+ land(detail({ behind: false, needsUpdate: false, mergeBaseSha: MERGED_FORK }));
204
+ await waitFor(() =>
205
+ expect(filesApi.readFileAtForkPoint).toHaveBeenCalledWith(21, MERGED_FORK, 'Sales/deal.yaml'),
206
+ );
192
207
  });
193
208
  });
@@ -22,7 +22,14 @@ vi.mock('../../pr/services/pr-approvals.api', () => ({
22
22
  revertPrFile: approvalsApi.revertPrFile,
23
23
  unapprovePrFile: approvalsApi.unapprovePrFile,
24
24
  }));
25
- vi.mock('../../pr/services/pr-merge.api', () => ({ mergePullRequest: vi.fn() }));
25
+ const mergeApi = vi.hoisted(() => ({
26
+ mergePullRequest: vi.fn(),
27
+ refreshChangeRequestFromTarget: vi.fn(),
28
+ }));
29
+ vi.mock('../../pr/services/pr-merge.api', () => ({
30
+ mergePullRequest: mergeApi.mergePullRequest,
31
+ refreshChangeRequestFromTarget: mergeApi.refreshChangeRequestFromTarget,
32
+ }));
26
33
  const cancelApi = vi.hoisted(() => ({ deleteChangeRequest: vi.fn() }));
27
34
  vi.mock('../../pr/services/pr-cancel.api', () => ({
28
35
  cancelPullRequest: vi.fn(),
@@ -32,6 +39,7 @@ vi.mock('../../pr/services/pr-cancel.api', () => ({
32
39
  import { ChangeRequestDialog } from '../components/ChangeRequestDialog';
33
40
  import { AuthContext } from '../../auth/state/auth.context';
34
41
  import { readFileOnBranch } from '../services/change-requests.api';
42
+ import { GitApiError } from '../../git/services/git.api';
35
43
 
36
44
  const CR: PullRequestSummary = {
37
45
  number: 12,
@@ -50,6 +58,8 @@ const CR: PullRequestSummary = {
50
58
 
51
59
  beforeEach(() => {
52
60
  detailMock.fetchPrDetail.mockReset();
61
+ mergeApi.refreshChangeRequestFromTarget.mockReset();
62
+ cancelApi.deleteChangeRequest.mockReset();
53
63
  });
54
64
 
55
65
  describe('ChangeRequestDialog: a request with no remaining changes', () => {
@@ -377,29 +387,186 @@ describe('ChangeRequestDialog: the apply gate and the per-file verbs', () => {
377
387
  await waitFor(() => expect(onResolved).toHaveBeenCalled());
378
388
  });
379
389
 
380
- it('Delete request appears for admins only, arms, then deletes and resolves', async () => {
390
+ /**
391
+ * Delete is the author's verb as much as the admin's. The dialog asks the
392
+ * server one question — `viewerCanDelete` — so these tests never encode
393
+ * "is this an admin"; that decision lives on the server, beside the DELETE
394
+ * route that enforces it.
395
+ */
396
+ it('shows Delete request whenever the server says the viewer may delete, arms, then deletes and resolves', async () => {
381
397
  detailMock.fetchPrDetail.mockResolvedValue({
382
398
  ...detailWith([approval({})]),
383
- viewerCanBypassMerge: true,
399
+ // An author with no admin rights: exactly the case that used to see
400
+ // nothing here.
401
+ viewerCanBypassMerge: false,
402
+ viewerCanDelete: true,
403
+ viewerIsAuthor: true,
384
404
  });
385
405
  cancelApi.deleteChangeRequest.mockResolvedValue(undefined);
386
406
  const onResolved = vi.fn();
387
407
  render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={onResolved} />);
388
408
 
389
409
  fireEvent.click(await screen.findByRole('button', { name: 'Delete request' }));
410
+ // Nothing sent yet — the armed second click is the verdict.
390
411
  expect(cancelApi.deleteChangeRequest).not.toHaveBeenCalled();
391
- fireEvent.click(screen.getByRole('button', { name: 'Really delete request and branch?' }));
412
+ fireEvent.click(
413
+ screen.getByRole('button', { name: `Really delete request and branch ${CR.branch}?` }),
414
+ );
392
415
  await waitFor(() => expect(cancelApi.deleteChangeRequest).toHaveBeenCalledWith(12));
393
416
  await waitFor(() => expect(onResolved).toHaveBeenCalled());
394
417
  });
395
418
 
396
- it('no Delete request for non-admins', async () => {
397
- detailMock.fetchPrDetail.mockResolvedValue(detailWith([approval({})]));
419
+ it('shows no Delete request when the server says the viewer may not delete', async () => {
420
+ // A signed-in stranger, or an owner of every changed file: they may
421
+ // decline, never destroy.
422
+ detailMock.fetchPrDetail.mockResolvedValue({
423
+ ...detailWith([approval({})]),
424
+ viewerCanDelete: false,
425
+ viewerIsAuthor: false,
426
+ });
398
427
  render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
399
428
  await screen.findByText('Waiting on Admin');
400
429
  expect(screen.queryByRole('button', { name: 'Delete request' })).not.toBeInTheDocument();
401
430
  });
402
431
 
432
+ it('an admin reads exactly the wording the author reads', async () => {
433
+ // Same request, same branch, different viewer: the sentence must not
434
+ // change with who is looking — only with which branch is at stake.
435
+ detailMock.fetchPrDetail.mockResolvedValue({
436
+ ...detailWith([approval({})]),
437
+ viewerCanBypassMerge: true,
438
+ viewerCanDelete: true,
439
+ viewerIsAuthor: false,
440
+ });
441
+ render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
442
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete request' }));
443
+ expect(
444
+ screen.getByRole('button', { name: `Really delete request and branch ${CR.branch}?` }),
445
+ ).toBeInTheDocument();
446
+ });
447
+
448
+ it('names a draft branch in the armed confirmation', async () => {
449
+ const named = { ...CR, branch: 'juan/fix-copy' } as PullRequestSummary;
450
+ detailMock.fetchPrDetail.mockResolvedValue({
451
+ ...detailWith([approval({})]),
452
+ branch: 'juan/fix-copy',
453
+ viewerCanDelete: true,
454
+ viewerIsAuthor: true,
455
+ });
456
+ render(<ChangeRequestDialog cr={named} onClose={() => {}} onResolved={() => {}} />);
457
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete request' }));
458
+ // The branch is about to be removed for good; the confirmation says which.
459
+ expect(
460
+ screen.getByRole('button', { name: 'Really delete request and branch juan/fix-copy?' }),
461
+ ).toBeInTheDocument();
462
+ });
463
+
464
+ it('keeps the generic wording for a platform-made suggestions branch', async () => {
465
+ // The author never chose `suggestions/ali/...`; the platform did. Naming it
466
+ // would ask them to confirm a path they cannot recognise.
467
+ const suggested = { ...CR, branch: 'suggestions/ali/notes' } as PullRequestSummary;
468
+ detailMock.fetchPrDetail.mockResolvedValue({
469
+ ...detailWith([approval({})]),
470
+ branch: 'suggestions/ali/notes',
471
+ viewerCanDelete: true,
472
+ viewerIsAuthor: true,
473
+ });
474
+ render(<ChangeRequestDialog cr={suggested} onClose={() => {}} onResolved={() => {}} />);
475
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete request' }));
476
+ expect(
477
+ screen.getByRole('button', { name: 'Really delete request and branch?' }),
478
+ ).toBeInTheDocument();
479
+ expect(screen.queryByText(/suggestions\/ali\/notes\?/)).not.toBeInTheDocument();
480
+ });
481
+
482
+ it('Keep disarms without sending anything', async () => {
483
+ detailMock.fetchPrDetail.mockResolvedValue({
484
+ ...detailWith([approval({})]),
485
+ viewerCanDelete: true,
486
+ viewerIsAuthor: true,
487
+ });
488
+ render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
489
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete request' }));
490
+ fireEvent.click(screen.getByRole('button', { name: 'Keep' }));
491
+ // Back to the unarmed label, and nothing was asked of the server.
492
+ expect(await screen.findByRole('button', { name: 'Delete request' })).toBeInTheDocument();
493
+ expect(cancelApi.deleteChangeRequest).not.toHaveBeenCalled();
494
+ });
495
+
496
+ it('reports the server’s refusal in the dialog and leaves the request alone', async () => {
497
+ detailMock.fetchPrDetail.mockResolvedValue({
498
+ ...detailWith([approval({})]),
499
+ viewerCanDelete: true,
500
+ viewerIsAuthor: true,
501
+ });
502
+ // Applied between opening the dialog and confirming.
503
+ cancelApi.deleteChangeRequest.mockRejectedValue(
504
+ new Error('This change request has already been applied.'),
505
+ );
506
+ const onResolved = vi.fn();
507
+ render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={onResolved} />);
508
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete request' }));
509
+ fireEvent.click(
510
+ screen.getByRole('button', { name: `Really delete request and branch ${CR.branch}?` }),
511
+ );
512
+ expect(
513
+ await screen.findByText('This change request has already been applied.'),
514
+ ).toBeInTheDocument();
515
+ // The dialog stays open — nothing was removed, so nothing is resolved.
516
+ expect(onResolved).not.toHaveBeenCalled();
517
+ });
518
+
519
+ it('still offers Delete on a request stuck on a conflict', async () => {
520
+ // The stuck request is the one its author most wants to throw away and
521
+ // propose again, which is why the button is no longer hidden while the
522
+ // dialog is blocked. Reached the way the dialog really reaches it: the
523
+ // auto-update on open is refused as conflicting. `needsUpdate` is what
524
+ // starts that update (the target moved in a file this request changes);
525
+ // `behind` alone, the target having moved anywhere, no longer does.
526
+ detailMock.fetchPrDetail.mockResolvedValue({
527
+ ...detailWith([approval({})]),
528
+ behind: true,
529
+ needsUpdate: true,
530
+ viewerCanUpdate: true,
531
+ viewerCanDelete: true,
532
+ viewerIsAuthor: true,
533
+ });
534
+ mergeApi.refreshChangeRequestFromTarget.mockRejectedValue(
535
+ new GitApiError(409, 'conflicts', { kind: 'change-request-conflicts' }),
536
+ );
537
+ render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
538
+
539
+ // The blocked state is on screen…
540
+ expect(await screen.findByText(/Nothing changes for anyone until/)).toBeInTheDocument();
541
+ // …and Delete is there with it, armed wording intact.
542
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete request' }));
543
+ expect(
544
+ screen.getByRole('button', { name: `Really delete request and branch ${CR.branch}?` }),
545
+ ).toBeInTheDocument();
546
+ });
547
+
548
+ it('points the author at Delete when nothing is left to change, and names them for everyone else', async () => {
549
+ const empty = {
550
+ ...detailWith([]),
551
+ files: [],
552
+ approvals: [],
553
+ viewerCanDelete: true,
554
+ };
555
+ detailMock.fetchPrDetail.mockResolvedValue({ ...empty, viewerIsAuthor: true });
556
+ const { unmount } = render(
557
+ <ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />,
558
+ );
559
+ // Withdraw is not in this dialog; Delete is, right below this sentence.
560
+ expect(await screen.findByText(/You can delete it below\./)).toBeInTheDocument();
561
+ expect(screen.queryByText(/can withdraw it/)).not.toBeInTheDocument();
562
+ unmount();
563
+
564
+ detailMock.fetchPrDetail.mockResolvedValue({ ...empty, viewerIsAuthor: false });
565
+ render(<ChangeRequestDialog cr={CR} onClose={() => {}} onResolved={() => {}} />);
566
+ // Third person, first name only — the author is who can clear it up.
567
+ expect(await screen.findByText(/Ali can delete it\./)).toBeInTheDocument();
568
+ });
569
+
403
570
  it("folds a long description to one line: Read more opens it, Hide folds it back", async () => {
404
571
  // Agents write essays. The decision is made on the diff — the quote gets
405
572
  // one row by default and only what the reader asks for beyond it.