@bevel-software/platform-core-frontend 0.11.2 → 0.12.1

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 (48) 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/git/__tests__/GitSyncFailedBanner.test.tsx +181 -0
  9. package/src/modules/git/components/GitSyncFailedBanner.tsx +106 -0
  10. package/src/modules/library/utils/clipboard.ts +4 -20
  11. package/src/modules/secrets-vault/components/SecretsPage.tsx +313 -313
  12. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +82 -82
  13. package/src/modules/workspace/components/FileExplorer.tsx +6 -14
  14. package/src/modules/workspace/components/FileViewer.tsx +20 -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/url-suffix-imports.d.ts +12 -0
@@ -1,82 +1,82 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { render, screen } from '@testing-library/react';
3
- import { MemoryRouter } from 'react-router-dom';
4
- import type { ToolSecrets } from '../../services/tool-secrets.api';
5
- import { SecretsPage } from '../SecretsPage';
6
-
7
- const toolSecretsMock = vi.hoisted(() => ({ listToolSecrets: vi.fn() }));
8
-
9
- vi.mock('../../services/secrets.api', () => ({
10
- listSecrets: vi.fn(async () => []),
11
- createOAuthSecret: vi.fn(async () => {}),
12
- deleteSecret: vi.fn(async () => {}),
13
- startOAuth: vi.fn(async () => ''),
14
- }));
15
- vi.mock('../../services/tool-secrets.api', () => ({
16
- listToolSecrets: toolSecretsMock.listToolSecrets,
17
- setAdminVar: vi.fn(async () => {}),
18
- setUserVar: vi.fn(async () => {}),
19
- setOAuthClientSecret: vi.fn(async () => {}),
20
- deleteAdminVar: vi.fn(async () => {}),
21
- deleteUserVar: vi.fn(async () => {}),
22
- }));
23
-
24
- /** The page carries links now, so it needs a router around it. */
25
- function renderPage() {
26
- return render(
27
- <MemoryRouter>
28
- <SecretsPage />
29
- </MemoryRouter>,
30
- );
31
- }
32
-
33
- describe('SecretsPage', () => {
34
- beforeEach(() => {
35
- // Each test starts on a clean /secrets URL (no leftover fragment).
36
- window.history.replaceState(null, '', '/secrets');
37
- toolSecretsMock.listToolSecrets.mockReset().mockResolvedValue([]);
38
- });
39
-
40
- it('renders as a full page (no dialog) and loads the secret lists', async () => {
41
- renderPage();
42
- expect(screen.getByRole('heading', { name: 'Secrets' })).toBeInTheDocument();
43
- expect(
44
- await screen.findByText('No tools you can access declare secrets yet.'),
45
- ).toBeInTheDocument();
46
- // Converted from the old gear-menu dialog: nothing modal is mounted.
47
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
48
- });
49
-
50
- it('links each tool name at its own page', async () => {
51
- const heyreach: ToolSecrets = {
52
- slug: 'heyreach',
53
- name: 'heyreach',
54
- path: 'Plugins/GTM/heyreach.tool',
55
- type: 'inline',
56
- setup: null,
57
- canWrite: false,
58
- variables: [],
59
- };
60
- toolSecretsMock.listToolSecrets.mockResolvedValue([heyreach]);
61
-
62
- renderPage();
63
- const link = await screen.findByRole('link', { name: 'Open heyreach' });
64
- expect(link).toHaveAttribute('href', '/skills-and-tools/tools/heyreach');
65
- });
66
-
67
- it('surfaces the OAuth-callback success carried in the #authorized fragment and strips it', async () => {
68
- window.history.replaceState(null, '', '/secrets#authorized');
69
- renderPage();
70
- expect(await screen.findByText('Authorization complete.')).toBeInTheDocument();
71
- // The fragment is consumed so a refresh doesn't re-announce it.
72
- expect(window.location.hash).toBe('');
73
- expect(window.location.pathname).toBe('/secrets');
74
- });
75
-
76
- it('surfaces the OAuth-callback error carried in the #error fragment and strips it', async () => {
77
- window.history.replaceState(null, '', '/secrets#error=Access%20denied');
78
- renderPage();
79
- expect(await screen.findByText('Access denied')).toBeInTheDocument();
80
- expect(window.location.hash).toBe('');
81
- });
82
- });
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen } from '@testing-library/react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import type { ToolSecrets } from '../../services/tool-secrets.api';
5
+ import { SecretsPage } from '../SecretsPage';
6
+
7
+ const toolSecretsMock = vi.hoisted(() => ({ listToolSecrets: vi.fn() }));
8
+
9
+ vi.mock('../../services/secrets.api', () => ({
10
+ listSecrets: vi.fn(async () => []),
11
+ createOAuthSecret: vi.fn(async () => {}),
12
+ deleteSecret: vi.fn(async () => {}),
13
+ startOAuth: vi.fn(async () => ''),
14
+ }));
15
+ vi.mock('../../services/tool-secrets.api', () => ({
16
+ listToolSecrets: toolSecretsMock.listToolSecrets,
17
+ setAdminVar: vi.fn(async () => {}),
18
+ setUserVar: vi.fn(async () => {}),
19
+ setOAuthClientSecret: vi.fn(async () => {}),
20
+ deleteAdminVar: vi.fn(async () => {}),
21
+ deleteUserVar: vi.fn(async () => {}),
22
+ }));
23
+
24
+ /** The page carries links now, so it needs a router around it. */
25
+ function renderPage() {
26
+ return render(
27
+ <MemoryRouter>
28
+ <SecretsPage />
29
+ </MemoryRouter>,
30
+ );
31
+ }
32
+
33
+ describe('SecretsPage', () => {
34
+ beforeEach(() => {
35
+ // Each test starts on a clean /secrets URL (no leftover fragment).
36
+ window.history.replaceState(null, '', '/secrets');
37
+ toolSecretsMock.listToolSecrets.mockReset().mockResolvedValue([]);
38
+ });
39
+
40
+ it('renders as a full page (no dialog) and loads the secret lists', async () => {
41
+ renderPage();
42
+ expect(screen.getByRole('heading', { name: 'Secrets' })).toBeInTheDocument();
43
+ expect(
44
+ await screen.findByText('No tools you can access declare secrets yet.'),
45
+ ).toBeInTheDocument();
46
+ // Converted from the old gear-menu dialog: nothing modal is mounted.
47
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
48
+ });
49
+
50
+ it('links each tool name at its own page', async () => {
51
+ const heyreach: ToolSecrets = {
52
+ slug: 'heyreach',
53
+ name: 'heyreach',
54
+ path: 'Plugins/GTM/heyreach.tool',
55
+ type: 'inline',
56
+ setup: null,
57
+ canWrite: false,
58
+ variables: [],
59
+ };
60
+ toolSecretsMock.listToolSecrets.mockResolvedValue([heyreach]);
61
+
62
+ renderPage();
63
+ const link = await screen.findByRole('link', { name: 'Open heyreach' });
64
+ expect(link).toHaveAttribute('href', '/skills-and-tools/tools/heyreach');
65
+ });
66
+
67
+ it('surfaces the OAuth-callback success carried in the #authorized fragment and strips it', async () => {
68
+ window.history.replaceState(null, '', '/secrets#authorized');
69
+ renderPage();
70
+ expect(await screen.findByText('Authorization complete.')).toBeInTheDocument();
71
+ // The fragment is consumed so a refresh doesn't re-announce it.
72
+ expect(window.location.hash).toBe('');
73
+ expect(window.location.pathname).toBe('/secrets');
74
+ });
75
+
76
+ it('surfaces the OAuth-callback error carried in the #error fragment and strips it', async () => {
77
+ window.history.replaceState(null, '', '/secrets#error=Access%20denied');
78
+ renderPage();
79
+ expect(await screen.findByText('Access denied')).toBeInTheDocument();
80
+ expect(window.location.hash).toBe('');
81
+ });
82
+ });
@@ -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);
@@ -12,6 +12,7 @@ import { LayoutContext } from '../../layout/state/layout.context';
12
12
  import { useParams } from 'react-router-dom';
13
13
  import { useCanonicalFileUrl, useFileNav } from '../routing/kb-routes';
14
14
  import { PullNeededBanner } from '../../git/components/PullNeededBanner';
15
+ import { GitSyncFailedBanner } from '../../git/components/GitSyncFailedBanner';
15
16
  import { useFileAccess } from '../../access/hooks/useFileAccess';
16
17
  import { FileHistoryPanel } from '../../git/components/FileHistoryPanel';
17
18
  import { FileComparisonPanel } from '../../git/components/FileComparisonPanel';
@@ -36,7 +37,8 @@ import { ChangeRequestDialog } from '../../change-requests/components/ChangeRequ
36
37
  import { formatEligible } from '../../access/hooks/useFileAccess';
37
38
  import { PR_STALE_EVENT } from '../../../core/events';
38
39
  import { suggestedPages } from '../utils/fileTree';
39
- import { getFileRenderer, getRendererLayout } from './renderers';
40
+ import { getFileRenderer, getRendererLayout, isViewOnlyFile } from './renderers';
41
+ import { CanDownloadContext } from './renderers/DownloadFileButton';
40
42
  import type { RendererSaveState } from './renderers';
41
43
  import { KbDocumentShell } from './KbDocumentShell';
42
44
  import { FilePaneCard } from './FilePaneCard';
@@ -835,6 +837,7 @@ export function FileViewer() {
835
837
  return (
836
838
  <div className="h-full w-full flex flex-col bg-white min-w-0 relative">
837
839
  <PullNeededBanner />
840
+ <GitSyncFailedBanner />
838
841
  <EditorTabs />
839
842
  <div className="flex-1 flex items-center justify-center px-6">
840
843
  <div className="w-full max-w-md text-center">
@@ -901,6 +904,12 @@ export function FileViewer() {
901
904
  const shellVariant =
902
905
  activeTab === 'content' ? getRendererLayout(openFilePath) : 'full-bleed';
903
906
 
907
+ // No-preview routes (legacy Office, ODF) have no editing surface at all —
908
+ // offering Edit/Propose there would acquire a lock for a mode the renderer
909
+ // ignores, and imply text can be saved over a binary document. Suppresses
910
+ // BOTH write-action homes (the pane bar and the header) below.
911
+ const viewOnly = isViewOnlyFile(openFilePath);
912
+
904
913
  // What the pane card's bar names — extension kept, unlike the `<h1>` above,
905
914
  // because the bar is the technical label (`SKILL.md`, `How to get
906
915
  // started.md`) exactly as the skill page's file bar renders it.
@@ -920,8 +929,11 @@ export function FileViewer() {
920
929
 
921
930
  const rendererElement = (
922
931
  // The renderer is a dynamic per-extension lookup resolved in a useMemo
923
- // above — not a component created during render.
932
+ // above — not a component created during render. The provider hands the
933
+ // open file's `download:` verdict to any DownloadFileButton inside the
934
+ // renderer without widening the renderer contract.
924
935
  // eslint-disable-next-line react-hooks/static-components
936
+ <CanDownloadContext.Provider value={access.canDownload}>
925
937
  <Renderer
926
938
  // **Why we key on `openFileSavedContent` (read-only mode only).**
927
939
  // When a teammate's save lands, the workspace state updates the
@@ -977,6 +989,7 @@ export function FileViewer() {
977
989
  onSaveStateChange={setManualSaveState}
978
990
  readOnly={isReviewingPending || !(editMode || proposeMode)}
979
991
  />
992
+ </CanDownloadContext.Provider>
980
993
  );
981
994
 
982
995
  // The pane bar's write action — the labelled button at the frame's top
@@ -986,7 +999,7 @@ export function FileViewer() {
986
999
  // rule). While a mode is OPEN it shows the way out instead. The header's
987
1000
  // own cluster is suppressed for prose files (`writeActionInPane`).
988
1001
  const lockedBy = fileLock.externalLock?.holderName ?? null;
989
- const paneActions = isReviewingPending ? null : proposeMode ? (
1002
+ const paneActions = isReviewingPending || viewOnly ? null : proposeMode ? (
990
1003
  <>
991
1004
  <Button variant="quiet" size="tiny" onClick={handleDiscardProposal} disabled={proposalBusy}>
992
1005
  Discard
@@ -1045,6 +1058,7 @@ export function FileViewer() {
1045
1058
  return (
1046
1059
  <div className="h-full w-full flex flex-col bg-white min-w-0 relative">
1047
1060
  <PullNeededBanner />
1061
+ <GitSyncFailedBanner />
1048
1062
  {/* No "you don't have permission to edit" banner, deliberately: for a
1049
1063
  reader the restriction is not news worth a stripe across every page —
1050
1064
  the Propose changes affordance already says what they CAN do, and the
@@ -1076,7 +1090,9 @@ export function FileViewer() {
1076
1090
  onPropose={handleEnterPropose}
1077
1091
  onSendProposal={() => void handleSendProposal()}
1078
1092
  onDiscardProposal={handleDiscardProposal}
1079
- writeActionInPane={shellVariant === 'prose'}
1093
+ // `viewOnly` rides the same flag: it tells the header "the write
1094
+ // action is not yours to render" — and the pane bar renders none.
1095
+ writeActionInPane={shellVariant === 'prose' || viewOnly}
1080
1096
  lockedBy={fileLock.externalLock?.holderName ?? null}
1081
1097
  historyAvailable={historyAvailable}
1082
1098
  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');
@@ -9,6 +9,7 @@ import mammoth from 'mammoth/mammoth.browser.js';
9
9
  import { useWorkspace } from '../../state/workspace.context';
10
10
  import { authFetch } from '../../../../lib/api';
11
11
  import { sanitizeDocxHtml } from './sanitizeDocxHtml';
12
+ import { DownloadFileButton } from './DownloadFileButton';
12
13
  import type { FileRendererProps } from './types';
13
14
 
14
15
  /**
@@ -69,8 +70,10 @@ export function DocxRenderer({ filePath }: FileRendererProps) {
69
70
 
70
71
  if (error) {
71
72
  return (
72
- <div className="flex items-center justify-center min-h-40 text-danger text-sm">
73
- {error}
73
+ <div className="flex min-h-40 flex-col items-center justify-center gap-3 text-center">
74
+ <p className="text-sm text-danger">{error}</p>
75
+ {/* The conversion failed; the bytes may still open fine in Word. */}
76
+ <DownloadFileButton filePath={filePath} />
74
77
  </div>
75
78
  );
76
79
  }
@@ -87,6 +90,12 @@ export function DocxRenderer({ filePath }: FileRendererProps) {
87
90
  // No scroller of its own: a Word document is a document, so it sits in
88
91
  // `KbDocumentShell`'s prose column and the column scrolls.
89
92
  <div className="min-w-0">
93
+ {/* The conversion is an approximation (headers/footers, tracked
94
+ changes and most layout are dropped) — the original stays one
95
+ click away. */}
96
+ <div className="mb-3 flex justify-end">
97
+ <DownloadFileButton filePath={filePath} />
98
+ </div>
90
99
  <div
91
100
  className="prose prose-sm max-w-none"
92
101
  dangerouslySetInnerHTML={{ __html: html }}
@@ -0,0 +1,88 @@
1
+ import { createContext, useCallback, useContext, useState } from 'react';
2
+ import { Download } from 'lucide-react';
3
+ import { Button } from '../../../../shared/components';
4
+ import { useWorkspace } from '../../state/workspace.context';
5
+ import { downloadViaBlob } from './downloadFile';
6
+
7
+ /**
8
+ * The open file's resolved `download:` permission, provided by FileViewer
9
+ * from the access lookup it already performs (null = unknown/in flight —
10
+ * treated optimistically, like the editor; the backend stays the
11
+ * authoritative gate either way). A context rather than a renderer prop so
12
+ * the renderer contract stays permission-agnostic.
13
+ */
14
+ export const CanDownloadContext = createContext<boolean | null>(null);
15
+
16
+ /**
17
+ * The document viewers' way out of the browser. Every office-document viewer
18
+ * here is a REDUCTION — a pptx becomes an outline, an xlsx grid gets capped,
19
+ * a legacy `.doc` is not rendered at all — so each one offers the original
20
+ * bytes alongside its own rendering.
21
+ *
22
+ * Same endpoint and `?download=1` shape as the file tree's context-menu
23
+ * Download (see `FileExplorer.handleDownload`): the backend resolves the
24
+ * per-path `download:` access verb and sets Content-Disposition; a 403
25
+ * surfaces in the error text below rather than being preflighted away.
26
+ */
27
+ export function DownloadFileButton({
28
+ filePath,
29
+ size = 'tiny',
30
+ }: {
31
+ filePath: string;
32
+ /** `sm` where the download is the page's main affordance (pptx outline). */
33
+ size?: 'tiny' | 'sm';
34
+ }) {
35
+ const { workspaceId } = useWorkspace();
36
+ const canDownload = useContext(CanDownloadContext);
37
+ const [busy, setBusy] = useState(false);
38
+ const [error, setError] = useState<string | null>(null);
39
+ const fileName = filePath.slice(filePath.lastIndexOf('/') + 1);
40
+
41
+ const handleDownload = useCallback(async () => {
42
+ if (!workspaceId || busy) return;
43
+ setBusy(true);
44
+ setError(null);
45
+ try {
46
+ const outcome = await downloadViaBlob(
47
+ `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(filePath)}&download=1`,
48
+ fileName,
49
+ );
50
+ if (!outcome.ok) {
51
+ setError(`Download failed (HTTP ${outcome.status})`);
52
+ return;
53
+ }
54
+ } catch (err) {
55
+ console.error('[DownloadFileButton] download failed:', err);
56
+ setError(err instanceof Error ? err.message : 'Download failed.');
57
+ } finally {
58
+ setBusy(false);
59
+ }
60
+ }, [workspaceId, busy, filePath, fileName]);
61
+
62
+ return (
63
+ <span className="inline-flex items-center gap-2">
64
+ {error && (
65
+ <span role="alert" className="text-detail text-danger">
66
+ {error}
67
+ </span>
68
+ )}
69
+ <Button
70
+ variant="outline"
71
+ size={size}
72
+ leadingIcon={<Download size={size === 'sm' ? 14 : 12} />}
73
+ onClick={() => void handleDownload()}
74
+ // Disabled only on a hard "no" — while the lookup is in flight the
75
+ // button stays optimistic, mirroring the editor; a wrong guess is
76
+ // still caught by the backend's own gate on the raw endpoint.
77
+ disabled={busy || canDownload === false}
78
+ title={
79
+ canDownload === false
80
+ ? 'You do not have download permission for this file.'
81
+ : `Download ${fileName}`
82
+ }
83
+ >
84
+ {busy ? 'Downloading…' : 'Download'}
85
+ </Button>
86
+ </span>
87
+ );
88
+ }