@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
@@ -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
+ }
@@ -0,0 +1,309 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react';
2
+ import { Check, Copy, ExternalLink, Mail, Paperclip } from 'lucide-react';
3
+ import { useWorkspace } from '../../state/workspace.context';
4
+ import { authFetch } from '../../../../lib/api';
5
+ import { copyToClipboard } from '../../../../lib/clipboard';
6
+ import { DownloadFileButton } from './DownloadFileButton';
7
+ import { MAX_EMAIL_BYTES, attachmentLine, type EmailMessageView } from './emailMessage';
8
+ import { buildEmailBody, type EmailLink } from './emailBody';
9
+ import { readBodyCapped } from './readBodyCapped';
10
+ import type { FileRendererProps } from './types';
11
+
12
+ /**
13
+ * The honest email view for `.eml` and `.msg`: labelled header fields, the
14
+ * body as PLAIN TEXT, attachments listed by name — the same story the
15
+ * backend's extractors tell agents through `read_file`, so human and agent
16
+ * conversations about one message point at the same thing.
17
+ *
18
+ * A message that carries HTML is RENDERED, the way a mail client renders it —
19
+ * inside a frame mounted `sandbox=""` (no scripts, ever) whose policy permits
20
+ * `img-src data:` and nothing else. Two consequences are the point of the
21
+ * design: no script in a stranger's mail can run, and no remote fetch can
22
+ * happen, so a tracking pixel cannot report that this message was opened.
23
+ * Images the sender EMBEDDED still appear — they travel inside the file, and
24
+ * are inlined as data: URIs. Links are made inert and listed below the body
25
+ * with their full address, because a click inside a script-free frame cannot
26
+ * be intercepted and a live anchor would open its destination unseen.
27
+ *
28
+ * A message with no HTML part falls back to the plain text, as before.
29
+ * Attachments are names, not downloads — v1 does not unpack them; the original
30
+ * file (with everything in it) is one Download away.
31
+ *
32
+ * Parsing is client-side, per format, behind its own dynamic import so the
33
+ * `.eml` path never pays for the CFB machinery: postal-mime for `.eml`
34
+ * (`emlMessage.ts`), SheetJS CFB for `.msg` (`msgMessage.ts` — msgreader
35
+ * itself does not load in a browser; see there).
36
+ *
37
+ * View-only: there is no edit mode for a message snapshot. The renderer
38
+ * ignores `onSave` / `onValueChange` / `readOnly`.
39
+ */
40
+ export function EmailRenderer({ filePath }: FileRendererProps) {
41
+ const { workspaceId } = useWorkspace();
42
+ const [view, setView] = useState<EmailMessageView | null>(null);
43
+ // The sender's own markup, made safe to show. Rebuilt only when the message
44
+ // changes — the sanitize + inline pass walks the whole body.
45
+ const rendered = useMemo(
46
+ () => (view?.bodyHtml !== undefined ? buildEmailBody(view.bodyHtml, view.attachments) : null),
47
+ [view],
48
+ );
49
+ const [error, setError] = useState<string | null>(null);
50
+
51
+ useEffect(() => {
52
+ setView(null);
53
+ setError(null);
54
+ if (!workspaceId) return;
55
+
56
+ let cancelled = false;
57
+ // Cleanup ABORTS, not just flags: flipping `cancelled` alone would let an
58
+ // abandoned view keep downloading and buffering the whole message.
59
+ const controller = new AbortController();
60
+ (async () => {
61
+ try {
62
+ const res = await authFetch(
63
+ `/api/workspace/${workspaceId}/file/raw?path=${encodeURIComponent(filePath)}`,
64
+ { signal: controller.signal },
65
+ );
66
+ if (cancelled) return;
67
+ if (!res.ok) {
68
+ setError(`Failed to load email (HTTP ${res.status})`);
69
+ return;
70
+ }
71
+ // The size bound belongs BEFORE the buffer, not after it: the parsers
72
+ // check the limit once they hold the bytes, by which point a 300 MB
73
+ // message has already been allocated in the tab. `readBodyCapped`
74
+ // refuses an over-cap Content-Length without reading a byte (and ends
75
+ // the transfer) and abandons an undeclared body the moment it crosses
76
+ // the cap.
77
+ const buffer = await readBodyCapped(res, MAX_EMAIL_BYTES, controller);
78
+ if (cancelled) return;
79
+ if (buffer === null) {
80
+ setError('This email is too large to display.');
81
+ return;
82
+ }
83
+ const parsed = filePath.toLowerCase().endsWith('.msg')
84
+ ? (await import('./msgMessage')).parseMsgMessage(buffer)
85
+ : await (await import('./emlMessage')).parseEmlMessage(buffer);
86
+ if (cancelled) return;
87
+ setView(parsed);
88
+ } catch (e) {
89
+ if (cancelled) return;
90
+ // The parsers throw "could not be parsed as a .eml/.msg (…)".
91
+ setError(`This file ${e instanceof Error ? e.message : String(e)}`);
92
+ }
93
+ })();
94
+
95
+ return () => {
96
+ cancelled = true;
97
+ controller.abort();
98
+ };
99
+ }, [workspaceId, filePath]);
100
+
101
+ if (error) {
102
+ return (
103
+ <div className="flex min-h-40 flex-col items-center justify-center gap-3 p-6 text-center">
104
+ <p className="text-ui text-danger">{error}</p>
105
+ <DownloadFileButton filePath={filePath} />
106
+ </div>
107
+ );
108
+ }
109
+
110
+ if (view === null) {
111
+ return (
112
+ <div className="flex min-h-40 items-center justify-center text-ui text-ink-muted">
113
+ Loading email…
114
+ </div>
115
+ );
116
+ }
117
+
118
+ const headerFields: Array<[string, string]> = [];
119
+ if (view.from !== undefined) headerFields.push(['From', view.from]);
120
+ if (view.to !== undefined) headerFields.push(['To', view.to]);
121
+ if (view.cc !== undefined) headerFields.push(['Cc', view.cc]);
122
+ if (view.bcc !== undefined) headerFields.push(['Bcc', view.bcc]);
123
+ if (view.subject !== undefined) headerFields.push(['Subject', view.subject]);
124
+ if (view.date !== undefined) headerFields.push(['Date', view.date]);
125
+
126
+ return (
127
+ // A document, not a viewport: sits in `KbDocumentShell`'s prose column.
128
+ <div className="min-w-0">
129
+ {/* What this view is, and the way to the real thing — up front: text
130
+ only, formatting omitted, attachments listed but not unpacked. */}
131
+ <div className="mb-4 flex items-center gap-3 rounded-sm bg-sunken px-3 py-2">
132
+ <Mail size={15} className="shrink-0 text-ink-faint" aria-hidden />
133
+ <p className="min-w-0 flex-1 text-detail text-ink-muted">
134
+ {rendered !== null
135
+ ? 'The sender’s formatting, shown without remote content: images hosted elsewhere are not loaded, and links open only after you confirm the address. Attachment contents are not shown.'
136
+ : 'Text view of the email — formatting, inline images and attachment contents are not shown.'}{' '}
137
+ Download the file to open it in a mail client.
138
+ </p>
139
+ <DownloadFileButton filePath={filePath} size="sm" />
140
+ </div>
141
+
142
+ {headerFields.length > 0 && (
143
+ <dl className="mb-4 border-b border-line pb-3">
144
+ {headerFields.map(([label, value]) => (
145
+ <div key={label} className="mb-1 flex gap-2">
146
+ <dt className="w-16 shrink-0 text-detail font-medium text-ink-faint">{label}</dt>
147
+ <dd className="min-w-0 flex-1 whitespace-pre-wrap break-words text-ui text-ink">
148
+ {value}
149
+ </dd>
150
+ </div>
151
+ ))}
152
+ </dl>
153
+ )}
154
+
155
+ {view.bodySource === 'rtf-only' ? (
156
+ <p className="text-detail italic text-ink-faint">
157
+ The message body is stored as RTF only — there is no plain-text part to show. Download
158
+ the file to read it in a mail client.
159
+ </p>
160
+ ) : rendered !== null ? (
161
+ <>
162
+ <iframe
163
+ // `sandbox=""` — NOT allow-scripts. Nothing in a stranger's message
164
+ // executes, and the document's CSP allows `img-src data:` only, so no
165
+ // remote fetch can happen: a tracking pixel cannot report that this
166
+ // message was opened. Images the sender EMBEDDED are inlined as data:
167
+ // URIs and do render.
168
+ sandbox=""
169
+ srcDoc={rendered.srcDoc}
170
+ title="Message body"
171
+ className="h-[32rem] w-full rounded-xs border border-line bg-white"
172
+ />
173
+ {(rendered.blockedRemoteImages > 0 || rendered.unavailableInlineImages > 0) && (
174
+ <p className="mt-2 text-detail text-ink-faint">
175
+ {rendered.blockedRemoteImages > 0 && (
176
+ <>
177
+ {rendered.blockedRemoteImages} remote image
178
+ {rendered.blockedRemoteImages === 1 ? '' : 's'} not loaded — fetching one would
179
+ tell the sender you opened this message.
180
+ </>
181
+ )}
182
+ {rendered.blockedRemoteImages > 0 && rendered.unavailableInlineImages > 0 && ' '}
183
+ {rendered.unavailableInlineImages > 0 && (
184
+ <>
185
+ {rendered.unavailableInlineImages} embedded image
186
+ {rendered.unavailableInlineImages === 1 ? '' : 's'} could not be shown — the part
187
+ is missing from the file or too large to inline.
188
+ </>
189
+ )}
190
+ </p>
191
+ )}
192
+ {rendered.links.length > 0 && <EmailLinks links={rendered.links} />}
193
+ </>
194
+ ) : view.body === '' ? (
195
+ <p className="text-detail italic text-ink-faint">No message body.</p>
196
+ ) : (
197
+ <div className="whitespace-pre-wrap break-words text-ui text-ink">{view.body}</div>
198
+ )}
199
+
200
+ {view.attachments.length > 0 && (
201
+ <div className="mt-6 border-t border-line pt-3">
202
+ <div className="mb-1 flex items-center gap-1.5 text-meta font-medium uppercase tracking-wide text-ink-faint">
203
+ <Paperclip size={12} aria-hidden />
204
+ Attachments
205
+ </div>
206
+ <ul>
207
+ {view.attachments.map((a, i) => (
208
+ <li key={i} className="mb-0.5 text-detail text-ink-muted">
209
+ {attachmentLine(a)}
210
+ </li>
211
+ ))}
212
+ </ul>
213
+ <p className="mt-1 text-meta text-ink-faint">
214
+ Attachments are listed by name only — download the email to get them.
215
+ </p>
216
+ </div>
217
+ )}
218
+ </div>
219
+ );
220
+ }
221
+
222
+
223
+ /**
224
+ * A copy button that says whether the copy LANDED.
225
+ *
226
+ * `navigator.clipboard` is absent outside a secure context and rejects when
227
+ * the document is not focused — ordinary conditions, not exceptions. A button
228
+ * that silently did nothing (or left an unhandled rejection) would leave the
229
+ * reader believing they hold an address they do not.
230
+ */
231
+ function CopyLinkButton({ url }: { url: string }): React.ReactElement {
232
+ const [state, setState] = useState<'idle' | 'copied' | 'failed'>('idle');
233
+ // One timer, cancelled before another is scheduled: two clicks inside the
234
+ // reset window let the FIRST timer clear the second click's answer, so the
235
+ // button stopped reporting the copy the reader had just made. Cleared on
236
+ // unmount too, so a late reset cannot land on a gone component.
237
+ const resetAt = useRef<number | undefined>(undefined);
238
+ useEffect(() => () => window.clearTimeout(resetAt.current), []);
239
+ return (
240
+ <button
241
+ type="button"
242
+ className="flex shrink-0 items-center gap-1 text-ink-faint hover:text-ink"
243
+ title={state === 'failed' ? 'Could not copy — select the address instead' : 'Copy this address'}
244
+ onClick={() => {
245
+ void copyToClipboard(url).then((ok) => {
246
+ setState(ok ? 'copied' : 'failed');
247
+ window.clearTimeout(resetAt.current);
248
+ resetAt.current = window.setTimeout(() => setState('idle'), 2000);
249
+ });
250
+ }}
251
+ >
252
+ {state === 'copied' ? <Check size={12} aria-hidden /> : <Copy size={12} aria-hidden />}
253
+ {state !== 'idle' && (
254
+ <span className="text-meta">{state === 'copied' ? 'Copied' : 'Copy failed'}</span>
255
+ )}
256
+ </button>
257
+ );
258
+ }
259
+
260
+ /**
261
+ * The message's links, in TRUSTED UI outside the sandbox.
262
+ *
263
+ * A click inside a script-free frame cannot be intercepted, so an anchor left
264
+ * live would open its destination with no chance to show the reader where it
265
+ * goes. The body renders them inert and numbered instead, and they are listed
266
+ * here with the whole address visible: copy it, or open it deliberately. A
267
+ * phishing link is never one stray click away, and nothing in the frame can
268
+ * reach `window.opener` or leak a referrer, because nothing in the frame
269
+ * navigates at all.
270
+ */
271
+ function EmailLinks({ links }: { links: readonly EmailLink[] }): React.ReactElement {
272
+ return (
273
+ <div className="mt-4 border-t border-line pt-3">
274
+ <div className="mb-1 flex items-center gap-1.5 text-meta font-medium uppercase tracking-wide text-ink-faint">
275
+ <ExternalLink size={12} aria-hidden />
276
+ Links
277
+ </div>
278
+ <ul className="space-y-1">
279
+ {links.map((link) => (
280
+ <li key={link.index} className="flex items-start gap-2 text-detail">
281
+ <span className="shrink-0 text-ink-faint">[{link.index}]</span>
282
+ <span className="min-w-0 flex-1">
283
+ {link.text !== '' && <span className="text-ink">{link.text} — </span>}
284
+ <span className="break-all text-ink-faint">{link.url}</span>
285
+ </span>
286
+ <CopyLinkButton url={link.url} />
287
+ <button
288
+ type="button"
289
+ className="shrink-0 text-ink-faint hover:text-ink"
290
+ title="Open in a new tab"
291
+ onClick={() => {
292
+ // Asked before anything opens, with the address in the prompt:
293
+ // the reader decides against the REAL destination, not against
294
+ // whatever text the sender chose to show.
295
+ if (window.confirm(`Open this link?
296
+
297
+ ${link.url}`)) {
298
+ window.open(link.url, '_blank', 'noopener,noreferrer');
299
+ }
300
+ }}
301
+ >
302
+ <ExternalLink size={12} aria-hidden />
303
+ </button>
304
+ </li>
305
+ ))}
306
+ </ul>
307
+ </div>
308
+ );
309
+ }
@@ -0,0 +1,60 @@
1
+ import { FileText } from 'lucide-react';
2
+ import { DownloadFileButton } from './DownloadFileButton';
3
+ import type { FileRendererProps } from './types';
4
+
5
+ /**
6
+ * The no-preview note, in two honest flavours:
7
+ *
8
+ * - Pre-2007 Office binaries (`.doc` / `.ppt` / `.xls`): nothing in the
9
+ * browser (or on the backend) parses these — they are OLE compound
10
+ * documents, not zipped XML — so the note names the format and the two
11
+ * ways forward: convert to the modern format the viewers next door DO
12
+ * render, or download the original. The backend's agent-facing
13
+ * `read_file` gives the same convert-to-modern hint.
14
+ *
15
+ * - OpenDocument files (`.odt` / `.odp` / `.ods`): agents read these fine
16
+ * (the backend extracts their text) — only the browser viewer is missing.
17
+ * So the copy says exactly that and offers Download, WITHOUT a convert
18
+ * hint that would wrongly imply the file is unusable as-is.
19
+ *
20
+ * Either way this beats the old behaviour: the text fallback printing
21
+ * megabytes of undecodable bytes.
22
+ */
23
+ const LEGACY_FORMATS: Record<string, { label: string; modern: string }> = {
24
+ '.doc': { label: 'Word', modern: '.docx' },
25
+ '.ppt': { label: 'PowerPoint', modern: '.pptx' },
26
+ '.xls': { label: 'Excel', modern: '.xlsx' },
27
+ };
28
+
29
+ /** ODF family → what the file is, for the no-preview-yet copy. */
30
+ const ODF_FORMATS: Record<string, string> = {
31
+ '.odt': 'text document',
32
+ '.odp': 'presentation',
33
+ '.ods': 'spreadsheet',
34
+ };
35
+
36
+ export function LegacyOfficeRenderer({ filePath }: FileRendererProps) {
37
+ const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();
38
+ const odf = ODF_FORMATS[ext];
39
+ const format = LEGACY_FORMATS[ext] ?? { label: 'Office', modern: 'a modern format' };
40
+
41
+ return (
42
+ <div className="flex min-h-40 flex-col items-center justify-center gap-3 p-6 text-center">
43
+ <FileText size={20} className="text-ink-faint" aria-hidden />
44
+ <p className="max-w-md text-ui text-ink-muted">
45
+ {odf !== undefined ? (
46
+ <>
47
+ No preview for OpenDocument files yet — this is an OpenDocument {odf} ({ext}).
48
+ Download the file to view it.
49
+ </>
50
+ ) : (
51
+ <>
52
+ This is a legacy {format.label} format ({ext}) that can't be previewed here. Convert
53
+ it to {format.modern} to view it, or download the original.
54
+ </>
55
+ )}
56
+ </p>
57
+ <DownloadFileButton filePath={filePath} size="sm" />
58
+ </div>
59
+ );
60
+ }