@bevel-software/platform-core-frontend 0.11.1 → 0.12.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 (50) hide show
  1. package/THIRD-PARTY-NOTICES.md +670 -395
  2. package/package.json +6 -2
  3. package/src/lib/__tests__/api.test.ts +95 -0
  4. package/src/lib/api.ts +30 -2
  5. package/src/lib/clipboard.ts +25 -0
  6. package/src/modules/access/__tests__/useFileAccess.test.tsx +47 -0
  7. package/src/modules/access/hooks/useFileAccess.ts +23 -5
  8. package/src/modules/library/components/tool-page/McpServerSection.tsx +1 -1
  9. package/src/modules/library/utils/clipboard.ts +4 -20
  10. package/src/modules/onboarding/__tests__/creator-welcome.test.tsx +16 -7
  11. package/src/modules/onboarding/__tests__/onboarding.test.tsx +1 -1
  12. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +7 -7
  13. package/src/modules/workspace/components/FileExplorer.tsx +6 -14
  14. package/src/modules/workspace/components/FileViewer.tsx +17 -4
  15. package/src/modules/workspace/components/KbPageHeader.tsx +1 -1
  16. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +3 -1
  17. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +17 -0
  18. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +15 -0
  19. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +11 -2
  20. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +88 -0
  21. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +309 -0
  22. package/src/modules/workspace/components/renderers/LegacyOfficeRenderer.tsx +60 -0
  23. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +261 -33
  24. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +184 -0
  25. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +195 -45
  26. package/src/modules/workspace/components/renderers/__tests__/DownloadFileButton.test.tsx +48 -0
  27. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.test.tsx +176 -0
  28. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +214 -76
  29. package/src/modules/workspace/components/renderers/__tests__/PptxRenderer.test.tsx +125 -0
  30. package/src/modules/workspace/components/renderers/__tests__/XlsxRenderer.test.tsx +245 -0
  31. package/src/modules/workspace/components/renderers/__tests__/emailBody.test.ts +117 -0
  32. package/src/modules/workspace/components/renderers/__tests__/emailMessage.test.ts +404 -0
  33. package/src/modules/workspace/components/renderers/__tests__/pptxOutline.test.ts +448 -0
  34. package/src/modules/workspace/components/renderers/__tests__/readBodyCapped.test.ts +117 -0
  35. package/src/modules/workspace/components/renderers/__tests__/rendererLayout.test.ts +73 -7
  36. package/src/modules/workspace/components/renderers/__tests__/rendererSelection.test.tsx +107 -0
  37. package/src/modules/workspace/components/renderers/downloadFile.ts +33 -0
  38. package/src/modules/workspace/components/renderers/emailBody.ts +168 -0
  39. package/src/modules/workspace/components/renderers/emailMessage.ts +223 -0
  40. package/src/modules/workspace/components/renderers/emlMessage.ts +91 -0
  41. package/src/modules/workspace/components/renderers/htmlSandbox.ts +9 -2
  42. package/src/modules/workspace/components/renderers/index.ts +82 -6
  43. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +9 -2
  44. package/src/modules/workspace/components/renderers/msgMessage.ts +219 -0
  45. package/src/modules/workspace/components/renderers/pptxOutline.ts +317 -0
  46. package/src/modules/workspace/components/renderers/readBodyCapped.ts +97 -0
  47. package/src/modules/workspace/components/renderers/xmlReading.ts +0 -0
  48. package/src/shared/mcp/__tests__/connect-snippets.test.ts +8 -8
  49. package/src/shared/mcp/connect-snippets.ts +4 -4
  50. package/src/url-suffix-imports.d.ts +12 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.11.1",
3
+ "version": "0.12.0",
4
4
  "description": "Open-source core UI of the Bevel platform (raw TS/TSX source): workspace explorer/viewer, branches & change requests, Library, secrets, tools, access control.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -28,9 +28,13 @@
28
28
  "@tailwindcss/typography": "^0.5.19",
29
29
  "@utcp/sdk": "^1.1.1",
30
30
  "clsx": "^2.1.1",
31
+ "htmlparser2": "^12.0.0",
32
+ "jszip": "^3.10.1",
31
33
  "lucide-react": "^1.7.0",
32
34
  "mammoth": "^1.12.0",
33
35
  "mermaid": "^11.16.1",
36
+ "pdfjs-dist": "^5.4.624",
37
+ "postal-mime": "^3.0.0",
34
38
  "react-markdown": "^10.1.0",
35
39
  "react-resizable-panels": "^4.10.0",
36
40
  "rehype-raw": "^7.0.0",
@@ -41,7 +45,7 @@
41
45
  "tailwind-merge": "^3.5.0",
42
46
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
43
47
  "yaml": "^2.9.0",
44
- "@bevel-software/platform-shared": "0.11.1"
48
+ "@bevel-software/platform-shared": "0.12.0"
45
49
  },
46
50
  "devDependencies": {
47
51
  "@testing-library/jest-dom": "^6.9.1",
@@ -0,0 +1,95 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+
3
+ import { authFetch, API_UNREACHABLE_EVENT } from '../api';
4
+
5
+ /** Counts API_UNREACHABLE_EVENT dispatches for the span of one test. */
6
+ function watchUnreachable(): { seen: () => number; stop: () => void } {
7
+ let count = 0;
8
+ const onEvent = (): void => {
9
+ count += 1;
10
+ };
11
+ window.addEventListener(API_UNREACHABLE_EVENT, onEvent);
12
+ return {
13
+ seen: () => count,
14
+ stop: () => window.removeEventListener(API_UNREACHABLE_EVENT, onEvent),
15
+ };
16
+ }
17
+
18
+ /** The rejection `fetch` produces when its signal is aborted. */
19
+ function abortError(): Error {
20
+ return new DOMException('The operation was aborted.', 'AbortError') as unknown as Error;
21
+ }
22
+
23
+ describe('authFetch transport-failure signalling', () => {
24
+ let watcher: ReturnType<typeof watchUnreachable>;
25
+
26
+ beforeEach(() => {
27
+ vi.restoreAllMocks();
28
+ watcher = watchUnreachable();
29
+ });
30
+
31
+ afterEach(() => {
32
+ watcher.stop();
33
+ });
34
+
35
+ it('does NOT signal unreachable when the caller aborted its own request', async () => {
36
+ // The binary viewers abort in flight on unmount and on every file switch.
37
+ // Treating that as backend downtime probes /api/health and can raise the
38
+ // maintenance overlay during ordinary navigation.
39
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(abortError());
40
+
41
+ await expect(authFetch('/api/workspace/file')).rejects.toMatchObject({ name: 'AbortError' });
42
+ expect(watcher.seen()).toBe(0);
43
+ });
44
+
45
+ it('does NOT signal unreachable when the abort carried a custom reason', async () => {
46
+ // `abort(reason)` rejects the fetch with THAT value rather than an
47
+ // AbortError, so the rejection alone cannot identify the abort.
48
+ const controller = new AbortController();
49
+ controller.abort('viewer closed');
50
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce('viewer closed');
51
+
52
+ await expect(
53
+ authFetch('/api/workspace/file', { signal: controller.signal }),
54
+ ).rejects.toBe('viewer closed');
55
+ expect(watcher.seen()).toBe(0);
56
+ });
57
+
58
+ it('does NOT signal unreachable when the aborted signal rode on a Request', async () => {
59
+ const controller = new AbortController();
60
+ controller.abort('viewer closed');
61
+ const request = { signal: controller.signal } as unknown as Request;
62
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce('viewer closed');
63
+
64
+ await expect(authFetch(request)).rejects.toBe('viewer closed');
65
+ expect(watcher.seen()).toBe(0);
66
+ });
67
+
68
+ it('still signals unreachable when init overrides a Request that was already aborted', async () => {
69
+ // `fetch` uses init's signal and ignores the Request's when both are
70
+ // given, so a stale aborted signal on the Request must not mask a real
71
+ // transport failure on the live one.
72
+ const stale = new AbortController();
73
+ stale.abort();
74
+ const live = new AbortController();
75
+ const request = { signal: stale.signal } as unknown as Request;
76
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new TypeError('Failed to fetch'));
77
+
78
+ await expect(authFetch(request, { signal: live.signal })).rejects.toThrow('Failed to fetch');
79
+ expect(watcher.seen()).toBe(1);
80
+ });
81
+
82
+ it('still signals unreachable when the connection genuinely fails', async () => {
83
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new TypeError('Failed to fetch'));
84
+
85
+ await expect(authFetch('/api/workspace/file')).rejects.toThrow('Failed to fetch');
86
+ expect(watcher.seen()).toBe(1);
87
+ });
88
+
89
+ it('still signals unreachable when the proxy answers for a dead upstream', async () => {
90
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({ status: 503 } as Response);
91
+
92
+ await authFetch('/api/workspace/file');
93
+ expect(watcher.seen()).toBe(1);
94
+ });
95
+ });
package/src/lib/api.ts CHANGED
@@ -6,7 +6,8 @@ const TOKEN_KEY = 'bevel_token';
6
6
  * the reverse proxy answered for a dead upstream (502/503/504). The
7
7
  * MaintenanceOverlay listens for this, confirms via /api/health, and takes
8
8
  * over the screen during a redeploy. Application-level errors (4xx, 500)
9
- * are NOT signalled — those mean the backend is up and responding.
9
+ * are NOT signalled — those mean the backend is up and responding. Neither is
10
+ * an aborted request, which says nothing about the backend at all.
10
11
  */
11
12
  export const API_UNREACHABLE_EVENT = 'bevel:api-unreachable';
12
13
 
@@ -16,6 +17,29 @@ function signalUnreachable(): void {
16
17
  window.dispatchEvent(new Event(API_UNREACHABLE_EVENT));
17
18
  }
18
19
 
20
+ /**
21
+ * Whether a rejection is a caller aborting its own request rather than a
22
+ * transport failure.
23
+ *
24
+ * The signal is asked first because it is the only reliable witness:
25
+ * `abort(reason)` rejects the fetch with THAT reason, which can be any value
26
+ * and carries no marking of its own. Only the signal the fetch actually ran on
27
+ * is asked — `init`'s wins where it has one, and a `Request` input's is used
28
+ * only otherwise — so a stale signal on a Request that `init` overrode cannot
29
+ * mask a real transport failure on the live one.
30
+ *
31
+ * The rejection is consulted as a fallback, for an abort whose signal never
32
+ * reached us; there it is matched by `name` rather than `instanceof
33
+ * DOMException`, which does not hold across realms.
34
+ */
35
+ function wasAborted(input: RequestInfo | URL, init: RequestInit | undefined, err: unknown): boolean {
36
+ const requestSignal =
37
+ typeof input === 'object' && 'signal' in input ? (input as Request).signal : undefined;
38
+ const signal = init?.signal ?? requestSignal;
39
+ if (signal?.aborted) return true;
40
+ return typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'AbortError';
41
+ }
42
+
19
43
  export function getToken(): string | null {
20
44
  return localStorage.getItem(TOKEN_KEY);
21
45
  }
@@ -41,7 +65,11 @@ export async function authFetch(input: RequestInfo | URL, init?: RequestInit): P
41
65
  try {
42
66
  response = await fetch(input, { ...init, headers });
43
67
  } catch (err) {
44
- signalUnreachable();
68
+ // An abort is the caller's own doing, not the backend going away: the
69
+ // binary viewers abort in flight on unmount and on every file switch.
70
+ // Signalling here would probe /api/health on ordinary navigation and
71
+ // could raise the maintenance overlay when a probe transiently fails.
72
+ if (!wasAborted(input, init, err)) signalUnreachable();
45
73
  throw err;
46
74
  }
47
75
 
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Copy text, and say whether it landed.
3
+ *
4
+ * `navigator.clipboard` is undefined outside a secure context (plain-HTTP
5
+ * staging, some embedded webviews), and `writeText` rejects when the document
6
+ * isn't focused. Both are ordinary conditions, not exceptions — a copy button
7
+ * hands over something the user can also select by hand, so a failure has a
8
+ * real answer and must never surface as success.
9
+ *
10
+ * Lives in `lib/` because more than one module needs it: the Library's copy
11
+ * buttons and the email viewer's link list.
12
+ */
13
+ export async function copyToClipboard(text: string): Promise<boolean> {
14
+ // `navigator` itself is undefined off the browser (SSR, a test runner with
15
+ // no DOM): reading through it would THROW rather than answer false, which is
16
+ // the one thing this function promises not to do.
17
+ const clipboard = typeof navigator === 'undefined' ? undefined : navigator.clipboard;
18
+ if (!clipboard?.writeText) return false;
19
+ try {
20
+ await clipboard.writeText(text);
21
+ return true;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
@@ -218,6 +218,53 @@ describe('useFileAccess', () => {
218
218
  expect(apiMock.fetchFileAccess).not.toHaveBeenCalled();
219
219
  });
220
220
 
221
+ // Switching files must not leak the PREVIOUS file's verdicts into the new
222
+ // lookup's in-flight window: both canWrite and canDownload reset to null
223
+ // (optimistic) the moment the new request starts.
224
+ it('resets canWrite/canDownload to null while a new file lookup is in flight', async () => {
225
+ apiMock.fetchFileAccess.mockResolvedValueOnce({
226
+ canWrite: false,
227
+ canDownload: false,
228
+ eligible: { roles: ['Admin'], users: [] },
229
+ owners: { roles: [], users: [] },
230
+ });
231
+ // The second file's request stays pending until we resolve it.
232
+ let resolveSecond!: (v: unknown) => void;
233
+ apiMock.fetchFileAccess.mockImplementationOnce(
234
+ () =>
235
+ new Promise((resolve) => {
236
+ resolveSecond = resolve;
237
+ }),
238
+ );
239
+
240
+ const { result, rerender } = renderHook(
241
+ ({ path }: { path: string }) => useFileAccess(path, PROTECTED),
242
+ {
243
+ wrapper: withWorkspace(makeWorkspace()),
244
+ initialProps: { path: 'knowledge-base/Knowledge/First.md' },
245
+ },
246
+ );
247
+ await waitFor(() => expect(result.current.loading).toBe(false));
248
+ expect(result.current.canWrite).toBe(false);
249
+ expect(result.current.canDownload).toBe(false);
250
+
251
+ rerender({ path: 'knowledge-base/Knowledge/Second.md' });
252
+ // In flight for the SECOND file: the first file's hard "no" must not show.
253
+ expect(result.current.loading).toBe(true);
254
+ expect(result.current.canWrite).toBeNull();
255
+ expect(result.current.canDownload).toBeNull();
256
+
257
+ resolveSecond({
258
+ canWrite: true,
259
+ canDownload: true,
260
+ eligible: { roles: [], users: [] },
261
+ owners: { roles: [], users: [] },
262
+ });
263
+ await waitFor(() => expect(result.current.loading).toBe(false));
264
+ expect(result.current.canWrite).toBe(true);
265
+ expect(result.current.canDownload).toBe(true);
266
+ });
267
+
221
268
  // Branch still loading: hold canWrite=null so the caller stays optimistic
222
269
  // (editor editable) until we know which gate applies. Don't fire the API
223
270
  // yet because we'd be guessing.
@@ -11,6 +11,8 @@ export interface FileAccessState {
11
11
  * — the backend is the authoritative gate at commit time anyway.
12
12
  */
13
13
  canWrite: boolean | null;
14
+ /** Same contract as `canWrite`, for the per-path `download:` verb. */
15
+ canDownload: boolean | null;
14
16
  eligible: AccessEligible;
15
17
  /**
16
18
  * The node's owners — who to contact about it. Populated only when the
@@ -62,6 +64,7 @@ export function useFileAccess(
62
64
  const { workspaceId, kbDirName } = useWorkspace();
63
65
  const [state, setState] = useState<FileAccessState>({
64
66
  canWrite: null,
67
+ canDownload: null,
65
68
  eligible: EMPTY_ELIGIBLE,
66
69
  owners: EMPTY_ELIGIBLE,
67
70
  loading: false,
@@ -70,7 +73,7 @@ export function useFileAccess(
70
73
 
71
74
  useEffect(() => {
72
75
  if (!workspacePath || !kbDirName || !workspaceId) {
73
- setState({ canWrite: null, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
76
+ setState({ canWrite: null, canDownload: null, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
74
77
  return;
75
78
  }
76
79
  // Files outside the KB repo dir are the user's own workspace — never
@@ -78,7 +81,12 @@ export function useFileAccess(
78
81
  // access tree can't lock users out of their own scratch files.
79
82
  const prefix = `${kbDirName}/`;
80
83
  if (!workspacePath.startsWith(prefix)) {
81
- setState({ canWrite: true, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
84
+ // `canDownload: null` — NOT true. The write short-circuits are this
85
+ // hook's own policy, and they match the backend's write gates; the raw
86
+ // endpoint gates EVERY download regardless of branch or path, so
87
+ // claiming permission here would promise something it can still refuse.
88
+ // Null keeps the button clickable and the backend authoritative.
89
+ setState({ canWrite: true, canDownload: null, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
82
90
  return;
83
91
  }
84
92
  // Drafts are free-for-all (mirrors the backend's branch-protected gates
@@ -87,16 +95,24 @@ export function useFileAccess(
87
95
  // draft. `branch === null` is the bootstrap window before status loads;
88
96
  // return canWrite=null so callers stay optimistic until we know.
89
97
  if (branch === null) {
90
- setState({ canWrite: null, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
98
+ setState({ canWrite: null, canDownload: null, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
91
99
  return;
92
100
  }
93
101
  if (!isProtectedBranch(branch)) {
94
- setState({ canWrite: true, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
102
+ // `canDownload: null` — NOT true. The write short-circuits are this
103
+ // hook's own policy, and they match the backend's write gates; the raw
104
+ // endpoint gates EVERY download regardless of branch or path, so
105
+ // claiming permission here would promise something it can still refuse.
106
+ // Null keeps the button clickable and the backend authoritative.
107
+ setState({ canWrite: true, canDownload: null, eligible: EMPTY_ELIGIBLE, owners: EMPTY_ELIGIBLE, loading: false, error: null });
95
108
  return;
96
109
  }
97
110
 
98
111
  let cancelled = false;
99
- setState((s) => ({ ...s, loading: true, error: null }));
112
+ // Reset the verdicts to null (= optimistic/unknown) for the NEW lookup —
113
+ // carrying the previous file's canWrite/canDownload across a file switch
114
+ // would briefly show the old file's permissions on the new file.
115
+ setState((s) => ({ ...s, canWrite: null, canDownload: null, loading: true, error: null }));
100
116
  // Strip kbDirName/ so the backend resolver receives the repo-relative
101
117
  // path it expects (`Knowledge/Foo.md`, not `knowledge-base/…`).
102
118
  const repoRelative = workspacePath.slice(prefix.length);
@@ -105,6 +121,7 @@ export function useFileAccess(
105
121
  if (cancelled) return;
106
122
  setState({
107
123
  canWrite: res.canWrite,
124
+ canDownload: res.canDownload,
108
125
  eligible: res.eligible,
109
126
  owners: res.owners,
110
127
  loading: false,
@@ -119,6 +136,7 @@ export function useFileAccess(
119
136
  // truly don't have access.
120
137
  setState({
121
138
  canWrite: true,
139
+ canDownload: true,
122
140
  eligible: EMPTY_ELIGIBLE,
123
141
  owners: EMPTY_ELIGIBLE,
124
142
  loading: false,
@@ -165,7 +165,7 @@ export function McpServerSection({
165
165
  )}
166
166
  {server.local && (
167
167
  <div className="mt-1 text-ink-faint">
168
- Runs locally — served by hexis-mcp on each member's machine, never by the workspace.
168
+ Runs locally — served by the local knowledge server on each member's machine, never by the workspace.
169
169
  </div>
170
170
  )}
171
171
  </dl>
@@ -1,23 +1,7 @@
1
- /**
2
- * Copy text, and say whether it landed.
3
- *
4
- * `navigator.clipboard` is undefined outside a secure context (plain-HTTP
5
- * staging, some embedded webviews), and `writeText` rejects when the document
6
- * isn't focused. Both are ordinary conditions here, not exceptions — the
7
- * Library's copy buttons hand over an agent prompt the user can also just
8
- * select, so a failure has a real answer ("select the text instead") and must
9
- * never surface as a success toast.
10
- */
11
- export async function copyToClipboard(text: string): Promise<boolean> {
12
- const clipboard = navigator.clipboard;
13
- if (!clipboard?.writeText) return false;
14
- try {
15
- await clipboard.writeText(text);
16
- return true;
17
- } catch {
18
- return false;
19
- }
20
- }
1
+ // The implementation moved to `lib/clipboard.ts` when the email viewer needed
2
+ // it too; re-exported here so the Library keeps importing its copy helper and
3
+ // its toast strings from one place.
4
+ export { copyToClipboard } from '../../../lib/clipboard';
21
5
 
22
6
  /** What a copy button tells the user, either way. */
23
7
  export const COPIED_TOAST = 'Prompt copied.';
@@ -245,11 +245,16 @@ describe('creator welcome actions', () => {
245
245
  await user.click(screen.getByRole('button', { name: 'Create plugin' }));
246
246
 
247
247
  await waitFor(() => expect(serviceMocks.createPlugin).toHaveBeenCalledWith('Design'));
248
+ // The navigation is the LAST link of the create chain (create -> refresh
249
+ // indexes -> navigate), so it is the settled state to wait for; asserting
250
+ // it immediately races the refresh microtasks and flakes under CI load.
251
+ await waitFor(() =>
252
+ expect(screen.getByLabelText('pathname')).toHaveTextContent(
253
+ '/skills-and-tools/plugins/Design',
254
+ ),
255
+ );
248
256
  expect(data.reload).toHaveBeenCalledOnce();
249
257
  expect(data.reloadPlugins).toHaveBeenCalledOnce();
250
- expect(screen.getByLabelText('pathname')).toHaveTextContent(
251
- '/skills-and-tools/plugins/Design',
252
- );
253
258
  });
254
259
 
255
260
  it('creates a personal skill and opens its skill page', async () => {
@@ -270,14 +275,18 @@ describe('creator welcome actions', () => {
270
275
  userName: 'Juan Viera',
271
276
  }),
272
277
  );
273
- expect(data.reload).toHaveBeenCalledOnce();
274
278
  // The skill's canonical address is its workspace FILE url, not the legacy
275
279
  // `skills/:name` route — that one survives only as a redirect. The dialog
276
280
  // owns this navigation, so the welcome page inherits whatever the rest of
277
- // the Library does, which is the point of routing through it.
278
- expect(screen.getByLabelText('pathname')).toHaveTextContent(
279
- '/workspace/target-company-state/knowledge-base/Plugins/personal-u1/weekly-report/SKILL.md',
281
+ // the Library does, which is the point of routing through it. Waited for,
282
+ // not asserted immediately: navigation is the last link of the create
283
+ // chain and racing its microtasks is what made this test flake in CI.
284
+ await waitFor(() =>
285
+ expect(screen.getByLabelText('pathname')).toHaveTextContent(
286
+ '/workspace/target-company-state/knowledge-base/Plugins/personal-u1/weekly-report/SKILL.md',
287
+ ),
280
288
  );
289
+ expect(data.reload).toHaveBeenCalledOnce();
281
290
  });
282
291
 
283
292
  it('holds the New skill dialog open while creation is pending', async () => {
@@ -388,7 +388,7 @@ describe('WelcomePage', () => {
388
388
  const href = new URL(link.getAttribute('href')!);
389
389
  expect(href.origin + href.pathname).toBe('https://claude.ai/customize/connectors');
390
390
  expect(href.searchParams.get('connectorUrl')).toBe('https://kb.acme.com/api/mcp');
391
- expect(href.searchParams.get('connectorName')).toBe('Hexis — kb.acme.com');
391
+ expect(href.searchParams.get('connectorName')).toBe('Knowledge — kb.acme.com');
392
392
  });
393
393
 
394
394
  /**
@@ -118,10 +118,10 @@ describe('the interactive tab: local first, hosted second, each with its own add
118
118
 
119
119
  const values = snippets();
120
120
  expect(values).toContain(
121
- `claude mcp add hexis-local --env HEXIS_URL="${window.location.origin}" -- npx -y @bevel-software/hexis-mcp`,
121
+ `claude mcp add knowledge --env HEXIS_URL="${window.location.origin}" -- npx -y @bevel-software/hexis-mcp`,
122
122
  );
123
- const json = values.find((v) => v.includes('mcpServers') && v.includes('hexis-local'));
124
- const parsed = JSON.parse(json!).mcpServers['hexis-local'];
123
+ const json = values.find((v) => v.includes('mcpServers') && v.includes('"knowledge"'));
124
+ const parsed = JSON.parse(json!).mcpServers['knowledge'];
125
125
  expect(parsed.args).toEqual(['-y', '@bevel-software/hexis-mcp']);
126
126
  expect(parsed.env.HEXIS_URL).toBe(window.location.origin);
127
127
  // Keyless = interactive: the browser-sign-in mode carries no key env.
@@ -209,11 +209,11 @@ describe('the key-bearing snippets quote the deployment too', () => {
209
209
 
210
210
  // 7. the Claude Code stdio one-liner
211
211
  expect(values).toContain(
212
- `claude mcp add hexis-local --env HEXIS_URL="${window.location.origin}" --env HEXIS_CONNECTION_KEY="${KEY}" -- npx -y @bevel-software/hexis-mcp`,
212
+ `claude mcp add knowledge --env HEXIS_URL="${window.location.origin}" --env HEXIS_CONNECTION_KEY="${KEY}" -- npx -y @bevel-software/hexis-mcp`,
213
213
  );
214
214
  // 8. the JSON config that spawns the package
215
- const json = values.find((v) => v.includes('mcpServers') && v.includes('hexis-local'));
216
- const parsed = JSON.parse(json!).mcpServers['hexis-local'];
215
+ const json = values.find((v) => v.includes('mcpServers') && v.includes('"knowledge"'));
216
+ const parsed = JSON.parse(json!).mcpServers['knowledge'];
217
217
  expect(parsed.args).toEqual(['-y', '@bevel-software/hexis-mcp']);
218
218
  expect(parsed.env.HEXIS_URL).toBe(window.location.origin);
219
219
  expect(parsed.env.HEXIS_CONNECTION_KEY).toBe(KEY);
@@ -246,7 +246,7 @@ describe('the one-click install link', () => {
246
246
  expect(href.origin + href.pathname).toBe('https://claude.ai/customize/connectors');
247
247
  expect(href.searchParams.get('modal')).toBe('add-custom-connector');
248
248
  expect(href.searchParams.get('connectorUrl')).toBe(PUBLIC_URL);
249
- expect(href.searchParams.get('connectorName')).toBe('Hexis — kb.acme.com');
249
+ expect(href.searchParams.get('connectorName')).toBe('Knowledge — kb.acme.com');
250
250
  });
251
251
 
252
252
  it('opens in a new tab without handing Claude a window reference', () => {
@@ -31,7 +31,7 @@ import { ChangeRequestDialog } from '../../change-requests/components/ChangeRequ
31
31
  import { PR_STALE_EVENT } from '../../../core/events';
32
32
  import { snapshotEntries } from '../utils/readDroppedEntries';
33
33
  import { useFileNav } from '../routing/kb-routes';
34
- import { authFetch } from '../../../lib/api';
34
+ import { downloadViaBlob } from './renderers/downloadFile';
35
35
  import { cn } from '../../../lib/utils';
36
36
  import { MenuPanel, MenuItem, TextField, IconButton } from '../../../shared/components';
37
37
  import { useDismissableMenu } from '../../../shared/components';
@@ -453,21 +453,13 @@ function FileTreeNode({
453
453
  : `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(entry.relativePath)}&download=1`;
454
454
  const savedAs = isFolder ? `${entry.name}.zip` : entry.name;
455
455
  try {
456
- const res = await authFetch(url);
457
- if (!res.ok) {
458
- const body = await res.text().catch(() => '');
459
- alert(`Failed to download ${entry.name} (HTTP ${res.status})${body ? `: ${body}` : ''}`);
456
+ const outcome = await downloadViaBlob(url, savedAs);
457
+ if (!outcome.ok) {
458
+ alert(
459
+ `Failed to download ${entry.name} (HTTP ${outcome.status})${outcome.body ? `: ${outcome.body}` : ''}`,
460
+ );
460
461
  return;
461
462
  }
462
- const blob = await res.blob();
463
- const blobUrl = URL.createObjectURL(blob);
464
- const a = document.createElement('a');
465
- a.href = blobUrl;
466
- a.download = savedAs;
467
- document.body.appendChild(a);
468
- a.click();
469
- a.remove();
470
- URL.revokeObjectURL(blobUrl);
471
463
  } catch (err) {
472
464
  console.error('Failed to download:', err);
473
465
  const msg = err instanceof Error ? err.message : String(err);
@@ -36,7 +36,8 @@ import { ChangeRequestDialog } from '../../change-requests/components/ChangeRequ
36
36
  import { formatEligible } from '../../access/hooks/useFileAccess';
37
37
  import { PR_STALE_EVENT } from '../../../core/events';
38
38
  import { suggestedPages } from '../utils/fileTree';
39
- import { getFileRenderer, getRendererLayout } from './renderers';
39
+ import { getFileRenderer, getRendererLayout, isViewOnlyFile } from './renderers';
40
+ import { CanDownloadContext } from './renderers/DownloadFileButton';
40
41
  import type { RendererSaveState } from './renderers';
41
42
  import { KbDocumentShell } from './KbDocumentShell';
42
43
  import { FilePaneCard } from './FilePaneCard';
@@ -901,6 +902,12 @@ export function FileViewer() {
901
902
  const shellVariant =
902
903
  activeTab === 'content' ? getRendererLayout(openFilePath) : 'full-bleed';
903
904
 
905
+ // No-preview routes (legacy Office, ODF) have no editing surface at all —
906
+ // offering Edit/Propose there would acquire a lock for a mode the renderer
907
+ // ignores, and imply text can be saved over a binary document. Suppresses
908
+ // BOTH write-action homes (the pane bar and the header) below.
909
+ const viewOnly = isViewOnlyFile(openFilePath);
910
+
904
911
  // What the pane card's bar names — extension kept, unlike the `<h1>` above,
905
912
  // because the bar is the technical label (`SKILL.md`, `How to get
906
913
  // started.md`) exactly as the skill page's file bar renders it.
@@ -920,8 +927,11 @@ export function FileViewer() {
920
927
 
921
928
  const rendererElement = (
922
929
  // The renderer is a dynamic per-extension lookup resolved in a useMemo
923
- // above — not a component created during render.
930
+ // above — not a component created during render. The provider hands the
931
+ // open file's `download:` verdict to any DownloadFileButton inside the
932
+ // renderer without widening the renderer contract.
924
933
  // eslint-disable-next-line react-hooks/static-components
934
+ <CanDownloadContext.Provider value={access.canDownload}>
925
935
  <Renderer
926
936
  // **Why we key on `openFileSavedContent` (read-only mode only).**
927
937
  // When a teammate's save lands, the workspace state updates the
@@ -977,6 +987,7 @@ export function FileViewer() {
977
987
  onSaveStateChange={setManualSaveState}
978
988
  readOnly={isReviewingPending || !(editMode || proposeMode)}
979
989
  />
990
+ </CanDownloadContext.Provider>
980
991
  );
981
992
 
982
993
  // The pane bar's write action — the labelled button at the frame's top
@@ -986,7 +997,7 @@ export function FileViewer() {
986
997
  // rule). While a mode is OPEN it shows the way out instead. The header's
987
998
  // own cluster is suppressed for prose files (`writeActionInPane`).
988
999
  const lockedBy = fileLock.externalLock?.holderName ?? null;
989
- const paneActions = isReviewingPending ? null : proposeMode ? (
1000
+ const paneActions = isReviewingPending || viewOnly ? null : proposeMode ? (
990
1001
  <>
991
1002
  <Button variant="quiet" size="tiny" onClick={handleDiscardProposal} disabled={proposalBusy}>
992
1003
  Discard
@@ -1076,7 +1087,9 @@ export function FileViewer() {
1076
1087
  onPropose={handleEnterPropose}
1077
1088
  onSendProposal={() => void handleSendProposal()}
1078
1089
  onDiscardProposal={handleDiscardProposal}
1079
- writeActionInPane={shellVariant === 'prose'}
1090
+ // `viewOnly` rides the same flag: it tells the header "the write
1091
+ // action is not yours to render" — and the pane bar renders none.
1092
+ writeActionInPane={shellVariant === 'prose' || viewOnly}
1080
1093
  lockedBy={fileLock.externalLock?.holderName ?? null}
1081
1094
  historyAvailable={historyAvailable}
1082
1095
  isDirty={isManualDirty}
@@ -29,7 +29,7 @@ import { useDismissableMenu } from '../../../shared/components';
29
29
 
30
30
  /** Extensions we strip from the `<h1>`. Anything else stays verbatim. */
31
31
  const KNOWN_EXTENSIONS =
32
- /\.(md|markdown|txt|csv|tsv|json|yaml|yml|html|htm|pdf|docx|xlsx|tool|png|jpe?g|gif|webp|svg)$/i;
32
+ /\.(md|markdown|txt|csv|tsv|json|yaml|yml|html|htm|pdf|docx|xlsx|pptx|doc|ppt|xls|odt|odp|ods|eml|msg|tool|png|jpe?g|gif|webp|svg)$/i;
33
33
 
34
34
  function titleOf(path: string): string {
35
35
  const base = path.slice(path.lastIndexOf('/') + 1);
@@ -403,7 +403,9 @@ describe('FileExplorer right-click: Download menu (per-path access)', () => {
403
403
  expect(url).toContain('path=brief.md');
404
404
  expect(url).toContain('download=1');
405
405
  expect(createObjectURL).toHaveBeenCalled();
406
- expect(revokeObjectURL).toHaveBeenCalledWith('blob:fake-url');
406
+ // The revoke is DEFERRED a tick (setTimeout 0) so the click's download
407
+ // starts before the blob URL dies — hence waitFor, not a sync assert.
408
+ await waitFor(() => expect(revokeObjectURL).toHaveBeenCalledWith('blob:fake-url'));
407
409
  });
408
410
 
409
411
  it('calls /folder/zip?download=1 and triggers a <folder>.zip save when clicking Download as zip on a folder', async () => {
@@ -551,6 +551,23 @@ describe('FileViewer', () => {
551
551
  expect(accessMock.fetchFileAccess).not.toHaveBeenCalled();
552
552
  });
553
553
 
554
+ // View-only routes (legacy Office, ODF) render a no-preview note — there is
555
+ // no editing surface behind an Edit click, so neither Edit nor Propose may
556
+ // be offered, even on a draft branch where editing is otherwise free.
557
+ it('offers no Edit or Propose on a legacy .doc — the no-preview note has no editing surface', async () => {
558
+ render(<ViewerHarness initialContent="" filePath="knowledge-base/old/memo.doc" />);
559
+ expect(await screen.findByText(/legacy Word format/)).toBeInTheDocument();
560
+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();
561
+ expect(screen.queryByRole('button', { name: 'Propose changes' })).not.toBeInTheDocument();
562
+ });
563
+
564
+ it('offers no Edit or Propose on an OpenDocument file — same view-only route, ODF-honest copy', async () => {
565
+ render(<ViewerHarness initialContent="" filePath="knowledge-base/docs/spec.odt" />);
566
+ expect(await screen.findByText(/No preview for OpenDocument files yet/)).toBeInTheDocument();
567
+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();
568
+ expect(screen.queryByRole('button', { name: 'Propose changes' })).not.toBeInTheDocument();
569
+ });
570
+
554
571
  // Bug B regression: the hook must strip the kbDirName prefix before
555
572
  // querying the backend, otherwise deeper access.md grants silently miss
556
573
  // and the editor falsely shows read-only. Exercised on a protected
@@ -42,6 +42,21 @@ describe('KbPageHeader', () => {
42
42
  expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('roles.unknownext');
43
43
  });
44
44
 
45
+ it.each([
46
+ ['Decks/all-hands.pptx', 'all-hands'],
47
+ ['old/memo.doc', 'memo'],
48
+ ['old/deck.ppt', 'deck'],
49
+ ['old/sheet.xls', 'sheet'],
50
+ ['docs/spec.odt', 'spec'],
51
+ ['Inbox/offer.eml', 'offer'],
52
+ ['Inbox/thread.msg', 'thread'],
53
+ ['decks/pitch.odp', 'pitch'],
54
+ ['data/numbers.ods', 'numbers'],
55
+ ])('strips the document extension of %s from the h1', (path, title) => {
56
+ renderHeader({ path });
57
+ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(title);
58
+ });
59
+
45
60
  it('shows the name verbatim for a file with no extension', () => {
46
61
  renderHeader({ path: 'Knowledge/LICENSE' });
47
62
  expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('LICENSE');