@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
@@ -0,0 +1,155 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { Banner, Button, TextAreaField } from '../../../shared/components';
3
+ import {
4
+ fetchAccessRequestStatus,
5
+ sendAccessRequest,
6
+ LEVEL_WORDS,
7
+ REQUEST_NOTE_MAX,
8
+ type AccessRequestStatus,
9
+ type RequestLevel,
10
+ } from '../requests.api';
11
+
12
+ /**
13
+ * "You can read this, but you can't share it" — with something to do about it.
14
+ *
15
+ * The read-only Manage access dialog used to end at "Ask an owner: Ed." and
16
+ * leave the reader to find Ed some other way. This is the rest of that
17
+ * sentence: choose Can edit or Owner, say why if it helps, and the people who
18
+ * can already edit the item answer it in the same dialog.
19
+ *
20
+ * ONE OPEN REQUEST PER PERSON PER ITEM. While it is open the control is
21
+ * replaced by what was asked and who is being waited on, and the level cannot
22
+ * be changed — a person who wants the other level waits for the answer, or an
23
+ * editor grants it directly. Sending twice (a double click, two tabs) is
24
+ * answered by the request the first send opened, so there is still exactly
25
+ * one.
26
+ *
27
+ * NOTHING SAYS "Requested" UNLESS THE REQUEST EXISTS. The state is read back
28
+ * from the server, and a send that fails says so and keeps the control — a
29
+ * hopeful local "sent!" is the one lie this surface must not tell, because
30
+ * the person would then wait on nobody.
31
+ */
32
+ export interface AccessRequestControlProps {
33
+ workspaceId: string;
34
+ /** The item, exactly as the dialog addresses it for a grant. */
35
+ target: { path: string; kind: 'folder' | 'file' };
36
+ /** `file` or `folder` — the word the surrounding sentences use. */
37
+ targetKind: 'folder' | 'file';
38
+ /**
39
+ * The same up-to-three names the "Ask an owner" line shows, or '' when the
40
+ * item names nobody. Kept identical on purpose: the line that says who to
41
+ * ask and the line that says who is being waited on must not disagree.
42
+ */
43
+ ownerNames: string;
44
+ }
45
+
46
+ export function AccessRequestControl({
47
+ workspaceId,
48
+ target,
49
+ targetKind,
50
+ ownerNames,
51
+ }: AccessRequestControlProps) {
52
+ const [status, setStatus] = useState<AccessRequestStatus | null>(null);
53
+ const [level, setLevel] = useState<RequestLevel>('write');
54
+ const [note, setNote] = useState('');
55
+ const [sending, setSending] = useState(false);
56
+ const [error, setError] = useState<string | null>(null);
57
+ const { path, kind } = target;
58
+
59
+ useEffect(() => {
60
+ let cancelled = false;
61
+ fetchAccessRequestStatus(workspaceId, { path, kind })
62
+ .then((next) => {
63
+ if (!cancelled) setStatus(next);
64
+ })
65
+ .catch(() => {
66
+ // A status that cannot be read is reported as nothing outstanding:
67
+ // the control stays, and a send would find the open request anyway.
68
+ if (!cancelled) setStatus({ state: 'none' });
69
+ });
70
+ return () => {
71
+ cancelled = true;
72
+ };
73
+ }, [workspaceId, path, kind]);
74
+
75
+ const send = useCallback(async () => {
76
+ setSending(true);
77
+ setError(null);
78
+ try {
79
+ const opened = await sendAccessRequest(workspaceId, {
80
+ path,
81
+ kind,
82
+ level,
83
+ note: note.trim() || undefined,
84
+ });
85
+ // The server's answer, not the click's hope: a second send while a
86
+ // request is open comes back with THAT request, level and all.
87
+ setStatus({ state: 'pending', level: opened.level, number: opened.number });
88
+ } catch (err) {
89
+ setError(err instanceof Error ? err.message : String(err));
90
+ } finally {
91
+ setSending(false);
92
+ }
93
+ }, [workspaceId, path, kind, level, note]);
94
+
95
+ // Nothing at all until the server has spoken: a control that flashes up and
96
+ // is then replaced by "Requested" reads as a send that happened by itself.
97
+ if (!status) return null;
98
+
99
+ if (status.state === 'pending') {
100
+ const who = ownerNames || `the people who can edit its access`;
101
+ return (
102
+ <p className="mt-2 text-detail text-ink-muted" role="status">
103
+ {`Requested: ${LEVEL_WORDS[status.level ?? 'write']}. Waiting on ${who}.`}
104
+ </p>
105
+ );
106
+ }
107
+
108
+ return (
109
+ <div className="mt-2 flex flex-col gap-2">
110
+ {status.state === 'not-accepted' && (
111
+ <p className="text-detail text-ink-muted">
112
+ {`Your last request for ${LEVEL_WORDS[status.level ?? 'write']} wasn't accepted.`}
113
+ </p>
114
+ )}
115
+ <div
116
+ role="radiogroup"
117
+ aria-label={`What to ask for on this ${targetKind}`}
118
+ className="flex items-center gap-4"
119
+ >
120
+ {(['write', 'owner'] as const).map((option) => (
121
+ <label key={option} className="flex items-center gap-1.5 text-detail text-ink">
122
+ <input
123
+ type="radio"
124
+ name="access-request-level"
125
+ value={option}
126
+ checked={level === option}
127
+ disabled={sending}
128
+ onChange={() => setLevel(option)}
129
+ />
130
+ {LEVEL_WORDS[option]}
131
+ </label>
132
+ ))}
133
+ </div>
134
+ <TextAreaField
135
+ aria-label="Why you need it (optional)"
136
+ placeholder="Why you need it (optional)"
137
+ maxLength={REQUEST_NOTE_MAX}
138
+ disabled={sending}
139
+ value={note}
140
+ onChange={(e) => setNote(e.target.value)}
141
+ />
142
+ <div>
143
+ <Button variant="outline" size="sm" disabled={sending} onClick={() => void send()}>
144
+ Request access
145
+ </Button>
146
+ </div>
147
+ {error && (
148
+ <Banner tone="danger" role="alert">
149
+ {/* One trailing stop, whatever the server's sentence ended with. */}
150
+ {`Couldn't send your request: ${error.replace(/\s*\.$/, '')}.`}
151
+ </Banner>
152
+ )}
153
+ </div>
154
+ );
155
+ }
@@ -1,11 +1,12 @@
1
1
  import type { ReactNode } from 'react';
2
2
  import { Banner, Button } from '../../../shared/components';
3
3
  import { cn } from '../../../lib/utils';
4
- import type { JoinProposal, JoinRequest } from '../services/plugins.api';
4
+ import type { AccessProposal, AccessRequestRow } from '../requests.api';
5
5
 
6
6
  /**
7
- * Somebody asked for access to this plugin — the manager-side face of a join change
8
- * request.
7
+ * Somebody asked for access to this item — the editor-side face of an access
8
+ * request, wherever the item lives: a plugin's page, a skill's page, or the
9
+ * Manage access dialog of any file or folder.
9
10
  *
10
11
  * It shows what the request PROPOSES, one row per grant, because that is what
11
12
  * accepting acts on: each Accept writes exactly that one grant onto the
@@ -14,42 +15,57 @@ import type { JoinProposal, JoinRequest } from '../services/plugins.api';
14
15
  * yeses and three ignores, and nothing the branch happens to carry besides
15
16
  * the grants can ride in on a click.
16
17
  *
17
- * Naming the verb is not pedantry: a request may propose `write` or `owner`
18
+ * Naming the level is not pedantry: a request may propose `write` or `owner`
18
19
  * rather than `read`, and "asked for access to" would hide that. Whatever the
19
- * branch asks for is what the row says.
20
+ * branch asks for is what the row says — in the caller's vocabulary, since a
21
+ * dialog that calls it "Can edit" everywhere else must not suddenly say
22
+ * "write" here.
20
23
  *
21
- * Decline rejects the whole request. Manage access is the third path — a
22
- * manager who wants to do something other than what was proposed opens the
23
- * dialog, and the request settles itself if that covers it.
24
+ * Decline rejects the whole request. Manage access is the third path — an
25
+ * editor who wants to do something other than what was proposed opens the
26
+ * dialog, and the request settles itself if that covers it. Inside that
27
+ * dialog there is nothing to link to, so `folders` is empty there and the
28
+ * link does not render.
24
29
  */
25
30
 
26
31
  export interface AccessRequestsBannerProps {
27
- plugin: string;
28
- /** Repo-relative plugin folder for `Manage access` (single-element today). */
32
+ /** What the item is called on the line: a plugin, a skill, a file, a folder. */
33
+ itemName: string;
34
+ /** Repo-relative folders for `Manage access`. Empty ⇒ no link (the dialog). */
29
35
  folders: string[];
30
- requests: JoinRequest[];
36
+ requests: AccessRequestRow[];
31
37
  onManage(folder: string): void;
32
- onAccept(request: JoinRequest, proposal: JoinProposal): void;
33
- onDecline(request: JoinRequest): void;
38
+ onAccept(request: AccessRequestRow, proposal: AccessProposal): void;
39
+ onDecline(request: AccessRequestRow): void;
40
+ /** How to spell a verb. Defaults to the verb itself (the Library's wording). */
41
+ verbLabel?(verb: AccessProposal['verb']): string;
42
+ /** What went wrong answering this request, shown on its own line. */
43
+ errorFor?(request: AccessRequestRow): string | null | undefined;
44
+ /** Requests being answered right now — their buttons wait. */
45
+ busyFor?(request: AccessRequestRow): boolean;
34
46
  className?: string;
35
47
  }
36
48
 
37
49
  export function AccessRequestsBanner({
38
- plugin,
50
+ itemName,
39
51
  folders,
40
52
  requests,
41
53
  onManage,
42
54
  onAccept,
43
55
  onDecline,
56
+ verbLabel = (verb) => verb,
57
+ errorFor,
58
+ busyFor,
44
59
  className,
45
60
  }: AccessRequestsBannerProps) {
46
61
  if (requests.length === 0) return null;
47
62
 
48
- const accept = (request: JoinRequest, proposal: JoinProposal) => (
63
+ const accept = (request: AccessRequestRow, proposal: AccessProposal) => (
49
64
  <Button
50
65
  variant="outline"
51
66
  size="sm"
52
- aria-label={`Grant ${proposal.verb} to ${proposal.label}`}
67
+ disabled={busyFor?.(request) ?? false}
68
+ aria-label={`Grant ${verbLabel(proposal.verb)} to ${proposal.label}`}
53
69
  onClick={() => onAccept(request, proposal)}
54
70
  >
55
71
  Accept
@@ -64,16 +80,37 @@ export function AccessRequestsBanner({
64
80
  const lines: { key: string; text: ReactNode; actions: ReactNode; nested?: boolean }[] = [];
65
81
  for (const request of requests) {
66
82
  const single = request.proposals.length === 1 ? request.proposals[0] : null;
83
+ const note = request.note?.trim();
84
+ const failure = errorFor?.(request);
67
85
  lines.push({
68
86
  key: `request:${request.number}`,
69
- text: single ? (
87
+ text: (
70
88
  <>
71
- {`${request.requesterName} asked for access to ${plugin}: `}
72
- {single.label !== request.requesterName && `${single.label}, `}
73
- <span className="font-semibold">{single.verb}</span>
89
+ {single ? (
90
+ <>
91
+ {`${request.requesterName} asked for access to ${itemName}: `}
92
+ {single.label !== request.requesterName && `${single.label}, `}
93
+ <span className="font-semibold">{verbLabel(single.verb)}</span>
94
+ </>
95
+ ) : (
96
+ `${request.requesterName} asked for access to ${itemName}.`
97
+ )}
98
+ {/* The requester's own words, under the line they belong to and as
99
+ plain text — it is someone else's writing, not markup. */}
100
+ {note && (
101
+ <span className="mt-0.5 block whitespace-pre-line text-detail text-ink-muted">
102
+ {note}
103
+ </span>
104
+ )}
105
+ {/* A refusal belongs to the request it refused, never only to a
106
+ toast: this banner lives inside a dialog that has no toast host,
107
+ and an error shown there would simply vanish. */}
108
+ {failure && (
109
+ <span role="alert" className="mt-0.5 block text-detail text-danger">
110
+ {failure}
111
+ </span>
112
+ )}
74
113
  </>
75
- ) : (
76
- `${request.requesterName} asked for access to ${plugin}.`
77
114
  ),
78
115
  actions: (
79
116
  <>
@@ -81,6 +118,7 @@ export function AccessRequestsBanner({
81
118
  <Button
82
119
  variant="quiet"
83
120
  size="sm"
121
+ disabled={busyFor?.(request) ?? false}
84
122
  aria-label={`Decline the request from ${request.requesterName}`}
85
123
  onClick={() => onDecline(request)}
86
124
  >
@@ -96,7 +134,7 @@ export function AccessRequestsBanner({
96
134
  text: (
97
135
  <>
98
136
  {`${proposal.label}: `}
99
- <span className="font-semibold">{proposal.verb}</span>
137
+ <span className="font-semibold">{verbLabel(proposal.verb)}</span>
100
138
  </>
101
139
  ),
102
140
  actions: accept(request, proposal),
@@ -117,7 +155,7 @@ export function AccessRequestsBanner({
117
155
  <span className="flex shrink-0 items-center gap-1.5">
118
156
  {line.actions}
119
157
  {/* The third path, said as a link rather than a button of its
120
- own: the manager who wants something other than what was
158
+ own: the editor who wants something other than what was
121
159
  proposed. It closes the banner's last line. */}
122
160
  {i === lines.length - 1 &&
123
161
  folders.map((folder) => (
@@ -13,6 +13,7 @@ import { X, Lock, Loader2, ChevronDown, Check, Globe, CircleHelp } from 'lucide-
13
13
  import {
14
14
  canCarryFrontmatter,
15
15
  conferredByOthers,
16
+ DEFAULT_BRANCH,
16
17
  effectiveVerbs,
17
18
  folderGovernsAccessMessage,
18
19
  KNOWN_VERBS,
@@ -55,6 +56,10 @@ import {
55
56
  type SuggestResponse,
56
57
  } from '../api';
57
58
  import { EMAIL_RE, initials, labelInitials } from '../../../lib/email';
59
+ import { AccessRequestControl } from './AccessRequestControl';
60
+ import { AccessRequestsBanner } from './AccessRequestsBanner';
61
+ import { useAccessRequests } from '../hooks/useAccessRequests';
62
+ import { listAccessRequests, reconcileAccessRequest, LEVEL_WORDS } from '../requests.api';
58
63
 
59
64
  interface Props {
60
65
  entry: FileTreeEntry;
@@ -1182,6 +1187,49 @@ export function ManageAccessDialog({
1182
1187
  // Never on a folder-governed file: there is nothing here to write to.
1183
1188
  const canManage = !!data?.canWrite && !folderGoverns;
1184
1189
 
1190
+ /**
1191
+ * Is this sheet showing the LIVE workspace?
1192
+ *
1193
+ * Asking for access is offered there and nowhere else. A draft branch's
1194
+ * rules may differ from the ones the person is actually asking about, and a
1195
+ * file that exists only on a change request has no live rules at all — a
1196
+ * request from either would propose a grant into a branch nobody merges.
1197
+ * Both cases keep today's dialog, unchanged.
1198
+ */
1199
+ const liveWorkspace = !proposal && workspaceId === encodeURIComponent(DEFAULT_BRANCH);
1200
+
1201
+ /** What Accept grants on, and what the request routes are asked about. */
1202
+ const requestTarget = useMemo(
1203
+ () => ({ path: entry.relativePath, kind: targetKind }),
1204
+ [entry.relativePath, targetKind],
1205
+ );
1206
+
1207
+ // The item's open requests, for the people who can answer them. Asked for
1208
+ // unconditionally on the live workspace: the endpoint answers `[]` to
1209
+ // everyone who is not an editor, so "may I answer these" stays the server's
1210
+ // ruling rather than a guess made from `canManage`.
1211
+ const requestsSource = useMemo(
1212
+ () => ({
1213
+ list: () =>
1214
+ workspaceId && governed && liveWorkspace
1215
+ ? listAccessRequests(workspaceId, requestTarget)
1216
+ : Promise.resolve([]),
1217
+ reconcile: (number: number) =>
1218
+ workspaceId
1219
+ ? reconcileAccessRequest(workspaceId, number, requestTarget)
1220
+ : Promise.resolve(false),
1221
+ }),
1222
+ [workspaceId, governed, liveWorkspace, requestTarget],
1223
+ );
1224
+ const accessRequests = useAccessRequests({
1225
+ itemKey: liveWorkspace && governed ? `${workspaceId}:${entry.relativePath}` : null,
1226
+ source: requestsSource,
1227
+ grantOn: requestTarget,
1228
+ // The new row has to be on screen before the request's line goes, or an
1229
+ // Accept looks like it did nothing at all.
1230
+ onGranted: reload,
1231
+ });
1232
+
1185
1233
  // Resolve the CURRENT typed query into a principal to append as a chip: an
1186
1234
  // exact group/role match or a free-typed email. (Suggestion clicks append
1187
1235
  // directly.) Group first — bare grant tokens resolve group-first, so a name
@@ -1826,6 +1874,21 @@ export function ManageAccessDialog({
1826
1874
  </Banner>
1827
1875
  )}
1828
1876
 
1877
+ {/* Somebody is waiting on an answer, at the top of the sheet where the
1878
+ answer is given. No "Manage access" link: this IS that dialog. */}
1879
+ <AccessRequestsBanner
1880
+ itemName={entry.name}
1881
+ folders={[]}
1882
+ requests={accessRequests.requests}
1883
+ onManage={() => {}}
1884
+ onAccept={(r, pr) => void accessRequests.accept(r, pr)}
1885
+ onDecline={(r) => void accessRequests.decline(r)}
1886
+ verbLabel={(verb) => LEVEL_WORDS[verb as 'write' | 'owner'] ?? verb}
1887
+ errorFor={(r) => accessRequests.errors[r.number]}
1888
+ busyFor={(r) => !!accessRequests.busy[r.number]}
1889
+ className="mb-0 mt-3"
1890
+ />
1891
+
1829
1892
  {governed && canManage && (
1830
1893
  <div className="mt-3">
1831
1894
  {/* `items-start`, not `items-stretch`: the verb button is `rounded-full`,
@@ -2149,10 +2212,24 @@ export function ManageAccessDialog({
2149
2212
  ) : (
2150
2213
  <>
2151
2214
  {!canManage && (
2152
- <Banner tone="neutral" role="note" className="mt-3">
2153
- Only people with edit access can share this {targetKind}.
2154
- {ownerNames && <> Ask an owner: {ownerNames}.</>}
2155
- </Banner>
2215
+ <>
2216
+ <Banner tone="neutral" role="note" className="mt-3">
2217
+ Only people with edit access can share this {targetKind}.
2218
+ {ownerNames && <> Ask an owner: {ownerNames}.</>}
2219
+ </Banner>
2220
+ {/* The rest of that sentence. Only on the live workspace,
2221
+ and only where the item has rules of its own to ask
2222
+ about — a folder-governed file keeps its pointer at the
2223
+ folder, whose dialog carries the control. */}
2224
+ {liveWorkspace && workspaceId && (
2225
+ <AccessRequestControl
2226
+ workspaceId={workspaceId}
2227
+ target={requestTarget}
2228
+ targetKind={targetKind}
2229
+ ownerNames={ownerNames}
2230
+ />
2231
+ )}
2232
+ </>
2156
2233
  )}
2157
2234
 
2158
2235
  {/* Names WHICH RULE you are editing, and adapts to the target
@@ -0,0 +1,183 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { DEFAULT_BRANCH } from '@bevel-software/platform-shared';
3
+ import { useLatestRef } from '../../../shared/components';
4
+ import { grantAccess } from '../api';
5
+ import { cancelPullRequest } from '../../pr/services/pr-cancel.api';
6
+ import type { AccessProposal, AccessRequestRow } from '../requests.api';
7
+
8
+ /**
9
+ * The access requests one item's editors can answer, and the two ways to
10
+ * answer them.
11
+ *
12
+ * ACCEPTING IS A GRANT, NOT A MERGE. A proposal is "give this principal this
13
+ * verb on this item", so accepting it calls the ordinary access-grant API —
14
+ * the same endpoint the Manage access dialog's own rows use, with the same
15
+ * gate, lock and commit, and the same answer for a person the rules explicitly
16
+ * deny. The request's branch is never merged, so nothing else it carries can
17
+ * ride in on an approval, and a request naming five people can be answered
18
+ * with two yeses and three ignores.
19
+ *
20
+ * The request then retires ITSELF: it is open exactly while it proposes
21
+ * something the person does not already hold, so once the accepted grant lands
22
+ * the server closes it and deletes the branch. `reconcile` just asks for that
23
+ * check immediately instead of waiting for the next listing (which does it
24
+ * too).
25
+ *
26
+ * Fetching is unconditional and degrades to `[]` — the endpoints answer `[]`
27
+ * to non-editors rather than 403, so "am I an editor here" stays a question
28
+ * only the server answers.
29
+ */
30
+ export interface AccessRequestsState {
31
+ requests: AccessRequestRow[];
32
+ /** Grant one proposal, then settle the request if that was the last one. */
33
+ accept(request: AccessRequestRow, proposal: AccessProposal): Promise<void>;
34
+ /** Decline the whole request — reject the change request. */
35
+ decline(request: AccessRequestRow): Promise<void>;
36
+ /** Why answering a request failed, by request number. Cleared by a retry. */
37
+ errors: Readonly<Record<number, string>>;
38
+ /** Request numbers being answered right now. */
39
+ busy: Readonly<Record<number, boolean>>;
40
+ reload(): void;
41
+ }
42
+
43
+ /** Where the requests come from — one item's listing and its settle call. */
44
+ export interface AccessRequestsSource {
45
+ list(): Promise<AccessRequestRow[]>;
46
+ reconcile(number: number): Promise<boolean>;
47
+ }
48
+
49
+ export interface UseAccessRequestsOptions {
50
+ /**
51
+ * What identifies the item. Requests are shown only while the key they
52
+ * arrived for is still the one being asked about: a page that moves from
53
+ * skill A to skill B without unmounting must not show A's requests until
54
+ * B's arrive — a banner that lets an editor grant A's proposal against B's
55
+ * rules.
56
+ */
57
+ itemKey: string | null;
58
+ source: AccessRequestsSource;
59
+ /** What an Accept grants on. Null ⇒ Accept does nothing. */
60
+ grantOn: { path: string; kind: 'folder' | 'file' } | null;
61
+ /** Run after a grant lands — where the caller re-reads what it shows. */
62
+ onGranted?(): void | Promise<void>;
63
+ /** Told what went wrong, on top of the per-request `errors` map. */
64
+ onError?(message: string): void;
65
+ /** Told what landed, for surfaces that announce it. */
66
+ onAccepted?(message: string): void;
67
+ }
68
+
69
+ export function useAccessRequests(opts: UseAccessRequestsOptions): AccessRequestsState {
70
+ const { itemKey, source, grantOn, onGranted, onError, onAccepted } = opts;
71
+ // Keyed by the item they came from — see `itemKey`.
72
+ const [loaded, setLoaded] = useState<{ key: string; rows: AccessRequestRow[] } | null>(null);
73
+ const requests = loaded && itemKey !== null && loaded.key === itemKey ? loaded.rows : [];
74
+ const [revision, setRevision] = useState(0);
75
+ const [errors, setErrors] = useState<Record<number, string>>({});
76
+ const [busy, setBusy] = useState<Record<number, boolean>>({});
77
+
78
+ // Held in a ref rather than in the effect's deps: these are values the
79
+ // caller rebuilds on every render, and depending on them would refetch the
80
+ // listing on every render — including the re-render the listing's own answer
81
+ // causes. Read only from effects and event handlers, never during render.
82
+ const live = useLatestRef({ source, grantOn, onGranted, onError, onAccepted });
83
+
84
+ useEffect(() => {
85
+ if (itemKey === null) return;
86
+ let cancelled = false;
87
+ live.current.source
88
+ .list()
89
+ .then((rows) => {
90
+ if (!cancelled) setLoaded({ key: itemKey, rows });
91
+ })
92
+ .catch(() => {
93
+ // Silent: an editor surface that fails must not put an error banner in
94
+ // front of somebody who came to read the item.
95
+ });
96
+ return () => {
97
+ cancelled = true;
98
+ };
99
+ // `live` is a stable ref object; it is listed only to satisfy the rule.
100
+ }, [itemKey, revision, live]);
101
+
102
+ const reload = useCallback(() => setRevision((r) => r + 1), []);
103
+
104
+ const mark = (number: number, running: boolean) =>
105
+ setBusy((b) => ({ ...b, [number]: running }));
106
+
107
+ const accept = useCallback(async (request: AccessRequestRow, proposal: AccessProposal) => {
108
+ const { grantOn: target, onGranted: granted, onError: fail, onAccepted: ok } = live.current;
109
+ if (!target) return;
110
+ setErrors((e) => {
111
+ if (!(request.number in e)) return e;
112
+ const next = { ...e };
113
+ delete next[request.number];
114
+ return next;
115
+ });
116
+ mark(request.number, true);
117
+ try {
118
+ await grantAccess(encodeURIComponent(DEFAULT_BRANCH), {
119
+ path: target.path,
120
+ kind: target.kind,
121
+ verb: proposal.verb,
122
+ principal: proposal.principal,
123
+ });
124
+ } catch (err) {
125
+ // The request STAYS OPEN: nothing was granted, so there is nothing to
126
+ // settle, and hiding the line would lose the only place the refusal is
127
+ // visible.
128
+ const message = err instanceof Error ? err.message : "Couldn't grant that: try again.";
129
+ setErrors((e) => ({ ...e, [request.number]: message }));
130
+ fail?.(message);
131
+ mark(request.number, false);
132
+ setRevision((r) => r + 1);
133
+ return;
134
+ }
135
+ // Drop the accepted proposal locally so the row goes immediately; the
136
+ // refetch below is what makes it true.
137
+ setLoaded((cur) =>
138
+ cur && itemKey !== null && cur.key === itemKey
139
+ ? {
140
+ ...cur,
141
+ rows: cur.rows.map((r) =>
142
+ r.number === request.number
143
+ ? {
144
+ ...r,
145
+ proposals: r.proposals.filter(
146
+ (p) => !(p.id === proposal.id && p.verb === proposal.verb),
147
+ ),
148
+ }
149
+ : r,
150
+ ),
151
+ }
152
+ : cur,
153
+ );
154
+ ok?.(`${proposal.label} now has ${proposal.verb} access.`);
155
+ // The caller re-reads FIRST: the new row has to be on screen by the time
156
+ // the request's line goes, or accepting looks like it did nothing.
157
+ await Promise.resolve(granted?.()).catch(() => undefined);
158
+ await live.current.source.reconcile(request.number).catch(() => false);
159
+ mark(request.number, false);
160
+ setRevision((r) => r + 1);
161
+ }, [itemKey, live]);
162
+
163
+ const decline = useCallback(async (request: AccessRequestRow) => {
164
+ mark(request.number, true);
165
+ try {
166
+ await cancelPullRequest(request.number);
167
+ setErrors((e) => {
168
+ if (!(request.number in e)) return e;
169
+ const next = { ...e };
170
+ delete next[request.number];
171
+ return next;
172
+ });
173
+ } catch (err) {
174
+ const message = err instanceof Error ? err.message : "Couldn't dismiss that: try again.";
175
+ setErrors((e) => ({ ...e, [request.number]: message }));
176
+ live.current.onError?.(message);
177
+ }
178
+ mark(request.number, false);
179
+ setRevision((r) => r + 1);
180
+ }, [live]);
181
+
182
+ return { requests, accept, decline, errors, busy, reload };
183
+ }