@bevel-software/platform-core-frontend 0.32.0 → 0.34.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 (207) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +1 -1
  3. package/src/lib/__tests__/api.test.ts +28 -1
  4. package/src/lib/api.ts +4 -2
  5. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +53 -1
  6. package/src/modules/access/api.ts +4 -5
  7. package/src/modules/access/components/ManageAccessDialog.tsx +11 -12
  8. package/src/modules/access/hooks/useAccessRequests.ts +1 -1
  9. package/src/modules/access/hooks/useFileAccess.ts +1 -1
  10. package/src/modules/access/index.ts +11 -0
  11. package/src/modules/access/requests.api.ts +1 -1
  12. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  13. package/src/modules/admin/components/AddMemberInput.tsx +1 -1
  14. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  15. package/src/modules/admin/components/UserAccountsPage.tsx +3 -3
  16. package/src/modules/admin/index.ts +7 -0
  17. package/src/modules/admin/services/groups.api.ts +11 -1
  18. package/src/modules/admin/state/admin.context.tsx +1 -1
  19. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  20. package/src/modules/agents/components/ConnectAsChoice.tsx +81 -0
  21. package/src/modules/agents/connect-as.ts +15 -0
  22. package/src/modules/agents/index.ts +5 -0
  23. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  24. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  25. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +13 -0
  26. package/src/modules/audit/components/AuditEventsPanel.tsx +1 -1
  27. package/src/modules/audit/components/AuditLogPage.tsx +11 -2
  28. package/src/modules/audit/services/audit.api.ts +5 -0
  29. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  30. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  31. package/src/modules/auth/components/AccountPage.tsx +8 -2
  32. package/src/modules/auth/index.ts +12 -0
  33. package/src/modules/auth/services/account.api.ts +18 -2
  34. package/src/modules/change-requests/__tests__/ChangeRequestDialog.access-rules.test.tsx +0 -1
  35. package/src/modules/change-requests/__tests__/ChangeRequestDialog.binary.test.tsx +0 -1
  36. package/src/modules/change-requests/__tests__/ChangeRequestDialog.brings-itself-up-to-date.test.tsx +0 -1
  37. package/src/modules/change-requests/__tests__/ChangeRequestDialog.edit.test.tsx +166 -0
  38. package/src/modules/change-requests/__tests__/ChangeRequestDialog.fork-point.test.tsx +0 -1
  39. package/src/modules/change-requests/__tests__/ChangeRequestDialog.initial-file.test.tsx +0 -1
  40. package/src/modules/change-requests/__tests__/ChangeRequestDialog.moved.test.tsx +0 -1
  41. package/src/modules/change-requests/__tests__/ChangeRequestDialog.sync-banner.test.tsx +0 -1
  42. package/src/modules/change-requests/__tests__/ChangeRequestDialog.test.tsx +0 -2
  43. package/src/modules/change-requests/__tests__/ChangeRequestDialog.unreadable.test.tsx +0 -1
  44. package/src/modules/change-requests/__tests__/apply-outcome-for-every-viewer.test.tsx +0 -1
  45. package/src/modules/change-requests/components/BranchFilePreview.tsx +4 -12
  46. package/src/modules/change-requests/components/ChangeRequestDialog.tsx +138 -30
  47. package/src/modules/change-requests/components/ChangeRequestLink.tsx +2 -3
  48. package/src/modules/change-requests/components/CrFileTree.tsx +1 -1
  49. package/src/modules/change-requests/components/FileChangeBoxes.tsx +2 -3
  50. package/src/modules/change-requests/hooks/useApplyChangeRequest.ts +3 -5
  51. package/src/modules/change-requests/hooks/useCrFileDiffs.ts +1 -1
  52. package/src/modules/change-requests/index.ts +14 -0
  53. package/src/modules/change-requests/services/change-requests.api.ts +2 -2
  54. package/src/modules/change-requests/services/denied-file.api.ts +2 -2
  55. package/src/modules/change-requests/services/propose.api.ts +3 -4
  56. package/src/modules/change-requests/utils/diff.ts +1 -1
  57. package/src/modules/change-requests/utils/readFailure.ts +1 -1
  58. package/src/modules/embed/__tests__/EmbedView.test.tsx +19 -2
  59. package/src/modules/embed/components/EmbedLinkPage.tsx +1 -2
  60. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  61. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  62. package/src/modules/git/components/BranchSwitcher.tsx +3 -4
  63. package/src/modules/git/components/FileHistoryPanel.tsx +2 -2
  64. package/src/modules/git/components/GitSyncFailedBanner.tsx +2 -4
  65. package/src/modules/git/components/HistoryVersionPreview.tsx +4 -15
  66. package/src/modules/git/components/PullNeededBanner.tsx +1 -1
  67. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  68. package/src/modules/git/hooks/useAutoPullUpdates.ts +1 -1
  69. package/src/modules/git/index.ts +11 -0
  70. package/src/modules/layout/components/MobileChatLayout.tsx +1 -1
  71. package/src/modules/layout/index.ts +9 -0
  72. package/src/modules/library/__tests__/SkillPage.test.tsx +268 -24
  73. package/src/modules/library/__tests__/propose-change.test.ts +75 -0
  74. package/src/modules/library/components/AddToPluginDialog.tsx +1 -1
  75. package/src/modules/library/components/ChangeRequestDock.tsx +1 -1
  76. package/src/modules/library/components/LibraryLayout.tsx +2 -2
  77. package/src/modules/library/components/LibraryPage.tsx +3 -3
  78. package/src/modules/library/components/ManagedPluginRequests.tsx +1 -1
  79. package/src/modules/library/components/NewSkillPanel.tsx +2 -2
  80. package/src/modules/library/components/PersonalAddDialog.tsx +1 -1
  81. package/src/modules/library/components/PersonalPluginPage.tsx +1 -1
  82. package/src/modules/library/components/PluginExtras.tsx +1 -4
  83. package/src/modules/library/components/PluginPage.tsx +1 -1
  84. package/src/modules/library/components/PluginRows.tsx +1 -1
  85. package/src/modules/library/components/SkillsTree.tsx +1 -4
  86. package/src/modules/library/components/plugin-page-parts.tsx +1 -1
  87. package/src/modules/library/components/skill-page/SkillFilePane.tsx +74 -14
  88. package/src/modules/library/components/skill-page/SkillPage.tsx +80 -47
  89. package/src/modules/library/components/tool-page/ToolConnectionSection.tsx +2 -4
  90. package/src/modules/library/components/tool-page/ToolVarRow.tsx +2 -2
  91. package/src/modules/library/hooks/useJoinRequests.ts +1 -1
  92. package/src/modules/library/hooks/useLibraryData.ts +3 -3
  93. package/src/modules/library/hooks/useToolPage.ts +1 -1
  94. package/src/modules/library/hooks/useToolSource.ts +1 -1
  95. package/src/modules/library/index.ts +12 -0
  96. package/src/modules/library/routes/LibraryRoutes.tsx +1 -1
  97. package/src/modules/library/routes/WorkspaceItemRoute.tsx +1 -3
  98. package/src/modules/library/routes/library-paths.ts +1 -1
  99. package/src/modules/library/services/library.api.ts +10 -8
  100. package/src/modules/library/services/plugins.api.ts +1 -1
  101. package/src/modules/library/services/teams.api.ts +1 -1
  102. package/src/modules/library/utils/status.ts +2 -2
  103. package/src/modules/onboarding/components/ConnectAgentPill.tsx +1 -1
  104. package/src/modules/onboarding/components/CreatorWelcomePage.tsx +2 -3
  105. package/src/modules/onboarding/components/GetStartedColumn.tsx +6 -13
  106. package/src/modules/onboarding/components/InviteButton.tsx +2 -2
  107. package/src/modules/onboarding/components/InviteDialog.tsx +4 -6
  108. package/src/modules/onboarding/components/RootLanding.tsx +2 -2
  109. package/src/modules/onboarding/components/StarterPackCard.tsx +1 -1
  110. package/src/modules/onboarding/components/WelcomePage.tsx +2 -5
  111. package/src/modules/onboarding/index.ts +10 -0
  112. package/src/modules/onboarding/paths.ts +1 -1
  113. package/src/modules/onboarding/state/agent-connection.ts +2 -2
  114. package/src/modules/onboarding/state/onboarding.ts +1 -1
  115. package/src/modules/onboarding/state/starter-packs.ts +1 -1
  116. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +1 -1
  117. package/src/modules/pr/index.ts +14 -0
  118. package/src/modules/pr/services/pr-approvals.api.ts +1 -1
  119. package/src/modules/pr/services/pr-cancel.api.ts +1 -1
  120. package/src/modules/pr/services/pr-detail.api.ts +2 -2
  121. package/src/modules/pr/services/pr-edit.api.ts +22 -0
  122. package/src/modules/pr/services/pr-merge.api.ts +1 -1
  123. package/src/modules/pr/services/pr-open.api.ts +1 -1
  124. package/src/modules/review/components/DiffViewer.tsx +1 -1
  125. package/src/modules/review/components/MarkdownDiffViewer.tsx +24 -3
  126. package/src/modules/review/components/ReviewPanel.tsx +10 -5
  127. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  128. package/src/modules/review/state/ReviewProvider.tsx +2 -2
  129. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  130. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +112 -2
  131. package/src/modules/secrets-vault/index.ts +6 -0
  132. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  133. package/src/modules/settings/components/DeploymentPage.tsx +2 -2
  134. package/src/modules/settings/components/SettingsLayout.tsx +2 -2
  135. package/src/modules/settings/index.ts +8 -0
  136. package/src/modules/setup/components/FirstRunStorage.tsx +1 -1
  137. package/src/modules/setup/index.ts +6 -0
  138. package/src/modules/toolbar/commands/actions.tsx +3 -3
  139. package/src/modules/toolbar/commands/useCommandActions.ts +5 -9
  140. package/src/modules/toolbar/components/AgentInstructionsCard.tsx +2 -2
  141. package/src/modules/toolbar/components/AppSwitcher.tsx +1 -2
  142. package/src/modules/toolbar/components/CoworkSetupSteps.tsx +1 -1
  143. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +39 -5
  144. package/src/modules/toolbar/components/ProfileMenu.tsx +3 -3
  145. package/src/modules/toolbar/components/SearchPalette.tsx +4 -8
  146. package/src/modules/toolbar/components/Toolbar.tsx +2 -5
  147. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +91 -2
  148. package/src/modules/toolbar/index.ts +6 -0
  149. package/src/modules/toolbar/search/sources.ts +4 -7
  150. package/src/modules/toolbar/services/agent-instructions.api.ts +1 -1
  151. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  152. package/src/modules/tools/ToolsExplorerPage.tsx +217 -18
  153. package/src/modules/tools/__tests__/ToolsExplorerPage.read-only.test.tsx +220 -0
  154. package/src/modules/tools/tool-hints.api.ts +44 -0
  155. package/src/modules/workflow/index.ts +7 -0
  156. package/src/modules/workflow/state/ChangeRequestStaleBinder.tsx +1 -0
  157. package/src/modules/workflow/state/EventBusFocusBinder.tsx +1 -1
  158. package/src/modules/workspace/components/FileExplorer.tsx +35 -8
  159. package/src/modules/workspace/components/FilePaneCard.tsx +37 -12
  160. package/src/modules/workspace/components/FileRoute.tsx +10 -3
  161. package/src/modules/workspace/components/FileViewer.tsx +169 -25
  162. package/src/modules/workspace/components/FullScreenView.tsx +93 -0
  163. package/src/modules/workspace/components/KbFileRail.tsx +1 -1
  164. package/src/modules/workspace/components/KbPageHeader.tsx +9 -0
  165. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +163 -0
  166. package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +11 -0
  167. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +487 -3
  168. package/src/modules/workspace/components/readingCarry.ts +59 -0
  169. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +74 -180
  170. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  171. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  172. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  173. package/src/modules/workspace/components/renderers/ToolRenderer.tsx +1 -1
  174. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  175. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +168 -42
  176. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  177. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  178. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +57 -7
  179. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +122 -4
  180. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +235 -1
  181. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +29 -4
  182. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  183. package/src/modules/workspace/components/renderers/__tests__/pageToolsHarness.ts +79 -0
  184. package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +316 -0
  185. package/src/modules/workspace/components/renderers/htmlSandbox.ts +123 -28
  186. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +215 -25
  187. package/src/modules/workspace/components/renderers/index.ts +10 -0
  188. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  189. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  190. package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +253 -0
  191. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  192. package/src/modules/workspace/hooks/useFullScreenView.ts +52 -0
  193. package/src/modules/workspace/hooks/useImageRevision.ts +1 -1
  194. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +1 -1
  195. package/src/modules/workspace/hooks/useLastCommit.ts +1 -1
  196. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  197. package/src/modules/workspace/hooks/useWorkspaceState.ts +4 -4
  198. package/src/modules/workspace/index.ts +50 -2
  199. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  200. package/src/modules/workspace/routing/kb-routes.ts +222 -54
  201. package/src/modules/workspace/state/__tests__/applied-request-clears-pending.test.tsx +0 -1
  202. package/src/modules/workspace/state/open-change-requests.tsx +1 -1
  203. package/src/modules/workspace/utils/fileTree.ts +1 -1
  204. package/src/modules/workspace/utils/frameEscape.ts +15 -0
  205. package/src/modules/workspace/utils/treeConfirm.ts +1 -1
  206. package/src/shared/theme/measure.ts +7 -0
  207. package/src/modules/pr/services/pr-comments.api.ts +0 -45
@@ -9,32 +9,45 @@ import { authFetch } from '../../../../lib/api';
9
9
  * the viewer's session, so a page sees and reaches exactly the tools the
10
10
  * viewer's own agent does — the same listing, the same refusals, nothing of
11
11
  * the enterprise agent's internal tools — and the server records it in the
12
- * Audit log under the page's path (`X-Bevel-Page`). The four members map to
12
+ * Audit log under the page's path (`X-Bevel-Page`). The five members map to
13
13
  * what an agent calls:
14
14
  *
15
- * searchTools(query) → `list_tools`, narrowed to the names that contain
16
- * every word of `query` (all of them for an empty one)
17
- * toolsInfo(names) → `tools_info`
18
- * callTool(name, args) → `tools/call`
19
- * callToolChain(code) → `call_tool_chain`
15
+ * searchTools(query) → `list_tools`, narrowed to the names that
16
+ * contain every word of `query` (all of them
17
+ * for an empty one)
18
+ * toolsInfo(names) → `tools_info`
19
+ * callTool(name, args) → `tools/call`
20
+ * callToolChain(code) → `call_tool_chain`
21
+ * uploadFile(file, options) → `request_file_upload`, the bytes POSTed to the
22
+ * upload endpoint, then `apply_file_upload`
20
23
  *
21
24
  * A call that only reads runs at once. A call that may write — a tool the
22
25
  * deployment's UTCP manual tags `write`, a tool the manual does not list (a
23
- * `.tool`'s, a plugin's MCP server's: nothing says they only read), and every
24
- * chain (a chain may call writers) — waits for the viewer's answer to one
25
- * card per page view. See {@link PageConsent}.
26
+ * `.tool`'s, a plugin's MCP server's: nothing says they only read), every
27
+ * chain (a chain may call writers) and every upload — waits for the viewer's
28
+ * answer to one card per page view. See {@link PageConsent}.
26
29
  */
27
30
 
28
- /** What the file page tells the HTML renderer: that tools are answered here, and for which page. */
31
+ /** What a host that is the platform tells the HTML renderer: that tools are answered here, and for which page. */
29
32
  export interface PageTools {
30
33
  /** The page's knowledge-base path (`Dashboards/Roadmap.html`), what the Audit log shows as the agent. */
31
34
  pagePath: string;
32
35
  }
33
36
 
34
37
  /**
35
- * Provided by the app's file page and nowhere else: its presence is what
36
- * gives a page `window.bevel.tools`. The embed, a skill page and every other
37
- * preview mount the renderer without it, and their pages get `null`.
38
+ * Its presence is what gives a page `window.bevel.tools`. The hosts that
39
+ * provide it — the surfaces the app itself shows a page on, and only those:
40
+ *
41
+ * - the file page (`FileViewer.tsx`);
42
+ * - the skill page's file pane (`SkillFilePane.tsx`), under the file's
43
+ * knowledge-base path — the one the file page uses — never the
44
+ * skill-relative tab name.
45
+ *
46
+ * Every other mount goes without, and its pages get `null`: the embed and
47
+ * the MCP App pane (outside the platform — they show the "only available in
48
+ * the platform" card), the change-request file preview and the history
49
+ * preview (a page shown as a version, not opened). A new host is added
50
+ * here, deliberately, or not at all.
38
51
  */
39
52
  export const PageToolsContext = createContext<PageTools | null>(null);
40
53
 
@@ -54,14 +67,42 @@ export function useOpenPageInPlatform(): (() => void) | null {
54
67
  return useContext(OpenPageInPlatformContext);
55
68
  }
56
69
 
57
- /** The four members a page calls, by the name the frame posts. */
58
- export type PageToolFunction = 'searchTools' | 'toolsInfo' | 'callTool' | 'callToolChain';
70
+ /**
71
+ * The file a page's links resolve against, for a host whose `filePath` is not
72
+ * a workspace path on this tab's branch — a skill page names its files
73
+ * relative to the skill and reads them from the default branch. Absent, a
74
+ * link resolves against `filePath` on the branch this tab stands on.
75
+ */
76
+ export interface PageLinkHome {
77
+ /** The page's workspace path. */
78
+ path: string;
79
+ /** The branch the page was read from. */
80
+ branch: string;
81
+ }
82
+
83
+ export const PageLinkHomeContext = createContext<PageLinkHome | null>(null);
59
84
 
60
- const PAGE_TOOL_FUNCTIONS: ReadonlySet<string> = new Set(['searchTools', 'toolsInfo', 'callTool', 'callToolChain']);
85
+ export function usePageLinkHome(): PageLinkHome | null {
86
+ return useContext(PageLinkHomeContext);
87
+ }
88
+
89
+ /** The five members a page calls, by the name the frame posts. */
90
+ export type PageToolFunction = 'searchTools' | 'toolsInfo' | 'callTool' | 'callToolChain' | 'uploadFile';
91
+
92
+ const PAGE_TOOL_FUNCTIONS: ReadonlySet<string> = new Set([
93
+ 'searchTools',
94
+ 'toolsInfo',
95
+ 'callTool',
96
+ 'callToolChain',
97
+ 'uploadFile',
98
+ ]);
61
99
 
62
100
  /** The code-mode meta-tools by the name a page may also `callTool` them under: two read, the chain may write. */
63
101
  const READING_META_TOOLS: ReadonlySet<string> = new Set(['list_tools', 'tools_info']);
64
102
  const CHAIN_TOOL = 'call_tool_chain';
103
+ /** The agent upload path a page's `uploadFile` runs: the token, then the bytes, then the landing. */
104
+ const UPLOAD_REQUEST_TOOL = 'request_file_upload';
105
+ const UPLOAD_APPLY_TOOL = 'apply_file_upload';
65
106
 
66
107
  /** The answer a page gets when its viewer chose Deny. */
67
108
  export const DENIED = 'denied';
@@ -133,6 +174,72 @@ export class PageToolsClient {
133
174
  return this.callTool(CHAIN_TOOL, { code });
134
175
  }
135
176
 
177
+ /**
178
+ * Put a file into the knowledge base the way an agent does, with the
179
+ * viewer's session: `request_file_upload` for a token, the file's bytes
180
+ * POSTed as the raw body to the upload endpoint with the token in the
181
+ * `x-upload-token` header (never in the address, and never back to the
182
+ * page), then `apply_file_upload` into `destination` on `branch`.
183
+ *
184
+ * Resolves with what `apply_file_upload` answers, every path listed (the
185
+ * apply is asked with `all: true`). Rejects with the message
186
+ * of the step that failed: the upload endpoint's own (a file over the
187
+ * deployment's limit is refused there, naming it, before the apply runs),
188
+ * or the apply's — thrown whole (a destination the viewer may not write),
189
+ * or, when the upload landed no path at all, the first path's refusal with
190
+ * its code (`exists` under `create`, `missing` under `update`).
191
+ *
192
+ * The token is this call's alone — the page never sees it, so nobody can
193
+ * retry with it — so whenever no apply answered, it is given up at once
194
+ * (`DELETE` on the same endpoint, the token again in the header) and any
195
+ * bytes staged with it are deleted rather than left until it expires. An
196
+ * apply that answered has spent the token itself.
197
+ */
198
+ async uploadFile(file: unknown, options: unknown): Promise<unknown> {
199
+ const opts = (options && typeof options === 'object' ? options : {}) as Record<string, unknown>;
200
+ if (!(file instanceof Blob)) throw new PageToolError('uploadFile needs a File, or a Blob with a `name` option.');
201
+ const name = typeof opts.name === 'string' && opts.name !== '' ? opts.name : file instanceof File ? file.name : '';
202
+ if (name === '') throw new PageToolError('uploadFile needs a file name: pass a File, or a Blob with a `name` option.');
203
+ const { branch, destination, mode } = opts;
204
+ if (typeof branch !== 'string' || branch === '') throw new PageToolError('uploadFile needs `branch`.');
205
+ if (typeof destination !== 'string' || destination === '') {
206
+ throw new PageToolError('uploadFile needs `destination`, the folder the file lands in.');
207
+ }
208
+
209
+ const issued = (await this.callTool(UPLOAD_REQUEST_TOOL, { body: {} })) as { uploadUrl?: unknown; token?: unknown };
210
+ if (typeof issued?.uploadUrl !== 'string' || typeof issued.token !== 'string') {
211
+ throw new PageToolError('The upload could not start: the server answered no upload address.');
212
+ }
213
+ const token = issued.token;
214
+ const address = headerAddress(issued.uploadUrl);
215
+ let answer: { count?: unknown; files?: unknown };
216
+ try {
217
+ const sent = await this.fetchImpl(`${address}?filename=${encodeURIComponent(name)}`, {
218
+ method: 'POST',
219
+ headers: { 'Content-Type': 'application/octet-stream', 'x-upload-token': token },
220
+ body: file,
221
+ });
222
+ if (!sent.ok) throw new PageToolError(await refusalOf(sent));
223
+ // `all: true`: the page gets every path's outcome, never the tool's
224
+ // 25-entry cut with a `truncated` flag it has no way to act on.
225
+ answer = (await this.callTool(UPLOAD_APPLY_TOOL, {
226
+ body: { branch, token, destination, all: true, ...(mode !== undefined ? { mode } : {}) },
227
+ })) as { count?: unknown; files?: unknown };
228
+ } catch (err) {
229
+ await this.discardUpload(address, token);
230
+ throw err;
231
+ }
232
+ const files = Array.isArray(answer?.files) ? (answer.files as Array<Record<string, unknown>>) : [];
233
+ if (answer?.count === 0 && files.length > 0) {
234
+ const refused = files[0]!;
235
+ throw new PageToolError(
236
+ typeof refused.message === 'string' ? refused.message : 'Nothing was written.',
237
+ typeof refused.error === 'string' ? refused.error : undefined,
238
+ );
239
+ }
240
+ return answer;
241
+ }
242
+
136
243
  /**
137
244
  * `tools/call`, answered the way the page reads it: the tool's structured
138
245
  * content when it has some, else its text — parsed when it is JSON. A tool
@@ -153,7 +260,7 @@ export class PageToolsClient {
153
260
  */
154
261
  async mayWrite(fn: PageToolFunction, args: unknown[]): Promise<boolean> {
155
262
  if (fn === 'searchTools' || fn === 'toolsInfo') return false;
156
- if (fn === 'callToolChain') return true;
263
+ if (fn === 'callToolChain' || fn === 'uploadFile') return true;
157
264
  const name = args[0];
158
265
  if (typeof name !== 'string') return false; // refused by callTool itself, before anything runs
159
266
  if (READING_META_TOOLS.has(name)) return false;
@@ -176,6 +283,15 @@ export class PageToolsClient {
176
283
  }
177
284
  }
178
285
 
286
+ /** Give an unapplied upload token up, with its staged bytes. Best-effort: the refusal stands either way. */
287
+ private async discardUpload(address: string, token: string): Promise<void> {
288
+ try {
289
+ await this.fetchImpl(address, { method: 'DELETE', headers: { 'x-upload-token': token } });
290
+ } catch {
291
+ // Unreached, the token still expires, and its bytes with it.
292
+ }
293
+ }
294
+
179
295
  /** The deployment's UTCP manual, read at most once a `MANUAL_TTL_MS`: tool name → whether it is tagged `write`. */
180
296
  private writingTools(): Promise<Map<string, boolean> | null> {
181
297
  const now = this.now();
@@ -219,6 +335,26 @@ export class PageToolsClient {
219
335
  }
220
336
  }
221
337
 
338
+ /**
339
+ * The upload endpoint's header-token address: `uploadUrl` without its token
340
+ * segment, on this app's own origin — the server builds `uploadUrl` from its
341
+ * public base URL, which the browser may reach under another name.
342
+ */
343
+ function headerAddress(uploadUrl: string): string {
344
+ return new URL(uploadUrl, 'http://app.invalid').pathname.replace(/\/[^/]*$/, '');
345
+ }
346
+
347
+ /** The `{ error }` an HTTP refusal carries, or its status when it carries none. */
348
+ async function refusalOf(res: Response): Promise<string> {
349
+ try {
350
+ const body = (await res.json()) as { error?: unknown };
351
+ if (typeof body?.error === 'string' && body.error !== '') return body.error;
352
+ } catch {
353
+ // Not JSON: say what the status says.
354
+ }
355
+ return `The upload was refused (HTTP ${res.status}).`;
356
+ }
357
+
222
358
  interface RpcMessage {
223
359
  id?: unknown;
224
360
  result?: unknown;
@@ -271,9 +407,15 @@ function toPageResult(result: CallToolResult | undefined): unknown {
271
407
  * call asks again. Calls that arrive while the card is open wait on that same
272
408
  * card, so a page that fires ten writes at once sees one card, and every one
273
409
  * of the ten gets the answer.
410
+ *
411
+ * When the view ends the renderer {@link PageConsent.close}s it: from then on
412
+ * nothing asks and nothing is allowed, so a call the old view made that is
413
+ * still being decided when it ends is answered `closed` instead of opening a
414
+ * card in the next view, or running on an Allow the old view gave.
274
415
  */
275
416
  export class PageConsent {
276
417
  private allowed = false;
418
+ private ended = false;
277
419
  private asking: Promise<boolean | null> | null = null;
278
420
  private readonly ask: () => Promise<boolean | null>;
279
421
 
@@ -287,12 +429,24 @@ export class PageConsent {
287
429
  return this.asking;
288
430
  }
289
431
 
290
- /** Whether the viewer allows this page to write, asking them if no answer holds; null when nobody answered. */
432
+ /** Whether the view this consent belongs to has ended. */
433
+ get closed(): boolean {
434
+ return this.ended;
435
+ }
436
+
437
+ /** The view ended: every request from now on answers null and asks nobody. */
438
+ close(): void {
439
+ this.ended = true;
440
+ }
441
+
442
+ /** Whether the viewer allows this page to write, asking them if no answer holds; null when nobody answered or the view ended. */
291
443
  request(): Promise<boolean | null> {
444
+ if (this.ended) return Promise.resolve(null);
292
445
  if (this.allowed) return Promise.resolve(true);
293
446
  this.asking ??= this.ask().then(
294
447
  (ok) => {
295
448
  this.asking = null;
449
+ if (this.ended) return null;
296
450
  if (ok) this.allowed = true;
297
451
  return ok;
298
452
  },
@@ -309,6 +463,8 @@ export class PageConsent {
309
463
  export interface ToolCallMessage {
310
464
  type: 'bevel.tool.call';
311
465
  requestId: string;
466
+ /** The identity the app minted for the document that posted this (see `htmlSandbox.ts`), when it was given one. */
467
+ documentId?: string;
312
468
  fn: PageToolFunction;
313
469
  args: unknown[];
314
470
  }
@@ -324,13 +480,22 @@ export function asToolCall(data: unknown): ToolCallMessage | null {
324
480
  const msg = data as Partial<ToolCallMessage>;
325
481
  if (msg.type !== 'bevel.tool.call' || typeof msg.requestId !== 'string') return null;
326
482
  if (typeof msg.fn !== 'string' || !PAGE_TOOL_FUNCTIONS.has(msg.fn)) return null;
327
- return { type: 'bevel.tool.call', requestId: msg.requestId, fn: msg.fn, args: Array.isArray(msg.args) ? msg.args : [] };
483
+ return {
484
+ type: 'bevel.tool.call',
485
+ requestId: msg.requestId,
486
+ ...(typeof msg.documentId === 'string' ? { documentId: msg.documentId } : {}),
487
+ fn: msg.fn,
488
+ args: Array.isArray(msg.args) ? msg.args : [],
489
+ };
328
490
  }
329
491
 
492
+ const CLOSED_MESSAGE = 'The page was closed before the viewer answered.';
493
+
330
494
  /**
331
495
  * Answer one of a page's tool calls: wait out an open card, ask for consent
332
- * when the call may write, run it, and say how it went. Never throws — every
333
- * outcome is a response for the frame.
496
+ * when the call may write, run it, and say how it went. A call whose view
497
+ * ended (its `consent` closed) before it was decided runs nothing and is
498
+ * answered `closed`. Never throws — every outcome is a response for the frame.
334
499
  */
335
500
  export async function answerToolCall(
336
501
  msg: ToolCallMessage,
@@ -349,10 +514,9 @@ export async function answerToolCall(
349
514
  // A write that arrives while the card is open joins it, and gets its answer.
350
515
  const allowed = await consent.request();
351
516
  // The view ended before the viewer chose: nothing ran, and nobody refused.
352
- if (allowed === null) return fail('The page was closed before the viewer answered.', 'closed');
517
+ if (allowed === null) return fail(CLOSED_MESSAGE, 'closed');
353
518
  if (!allowed) {
354
- const name = msg.fn === 'callToolChain' ? CHAIN_TOOL : String(msg.args[0] ?? '');
355
- const args = msg.fn === 'callToolChain' ? { code: msg.args[0] } : msg.args[1];
519
+ const { name, args } = refusedCall(msg);
356
520
  void client.recordRefusal(name, args);
357
521
  return fail(DENIED, DENIED);
358
522
  }
@@ -360,6 +524,8 @@ export async function answerToolCall(
360
524
  // Nothing of the page runs while the viewer is being asked about it.
361
525
  while (consent.open) await consent.open;
362
526
  }
527
+ // The view ended while the call was being decided: it is no longer the view's to run.
528
+ if (consent.closed) return fail(CLOSED_MESSAGE, 'closed');
363
529
  const [a, b] = msg.args;
364
530
  const result =
365
531
  msg.fn === 'searchTools'
@@ -368,13 +534,37 @@ export async function answerToolCall(
368
534
  ? await client.toolsInfo(a)
369
535
  : msg.fn === 'callToolChain'
370
536
  ? await client.callToolChain(a)
371
- : await client.callTool(a, b);
537
+ : msg.fn === 'uploadFile'
538
+ ? await client.uploadFile(a, b)
539
+ : await client.callTool(a, b);
372
540
  return { type: 'bevel.tool.response', requestId: msg.requestId, ok: true, result };
373
541
  } catch (err) {
374
542
  return fail(err instanceof Error ? err.message : String(err), err instanceof PageToolError ? err.code : undefined);
375
543
  }
376
544
  }
377
545
 
546
+ /**
547
+ * A refused call as the Audit log names it: the tool the page asked for, with
548
+ * the arguments it would have run with. An upload is refused as the
549
+ * `apply_file_upload` it would have ended in: its `body` holds only what that
550
+ * tool takes (no token, since none was asked for), and the file's name — not
551
+ * an argument of the tool, it travels with the bytes — sits beside it as
552
+ * `file`, so the record says what was refused without inventing an argument.
553
+ */
554
+ function refusedCall(msg: ToolCallMessage): { name: string; args: unknown } {
555
+ const [a, b] = msg.args;
556
+ if (msg.fn === 'callToolChain') return { name: CHAIN_TOOL, args: { code: a } };
557
+ if (msg.fn === 'uploadFile') {
558
+ const opts = (b && typeof b === 'object' ? b : {}) as Record<string, unknown>;
559
+ const file = typeof opts.name === 'string' ? opts.name : a instanceof File ? a.name : undefined;
560
+ return {
561
+ name: UPLOAD_APPLY_TOOL,
562
+ args: { body: { branch: opts.branch, destination: opts.destination, mode: opts.mode }, file },
563
+ };
564
+ }
565
+ return { name: String(a ?? ''), args: b };
566
+ }
567
+
378
568
  /** A page's display name: its file name without the extension. */
379
569
  export function pageName(path: string): string {
380
570
  const file = path.slice(path.lastIndexOf('/') + 1);
@@ -21,6 +21,16 @@ export {
21
21
  // and a renderer is tested through this module's entry, never its files.
22
22
  export { RendererSurfaceContext, useRendererSurface, type RendererRawRead, type RendererSurface } from './rendererSurface';
23
23
  export { CanDownloadContext } from './DownloadFileButton';
24
+ // The page tool bridge, for every renderer that shows an HTML page: the one
25
+ // controller a renderer calls for a page's `window.bevel.tools`, and the two
26
+ // contexts a host provides it through (the file page's tools; a skill
27
+ // page's way to the platform). A renderer and its tests need nothing else.
28
+ export {
29
+ useHtmlToolBridge,
30
+ type HtmlToolBridgeOptions,
31
+ type HtmlToolBridgeResult,
32
+ } from './useHtmlToolBridge';
33
+ export { OpenPageInPlatformContext, PageToolsContext, type PageTools } from './htmlToolBridge';
24
34
  export { useKbGraphLoader } from './kbGraphLoader';
25
35
 
26
36
  /**
@@ -44,7 +44,8 @@ import rehypeSanitize from 'rehype-sanitize';
44
44
  import rehypeSlug from 'rehype-slug';
45
45
  import { CopyAnchorButton } from './CopyAnchorButton';
46
46
  import { KbImage, type KbImageResolver } from './KbImage';
47
- import { normalizeHref } from '../../../../shared/markdown/hrefs';
47
+ import { isExternalHref, normalizeHref } from '../../../../shared/markdown/hrefs';
48
+ import { KbAppLink, type KbLinkTarget } from './KbAppLink';
48
49
 
49
50
  export type { KbImageResolver, KbImageSource } from './KbImage';
50
51
 
@@ -106,6 +107,14 @@ export interface KbMarkdownComponentOptions {
106
107
  * text rather than falling through as relative-URL links.
107
108
  */
108
109
  onOpenNodeId?: (id: string) => void;
110
+ /**
111
+ * Where an internal `.md` link leads, so its anchor can say so (see
112
+ * {@link KbAppLink}); `onOpenFile` still follows the click. Omitted (the
113
+ * diff, the skill page, the embed) → the anchor carries the href as written.
114
+ */
115
+ fileLinkTarget?: (href: string) => KbLinkTarget | null;
116
+ /** The same for an id-link, beside {@link onOpenNodeId}. */
117
+ nodeIdLinkTarget?: (id: string) => KbLinkTarget | null;
109
118
  /**
110
119
  * When provided, each heading gets a hover-revealed button copying
111
120
  * `headingLink(slug)`. Requires {@link KB_REHYPE_PLUGINS} (slug ids); pass it
@@ -137,7 +146,8 @@ export interface KbMarkdownComponentOptions {
137
146
  * WHICH links this surface wants handed to `onOpenFile`, rather than left
138
147
  * to the browser.
139
148
  *
140
- * - `'browser'` (default, the app): the internal `.md` path links only.
149
+ * - `'browser'` (default, the app): the internal `.md` path links, and
150
+ * with a {@link fileLinkTarget} every workspace destination it resolves.
141
151
  * An `http(s)` destination becomes a plain `target="_blank"` anchor,
142
152
  * because in a tab that is exactly right — the browser opens a new tab
143
153
  * and nothing needs intercepting.
@@ -165,6 +175,8 @@ export interface KbMarkdownComponentOptions {
165
175
  export function useKbMarkdownComponents({
166
176
  onOpenFile,
167
177
  onOpenNodeId,
178
+ fileLinkTarget,
179
+ nodeIdLinkTarget,
168
180
  headingLink,
169
181
  onMermaidError = 'error',
170
182
  resolveImage,
@@ -213,39 +225,34 @@ export function useKbMarkdownComponents({
213
225
  // anchor, so a bare id can't fall through as a relative-URL link.
214
226
  if (!onOpenNodeId) return <span {...props}>{children}</span>;
215
227
  return (
216
- <a
228
+ <KbAppLink
217
229
  {...props}
218
230
  href={href}
219
- onClick={(e) => {
220
- e.preventDefault();
221
- onOpenNodeId(href);
222
- }}
223
- className="cursor-pointer"
231
+ target={nodeIdLinkTarget?.(href) ?? null}
232
+ onOpen={() => onOpenNodeId(href)}
224
233
  >
225
234
  {children}
226
- </a>
235
+ </KbAppLink>
227
236
  );
228
237
  }
229
238
  // Legacy/internal path link: a `.md` destination, optionally with a
230
239
  // heading anchor (`Node.md#goal`) — still used by frontmatter `nodeType`.
231
- // External (`http…`) and same-page (`#…`) links fall through to <a>.
232
- if (
233
- onOpenFile &&
234
- href && !href.startsWith('http') && !href.startsWith('#') && /\.md(#|$)/.test(href)
235
- ) {
236
- return (
237
- <a
238
- {...props}
239
- href={href}
240
- onClick={(e) => {
241
- e.preventDefault();
242
- onOpenFile(href);
243
- }}
244
- className="cursor-pointer"
245
- >
246
- {children}
247
- </a>
248
- );
240
+ // External (any scheme, as `resolveKbHref` reads one — not a name
241
+ // that merely starts `http`, like `http-notes.md`) and same-page
242
+ // (`#…`) links fall through to <a>.
243
+ // Where the caller resolves link targets (the app's file page) every
244
+ // other workspace destination is taken too — a page, an image, a PDF —
245
+ // so none of them is left to the browser as a relative URL that
246
+ // replaces the page being read.
247
+ if (onOpenFile && href && !isExternalHref(href) && !normalizeHref(href).startsWith('#')) {
248
+ const target = fileLinkTarget?.(href) ?? null;
249
+ if (target || /\.md(#|$)/.test(href)) {
250
+ return (
251
+ <KbAppLink {...props} href={href} target={target} onOpen={() => onOpenFile(href)}>
252
+ {children}
253
+ </KbAppLink>
254
+ );
255
+ }
249
256
  }
250
257
  // A surface that owns every outgoing link takes the rest: an
251
258
  // `http(s)` address, and a workspace path the `.md` rule above did
@@ -308,5 +315,5 @@ export function useKbMarkdownComponents({
308
315
  return <pre {...props}>{children}</pre>;
309
316
  },
310
317
  };
311
- }, [onOpenFile, onOpenNodeId, headingLink, onMermaidError, resolveImage, linkPolicy]);
318
+ }, [onOpenFile, onOpenNodeId, fileLinkTarget, nodeIdLinkTarget, headingLink, onMermaidError, resolveImage, linkPolicy]);
312
319
  }
@@ -0,0 +1,35 @@
1
+ /** Decode a URL hash (`#some%20slug`) to its bare slug, tolerating bad escapes. */
2
+ function safeDecodeHash(hash: string): string {
3
+ const raw = hash.replace(/^#/, '');
4
+ try {
5
+ return decodeURIComponent(raw);
6
+ } catch {
7
+ return raw;
8
+ }
9
+ }
10
+
11
+ /** Escape a slug for safe interpolation into an attribute-selector string. */
12
+ function escapeForSelector(value: string): string {
13
+ return (
14
+ value
15
+ .replace(/["\\]/g, '\\$&')
16
+ // CSS-hex-escape control characters (newline, CR, …): a raw control char in
17
+ // a CSS string is a syntax error that would make querySelector throw. The
18
+ // trailing space terminates the hex escape.
19
+ // eslint-disable-next-line no-control-regex
20
+ .replace(/[\x00-\x1f\x7f]/g, (c) => `\\${c.charCodeAt(0).toString(16)} `)
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Scroll the heading a fragment names (`#goal`, the id rehype-slug gave it)
26
+ * into view inside `container` — the one way a rendered markdown file goes
27
+ * to one of its own sections: the file page on its address's fragment, the
28
+ * skill page on a section link's. A fragment naming nothing does nothing.
29
+ */
30
+ export function scrollToHeading(container: ParentNode | null, hash: string): void {
31
+ const slug = hash ? safeDecodeHash(hash) : '';
32
+ if (!slug || !container) return;
33
+ const target = container.querySelector(`[id="${escapeForSelector(slug)}"]`);
34
+ target?.scrollIntoView({ block: 'start' });
35
+ }