Skip to content

Commit ba76144

Browse files
feat(web): preview Excel values and basic PowerPoint slides
1 parent ba35822 commit ba76144

22 files changed

Lines changed: 3503 additions & 54 deletions

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,165 @@ describe("AssetAccess", () => {
919919
}).pipe(Effect.provide(layerTest)),
920920
);
921921

922+
it.effect(
923+
"serves Office bytes through signed workspace and host URLs without sibling access",
924+
() =>
925+
Effect.gen(function* () {
926+
const fs = yield* FileSystem.FileSystem;
927+
const path = yield* Path.Path;
928+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-office-workspace-" });
929+
const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-office-host-" });
930+
// Asset access transports bytes; parsing and format validation belong to the viewer.
931+
const bytes = new Uint8Array([0x50, 0x4b, 3, 4, 0, 0xff]);
932+
for (const [extension, mimeType] of [
933+
["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
934+
["xls", "application/vnd.ms-excel"],
935+
["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
936+
] as const) {
937+
for (const source of ["workspace", "draft", "host"] as const) {
938+
const directory = source === "host" ? outside : root;
939+
const name = `report.${extension}`;
940+
const filePath = path.join(directory, name);
941+
yield* fs.writeFile(filePath, bytes);
942+
yield* fs.writeFile(path.join(directory, `sibling.${extension}`), bytes);
943+
const resource =
944+
source === "workspace"
945+
? {
946+
_tag: "workspace-file" as const,
947+
threadId: ThreadId.make("thread-1"),
948+
path: name,
949+
}
950+
: source === "draft"
951+
? { _tag: "draft-workspace-file" as const, cwd: root, path: name }
952+
: {
953+
_tag: "media-file" as const,
954+
threadId: ThreadId.make("thread-1"),
955+
path: filePath,
956+
};
957+
const issued = yield* issueAssetUrl({ resource, workspaceRoot: root });
958+
const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
959+
const separator = suffix.indexOf("/");
960+
const token = suffix.slice(0, separator);
961+
const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
962+
expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(filePath) });
963+
if (asset?.kind !== "file") throw new Error("Expected Office asset");
964+
const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
965+
expect(response.headers.get("content-type")).toBe(mimeType);
966+
expect(response.headers.get("content-disposition")).toBeNull();
967+
expect(new Uint8Array(yield* Effect.promise(() => response.arrayBuffer()))).toEqual(
968+
bytes,
969+
);
970+
expect(yield* resolveAsset(token, `sibling.${extension}`)).toBeNull();
971+
expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
972+
expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
973+
}
974+
}
975+
}).pipe(Effect.provide(layerTest)),
976+
);
977+
978+
it.effect(
979+
"does not issue workspace or host previews for Office-named directories or legacy ppt",
980+
() =>
981+
Effect.gen(function* () {
982+
const fs = yield* FileSystem.FileSystem;
983+
const path = yield* Path.Path;
984+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-office-directory-" });
985+
for (const extension of ["xlsx", "xls", "pptx"]) {
986+
const filePath = path.join(root, `folder.${extension}`);
987+
yield* fs.makeDirectory(filePath);
988+
for (const resource of [
989+
{
990+
_tag: "workspace-file" as const,
991+
threadId: ThreadId.make("thread-1"),
992+
path: filePath,
993+
},
994+
{ _tag: "draft-workspace-file" as const, cwd: root, path: filePath },
995+
{ _tag: "media-file" as const, threadId: ThreadId.make("thread-1"), path: filePath },
996+
]) {
997+
const error = yield* issueAssetUrl({ resource, workspaceRoot: root }).pipe(Effect.flip);
998+
expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
999+
}
1000+
}
1001+
const legacyPath = path.join(root, "legacy.ppt");
1002+
yield* fs.writeFile(legacyPath, new Uint8Array([0xd0, 0xcf, 0x11, 0xe0]));
1003+
const error = yield* issueAssetUrl({
1004+
resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: legacyPath },
1005+
}).pipe(Effect.flip);
1006+
expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
1007+
}).pipe(Effect.provide(layerTest)),
1008+
);
1009+
1010+
it.effect(
1011+
"serves Office attachment previews by stored extension and preserves explicit downloads",
1012+
() =>
1013+
Effect.gen(function* () {
1014+
const config = yield* ServerConfig.ServerConfig;
1015+
const fs = yield* FileSystem.FileSystem;
1016+
const path = yield* Path.Path;
1017+
const bytes = new Uint8Array([0x50, 0x4b, 3, 4, 0, 0xff]);
1018+
yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
1019+
for (const [extension, mimeType] of [
1020+
["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
1021+
["xls", "application/vnd.ms-excel"],
1022+
["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
1023+
] as const) {
1024+
const attachmentId = `thread-1-00000000-0000-4000-8000-000000000042-${extension}`;
1025+
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
1026+
yield* fs.writeFile(attachmentPath, bytes);
1027+
for (const disposition of ["inline", "attachment"] as const) {
1028+
const issued = yield* issueAssetUrl({
1029+
resource: {
1030+
_tag: "attachment",
1031+
attachmentId,
1032+
fileName: `report.${extension}`,
1033+
mimeType: "application/octet-stream",
1034+
disposition,
1035+
},
1036+
});
1037+
const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1038+
const separator = suffix.indexOf("/");
1039+
const token = suffix.slice(0, separator);
1040+
const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
1041+
expect(asset).toMatchObject({ kind: "file", path: attachmentPath });
1042+
if (asset?.kind !== "file") throw new Error("Expected Office attachment");
1043+
const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
1044+
expect(response.headers.get("content-type")).toBe(
1045+
disposition === "inline" ? mimeType : "application/octet-stream",
1046+
);
1047+
if (disposition === "attachment") {
1048+
expect(response.headers.get("content-disposition")).toContain("attachment;");
1049+
} else {
1050+
expect(response.headers.get("content-disposition")).toBeNull();
1051+
}
1052+
expect(new Uint8Array(yield* Effect.promise(() => response.arrayBuffer()))).toEqual(
1053+
bytes,
1054+
);
1055+
expect(yield* resolveAsset(`${token}tampered`, `report.${extension}`)).toBeNull();
1056+
}
1057+
yield* fs.remove(attachmentPath);
1058+
yield* fs.makeDirectory(attachmentPath);
1059+
const issued = yield* issueAssetUrl({
1060+
resource: { _tag: "attachment", attachmentId, disposition: "inline" },
1061+
});
1062+
const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1063+
const separator = suffix.indexOf("/");
1064+
expect(
1065+
yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
1066+
).toBeNull();
1067+
}
1068+
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000043-ppt";
1069+
yield* fs.writeFile(path.join(config.attachmentsDir, `${attachmentId}.ppt`), bytes);
1070+
const issued = yield* issueAssetUrl({
1071+
resource: { _tag: "attachment", attachmentId, disposition: "inline" },
1072+
});
1073+
const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1074+
const separator = suffix.indexOf("/");
1075+
expect(
1076+
yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
1077+
).toMatchObject({ download: true });
1078+
}).pipe(Effect.provide(layerTest)),
1079+
);
1080+
9221081
it.effect("previews workspace files with literal fragment characters in their paths", () =>
9231082
Effect.gen(function* () {
9241083
const fileSystem = yield* FileSystem.FileSystem;

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ import {
2222
hostPreviewMimeTypeFromExtension,
2323
isWorkspaceImagePreviewPath,
2424
isWorkspacePreviewEntryPath,
25+
officePreviewMimeTypeFromExtension,
26+
officePreviewFormat,
2527
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
2628
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
2729
} from "@t3tools/shared/filePreview";
@@ -84,10 +86,16 @@ const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
8486
htm: "text/html",
8587
};
8688
const inlinePreviewMimeTypeForExtension = (extension: string) =>
87-
INLINE_PREVIEW_MIME_TYPES[extension] ?? audioMimeTypeFromExtension(`.${extension}`) ?? undefined;
89+
INLINE_PREVIEW_MIME_TYPES[extension] ??
90+
audioMimeTypeFromExtension(`.${extension}`) ??
91+
officePreviewMimeTypeFromExtension(`.${extension}`) ??
92+
undefined;
8893
const PREVIEW_ASSET_EXTENSIONS = new Set([
8994
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
9095
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
96+
".xlsx",
97+
".xls",
98+
".pptx",
9199
".css",
92100
".js",
93101
".mjs",
@@ -480,21 +488,23 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA
480488
? yield* readImageDimensionsFromHeader(canonicalFile)
481489
: null;
482490
return {
483-
claims: isWorkspaceImagePreviewPath(resolved.relativePath)
484-
? {
485-
version: 1 as const,
486-
kind: "workspace-file-exact" as const,
487-
workspaceRoot: canonicalWorkspaceRoot,
488-
relativePath: resolved.relativePath,
489-
expiresAt: input.expiresAt,
490-
}
491-
: {
492-
version: 1 as const,
493-
kind: "workspace-file" as const,
494-
workspaceRoot: canonicalWorkspaceRoot,
495-
baseRelativePath: path.dirname(resolved.relativePath),
496-
expiresAt: input.expiresAt,
497-
},
491+
claims:
492+
isWorkspaceImagePreviewPath(resolved.relativePath) ||
493+
officePreviewFormat({ name: resolved.relativePath }) !== null
494+
? {
495+
version: 1 as const,
496+
kind: "workspace-file-exact" as const,
497+
workspaceRoot: canonicalWorkspaceRoot,
498+
relativePath: resolved.relativePath,
499+
expiresAt: input.expiresAt,
500+
}
501+
: {
502+
version: 1 as const,
503+
kind: "workspace-file" as const,
504+
workspaceRoot: canonicalWorkspaceRoot,
505+
baseRelativePath: path.dirname(resolved.relativePath),
506+
expiresAt: input.expiresAt,
507+
},
498508
fileName: path.basename(resolved.relativePath),
499509
imageDimensions,
500510
};

‎apps/server/src/http.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import {
55
EnvironmentHttpApi,
66
} from "@t3tools/contracts";
77
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
8+
import {
9+
officePreviewFormat,
10+
officePreviewMimeTypeFromExtension,
11+
} from "@t3tools/shared/filePreview";
812
import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";
913
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
1014
import * as Data from "effect/Data";
@@ -75,7 +79,9 @@ const isSafeDownloadMimeType = (mimeType: string): boolean =>
7579
const isSafeInlineMediaMimeType = (mimeType: string): boolean =>
7680
DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && /^(?:audio|video)\//i.test(mimeType);
7781
const isSafeInlineDocumentMimeType = (mimeType: string): boolean =>
78-
mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html";
82+
mimeType.toLowerCase() === "application/pdf" ||
83+
mimeType.toLowerCase() === "text/html" ||
84+
officePreviewFormat({ name: "", mimeType }) !== null;
7985

8086
/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
8187
export function downloadContentDisposition(fileName?: string): string {
@@ -124,7 +130,7 @@ export function assetResponseHeaders(
124130
"Content-Type":
125131
inlineMimeType.toLowerCase() === "text/html"
126132
? "text/html; charset=utf-8"
127-
: "application/pdf",
133+
: inlineMimeType.toLowerCase(),
128134
...(inlineMimeType.toLowerCase() === "text/html"
129135
? { "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY }
130136
: {}),
@@ -134,7 +140,13 @@ export function assetResponseHeaders(
134140
"Content-Type": "text/html; charset=utf-8",
135141
"Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
136142
}
137-
: {}),
143+
: officePreviewMimeTypeFromExtension(lowerPath.slice(lowerPath.lastIndexOf(".")))
144+
? {
145+
"Content-Type": officePreviewMimeTypeFromExtension(
146+
lowerPath.slice(lowerPath.lastIndexOf(".")),
147+
)!,
148+
}
149+
: {}),
138150
...(!options?.download && lowerPath.endsWith(".svg")
139151
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
140152
: {}),

‎apps/web/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
"culori": "^4.0.2",
5656
"dompurify": "^3.4.16",
5757
"effect": "catalog:",
58+
"fflate": "0.8.3",
5859
"hast-util-to-html": "^9.0.5",
5960
"hast-util-to-jsx-runtime": "^2.3.6",
6061
"heic-to": "^1.5.2",
@@ -69,8 +70,10 @@
6970
"react-dom": "19.2.6",
7071
"react-markdown": "^10.1.0",
7172
"remark-gfm": "catalog:",
73+
"saxes": "6.0.0",
7274
"tailwind-merge": "^3.4.0",
7375
"unbash": "^5.0.0",
76+
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
7477
"zustand": "^5.0.11"
7578
},
7679
"devDependencies": {

‎apps/web/src/components/files/AttachmentFilePreview.tsx‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
22
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
33
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
44
import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
5-
import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
5+
import {
6+
filePreviewKind,
7+
FILE_TEXT_PREVIEW_MAX_BYTES,
8+
officePreviewFormat,
9+
} from "@t3tools/shared/filePreview";
610
import { ChevronRightIcon, DownloadIcon, Trash2Icon, WrapTextIcon, XIcon } from "lucide-react";
711
import { Check, Code2, Copy, Eye, Table2 } from "lucide";
812
import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
@@ -28,6 +32,7 @@ import {
2832
} from "./fileSurfaceChrome";
2933

3034
const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
35+
const OfficeDocumentPreview = lazy(() => import("./OfficeDocumentPreview"));
3136

3237
/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
3338
const STALE_URL_MS = 5 * 60_000;
@@ -69,6 +74,7 @@ export function AttachmentFilePreview(props: {
6974
onClose?: () => void;
7075
}) {
7176
const kind = filePreviewKind(props);
77+
const officeFormat = officePreviewFormat(props);
7278
const delimiter = filePreviewDelimiter(props);
7379
const renderedMode =
7480
kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
@@ -138,7 +144,9 @@ export function AttachmentFilePreview(props: {
138144
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
139145
}, [props.file, refresh, revision]);
140146
const url = props.file ? localUrl : remoteUrl;
141-
const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
147+
const needsText =
148+
officeFormat === null &&
149+
(kind === "text" || kind === "markdown" || (kind === "html" && !rendered));
142150
useEffect(() => {
143151
if (!needsText || !url) return;
144152
const controller = new AbortController();
@@ -246,6 +254,17 @@ export function AttachmentFilePreview(props: {
246254
) : (
247255
<ReadOnlySourcePreview name={props.name} text={content.text} />
248256
)
257+
) : officeFormat ? (
258+
<Suspense fallback={<FileSurfaceLoading />}>
259+
<OfficeDocumentPreview
260+
key={`${props.name}:${url}:${revision}`}
261+
name={props.name}
262+
format={officeFormat}
263+
src={url}
264+
file={props.file}
265+
onRetry={() => setRevision((value) => value + 1)}
266+
/>
267+
</Suspense>
249268
) : kind === "pdf" || kind === "html" ? (
250269
<BrowserDocumentFrame
251270
src={url}

0 commit comments

Comments
 (0)