@bevel-software/platform-core-frontend 0.25.2 → 0.27.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 (193) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +87 -25
  3. package/src/core/ProductName.tsx +49 -0
  4. package/src/core/__tests__/ShellRoutes.test.tsx +22 -0
  5. package/src/core/__tests__/core-contributions.test.ts +16 -0
  6. package/src/core/core-contributions.ts +17 -0
  7. package/src/core/registry.ts +51 -1
  8. package/src/index.css +23 -5
  9. package/src/index.ts +5 -0
  10. package/src/modules/access/__tests__/ManageAccessDialog.proposal.test.tsx +1 -1
  11. package/src/modules/access/components/ManageAccessDialog.tsx +1 -1
  12. package/src/modules/admin/__tests__/RolesCorruptedBanner.test.tsx +70 -0
  13. package/src/modules/admin/components/RolesCorruptedBanner.tsx +9 -4
  14. package/src/modules/auth/components/LoginScreen.tsx +4 -1
  15. package/src/modules/auth/services/account.api.ts +28 -1
  16. package/src/modules/auth/services/sso.ts +1 -2
  17. package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +176 -0
  18. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +68 -0
  19. package/src/modules/change-requests/__tests__/ChangeRequestLink.test.tsx +182 -0
  20. package/src/modules/change-requests/__tests__/FileChangeBoxes.test.tsx +1 -1
  21. package/src/modules/change-requests/__tests__/readFileOnBranch.test.ts +79 -0
  22. package/src/modules/change-requests/components/ChangeBox.tsx +6 -1
  23. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +45 -15
  24. package/src/modules/change-requests/components/ChangeRequestLink.tsx +151 -0
  25. package/src/modules/change-requests/components/CrFileTree.tsx +2 -1
  26. package/src/modules/change-requests/components/FileChangeBoxes.tsx +4 -2
  27. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +6 -3
  28. package/src/modules/change-requests/services/change-requests.api.ts +15 -2
  29. package/src/modules/change-requests/utils/readFailure.ts +22 -0
  30. package/src/modules/embed/__tests__/EmbedLinkPage.test.tsx +74 -0
  31. package/src/modules/embed/__tests__/EmbedView.test.tsx +473 -0
  32. package/src/modules/embed/__tests__/embed-config.test.ts +128 -0
  33. package/src/modules/embed/__tests__/embed-host.test.ts +111 -0
  34. package/src/modules/embed/__tests__/mcp-app-view.test.ts +295 -0
  35. package/src/modules/embed/__tests__/mount.test.tsx +157 -0
  36. package/src/modules/embed/components/EmbedLinkPage.tsx +109 -0
  37. package/src/modules/embed/components/EmbedView.tsx +545 -0
  38. package/src/modules/embed/embed-config.ts +132 -0
  39. package/src/modules/embed/embed-host.ts +120 -0
  40. package/src/modules/embed/mount.tsx +80 -0
  41. package/src/modules/embed/services/embed-token.ts +22 -0
  42. package/src/modules/embed/services/embed.api.ts +158 -0
  43. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +202 -4
  44. package/src/modules/git/__tests__/GitSyncFailedBanner.test.tsx +59 -1
  45. package/src/modules/git/__tests__/PullNeededBanner.test.tsx +39 -22
  46. package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +7 -2
  47. package/src/modules/git/branch-delete-menu-item.tsx +24 -0
  48. package/src/modules/git/components/BranchSwitcher.tsx +29 -5
  49. package/src/modules/git/components/GitSyncFailedBanner.tsx +53 -15
  50. package/src/modules/git/components/HistoryVersionPreview.tsx +5 -3
  51. package/src/modules/git/components/PullNeededBanner.tsx +15 -49
  52. package/src/modules/git/hooks/useAutoPullUpdates.ts +9 -5
  53. package/src/modules/git/index.ts +15 -0
  54. package/src/modules/git/services/__tests__/error-messages.test.ts +67 -0
  55. package/src/modules/git/services/__tests__/pull-failure.test.ts +36 -0
  56. package/src/modules/git/services/error-messages.ts +58 -1
  57. package/src/modules/git/services/pull-failure.ts +68 -0
  58. package/src/modules/git/state/branch-delete-confirm.ts +46 -0
  59. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +1 -0
  60. package/src/modules/layout/__tests__/breakpoints.test.ts +7 -1
  61. package/src/modules/layout/breakpoints.ts +8 -0
  62. package/src/modules/library/__tests__/PluginExtras.test.tsx +9 -9
  63. package/src/modules/library/__tests__/PluginPage.test.tsx +8 -1
  64. package/src/modules/library/__tests__/SkillsTree.test.tsx +13 -4
  65. package/src/modules/library/__tests__/ToolPage.test.tsx +53 -0
  66. package/src/modules/library/components/LibraryPage.tsx +22 -0
  67. package/src/modules/library/components/PluginExtras.tsx +23 -6
  68. package/src/modules/library/components/PluginPage.tsx +6 -1
  69. package/src/modules/library/components/tool-page/ToolPage.tsx +45 -1
  70. package/src/modules/library/routes/LibraryRoutes.tsx +8 -7
  71. package/src/modules/library/services/plugins.api.ts +4 -1
  72. package/src/modules/library/services/tools.api.ts +27 -0
  73. package/src/modules/library/state/plugins-revision.ts +28 -0
  74. package/src/modules/onboarding/__tests__/agent-connection-api.test.ts +55 -0
  75. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +87 -82
  76. package/src/modules/onboarding/__tests__/first-page-prompt.test.ts +109 -0
  77. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +1001 -0
  78. package/src/modules/onboarding/__tests__/invite-dialog.test.tsx +392 -0
  79. package/src/modules/onboarding/__tests__/onboarding.test.tsx +226 -193
  80. package/src/modules/onboarding/__tests__/starter-pack-card.test.tsx +136 -0
  81. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +7 -11
  82. package/src/modules/onboarding/components/EmailChipsInput.tsx +138 -0
  83. package/src/modules/onboarding/components/GetStartedColumn.tsx +651 -0
  84. package/src/modules/onboarding/components/InviteButton.tsx +35 -0
  85. package/src/modules/onboarding/components/InviteDialog.tsx +424 -0
  86. package/src/modules/onboarding/components/RootLanding.tsx +8 -24
  87. package/src/modules/onboarding/components/StarterPackCard.tsx +98 -0
  88. package/src/modules/onboarding/components/WelcomePage.tsx +65 -154
  89. package/src/modules/onboarding/first-page-prompt.ts +89 -0
  90. package/src/modules/onboarding/invite-emails.ts +175 -0
  91. package/src/modules/onboarding/services/agent-connection.api.ts +53 -0
  92. package/src/modules/onboarding/services/starter-packs.api.ts +83 -0
  93. package/src/modules/onboarding/state/agent-connection.ts +167 -0
  94. package/src/modules/onboarding/state/invite-dialog.context.ts +32 -0
  95. package/src/modules/onboarding/state/invite-dialog.tsx +31 -0
  96. package/src/modules/onboarding/state/onboarding.ts +133 -59
  97. package/src/modules/onboarding/state/starter-packs.ts +169 -0
  98. package/src/modules/settings/settings-nav-items.tsx +8 -3
  99. package/src/modules/setup/__tests__/setup.first-run-storage.test.tsx +389 -0
  100. package/src/modules/setup/__tests__/setup.github.test.tsx +5 -5
  101. package/src/modules/setup/__tests__/setup.kept-draft.test.tsx +1 -1
  102. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +1 -1
  103. package/src/modules/setup/__tests__/setup.repository.test.tsx +21 -21
  104. package/src/modules/setup/__tests__/setup.test.tsx +65 -81
  105. package/src/modules/setup/__tests__/useConnectionProbe.test.tsx +123 -0
  106. package/src/modules/setup/components/FirstRunStorage.tsx +560 -0
  107. package/src/modules/setup/components/SetupGate.tsx +46 -1
  108. package/src/modules/setup/components/SetupScreen.tsx +92 -152
  109. package/src/modules/setup/hooks/useConnectionProbe.ts +93 -0
  110. package/src/modules/setup/services/setup.api.ts +3 -3
  111. package/src/modules/setup/utils/suggested-branch.ts +27 -0
  112. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +210 -0
  113. package/src/modules/toolbar/commands/actions.tsx +324 -0
  114. package/src/modules/toolbar/commands/command-menu.ts +44 -0
  115. package/src/modules/toolbar/commands/useCommandActions.ts +69 -0
  116. package/src/modules/toolbar/commands/useCommandShortcuts.ts +121 -0
  117. package/src/modules/toolbar/components/AppSwitcher.tsx +106 -22
  118. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +1 -1
  119. package/src/modules/toolbar/components/ProfileMenu.tsx +9 -4
  120. package/src/modules/toolbar/components/SearchPalette.tsx +540 -0
  121. package/src/modules/toolbar/components/Toolbar.tsx +10 -0
  122. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +187 -54
  123. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +4 -4
  124. package/src/modules/toolbar/components/__tests__/ProfileMenu.test.tsx +64 -0
  125. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +832 -0
  126. package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +57 -2
  127. package/src/modules/toolbar/search/__tests__/rank.test.ts +93 -0
  128. package/src/modules/toolbar/search/__tests__/sources.test.ts +131 -0
  129. package/src/modules/toolbar/search/rank.ts +111 -0
  130. package/src/modules/toolbar/search/sources.ts +169 -0
  131. package/src/modules/workflow/hooks/useFileLock.ts +10 -7
  132. package/src/modules/workflow/services/__tests__/lock.api.test.ts +41 -0
  133. package/src/modules/workflow/services/lock.api.ts +17 -2
  134. package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +49 -1
  135. package/src/modules/workspace/components/EditorTabs.tsx +39 -15
  136. package/src/modules/workspace/components/FileExplorer.tsx +39 -6
  137. package/src/modules/workspace/components/FilePaneCard.tsx +6 -2
  138. package/src/modules/workspace/components/FileRoute.tsx +12 -7
  139. package/src/modules/workspace/components/FileViewer.tsx +271 -74
  140. package/src/modules/workspace/components/KbPageHeader.tsx +13 -6
  141. package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +88 -21
  142. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +101 -11
  143. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +23 -3
  144. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +330 -6
  145. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +17 -2
  146. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +11 -16
  147. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +6 -0
  148. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +23 -21
  149. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +13 -29
  150. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +9 -2
  151. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +8 -0
  152. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +14 -19
  153. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +11 -17
  154. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +35 -7
  155. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +11 -17
  156. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.links.test.tsx +73 -0
  157. package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.scaffold.test.tsx +64 -0
  158. package/src/modules/workspace/components/renderers/__tests__/ToolRenderer.surface.test.tsx +82 -0
  159. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +99 -0
  160. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +129 -35
  161. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +149 -0
  162. package/src/modules/workspace/components/renderers/__tests__/kbMarkdownLinkPolicy.test.tsx +100 -0
  163. package/src/modules/workspace/components/renderers/htmlSandbox.ts +76 -20
  164. package/src/modules/workspace/components/renderers/index.ts +26 -0
  165. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +51 -1
  166. package/src/modules/workspace/components/renderers/rendererRawRead.ts +53 -0
  167. package/src/modules/workspace/components/renderers/rendererSurface.ts +109 -0
  168. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +8 -2
  169. package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +126 -21
  170. package/src/modules/workspace/hooks/useCreatePage.ts +116 -0
  171. package/src/modules/workspace/hooks/useWorkspaceImageResolver.ts +24 -7
  172. package/src/modules/workspace/hooks/useWorkspaceState.ts +42 -8
  173. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +10 -0
  174. package/src/modules/workspace/routing/__tests__/md-links-parity.test.tsx +113 -0
  175. package/src/modules/workspace/routing/kb-routes.ts +66 -12
  176. package/src/modules/workspace/state/editable-page.ts +42 -0
  177. package/src/modules/workspace/state/workspace.context.ts +13 -4
  178. package/src/modules/workspace/utils/__tests__/display-file-name.test.ts +60 -0
  179. package/src/modules/workspace/utils/__tests__/fileTree.test.ts +75 -0
  180. package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +26 -14
  181. package/src/modules/workspace/utils/display-file-name.ts +102 -0
  182. package/src/modules/workspace/utils/fileTree.ts +49 -14
  183. package/src/modules/workspace/utils/treeConfirm.ts +22 -5
  184. package/src/shared/__tests__/no-builtin-confirm.test.ts +102 -0
  185. package/src/shared/components/ConfirmProvider.tsx +156 -0
  186. package/src/shared/components/Dialog.tsx +7 -0
  187. package/src/shared/components/__tests__/ConfirmProvider.test.tsx +198 -0
  188. package/src/shared/components/confirm-context.ts +94 -0
  189. package/src/shared/components/index.ts +3 -0
  190. package/src/shared/mcp/__tests__/connect-snippets.test.ts +2 -2
  191. package/src/shared/mcp/connect-snippets.ts +8 -5
  192. package/src/modules/onboarding/components/WelcomeRoute.tsx +0 -57
  193. package/src/modules/onboarding/welcome-state.ts +0 -36
@@ -0,0 +1,116 @@
1
+ import { useCallback } from 'react';
2
+ import { useLocation } from 'react-router-dom';
3
+ import { KNOWLEDGE_BASE_DIR, type FileTreeEntry } from '@bevel-software/platform-shared';
4
+ import { useWorkspace } from '../state/workspace.context';
5
+ import { WorkspaceApiError } from '../services/workspace.api';
6
+ import { branchFromPathname, useFileNav } from '../routing/kb-routes';
7
+ import { useMergedWorkspaceTree } from './useMergedWorkspaceTree';
8
+ import { pathExistsInTree } from '../utils/fileTree';
9
+
10
+ /**
11
+ * What "New page" writes: a title, so the page is a page from its first save,
12
+ * and a blank line under it for the cursor to land on.
13
+ */
14
+ export const NEW_PAGE_CONTENT = '# Untitled\n\n';
15
+
16
+ /** `Untitled.md` for the first page, `Untitled N.md` after it. */
17
+ export function untitledPagePath(folder: string, n: number): string {
18
+ return n === 1 ? `${folder}/Untitled.md` : `${folder}/Untitled ${n}.md`;
19
+ }
20
+
21
+ /**
22
+ * The first number, from `from` on, whose untitled name the tree does not
23
+ * already hold — a second New page makes a second page rather than reusing
24
+ * the first one's name.
25
+ */
26
+ function freeUntitledNumber(tree: FileTreeEntry | null, folder: string, from = 1): number {
27
+ let n = from;
28
+ while (pathExistsInTree(tree, untitledPagePath(folder, n))) n++;
29
+ return n;
30
+ }
31
+
32
+ /**
33
+ * How many names New page tries before it gives up. The tree it picks from
34
+ * can be a moment behind (a teammate or an agent creating pages too), so a
35
+ * refusal moves on to the next name; a handful covers any real race.
36
+ */
37
+ const NEW_PAGE_ATTEMPTS = 5;
38
+
39
+ /**
40
+ * The exclusive create's "that name is taken": 409, for a file that exists
41
+ * now — or one somebody holds the lock on, which is a page being made there.
42
+ */
43
+ function isNameTaken(err: unknown): boolean {
44
+ return err instanceof WorkspaceApiError && err.status === 409;
45
+ }
46
+
47
+ export interface CreatePage {
48
+ /**
49
+ * The Knowledge folder pages are created in, or null while there is nowhere
50
+ * safe to create one: before the workspace has bootstrapped, and while the
51
+ * workspace on screen is not yet the branch the URL names.
52
+ */
53
+ knowledgeRoot: string | null;
54
+ /**
55
+ * Create `Untitled.md` (or the next free `Untitled N.md`) in the Knowledge
56
+ * folder and open it in edit mode. Resolves with the path; rejects with an
57
+ * Error whose message is ready to show ("Couldn’t create the page: …").
58
+ */
59
+ createPage(): Promise<string>;
60
+ }
61
+
62
+ /**
63
+ * "New page", shared by everything that offers it — the Get set up list and
64
+ * the command menu — so both pick names the same way and neither can ever
65
+ * overwrite a page.
66
+ *
67
+ * The create is EXCLUSIVE (`ifAbsent`): the name comes from the tree on
68
+ * screen, which may not yet show a page someone else just made, and a plain
69
+ * write would replace that page with an empty one. The page opens through
70
+ * `openWorkspacePath(path, { edit: true })`, which the viewer honours the way
71
+ * an Edit click is honoured — lock, fresh read and all.
72
+ *
73
+ * The caller owns how it says "busy" and where it shows a failure: the
74
+ * column keeps it on its step, the menu reopens with it.
75
+ */
76
+ export function useCreatePage(): CreatePage {
77
+ const { kbDirName, createFile, workspaceBranch } = useWorkspace();
78
+ const { tree } = useMergedWorkspaceTree();
79
+ const { openWorkspacePath } = useFileNav();
80
+ const { pathname } = useLocation();
81
+ // Where the page would be WRITTEN against where it would OPEN. `createFile`
82
+ // writes to the workspace on screen (`workspaceBranch`), while the page
83
+ // opens on the branch the URL names; mid-switch those differ, the URL
84
+ // already naming the destination. A page made in that gap lands on the
85
+ // branch the person just left, and the viewer then looks for it on the new
86
+ // one and finds nothing. So there is no folder to create in until the two
87
+ // agree. No branch in the URL (the Library) means the workspace on screen
88
+ // is the destination, as `openWorkspacePath` reads it.
89
+ const destination = branchFromPathname(pathname) ?? workspaceBranch;
90
+ const ready = kbDirName !== null && workspaceBranch !== null && destination === workspaceBranch;
91
+ const knowledgeRoot = ready ? `${kbDirName}/${KNOWLEDGE_BASE_DIR}` : null;
92
+
93
+ const createPage = useCallback(async (): Promise<string> => {
94
+ if (!knowledgeRoot) throw new Error('Couldn’t create the page: the workspace is still loading.');
95
+ let n = freeUntitledNumber(tree, knowledgeRoot);
96
+ let path = untitledPagePath(knowledgeRoot, n);
97
+ for (let attempt = 1; ; attempt++) {
98
+ try {
99
+ await createFile(path, NEW_PAGE_CONTENT, { ifAbsent: true });
100
+ break;
101
+ } catch (err) {
102
+ if (isNameTaken(err) && attempt < NEW_PAGE_ATTEMPTS) {
103
+ n = freeUntitledNumber(tree, knowledgeRoot, n + 1);
104
+ path = untitledPagePath(knowledgeRoot, n);
105
+ continue;
106
+ }
107
+ const msg = err instanceof Error ? err.message : String(err);
108
+ throw new Error(`Couldn’t create the page: ${msg}`, { cause: err });
109
+ }
110
+ }
111
+ openWorkspacePath(path, { edit: true });
112
+ return path;
113
+ }, [knowledgeRoot, tree, createFile, openWorkspacePath]);
114
+
115
+ return { knowledgeRoot, createPage };
116
+ }
@@ -1,7 +1,8 @@
1
- import { useCallback } from 'react';
1
+ import { useCallback, useContext } from 'react';
2
2
  import { resolveKbHref } from '../routing/kb-routes';
3
3
  import { rawFileUrl } from '../services/workspace.api';
4
- import { useWorkspace } from '../state/workspace.context';
4
+ import { WorkspaceContext } from '../state/workspace.context';
5
+ import { useRendererSurface } from '../components/renderers/rendererSurface';
5
6
  import { useImageRevision } from './useImageRevision';
6
7
  import type { KbImageResolver } from '../components/renderers/kbMarkdownPipeline';
7
8
 
@@ -12,7 +13,7 @@ import type { KbImageResolver } from '../components/renderers/kbMarkdownPipeline
12
13
  * not ours to serve.
13
14
  *
14
15
  * There were three copies of this — the markdown renderer, the review panel
15
- * and the skill page — each spelling out resolve → kind-check → `rawFileUrl`
16
+ * and the skill page — each spelling out resolve → kind-check → the raw URL
16
17
  * with its own workspace id. That is the same drift-shape this PR removed for
17
18
  * the LINK handlers (one decoded its href, one did not) and it was already
18
19
  * paying out: the repair-heuristic bug below had to be fixed in one place, not
@@ -23,6 +24,11 @@ import type { KbImageResolver } from '../components/renderers/kbMarkdownPipeline
23
24
  * branch's tree no matter which branch is checked out. `basePath` is the file
24
25
  * the image sits in; null means "no file yet" and every src resolves to null.
25
26
  *
27
+ * On a {@link RendererSurface} — the embed — the bytes come from that
28
+ * surface's own route instead, because there is no session to send; the
29
+ * grammar above is unchanged. `workspaceId` is then not consulted at all: a
30
+ * surface shows one page of one branch, and the token is what names it.
31
+ *
26
32
  * The image revision is folded into the URL as `&v=` so a teammate replacing
27
33
  * a picture under the same name reaches an open tab. `useImageRevision`
28
34
  * subscribes to `workspaceId` — including one the session is not focused on,
@@ -33,11 +39,20 @@ export function useWorkspaceImageResolver(
33
39
  workspaceId: string | null,
34
40
  basePath: string | null,
35
41
  ): KbImageResolver {
36
- const { kbDirName } = useWorkspace();
42
+ const surface = useRendererSurface();
43
+ // Read optionally: a surface knows its own `kbDirName` and stands up no
44
+ // workspace provider.
45
+ const workspaceKbDirName = useContext(WorkspaceContext)?.kbDirName ?? null;
46
+ const kbDirName = surface?.kbDirName ?? workspaceKbDirName;
37
47
  const revision = useImageRevision(workspaceId);
38
48
  return useCallback<KbImageResolver>(
39
49
  (src) => {
40
- if (!workspaceId || basePath === null) return null;
50
+ // In the app, the workspace this resolver was POINTED AT — which is not
51
+ // always the one on screen (the skill page renders the default branch's
52
+ // tree from a suggestion branch), so it must stay the resolver's own
53
+ // argument and never be re-derived from a renderer context.
54
+ if (!surface && !workspaceId) return null;
55
+ if (basePath === null || kbDirName === null) return null;
41
56
  // `repairMangledPath: false` — the junk-segment repair is for LINK
42
57
  // destinations a model may have mangled. An image src is a path the
43
58
  // author wrote, and the repair rewrites any path with a later segment
@@ -46,10 +61,12 @@ export function useWorkspaceImageResolver(
46
61
  const target = resolveKbHref(src, { basePath, kbDirName, repairMangledPath: false });
47
62
  if (target?.kind !== 'workspace') return null;
48
63
  return {
49
- src: rawFileUrl(workspaceId, target.path, { version: revision }),
64
+ src: surface
65
+ ? surface.rawUrl(target.path, { version: revision })
66
+ : rawFileUrl(workspaceId!, target.path, { version: revision }),
50
67
  path: target.path,
51
68
  };
52
69
  },
53
- [workspaceId, basePath, kbDirName, revision],
70
+ [surface, workspaceId, basePath, kbDirName, revision],
54
71
  );
55
72
  }
@@ -43,6 +43,8 @@ import { contentChanged } from '../utils/diff';
43
43
  import { isUploadNoise, walkEntries, type DroppedItem } from '../utils/readDroppedEntries';
44
44
  import { tabsKey, type PersistedTabState } from '../utils/tab-persistence';
45
45
  import { traceFiles } from '../utils/file-trace';
46
+ import { displayFileName } from '../utils/display-file-name';
47
+ import { useConfirm } from '../../../shared/components';
46
48
 
47
49
  const PERSIST_DEBOUNCE_MS = 200;
48
50
  // Bounded concurrency cap for upload requests. The server serializes git
@@ -274,6 +276,11 @@ export function useWorkspaceState(): UseWorkspaceStateReturn {
274
276
  * workspaceId it was started with against this before touching state.
275
277
  */
276
278
  const workspaceIdRef = useRef<string | null>(workspaceId);
279
+ // Unsaved-work questions are asked in the app's own dialog and awaited.
280
+ const confirm = useConfirm();
281
+ // Paths whose close is waiting on that question: a second close of the same
282
+ // tab while it is asked must not queue the same question twice.
283
+ const askingClosePathsRef = useRef(new Set<string>());
277
284
  useEffect(() => { openTabsRef.current = openTabs; }, [openTabs]);
278
285
  useEffect(() => { activeTabPathRef.current = activeTabPath; }, [activeTabPath]);
279
286
  useEffect(() => { fileTreeRef.current = fileTree; }, [fileTree]);
@@ -508,11 +515,31 @@ export function useWorkspaceState(): UseWorkspaceStateReturn {
508
515
 
509
516
  const closeTab = useCallback(async (
510
517
  tab: OpenTab,
511
- options?: { skipConfirm?: boolean },
518
+ options?: { skipConfirm?: boolean; workspaceId?: string | null },
512
519
  ): Promise<{ closed: boolean; newActivePath: string | null }> => {
520
+ // Pin the workspace the close was decided in. The question waits on the
521
+ // person; if the workspace moves to another branch meanwhile, a tab with
522
+ // the same path there is not the one they agreed to close.
523
+ const closeWorkspaceId =
524
+ options?.workspaceId !== undefined ? options.workspaceId : workspaceIdRef.current;
525
+ const notClosed = () => ({ closed: false, newActivePath: activeTabPathRef.current });
526
+ if (workspaceIdRef.current !== closeWorkspaceId) return notClosed();
513
527
  if (tab.isDirty && !options?.skipConfirm) {
514
- const confirmed = window.confirm(UNSAVED_TAB_WARNING(basename(tab.path)));
515
- if (!confirmed) return { closed: false, newActivePath: activeTabPathRef.current };
528
+ // The name the tab shows, so this prompt and the bulk one agree.
529
+ if (askingClosePathsRef.current.has(tab.path)) return notClosed();
530
+ askingClosePathsRef.current.add(tab.path);
531
+ let confirmed: boolean;
532
+ try {
533
+ ({ confirmed } = await confirm({
534
+ title: 'Unsaved changes',
535
+ message: UNSAVED_TAB_WARNING(displayFileName(tab.path, kbDirName)),
536
+ confirmLabel: 'Close anyway',
537
+ destructive: true,
538
+ }));
539
+ } finally {
540
+ askingClosePathsRef.current.delete(tab.path);
541
+ }
542
+ if (!confirmed || workspaceIdRef.current !== closeWorkspaceId) return notClosed();
516
543
  }
517
544
  const tabs = openTabsRef.current;
518
545
  const idx = tabs.findIndex((t) => t.path === tab.path);
@@ -527,7 +554,7 @@ export function useWorkspaceState(): UseWorkspaceStateReturn {
527
554
  setActiveTabPath(newActivePath);
528
555
  }
529
556
  return { closed: true, newActivePath };
530
- }, []);
557
+ }, [kbDirName, confirm]);
531
558
 
532
559
  const closeAllTabs = useCallback(() => {
533
560
  setOpenTabs([]);
@@ -694,9 +721,9 @@ export function useWorkspaceState(): UseWorkspaceStateReturn {
694
721
 
695
722
  // ── Working-tree mutations ────────────────────────────────────────────────
696
723
 
697
- const createFile = useCallback(async (relativePath: string, content?: string) => {
724
+ const createFile = useCallback(async (relativePath: string, content?: string, options?: { ifAbsent?: boolean }) => {
698
725
  if (!workspaceId) return;
699
- await writeFile(workspaceId, relativePath, content ?? '');
726
+ await writeFile(workspaceId, relativePath, content ?? '', options);
700
727
  await refreshFileTree();
701
728
  bumpFs();
702
729
  }, [workspaceId, refreshFileTree, bumpFs]);
@@ -1232,8 +1259,15 @@ export function useWorkspaceState(): UseWorkspaceStateReturn {
1232
1259
  );
1233
1260
  const dirty = toClose.filter((t) => t.isDirty);
1234
1261
  if (dirty.length > 0) {
1235
- const confirmed = window.confirm(UNSAVED_TABS_BULK_WARNING(dirty.map((t) => basename(t.path))));
1262
+ const { confirmed } = await confirm({
1263
+ title: 'Unsaved changes',
1264
+ message: UNSAVED_TABS_BULK_WARNING(dirty.map((t) => displayFileName(t.path, kbDirName))),
1265
+ confirmLabel: 'Close anyway',
1266
+ destructive: true,
1267
+ });
1236
1268
  if (!confirmed) return false;
1269
+ // The question waited on the person; the workspace may have moved on.
1270
+ if (!isCurrent()) return false;
1237
1271
  }
1238
1272
  // Optimistic tree removal. A folder delete on the server takes 2-3s
1239
1273
  // (N per-file commits batched into one push) — without optimism the
@@ -1276,7 +1310,7 @@ export function useWorkspaceState(): UseWorkspaceStateReturn {
1276
1310
  // server state. The backend's end-of-batch `fs-tree-changed` SSE
1277
1311
  // event triggers a refresh anyway as belt-and-suspenders. No second
1278
1312
  // `bumpFs()` either — the optimistic bump above already counted.
1279
- }, [workspaceId, refreshFileTree, bumpFs]);
1313
+ }, [workspaceId, kbDirName, refreshFileTree, bumpFs, confirm]);
1280
1314
 
1281
1315
  const reloadTabFromDisk = useCallback(async (relativePath: string) => {
1282
1316
  if (!workspaceId) return;
@@ -111,6 +111,16 @@ describe('useFileNav.openFile', () => {
111
111
  );
112
112
  });
113
113
 
114
+ it('asks the viewer for the editor through router state, never through the URL', () => {
115
+ navigateMock.mockClear();
116
+ const { result } = renderNav('alice/draft');
117
+ result.current.openWorkspacePath('knowledge-base/KnowledgeBase/Untitled.md', { edit: true });
118
+ expect(navigateMock).toHaveBeenCalledWith(
119
+ '/workspace/alice%2Fdraft/knowledge-base/KnowledgeBase/Untitled.md',
120
+ { state: { startEditing: true, startEditingPath: 'knowledge-base/KnowledgeBase/Untitled.md' } },
121
+ );
122
+ });
123
+
114
124
  it('opens a tree path verbatim even when a folder inside it is named like the kbDirName', () => {
115
125
  navigateMock.mockClear();
116
126
  const { result } = renderNav('alice/draft');
@@ -0,0 +1,113 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { renderToStaticMarkup } from 'react-dom/server';
3
+ import Markdown from 'react-markdown';
4
+ import remarkGfm from 'remark-gfm';
5
+ import remarkFrontmatter from 'remark-frontmatter';
6
+ import { MD_ID_LINK_RE, resolveMdLink, scanMarkdownLinks } from '@bevel-software/platform-shared';
7
+ import { NODE_ID_LINK_RE, resolveKbHref, safeDecode } from '../kb-routes';
8
+
9
+ /**
10
+ * The link grammar `move_file` rewrites with (platform-shared `md-links`) and
11
+ * the app that renders and follows those links must agree on two things, over
12
+ * one fixture set:
13
+ * - WHICH destinations a page holds: what the scanner finds in a page's body
14
+ * is exactly what react-markdown renders as an `href` or `src`;
15
+ * - WHERE each one points: `resolveMdLink` and `resolveKbHref` give the same
16
+ * path, branch and anchor, and the same id-link verdict.
17
+ *
18
+ * One deliberate difference is pinned at the end: link syntax inside inline
19
+ * code. Neither the renderer nor the rewriter treats it as a link — but the
20
+ * graph parser and `validate_graph` do, so after a move such a code example
21
+ * reads as dangling there.
22
+ */
23
+
24
+ const KB = 'knowledge-base';
25
+ const BASE = `${KB}/Projects/A/One.md`;
26
+
27
+ /** The shared fixture set: pages whose every link destination both sides must agree on. */
28
+ const PAGES: string[] = [
29
+ '[rel](../B/Two.md) [dot](./Three.md#goal) [up](../../Index.md "Index")',
30
+ `[root](/${KB}/Projects/B/Two.md) [app](/workspace/main/${KB}/Projects/My%20Doc.md#x)`,
31
+ '[angle](<../B/My Doc.md>) [enc](../B/My%20Doc.md) ![img](../assets/shot.png "Shot")',
32
+ '[id](project-hexis) [id-anchor](project-hexis#scope) [same](#overview) [web](https://example.com/a.md)',
33
+ '[ref][r1] and [collapsed][]\n\n[r1]: ../B/Ref.md "Ref"\n[collapsed]: <../B/Col lapsed.md>',
34
+ '[parens](../B/Plan(v2).md) [escaped](../B/a\\_b.md) [![inner](i.png)](../B/Outer.md)',
35
+ '- item [in list](../B/List.md)\n\n> quoted [in quote](../B/Quote.md)\n\n| a | b |\n|---|---|\n| [cell](../B/Cell.md) | x |',
36
+ 'Text with `code [not](../B/Code.md)` and\n\n```\n[fenced](../B/Fenced.md)\n```\n\n~~~md\n![fenced](x.png)\n~~~\n\nafter [after](../B/After.md)',
37
+ '---\nnodeType: "[Task](../../NodeTypes/Task.md)"\nid: one\n---\n\n# One\n[body](../B/Body.md)',
38
+ '[folder](../B/) [mangled](junk/knowledge-base/Projects/C.md)',
39
+ // Indented code blocks: four columns in, where a paragraph cannot continue.
40
+ '[before](../B/Before.md)\n\n [indented](../B/Indented.md)\n ![x](y.png)\n\n still code [c](../B/C2.md)\n\n[after](../B/After2.md)',
41
+ '# Heading\n [code after heading](../B/H.md)\n\npara\n [lazy continuation](../B/Lazy.md)',
42
+ '\t[tab code](../B/Tab.md)\n\ntext [t](../B/T.md)',
43
+ '- item\n\n [list paragraph](../B/ListPara.md)\n\n [list code](../B/ListCode.md)\n\nback [out](../B/Out.md)\n\n [code again](../B/Code2.md)',
44
+ '1. one\n2. two\n\n [ordered para](../B/Ord.md)\n\n [ordered code](../B/OrdCode.md)',
45
+ '> quote\n\n [code after quote](../B/Q.md)\n\n [two spaces](../B/Two2.md)',
46
+ // A fence line four columns in opens or closes nothing (a paragraph's continuation, or still code).
47
+ 'para\n ~~~\n [lazy fence](../B/LazyFence.md)\n ~~~\n\npara\n ```\n [tick span](../B/Span.md)\n ```',
48
+ '~~~\n ~~~\n[in fence](../B/InFence.md)\n~~~\n[out of fence](../B/OutFence.md)',
49
+ '- item\n\n ~~~\n [list fence](../B/ListFence.md)\n ~~~\n\n[after list](../B/AfterList.md)',
50
+ // Reference definitions inside blockquotes.
51
+ '> [q1]: ../B/Q1.md "t"\n> > [q2]: <../B/Q 2.md>\n\n[one][q1] [two][q2]',
52
+ ];
53
+
54
+ /** The destinations react-markdown renders for a page, in document order, as the attribute values. */
55
+ function rendered(page: string): string[] {
56
+ const html = renderToStaticMarkup(<Markdown remarkPlugins={[remarkGfm, remarkFrontmatter]}>{page}</Markdown>);
57
+ const doc = new DOMParser().parseFromString(html, 'text/html');
58
+ return [...doc.querySelectorAll('a[href], img[src]')].map((el) => el.getAttribute(el.tagName === 'A' ? 'href' : 'src')!);
59
+ }
60
+
61
+ /** Destinations compared as what they name: decoded, markdown escapes undone. */
62
+ const canonical = (d: string) => safeDecode(d.replace(/\\([!-/:-@[-`{-~])/g, '$1'));
63
+
64
+ describe('md-links agrees with the app on a shared fixture set', () => {
65
+ it.each(PAGES.map((p, i) => [i, p]))('page %i: the scanner finds exactly the destinations the app renders', (_i, page) => {
66
+ const scanned = scanMarkdownLinks(page).filter((s) => !s.inFrontmatter);
67
+ // The renderer emits a definition where a reference USES it; order by first use.
68
+ const ours = scanned.map((s) => canonical(s.destination)).sort();
69
+ const theirs = rendered(page).map(canonical).sort();
70
+ expect(theirs.length).toBeGreaterThan(0);
71
+ expect(ours).toEqual(theirs);
72
+ });
73
+
74
+ it.each(PAGES.map((p, i) => [i, p]))('page %i: every destination resolves to the same place', (_i, page) => {
75
+ for (const span of scanMarkdownLinks(page)) {
76
+ const image = span.kind === 'image';
77
+ const ours = resolveMdLink(span.destination, { basePath: BASE, kbDirName: KB, image });
78
+ const href = canonical(span.destination);
79
+ // The app follows an id-link by id before it resolves anything as a path.
80
+ expect(MD_ID_LINK_RE.test(href), href).toBe(NODE_ID_LINK_RE.test(href));
81
+ if (NODE_ID_LINK_RE.test(href)) {
82
+ expect(ours, href).toBeNull();
83
+ continue;
84
+ }
85
+ const theirs = resolveKbHref(span.destination.replace(/\\([!-/:-@[-`{-~])/g, '$1'), {
86
+ basePath: BASE,
87
+ kbDirName: KB,
88
+ repairMangledPath: !image,
89
+ });
90
+ if (theirs === null || theirs.kind === 'external') {
91
+ expect(ours, href).toBeNull();
92
+ continue;
93
+ }
94
+ // A same-page anchor names the page itself: nothing a move rewrites.
95
+ if (href.startsWith('#')) {
96
+ expect(ours, href).toBeNull();
97
+ continue;
98
+ }
99
+ expect(ours, href).toEqual({
100
+ form: href.startsWith('/workspace/') ? 'workspace' : href.startsWith('/') ? 'root' : 'relative',
101
+ path: theirs.path,
102
+ branch: theirs.branch,
103
+ hash: theirs.hash,
104
+ });
105
+ }
106
+ });
107
+
108
+ it('link syntax inside inline code: a link to neither the app nor the rewriter', () => {
109
+ const page = 'Example: `[x](../B/Two.md)`';
110
+ expect(rendered(page)).toEqual([]);
111
+ expect(scanMarkdownLinks(page)).toEqual([]);
112
+ });
113
+ });
@@ -1,7 +1,8 @@
1
- import { useCallback, useEffect, useState } from 'react';
1
+ import { useCallback, useContext, useEffect, useState } from 'react';
2
2
  import { useLocation, useNavigate } from 'react-router-dom';
3
- import { useGit } from '../../git/state/git.context';
4
- import { useWorkspace } from '../state/workspace.context';
3
+ import { GitContext } from '../../git/state/git.context';
4
+ import { WorkspaceContext } from '../state/workspace.context';
5
+ import { useRendererSurface } from '../components/renderers/rendererSurface';
5
6
  import { authFetch } from '../../../lib/api';
6
7
  import {
7
8
  isExternalHref,
@@ -136,8 +137,12 @@ export function fetchNodeId(branch: string, workspacePath: string): Promise<stri
136
137
  * links id-based on their own, independent of the `FileRoute` path→id redirect.
137
138
  */
138
139
  export function useCanonicalFileUrl(workspacePath: string | null): string | null {
139
- const git = useGit();
140
- const branch = git.status?.branch ?? null;
140
+ // A surface outside the app knows the address of the file it is showing —
141
+ // it was told it by whatever opened it — and has no git status to resolve
142
+ // one from. Asked FIRST, and before `useGit`, which has no provider there.
143
+ const surface = useRendererSurface();
144
+ const git = useContext(GitContext);
145
+ const branch = surface ? null : (git?.status?.branch ?? null);
141
146
  // Tie the resolved id to the exact (branch, path) it was fetched for. Inputs
142
147
  // change a render before the effect re-resolves, so without this key the URL
143
148
  // would briefly pair the new path with the *previous* node's id.
@@ -156,6 +161,7 @@ export function useCanonicalFileUrl(workspacePath: string | null): string | null
156
161
  };
157
162
  }, [key, branch, workspacePath]);
158
163
 
164
+ if (surface) return workspacePath ? surface.canonicalUrlFor(workspacePath) : null;
159
165
  if (!branch || !workspacePath) return null;
160
166
  const nodeId = resolved && resolved.key === key ? resolved.id : null;
161
167
  const relative = nodeId ? kbNodeUrl(branch, nodeId) : kbFileUrl(branch, workspacePath);
@@ -317,10 +323,19 @@ export function branchFromPathname(pathname: string): string | null {
317
323
  }
318
324
 
319
325
  export function useFileNav() {
326
+ // Outside the app every opener is the surface's: the embed opens a page in
327
+ // a NEW TAB through its host and never navigates itself. Read before the
328
+ // two app contexts, which have no provider there — so they are read
329
+ // non-throwing and asserted only on the app path below.
330
+ const surface = useRendererSurface();
320
331
  const navigate = useNavigate();
321
332
  const location = useLocation();
322
- const git = useGit();
323
- const { kbDirName } = useWorkspace();
333
+ const git = useContext(GitContext);
334
+ const workspace = useContext(WorkspaceContext);
335
+ if (!surface && (!git || !workspace)) {
336
+ throw new Error('useFileNav must be used within GitContext/WorkspaceContext or a RendererSurface');
337
+ }
338
+ const kbDirName = surface?.kbDirName ?? workspace?.kbDirName ?? '';
324
339
  // The URL's branch first, the git status second. During a branch switch the
325
340
  // status still reports the branch being LEFT — it only catches up once the
326
341
  // destination workspace has bootstrapped and answered — so building a click
@@ -329,7 +344,7 @@ export function useFileNav() {
329
344
  // which branch is on screen (`FileRoute` bootstraps to match it), so a click
330
345
  // lands on the branch being switched TO. Off a workspace route there is no
331
346
  // branch in the URL and the status is the only answer there is.
332
- const branch = branchFromPathname(location.pathname) ?? git.status?.branch ?? null;
347
+ const branch = branchFromPathname(location.pathname) ?? git?.status?.branch ?? null;
333
348
 
334
349
  const openFile = useCallback(
335
350
  (pathOrUrl: string) => {
@@ -423,11 +438,28 @@ export function useFileNav() {
423
438
  * later segment happens to equal `kbDirName` — which a real folder inside
424
439
  * the tree is allowed to be. A path that came from the tree needs no
425
440
  * repair, so applying one could only ever open the wrong file.
441
+ *
442
+ * `edit` asks the viewer to open the file straight into edit mode — for a
443
+ * page the caller has just created, which is there to be written, not read.
444
+ * It travels as router state (`startEditing`, the key the skill page
445
+ * already answers to), not in the URL, so a shared or bookmarked link never
446
+ * drops anyone into the editor; `FileViewer` honours it once and clears it.
447
+ * The path rides along (`startEditingPath`) because the URL does not keep
448
+ * naming it: `FileRoute` swaps a node's path URL for its id URL.
449
+ *
450
+ * `replace` swaps the current history entry instead of adding one — for
451
+ * asking to edit the page already on screen, where a second entry for the
452
+ * same URL would make Back look like it did nothing.
426
453
  */
427
454
  const openWorkspacePath = useCallback(
428
- (path: string) => {
455
+ (path: string, options?: { edit?: boolean; replace?: boolean }) => {
429
456
  if (!branch) return;
430
- navigate(kbFileUrl(branch, path));
457
+ const url = kbFileUrl(branch, path);
458
+ const replace = options?.replace === true;
459
+ const state = { startEditing: true, startEditingPath: path };
460
+ if (options?.edit) navigate(url, replace ? { state, replace } : { state });
461
+ else if (replace) navigate(url, { replace });
462
+ else navigate(url);
431
463
  },
432
464
  [branch, navigate],
433
465
  );
@@ -437,6 +469,19 @@ export function useFileNav() {
437
469
  navigate(kbFileUrl(branch));
438
470
  }, [branch, navigate]);
439
471
 
472
+ // One return for the app, one for a surface. The surface's verbs are
473
+ // substituted WHOLESALE rather than branched inside each opener: "open it
474
+ // in a new tab, never navigate" is a different behaviour, not a parameter
475
+ // of this one, and a half-overridden navigator is how an embed ends up on
476
+ // a page no token was minted for.
477
+ if (surface) {
478
+ return {
479
+ openFile: (pathOrUrl: string) => surface.openLink(pathOrUrl, ''),
480
+ openLink: surface.openLink,
481
+ openWorkspacePath: surface.openWorkspacePath,
482
+ closeFile: () => undefined,
483
+ };
484
+ }
440
485
  return { openFile, openLink, openWorkspacePath, closeFile };
441
486
  }
442
487
 
@@ -449,9 +494,14 @@ export function useFileNav() {
449
494
  * the chat citation renderer so both resolve id-links identically.
450
495
  */
451
496
  export function useNodeIdNav() {
497
+ const surface = useRendererSurface();
452
498
  const { openFile } = useFileNav();
453
- const git = useGit();
454
- const branch = git.status?.branch ?? null;
499
+ const git = useContext(GitContext);
500
+ const location = useLocation();
501
+ // The URL's branch first, the git status second — the same order as
502
+ // `useFileNav`: during a branch switch the status still names the branch
503
+ // being left, and an id resolved against it would open the wrong tree.
504
+ const branch = branchFromPathname(location.pathname) ?? git?.status?.branch ?? null;
455
505
 
456
506
  const openNodeId = useCallback(
457
507
  async (idOrLink: string) => {
@@ -476,5 +526,9 @@ export function useNodeIdNav() {
476
526
  [branch, openFile],
477
527
  );
478
528
 
529
+ // The surface resolves an id its own way — the embed hands it to its host
530
+ // as an app address, which the app then resolves with the reader's own
531
+ // session. Resolving it HERE would need a session the embed does not have.
532
+ if (surface) return { openNodeId: surface.openNodeId };
479
533
  return { openNodeId };
480
534
  }
@@ -0,0 +1,42 @@
1
+ import { useSyncExternalStore } from 'react';
2
+
3
+ /**
4
+ * The page on screen that an Edit click would open for editing right now, or
5
+ * null: no page open, already editing (or entering it, or proposing), a file
6
+ * with no editing surface, someone else holding the lock, or a reader who may
7
+ * only propose.
8
+ *
9
+ * Edit mode is the viewer's own state, and should stay so — but the command
10
+ * menu offers "Edit this page", and an entry that does nothing when chosen
11
+ * is worse than none. So the viewer PUBLISHES its verdict here, the same
12
+ * conditions its Edit button is drawn and enabled by, and the menu reads it.
13
+ * One string rather than a context, because the menu lives in the toolbar,
14
+ * above and beside the viewer, not under it.
15
+ */
16
+ let editablePage: string | null = null;
17
+ const listeners = new Set<() => void>();
18
+
19
+ function subscribe(listener: () => void): () => void {
20
+ listeners.add(listener);
21
+ return () => listeners.delete(listener);
22
+ }
23
+
24
+ /** Called by the viewer whenever its answer changes. */
25
+ export function publishEditablePage(path: string | null): void {
26
+ if (editablePage === path) return;
27
+ editablePage = path;
28
+ listeners.forEach((l) => l());
29
+ }
30
+
31
+ /** Withdraw `path` — but only if it is still the published one (another viewer may have taken over). */
32
+ export function withdrawEditablePage(path: string): void {
33
+ if (editablePage === path) publishEditablePage(null);
34
+ }
35
+
36
+ export function useEditablePage(): string | null {
37
+ return useSyncExternalStore(
38
+ subscribe,
39
+ () => editablePage,
40
+ () => null,
41
+ );
42
+ }
@@ -248,16 +248,19 @@ export interface WorkspaceContextValue {
248
248
  */
249
249
  addTab: (relativePath: string) => Promise<boolean>;
250
250
  /**
251
- * Close a tab. Prompts via `window.confirm` if the tab has unsaved edits;
251
+ * Close a tab. Asks in the app's own dialog if the tab has unsaved edits;
252
252
  * pass `{ skipConfirm: true }` from bulk-close paths that have already
253
253
  * collected one consolidated confirm. If the closed tab was active,
254
254
  * activates the tab to its left (or right) and returns its path so the
255
255
  * caller can update the URL. Returns `{ closed: false }` when the user
256
- * cancelled the dirty-confirm.
256
+ * cancelled the dirty-confirm, or when the workspace moved to another
257
+ * branch while it was asked. A bulk close that asked its own question
258
+ * passes the `workspaceId` it asked in, and closes nothing if that has
259
+ * moved on since: the same path on the new branch is a different tab.
257
260
  */
258
261
  closeTab: (
259
262
  tab: OpenTab,
260
- options?: { skipConfirm?: boolean },
263
+ options?: { skipConfirm?: boolean; workspaceId?: string | null },
261
264
  ) => Promise<{ closed: boolean; newActivePath: string | null }>;
262
265
  /** Activate a tab without prompting. Triggers a refetch if the tab's cache was invalidated. */
263
266
  activateTab: (tab: OpenTab) => void;
@@ -283,7 +286,13 @@ export interface WorkspaceContextValue {
283
286
  activePath: string | null,
284
287
  ) => Promise<HydrateResult>;
285
288
 
286
- createFile: (relativePath: string, content?: string) => Promise<void>;
289
+ /**
290
+ * Write a new file and refresh the tree. Unconditional by default, as the
291
+ * explorer's New file has always been; `ifAbsent` makes it an exclusive
292
+ * create, refused with a 409 `WorkspaceApiError` when the path already
293
+ * exists, for a caller that picked the name from a tree that may be stale.
294
+ */
295
+ createFile: (relativePath: string, content?: string, options?: { ifAbsent?: boolean }) => Promise<void>;
287
296
  createDirectory: (relativePath: string) => Promise<void>;
288
297
  /**
289
298
  * Extract a `.zip` file already in the workspace. Defaults to "unzip here":