@bevel-software/platform-core-frontend 0.28.1 → 0.30.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 (59) hide show
  1. package/package.json +11 -4
  2. package/src/core/CoreAppShell.tsx +29 -11
  3. package/src/core/__tests__/ShellRoutes.test.tsx +43 -1
  4. package/src/core/events.ts +4 -2
  5. package/src/core/registry.ts +25 -3
  6. package/src/modules/embed/__tests__/EmbedView.test.tsx +560 -17
  7. package/src/modules/embed/__tests__/embed-config.test.ts +77 -1
  8. package/src/modules/embed/__tests__/mcp-app-view.test.ts +203 -1
  9. package/src/modules/embed/components/EmbedView.tsx +233 -47
  10. package/src/modules/embed/embed-config.ts +126 -2
  11. package/src/modules/embed/embed-host.ts +11 -2
  12. package/src/modules/embed/mount.tsx +1 -0
  13. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +213 -4
  14. package/src/modules/library/__tests__/PluginPage.test.tsx +1 -1
  15. package/src/modules/library/__tests__/SkillPage.test.tsx +10 -0
  16. package/src/modules/library/components/LibraryLayout.tsx +2 -2
  17. package/src/modules/library/components/PluginPage.tsx +2 -1
  18. package/src/modules/library/components/skill-page/SkillPage.tsx +2 -2
  19. package/src/modules/library/components/tool-page/ToolPage.tsx +1 -1
  20. package/src/modules/library/index.ts +18 -0
  21. package/src/modules/library/routes/LibraryRoutes.tsx +17 -1
  22. package/src/modules/library/routes/library-paths.ts +16 -2
  23. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +3 -3
  24. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +39 -32
  25. package/src/modules/secrets-vault/components/SecretsPage.tsx +9 -24
  26. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +111 -8
  27. package/src/modules/secrets-vault/components/__tests__/connect-lists-what-the-banner-counted.test.tsx +1 -1
  28. package/src/modules/secrets-vault/index.ts +7 -0
  29. package/src/modules/settings/settings-nav-items.tsx +3 -3
  30. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -37
  31. package/src/modules/toolbar/commands/actions.tsx +62 -50
  32. package/src/modules/toolbar/commands/command-menu.ts +37 -3
  33. package/src/modules/toolbar/commands/useCommandShortcuts.ts +29 -76
  34. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +4 -2
  35. package/src/modules/toolbar/components/SearchPalette.tsx +20 -21
  36. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +5 -2
  37. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +242 -103
  38. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +51 -1
  39. package/src/modules/toolbar/search/__tests__/rank.test.ts +7 -3
  40. package/src/modules/workflow/hooks/__tests__/useFileLock.test.tsx +475 -0
  41. package/src/modules/workflow/hooks/__tests__/useFileLock.wire.test.tsx +115 -0
  42. package/src/modules/workflow/hooks/useFileLock.ts +321 -57
  43. package/src/modules/workflow/index.ts +8 -0
  44. package/src/modules/workflow/services/__tests__/lock.api.test.ts +4 -0
  45. package/src/modules/workflow/services/lock.api.ts +28 -9
  46. package/src/modules/workspace/components/FileViewer.tsx +30 -16
  47. package/src/modules/workspace/components/KbPageHeader.tsx +8 -1
  48. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +107 -4
  49. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +12 -0
  50. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +118 -13
  51. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.test.tsx +189 -0
  52. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +9 -0
  53. package/src/modules/workspace/components/renderers/__tests__/kbGraphLoader.test.tsx +60 -0
  54. package/src/modules/workspace/components/renderers/frameResizeHandle.ts +116 -0
  55. package/src/modules/workspace/components/renderers/index.ts +6 -0
  56. package/src/modules/workspace/components/renderers/kbGraphLoader.ts +27 -0
  57. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +1 -1
  58. package/src/modules/workspace/components/renderers/rendererSurface.ts +19 -0
  59. package/src/modules/workspace/index.ts +33 -0
@@ -1,14 +1,16 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
1
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
2
2
  import { useLocation, useNavigate } from 'react-router-dom';
3
3
  import { Button } from '../../../shared/components';
4
4
  import { useAppRegistry } from '../../../core/registry';
5
- import { isViewOnlyFile, pickFileRenderer } from '../../workspace/components/renderers';
6
- import { CanDownloadContext } from '../../workspace/components/renderers/DownloadFileButton';
7
5
  import {
6
+ CanDownloadContext,
7
+ isViewOnlyFile,
8
+ kbFileUrl,
9
+ pickFileRenderer,
8
10
  RendererSurfaceContext,
11
+ RendererWorkspaceContext,
9
12
  type RendererSurface,
10
- } from '../../workspace/components/renderers/rendererSurface';
11
- import { RendererWorkspaceContext } from '../../workspace/components/renderers/rendererWorkspace';
13
+ } from '../../workspace';
12
14
  import {
13
15
  cancelEmbed,
14
16
  embedRawUrl,
@@ -20,9 +22,17 @@ import {
20
22
  saveEmbed,
21
23
  type EmbedFileView,
22
24
  } from '../services/embed.api';
23
- import { EMBED_EXPIRED, openThroughHost } from '../embed-host';
24
- import { embedBaseUrl, embedToken } from '../embed-config';
25
- import { kbFileUrl } from '../../workspace/routing/kb-routes';
25
+ import { EMBED_EXPIRED, EMBED_HEIGHT_MESSAGE, hostOrigin, openThroughHost } from '../embed-host';
26
+ import {
27
+ embedApiBase,
28
+ embedBaseUrl,
29
+ embedCanRenew,
30
+ embedSizing,
31
+ embedToken,
32
+ onEmbedTokenRenewed,
33
+ renewEmbedToken,
34
+ withEmbedToken,
35
+ } from '../embed-config';
26
36
 
27
37
  /** How often a held lock is kept alive while somebody is editing. */
28
38
  const HEARTBEAT_MS = 30_000;
@@ -39,6 +49,15 @@ const READ_WITHDRAWN =
39
49
  "You no longer have access to this page, so these changes can't be saved or proposed. " +
40
50
  'Copy anything you want to keep before you discard them.';
41
51
 
52
+ /**
53
+ * A call refused for its token AFTER the renewal `withEmbedToken` tries —
54
+ * or where there was nothing to renew with (the SPA page). The view has
55
+ * expired.
56
+ */
57
+ function refusedForToken(err: unknown): boolean {
58
+ return err instanceof EmbedApiError && err.status === 401;
59
+ }
60
+
42
61
  function lockLostMessage(holder: string): string {
43
62
  return `${holder} started editing this page while it was in the background — your draft can't be saved over theirs.`;
44
63
  }
@@ -94,11 +113,21 @@ function embedRawPath(
94
113
 
95
114
  export function EmbedView() {
96
115
  // Handed over by the MCP App view that mounted this, or read from the
97
- // page URL on the SPA's `/embed` route — see `embed-config`.
98
- const token = embedToken();
116
+ // page URL on the SPA's `/embed` route — see `embed-config`. Every call
117
+ // reads it afresh through `withEmbedToken`, which renews it once when a
118
+ // call is refused for it (the chat view; the SPA page has no way to); the
119
+ // copy here is for the byte addresses a renderer holds, and follows a
120
+ // renewal.
121
+ const [token, setToken] = useState(embedToken);
122
+ useEffect(() => onEmbedTokenRenewed(() => setToken(embedToken())), []);
99
123
  const registry = useAppRegistry();
124
+ const graphSource = registry.kbGraphSource;
100
125
  const [view, setView] = useState<EmbedFileView | null>(null);
101
- /** An expired/absent/rejected token — the one state that shows no content. */
126
+ /**
127
+ * An expired/absent/rejected token that could not be renewed — the one
128
+ * state that shows no content. A draft that was open stays on screen
129
+ * above the sentence, so nothing typed is lost.
130
+ */
102
131
  const [expired, setExpired] = useState(!token);
103
132
  const [loadError, setLoadError] = useState<string | null>(null);
104
133
  const [mode, setMode] = useState<'read' | 'write'>('read');
@@ -117,13 +146,56 @@ export function EmbedView() {
117
146
  // nothing typed vanishes, but nothing can be sent from it.
118
147
  const [accessLost, setAccessLost] = useState(false);
119
148
 
149
+ // A picture is bytes under the token too, but the browser fetches it
150
+ // itself (`<img src>`), so its refusal never reaches `withEmbedToken`. A
151
+ // picture that fails to load is asked once more with `fetch` to learn why,
152
+ // and when the token was the reason, it is renewed — the addresses follow
153
+ // the renewal above, so the picture loads again under the fresh one. One
154
+ // renewal per token a picture was refused with: a picture refused under a
155
+ // token a picture already renewed to is left broken, never a loop. When no
156
+ // fresh token can be had, the token is dead and the view is expired, as
157
+ // for any other refused call. The SPA page cannot renew and so does not
158
+ // ask: a picture refused there stays broken, as it always has.
159
+ const contentRef = useRef<HTMLDivElement | null>(null);
160
+ const imageRenewedTo = useRef<string | null>(null);
161
+ // A layout effect, so the listener is in place in the same commit that
162
+ // puts the pictures in the DOM: a cached picture can fail before a passive
163
+ // effect would have run, and an error that fires into no listener is a
164
+ // refusal nobody learns of.
165
+ useLayoutEffect(() => {
166
+ const root = contentRef.current;
167
+ if (!root) return;
168
+ const onError = (event: Event) => {
169
+ const img = event.target;
170
+ if (!(img instanceof HTMLImageElement) || !embedCanRenew()) return;
171
+ const src = img.currentSrc || img.src;
172
+ // The browser reports the address absolute; the API base may be relative.
173
+ const raw = new URL(`${embedApiBase()}/api/embed/raw`, window.location.href).href;
174
+ if (!src.startsWith(`${raw}?`)) return;
175
+ const sent = new URL(src).searchParams.get('token');
176
+ // Under a token already replaced: the fresh address is on its way.
177
+ if (!sent || sent !== embedToken() || sent === imageRenewedTo.current) return;
178
+ void fetch(src, { credentials: 'omit' })
179
+ .then(async (res) => {
180
+ if (res.status !== 401 || sent !== embedToken()) return;
181
+ const renewed = await renewEmbedToken();
182
+ imageRenewedTo.current = renewed;
183
+ if (!renewed && sent === embedToken()) setExpired(true);
184
+ })
185
+ .catch(() => undefined);
186
+ };
187
+ // `error` does not bubble; an ancestor hears it on the way down.
188
+ root.addEventListener('error', onError, true);
189
+ return () => root.removeEventListener('error', onError, true);
190
+ });
191
+
120
192
  const reload = useCallback(() => {
121
- if (!token) {
193
+ if (!embedToken()) {
122
194
  setExpired(true);
123
195
  return;
124
196
  }
125
197
  setNotice(null);
126
- loadEmbed(token)
198
+ withEmbedToken(loadEmbed)
127
199
  .then((next) => {
128
200
  setView(next);
129
201
  setExpired(false);
@@ -135,16 +207,17 @@ export function EmbedView() {
135
207
  if (next.linked) setAwaitingLink(false);
136
208
  })
137
209
  .catch((err: unknown) => {
138
- // 401 is the token: absent, malformed, or past its hour. That is
139
- // the expired view — a plain sentence and NO content, ever.
140
- if (err instanceof EmbedApiError && err.status === 401) {
210
+ // 401 is the token: absent, malformed, or past its life, and not
211
+ // renewed. That is the expired view — a plain sentence and NO
212
+ // content, ever (a draft the reader typed is theirs, not content).
213
+ if (refusedForToken(err)) {
141
214
  setExpired(true);
142
215
  setView(null);
143
216
  return;
144
217
  }
145
218
  setLoadError(err instanceof Error ? err.message : 'This page could not be loaded.');
146
219
  });
147
- }, [token]);
220
+ }, []);
148
221
 
149
222
  useEffect(() => reload(), [reload]);
150
223
 
@@ -170,20 +243,29 @@ export function EmbedView() {
170
243
  // sent, and the reader is told why. Either way the edits are not lost. Any
171
244
  // other failure is left to the lock's TTL and to Save, which refuses with
172
245
  // its own reason.
173
- const holdsLock = mode === 'write' && (view?.canWrite ?? false) && !accessLost;
246
+ //
247
+ // An expired view holds nothing either: its token was refused even after a
248
+ // renewal, so a heartbeat would only ask the host for another every beat —
249
+ // the loop one renewal per refused call rules out. The draft stays on
250
+ // screen; the lock is left to its TTL.
251
+ const holdsLock = mode === 'write' && (view?.canWrite ?? false) && !accessLost && !expired;
174
252
  useEffect(() => {
175
253
  // Nothing to keep alive while the frame is hidden: the lock was let go on
176
254
  // the way out, and a heartbeat now would only renew somebody else's.
177
255
  if (!holdsLock || hidden) return;
178
256
  const id = window.setInterval(() => {
179
- heartbeatEmbed(token).catch((err: unknown) => {
257
+ withEmbedToken(heartbeatEmbed).catch((err: unknown) => {
258
+ if (refusedForToken(err)) {
259
+ setExpired(true);
260
+ return;
261
+ }
180
262
  if (!(err instanceof EmbedApiError && err.status === 403)) return;
181
263
  // The edit lock goes NOW, whichever access went: nothing from this
182
264
  // editor can be saved any more, and holding it would block every
183
265
  // other writer until the TTL. Releasing needs no access — the
184
266
  // server lets go only of a lock this identity holds.
185
- cancelEmbed(token).catch(() => undefined);
186
- loadEmbed(token)
267
+ withEmbedToken(cancelEmbed).catch(() => undefined);
268
+ withEmbedToken(loadEmbed)
187
269
  .then((next) => {
188
270
  if (!next.linked || !next.canRead) {
189
271
  setAccessLost(true);
@@ -194,13 +276,16 @@ export function EmbedView() {
194
276
  setView(next);
195
277
  })
196
278
  .catch((loadErr: unknown) => {
197
- // A 401 here is the token running out, which Save reports anyway.
279
+ if (refusedForToken(loadErr)) {
280
+ setExpired(true);
281
+ return;
282
+ }
198
283
  setNotice(loadErr instanceof Error ? loadErr.message : 'Your access to this page changed.');
199
284
  });
200
285
  });
201
286
  }, HEARTBEAT_MS);
202
287
  return () => window.clearInterval(id);
203
- }, [holdsLock, hidden, token]);
288
+ }, [holdsLock, hidden]);
204
289
 
205
290
  // Best-effort lock release when the frame is hidden or closed mid-edit. The
206
291
  // server's lock TTL plus the heartbeat above is the real backstop — a
@@ -211,13 +296,18 @@ export function EmbedView() {
211
296
  // mean anything — and if somebody else took it meanwhile, the reader is
212
297
  // told so and Save is refused (the server refuses it too: it saves only
213
298
  // under a lock this reader holds).
299
+ // Kept in step in the same commit that changes it: a passive effect runs
300
+ // after the screen already shows the change, and a tab coming back in
301
+ // that gap would take the lock again for a view that has just expired.
214
302
  const holdsLockRef = useRef(holdsLock);
215
- useEffect(() => {
303
+ useLayoutEffect(() => {
216
304
  holdsLockRef.current = holdsLock;
217
305
  }, [holdsLock]);
218
306
  useEffect(() => {
307
+ // Not renewed: a page going away has no time to wait for a host, and the
308
+ // lock's TTL is the backstop when the token has run out.
219
309
  const release = () => {
220
- if (holdsLockRef.current) cancelEmbed(token).catch(() => undefined);
310
+ if (holdsLockRef.current) cancelEmbed(embedToken()).catch(() => undefined);
221
311
  };
222
312
  const onVisibility = () => {
223
313
  if (document.visibilityState === 'hidden') {
@@ -230,11 +320,14 @@ export function EmbedView() {
230
320
  // Until the lock is held again, Save is refused here rather than by
231
321
  // the server: the editor is on screen, but the claim behind it is not.
232
322
  setReacquiring(true);
233
- lockEmbed(token)
323
+ withEmbedToken(lockEmbed)
234
324
  .then((result) => {
235
325
  setLockLost(result.acquired ? null : (result.holderName ?? 'Someone else'));
236
326
  })
237
- .catch(() => setLockLost('Someone else'))
327
+ .catch((err: unknown) => {
328
+ if (refusedForToken(err)) setExpired(true);
329
+ else setLockLost('Someone else');
330
+ })
238
331
  .finally(() => setReacquiring(false));
239
332
  };
240
333
  window.addEventListener('pagehide', release);
@@ -248,12 +341,63 @@ export function EmbedView() {
248
341
  // React unmount, so this is where it has to happen.
249
342
  release();
250
343
  };
251
- }, [token]);
344
+ }, []);
345
+
346
+ // The content's height, reported to the host whenever it changes, so a
347
+ // host that sizes its frame to the content (the Atlassian issue panel)
348
+ // can follow instead of showing a gap or an inner scrollbar. The app's
349
+ // global CSS pins html, body and #root to 100% height for the three-pane
350
+ // shell; inside a fixed-height frame that is exactly the gap, so the
351
+ // embed relaxes them to natural height for as long as it is mounted.
352
+ // Only for a host that asked to size its frame to the content
353
+ // (`sizing=content`, which the connector's mint puts on the address): a
354
+ // host with a fixed reading pane — the MCP App's — keeps its pane as it
355
+ // is, and the view scrolls inside it as it always did. Nothing is posted
356
+ // when the page is not framed either: there is nobody to tell.
357
+ const fitContent = useMemo(() => embedSizing() === 'content', []);
358
+ const reportHeight = useCallback(() => {
359
+ if (!fitContent || window.parent === window) return;
360
+ const height = Math.ceil(document.documentElement.getBoundingClientRect().height);
361
+ window.parent.postMessage({ type: EMBED_HEIGHT_MESSAGE, height }, hostOrigin() ?? '*');
362
+ }, [fitContent]);
363
+ useEffect(() => {
364
+ if (!fitContent || window.parent === window) return;
365
+ const targets = [document.documentElement, document.body, document.getElementById('root')].filter(
366
+ (el): el is HTMLElement => el !== null,
367
+ );
368
+ const prev = targets.map((el) => ({ el, height: el.style.height, overflow: el.style.overflow }));
369
+ for (const el of targets) {
370
+ el.style.height = 'auto';
371
+ el.style.overflow = 'visible';
372
+ }
373
+ reportHeight();
374
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(reportHeight) : null;
375
+ observer?.observe(document.body);
376
+ return () => {
377
+ observer?.disconnect();
378
+ for (const { el, height, overflow } of prev) {
379
+ el.style.height = height;
380
+ el.style.overflow = overflow;
381
+ }
382
+ };
383
+ }, [fitContent, reportHeight]);
384
+ // The height again whenever what is on screen changes — the page arriving,
385
+ // the editor opening or closing, a notice, an expiry or a load failure, the
386
+ // link prompt, a button going busy — so the first real height never
387
+ // depends on a `ResizeObserver` the host's runtime may not have. Here, with
388
+ // the other hooks: the view returns early below for a page not yet loaded.
389
+ useEffect(() => {
390
+ reportHeight();
391
+ }, [reportHeight, view, mode, notice, sent, lockLost, expired, loadError, awaitingLink, busy]);
252
392
 
253
393
  /**
254
- * The surface the app's renderers are mounted on. Rebuilt only when the
255
- * page changes: the renderers take it as a context, and a fresh object per
256
- * render would re-run every read effect that depends on it.
394
+ * The surface the app's renderers are mounted on. Rebuilt when the page
395
+ * changes and when the token is renewed, and at no other time: the
396
+ * renderers take it as a context, and a fresh object per render would
397
+ * re-run every read effect that depends on it. A renewal has to rebuild
398
+ * it, because the byte addresses it hands out carry the token, and a
399
+ * picture refused under the old one loads again only through a fresh
400
+ * address.
257
401
  */
258
402
  const surface = useMemo<RendererSurface | null>(() => {
259
403
  if (!view) return null;
@@ -273,16 +417,39 @@ export function EmbedView() {
273
417
  // link appends its own fragment, and two fragments is no address.
274
418
  canonicalUrlFor: () => absolute(view.appUrl).split('#', 1)[0],
275
419
  rawUrl: (path, options) => embedRawUrl(token, embedRawPath(path, view), options),
276
- rawFetch: (path, options) =>
277
- fetch(embedRawUrl(token, embedRawPath(path, view), options), {
278
- credentials: 'omit',
279
- signal: options?.signal,
280
- }),
420
+ // Bytes a renderer fetches itself are renewed like every other call:
421
+ // a 401 is retried once with a fresh token, and one that stays refused
422
+ // is the expired view.
423
+ rawFetch: async (path, options) => {
424
+ const seen: { last?: Response } = {};
425
+ try {
426
+ return await withEmbedToken(async (current) => {
427
+ const res = await fetch(embedRawUrl(current, embedRawPath(path, view), options), {
428
+ credentials: 'omit',
429
+ signal: options?.signal,
430
+ });
431
+ seen.last = res;
432
+ if (res.status === 401) throw new EmbedApiError(401, 'The token was refused');
433
+ return res;
434
+ });
435
+ } catch (err) {
436
+ if (!seen.last || !refusedForToken(err)) throw err;
437
+ setExpired(true);
438
+ return seen.last;
439
+ }
440
+ },
281
441
  // No download route under the token: `download:` is its own verb, which
282
442
  // the embed has nothing to resolve it with.
283
443
  offersDownload: false,
444
+ // The knowledge graph a dashboard draws, as this token's viewer may see
445
+ // it — when the distribution registered where the embed reads it from.
446
+ ...(graphSource ? { loadKbGraph: () => graphSource.inEmbed(token) } : {}),
447
+ // A host that sizes its frame to the content is told so: a renderer
448
+ // that draws inside its own frame then gives it a standard height the
449
+ // reader can drag, instead of filling a pane nobody gave it.
450
+ sizesToContent: fitContent,
284
451
  };
285
- }, [view, token]);
452
+ }, [view, token, graphSource, fitContent]);
286
453
 
287
454
  /**
288
455
  * The workspace the renderers believe they are reading from. Never dialled:
@@ -300,7 +467,7 @@ export function EmbedView() {
300
467
  setBusy(true);
301
468
  setNotice(null);
302
469
  try {
303
- const result = await lockEmbed(token);
470
+ const result = await withEmbedToken(lockEmbed);
304
471
  if (!result.acquired) {
305
472
  setNotice(`${result.holderName ?? 'Someone else'} is editing this page — try again shortly.`);
306
473
  return;
@@ -309,11 +476,12 @@ export function EmbedView() {
309
476
  setLockLost(null);
310
477
  setMode('write');
311
478
  } catch (err) {
312
- setNotice(err instanceof Error ? err.message : 'Could not start editing.');
479
+ if (refusedForToken(err)) setExpired(true);
480
+ else setNotice(err instanceof Error ? err.message : 'Could not start editing.');
313
481
  } finally {
314
482
  setBusy(false);
315
483
  }
316
- }, [view, token]);
484
+ }, [view]);
317
485
 
318
486
  const onPropose = useCallback(() => {
319
487
  if (!view) return;
@@ -338,21 +506,24 @@ export function EmbedView() {
338
506
  setNotice(null);
339
507
  try {
340
508
  if (view.canWrite) {
341
- await saveEmbed(token, content);
509
+ await withEmbedToken((current) => saveEmbed(current, content));
342
510
  reload();
343
511
  } else {
344
- const result = await proposeEmbed(token, content);
512
+ const result = await withEmbedToken((current) => proposeEmbed(current, content));
345
513
  setSent({ url: result.url });
346
514
  setMode('read');
347
515
  }
348
516
  } catch (err) {
349
- setNotice(err instanceof Error ? err.message : 'That could not be saved.');
517
+ // Refused for the token even after a renewal: the expired sentence,
518
+ // with the draft kept above it for the reader to copy.
519
+ if (refusedForToken(err)) setExpired(true);
520
+ else setNotice(err instanceof Error ? err.message : 'That could not be saved.');
350
521
  throw err;
351
522
  } finally {
352
523
  setBusy(false);
353
524
  }
354
525
  },
355
- [view, token, reload, lockLost, accessLost, reacquiring],
526
+ [view, reload, lockLost, accessLost, reacquiring],
356
527
  );
357
528
 
358
529
  const onCancel = useCallback(async () => {
@@ -360,7 +531,7 @@ export function EmbedView() {
360
531
  try {
361
532
  // Released even after access was withdrawn (see the heartbeat above):
362
533
  // a second release is a no-op, a skipped one blocks other writers.
363
- if (view?.canWrite) await cancelEmbed(token).catch(() => undefined);
534
+ if (view?.canWrite) await withEmbedToken(cancelEmbed).catch(() => undefined);
364
535
  } finally {
365
536
  setBusy(false);
366
537
  setMode('read');
@@ -370,11 +541,26 @@ export function EmbedView() {
370
541
  // reader lands on what they may now see, not on the old content.
371
542
  if (accessLost) reload();
372
543
  }
373
- }, [view, token, accessLost, reload]);
544
+ }, [view, accessLost, reload]);
374
545
 
375
546
  // ── the states that show no content ──────────────────────────────────────
376
547
 
377
548
  if (expired) {
549
+ // A draft that was open stays on screen, read-only, above the sentence:
550
+ // nothing can be sent from it any more, but the reader can copy it out.
551
+ if (mode === 'write') {
552
+ return (
553
+ <div className="flex h-full min-w-0 flex-col gap-2 p-3">
554
+ <textarea
555
+ readOnly
556
+ aria-label="Your draft"
557
+ value={draft}
558
+ className="min-h-32 w-full flex-1 resize-none rounded border border-line bg-sunken px-2 py-1.5 font-mono text-detail text-ink"
559
+ />
560
+ <EmbedNotice>{EMBED_EXPIRED}</EmbedNotice>
561
+ </div>
562
+ );
563
+ }
378
564
  return (
379
565
  <EmbedNotice>
380
566
  {EMBED_EXPIRED}
@@ -477,7 +663,7 @@ export function EmbedView() {
477
663
  </p>
478
664
  )}
479
665
 
480
- <div className="min-h-0 min-w-0 flex-1 overflow-auto">
666
+ <div ref={contentRef} className="min-h-0 min-w-0 flex-1 overflow-auto">
481
667
  <RendererSurfaceContext.Provider value={surface}>
482
668
  {/* The renderers read bytes through the surface above, so the
483
669
  workspace id here is never dialled — it is the default branch's,
@@ -35,20 +35,49 @@ export interface EmbedRuntimeConfig {
35
35
  token: string | null;
36
36
  /** How a link leaves the view, when the host lent a way; null means parent window or a new tab. */
37
37
  openLink: ((url: string) => void) | null;
38
+ /**
39
+ * How a fresh token is had when a call is refused for this one: the MCP App
40
+ * view asks its host to call `open_page` again. Null on the SPA's `/embed`
41
+ * page, which has no host to ask — a refused token there is the end of it.
42
+ */
43
+ renew: (() => Promise<string | null>) | null;
44
+ /**
45
+ * Who decides the view's height. `'host'`: the host gives the view a fixed
46
+ * reading pane and the view scrolls inside it (the MCP App's pane). `'content'`:
47
+ * the host sizes its frame to the content and the view reports its height
48
+ * (the Atlassian issue panel, whose mint puts `sizing=content` on the
49
+ * view's address). Null means "read the page URL", which defaults to the
50
+ * host's pane.
51
+ */
52
+ sizing: EmbedSizing | null;
38
53
  }
39
54
 
40
- const UNCONFIGURED: EmbedRuntimeConfig = { baseUrl: '', token: null, openLink: null };
55
+ export type EmbedSizing = 'host' | 'content';
56
+
57
+ const UNCONFIGURED: EmbedRuntimeConfig = { baseUrl: '', token: null, openLink: null, renew: null, sizing: null };
41
58
 
42
59
  let current: EmbedRuntimeConfig = UNCONFIGURED;
43
60
 
61
+ /**
62
+ * Which runtime is current: replaced each time the embed is configured or
63
+ * reset (a new mount, an unmount), and NOT by a renewal, which only changes
64
+ * the token. What a call or a renewal started under one runtime learns must
65
+ * not reach the next: its successor's token is for another page.
66
+ */
67
+ let runtime: object = {};
68
+
44
69
  /** Hand the embed its runtime: called by {@link mountEmbed} before anything renders. */
45
70
  export function configureEmbed(config: Partial<EmbedRuntimeConfig>): void {
46
71
  current = { ...current, ...config };
72
+ runtime = {};
73
+ renewing = null;
47
74
  }
48
75
 
49
76
  /** Back to the SPA page's own answers — on unmount, and in tests. */
50
77
  export function resetEmbedConfig(): void {
51
78
  current = UNCONFIGURED;
79
+ runtime = {};
80
+ renewing = null;
52
81
  }
53
82
 
54
83
  /**
@@ -80,11 +109,103 @@ export function embedToken(): string {
80
109
  return current.token ?? new URLSearchParams(window.location.search).get('token') ?? '';
81
110
  }
82
111
 
112
+ /**
113
+ * Who sizes the view: handed over, or read from the page URL
114
+ * (`sizing=content`), else the host's fixed pane. See {@link EmbedRuntimeConfig.sizing}.
115
+ */
116
+ export function embedSizing(): EmbedSizing {
117
+ if (current.sizing) return current.sizing;
118
+ return new URLSearchParams(window.location.search).get('sizing') === 'content' ? 'content' : 'host';
119
+ }
120
+
83
121
  /** The host's way of opening a link, when it lent one. */
84
122
  export function embedOpenLink(): ((url: string) => void) | null {
85
123
  return current.openLink;
86
124
  }
87
125
 
126
+ /** Whether a refused token can be renewed here: the chat view can, the SPA page cannot. */
127
+ export function embedCanRenew(): boolean {
128
+ return current.renew !== null;
129
+ }
130
+
131
+ /** The renewal in flight, shared by every call refused while it runs. */
132
+ let renewing: Promise<string | null> | null = null;
133
+
134
+ /** Who wants to know when a renewal replaced the token. */
135
+ const renewedListeners = new Set<() => void>();
136
+
137
+ /**
138
+ * Be told when a renewal replaced the token — for what holds the token
139
+ * rather than asking for it per call (an image address). Returns the way to
140
+ * stop listening.
141
+ */
142
+ export function onEmbedTokenRenewed(listener: () => void): () => void {
143
+ renewedListeners.add(listener);
144
+ return () => {
145
+ renewedListeners.delete(listener);
146
+ };
147
+ }
148
+
149
+ /**
150
+ * A fresh token in place of the current one, or null when none can be had —
151
+ * no way to renew (the SPA page), or the host and `open_page` gave none.
152
+ * Calls refused together share one renewal; a fresh token replaces the one
153
+ * every later call reads.
154
+ */
155
+ export function renewEmbedToken(): Promise<string | null> {
156
+ const renew = current.renew;
157
+ if (!renew) return Promise.resolve(null);
158
+ if (!renewing) {
159
+ const mount = runtime;
160
+ // A renewal that throws instead of answering null is a renewal that failed.
161
+ const mine: Promise<string | null> = Promise.resolve()
162
+ .then(renew)
163
+ .catch(() => null)
164
+ .then((token) => {
165
+ // A mount that was taken down meanwhile must not have its successor's
166
+ // token replaced by the answer to its own question.
167
+ if (runtime !== mount) return null;
168
+ if (!token) return null;
169
+ current = { ...current, token };
170
+ for (const listener of renewedListeners) listener();
171
+ return token;
172
+ })
173
+ .finally(() => {
174
+ if (renewing === mine) renewing = null;
175
+ });
176
+ renewing = mine;
177
+ }
178
+ return renewing;
179
+ }
180
+
181
+ /**
182
+ * Run an embed call with the current token, and when it is refused for the
183
+ * token (401) renew the token once and run it once more with the fresh one.
184
+ * At most one renewal per refused call: a second refusal is the caller's to
185
+ * report, never another round.
186
+ *
187
+ * A call that was sent with a token another call has already replaced is
188
+ * retried with the new one without asking for a third.
189
+ *
190
+ * Only within the runtime it was sent under: a call whose mount was replaced
191
+ * while it ran (another `open_page` in the chat, for another page) is never
192
+ * retried with the successor's token — that would send an old draft to the
193
+ * other page. Its refusal is reported as it came.
194
+ */
195
+ export async function withEmbedToken<T>(call: (token: string) => Promise<T>): Promise<T> {
196
+ const mount = runtime;
197
+ const sent = embedToken();
198
+ try {
199
+ return await call(sent);
200
+ } catch (err) {
201
+ if ((err as { status?: unknown } | null)?.status !== 401 || runtime !== mount) throw err;
202
+ const now = embedToken();
203
+ const fresh = now !== sent ? now : await renewEmbedToken();
204
+ if (!fresh || runtime !== mount) throw err;
205
+ return call(fresh);
206
+ }
207
+ }
208
+
88
209
  /**
89
210
  * The global the MCP App view sets on its window before it loads the
90
211
  * deployment's embed bundle — the one contract between the view (a static
@@ -101,6 +222,8 @@ export interface EmbedHandoff {
101
222
  token: string;
102
223
  /** Opens an address in a new tab through the host (`ui/open-link`). */
103
224
  openLink?: (url: string) => void;
225
+ /** A fresh token through the host (`open_page` again), or null when there is none. */
226
+ renew?: () => Promise<string | null>;
104
227
  }
105
228
 
106
229
  /**
@@ -114,7 +237,7 @@ export interface EmbedHandoff {
114
237
  export function readEmbedHandoff(): EmbedHandoff | null {
115
238
  const raw = (window as unknown as Record<string, unknown>)[EMBED_HANDOFF_GLOBAL];
116
239
  if (!raw || typeof raw !== 'object') return null;
117
- const h = raw as { baseUrl?: unknown; token?: unknown; openLink?: unknown };
240
+ const h = raw as { baseUrl?: unknown; token?: unknown; openLink?: unknown; renew?: unknown };
118
241
  if (typeof h.baseUrl !== 'string' || !/^https?:\/\//i.test(h.baseUrl)) return null;
119
242
  if (typeof h.token !== 'string' || h.token === '') return null;
120
243
  let baseUrl: string;
@@ -128,5 +251,6 @@ export function readEmbedHandoff(): EmbedHandoff | null {
128
251
  baseUrl,
129
252
  token: h.token,
130
253
  ...(typeof h.openLink === 'function' ? { openLink: h.openLink as (url: string) => void } : {}),
254
+ ...(typeof h.renew === 'function' ? { renew: h.renew as () => Promise<string | null> } : {}),
131
255
  };
132
256
  }
@@ -1,4 +1,4 @@
1
- import { kbFileUrl, resolveKbHref } from '../workspace/routing/kb-routes';
1
+ import { kbFileUrl, resolveKbHref } from '../workspace';
2
2
  import { isOpenableExternalHref, normalizeHref } from '../../shared/markdown/hrefs';
3
3
  import { embedBaseUrl, embedOpenLink } from './embed-config';
4
4
 
@@ -14,6 +14,15 @@ export const EMBED_EXPIRED =
14
14
 
15
15
  /** The message the embed page sends its host to have a link opened. */
16
16
  export const EMBED_OPEN_MESSAGE = 'bevel-embed-open';
17
+ /**
18
+ * What the embed posts to its host when its content height changes, so a
19
+ * host that sizes its frame to the content (the Atlassian issue panel does)
20
+ * can follow. `{ type, height }`, height in CSS pixels. Posted only when the
21
+ * host asked for content sizing (`embedSizing() === 'content'`): a host with
22
+ * a fixed reading pane, the MCP App's, keeps its pane and the view scrolls
23
+ * inside it.
24
+ */
25
+ export const EMBED_HEIGHT_MESSAGE = 'bevel-embed-height';
17
26
 
18
27
  /**
19
28
  * The host's origin, from the referrer — used as the explicit `postMessage`
@@ -24,7 +33,7 @@ export const EMBED_OPEN_MESSAGE = 'bevel-embed-open';
24
33
  * and not a leak: the payload is a URL to open, the host re-validates it
25
34
  * before acting, and the alternative is a dead link.
26
35
  */
27
- function hostOrigin(): string | null {
36
+ export function hostOrigin(): string | null {
28
37
  try {
29
38
  return new URL(document.referrer).origin;
30
39
  } catch {