Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Support Office attachments and previews
wyt527612bbdbb5
diff --git a/src/main/features/chat_attachments.ts b/src/main/features/chat_attachments.tsindex 13d0ff5a..05eb2f90 100644--- a/src/main/features/chat_attachments.ts+++ b/src/main/features/chat_attachments.ts@@ -5,15 +5,17 @@* Supported kinds — mirrors `contexts` upload whitelist:* text — .md / .markdown / .txt / .csv / .tsv / .json / .yaml / .yml / .log* pdf — .pdf- * docx — .docx+ * docx — .docx / .docm+ * spreadsheet — .xlsx / .xlsm+ * presentation — .pptx / .pptm* image — .png / .jpg / .jpeg / .webp / .gif* video — .mp4 / .webm / .mov / .m4v / .ogv (display-only, not sent to* the model; bytes streamed to the renderer via the* `chat-media://` protocol)** Lifecycle:- * uploadAttachment — write original to disk; NO preprocessing. PDF/DOCX- * extract + image grayscale happen lazily on read via+ * uploadAttachment — write original to disk; NO preprocessing. PDF/DOCX/+ * XLSX/PPTX extract + image grayscale happen lazily on read via* features/file_indexer (which caches under* <uid>/local/file_cache/<hash>/). Video is kept raw* and never cached.@@ -59,13 +61,18 @@ const TEXT_EXTS: ReadonlySet<string> = new Set([const IMAGE_EXTS: ReadonlySet<string> = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);const VIDEO_EXTS: ReadonlySet<string> = new Set(['.mp4', '.webm', '.mov', '.m4v', '.ogv']);const PDF_EXT = '.pdf';-const DOCX_EXT = '.docx';+const DOCX_EXTS: ReadonlySet<string> = new Set(['.docx', '.docm']);+const SPREADSHEET_EXTS: ReadonlySet<string> = new Set(['.xlsx', '.xlsm']);+const PRESENTATION_EXTS: ReadonlySet<string> = new Set(['.pptx', '.pptm']);export const ALLOWED_EXTENSIONS: ReadonlySet<string> = new Set([- ...TEXT_EXTS, PDF_EXT, DOCX_EXT, ...IMAGE_EXTS, ...VIDEO_EXTS,+ ...TEXT_EXTS,+ PDF_EXT, ...DOCX_EXTS, ...SPREADSHEET_EXTS, ...PRESENTATION_EXTS,+ ...IMAGE_EXTS, ...VIDEO_EXTS,]);const MAX_BYTES_TEXT = 5 * 1024 * 1024;const MAX_BYTES_DOCX = 20 * 1024 * 1024;+const MAX_BYTES_OFFICE = 50 * 1024 * 1024;const MAX_BYTES_IMAGE = 20 * 1024 * 1024;const MAX_BYTES_PDF = 100 * 1024 * 1024;const MAX_BYTES_VIDEO = 200 * 1024 * 1024;@@ -74,7 +81,14 @@ const MAX_FILENAME_LEN = 200;// ── Types ────────────────────────────────────────────────────────────────-export type AttachmentKind = 'text' | 'pdf' | 'docx' | 'image' | 'video';+export type AttachmentKind =+ | 'text'+ | 'pdf'+ | 'docx'+ | 'spreadsheet'+ | 'presentation'+ | 'image'+ | 'video';export type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif';export interface AttachmentInfo {@@ -115,7 +129,9 @@ function safeCid(cid: unknown): string {function kindOf(ext: string): AttachmentKind {const e = ext.toLowerCase();if (e === PDF_EXT) return 'pdf';- if (e === DOCX_EXT) return 'docx';+ if (DOCX_EXTS.has(e)) return 'docx';+ if (SPREADSHEET_EXTS.has(e)) return 'spreadsheet';+ if (PRESENTATION_EXTS.has(e)) return 'presentation';if (IMAGE_EXTS.has(e)) return 'image';if (VIDEO_EXTS.has(e)) return 'video';return 'text';@@ -124,7 +140,8 @@ function kindOf(ext: string): AttachmentKind {function maxBytesFor(ext: string): number {const e = ext.toLowerCase();if (e === PDF_EXT) return MAX_BYTES_PDF;- if (e === DOCX_EXT) return MAX_BYTES_DOCX;+ if (DOCX_EXTS.has(e)) return MAX_BYTES_DOCX;+ if (SPREADSHEET_EXTS.has(e) || PRESENTATION_EXTS.has(e)) return MAX_BYTES_OFFICE;if (IMAGE_EXTS.has(e)) return MAX_BYTES_IMAGE;if (VIDEO_EXTS.has(e)) return MAX_BYTES_VIDEO;return MAX_BYTES_TEXT;@@ -703,8 +720,8 @@ export async function purgeByCid(userId: string, cid: string): Promise<number> {// ── Prompt injection (manifest + images) ─────────────────────────────────export interface AttachmentManifest {- /** `<attachments>…</attachments>` XML listing text/pdf/docx attachments- * with absolute paths + kind + byte count. Empty string when no text-ish+ /** `<attachments>…</attachments>` XML listing model-readable attachments+ * with absolute paths + kind + optional total_chars. Empty string when no text-ish* attachments are attached. The model uses this as a directory listing* and calls the on-demand file tools for content. */manifest: string;@@ -725,11 +742,13 @@ export interface BuildManifestOpts {* - text → listed with `total_chars` (cheap: one fs.readFileSync* + .length via file_indexer.statFile). Model can go* straight to read_file.- * - pdf / docx → listed with `total_chars` ONLY if the cache already- * has it (i.e. someone has read/stated this file- * before). Otherwise `total_chars` is omitted and the- * model must call stat_file before read_file.- * Never eagerly extract here — upload stays zero-cost.+ * - pdf / docx /+ * spreadsheet /+ * presentation → listed with `total_chars` ONLY if the cache already has+ * it (i.e. someone has read/stated this file before).+ * Otherwise `total_chars` is omitted and the model must+ * call stat_file before read_file. Never eagerly extract+ * here — upload stays zero-cost.* - image → compressed grayscale JPEG via real-time* toCompressedGrayJpeg on the raw source → images[]* for pi-ai vision.@@ -786,7 +805,7 @@ export async function buildAttachmentManifest(continue;}- // text / pdf / docx → manifest entry (path + kind + total_chars if known).+ // text / pdf / modern Office → manifest entry (path + kind + total_chars if known).let totalChars: number | undefined;if (kind === 'text') {// Text is cheap to stat (one fs.readFileSync). Always include total_chars@@ -798,8 +817,8 @@ export async function buildAttachmentManifest(log.warn(`manifest statFile text failed name=${nm}: ${(err as Error).message}`);}} else {- // pdf / docx: peek only — no extract. total_chars appears only when a- // prior read/stat already materialised the cache.+ // Rich documents: peek only — no extract. total_chars appears only when+ // a prior read/stat already materialised the cache.const cached = getCachedMeta(userId, abs);if (cached?.totalChars !== undefined) totalChars = cached.totalChars;}diff --git a/src/main/features/file_indexer.ts b/src/main/features/file_indexer.tsindex 0907602f..87be74dc 100644--- a/src/main/features/file_indexer.ts+++ b/src/main/features/file_indexer.ts@@ -9,9 +9,9 @@* <uid>/local/file_cache/<sha1(absPath).slice(0,16)>/* meta.json { absPath, mtime, size, kind, source: 'attachment'|'workspace',* cid?, totalChars?, pageMap?, cacheVersion, lastAccessed }- * text.md (pdf / docx only) — full extracted text; enables range reads- * without re-parsing. text files read directly from source;- * images never cached (realtime compress+grayscale).+ * text.md (pdf / docx / xlsx / pptx) — full extracted text; enables+ * range reads without re-parsing. text files read directly+ * from source; images never cached (realtime compress+grayscale).** Scope is recorded in `meta.source` / `meta.cid` for cleanup routing only —* the cache location does NOT depend on scope. Tool-layer path-sandbox is@@ -21,9 +21,9 @@* - `getCachedMeta` / `peekMeta` — pure read-only; never materialises. Used* by manifest + search_files so "list a file" doesn't pay extract cost.* - `statFile` — `ensureFresh` + return FileMeta. Triggers- * extract when needed. For pdf/docx this is the only path that runs- * pdfjs / mammoth.- * - `readRange` — pure slice by char offsets. For pdf/docx+ * extract when needed. For rich documents this is the only path that runs+ * pdfjs / mammoth / OOXML parsers.+ * - `readRange` — pure slice by char offsets. For rich docs* throws `NeedStatError` when cache is missing so the caller decides* whether to extract first.*@@ -44,13 +44,14 @@ import { createLogger } from '../logger';import { macosTccSensitivePath } from '../util/macos-tcc';import { pdfBufferToPages, EXTRACT_CACHE_VERSION } from '../util/extract-pdf';import { docxBufferToMarkdown } from '../util/extract-docx';+import { xlsxBufferToMarkdown, pptxBufferToMarkdown } from '../util/extract-office';import { toCompressedGrayJpeg } from '../util/image-transform';const log = createLogger('file_indexer');export { EXTRACT_CACHE_VERSION };-/** Thrown by `readRange` when the target is pdf/docx and no cache exists yet.+/** Thrown by `readRange` when the target is rich-document kind and no cache exists yet.* Caller decides whether to `statFile` (which triggers extract) or surface* an error to the model. */export class NeedStatError extends Error {@@ -69,17 +70,29 @@ export class NoTextError extends Error {}}+/** Thrown when the file extension is uploadable/listable but cannot be+ * converted to text by the current model-side extractor. */+export class UnsupportedFileKindError extends Error {+ constructor(public readonly absPath: string, public readonly kind: FileKind) {+ super(`${kind} is not readable by the model: ${absPath}`);+ this.name = 'UnsupportedFileKindError';+ }+}+const TEXT_EXTS: ReadonlySet<string> = new Set(['.md', '.markdown', '.txt', '.csv', '.tsv','.json', '.yaml', '.yml', '.log',]);const IMAGE_EXTS: ReadonlySet<string> = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);const PDF_EXT = '.pdf';-const DOCX_EXT = '.docx';+const DOCX_EXTS: ReadonlySet<string> = new Set(['.docx', '.docm']);+const SPREADSHEET_EXTS: ReadonlySet<string> = new Set(['.xlsx', '.xlsm']);+const PRESENTATION_EXTS: ReadonlySet<string> = new Set(['.pptx', '.pptm']);+const LEGACY_OFFICE_EXTS: ReadonlySet<string> = new Set(['.doc', '.xls', '.ppt']);// ── Types ────────────────────────────────────────────────────────────────-export type FileKind = 'text' | 'pdf' | 'docx' | 'image';+export type FileKind = 'text' | 'pdf' | 'docx' | 'spreadsheet' | 'presentation' | 'legacy_office' | 'image';export type SourceScope = 'attachment' | 'workspace';export interface FileMeta {@@ -90,7 +103,7 @@ export interface FileMeta {source: SourceScope;cid?: string;/** Total character length of the text representation. Populated after- * materialisation for text / pdf / docx; undefined for image (no text). */+ * materialisation for text / rich documents; undefined for image (no text). */totalChars?: number;/** pdf only: the extractor (pdfjs) produced empty text on EVERY page —* almost always a font-mapping failure (embedded / subset / CJK cmap@@ -123,7 +136,10 @@ export interface ImageReadResult {export function kindOf(absPath: string): FileKind {const e = path.extname(absPath).toLowerCase();if (e === PDF_EXT) return 'pdf';- if (e === DOCX_EXT) return 'docx';+ if (DOCX_EXTS.has(e)) return 'docx';+ if (SPREADSHEET_EXTS.has(e)) return 'spreadsheet';+ if (PRESENTATION_EXTS.has(e)) return 'presentation';+ if (LEGACY_OFFICE_EXTS.has(e)) return 'legacy_office';if (IMAGE_EXTS.has(e)) return 'image';if (TEXT_EXTS.has(e)) return 'text';// Unknown extension: treat as text so the model can still peek at it.@@ -228,7 +244,7 @@ function statSource(absPath: string): { size: number; mtime: number; stat: fs.Streturn { size: stat.size, mtime: Math.floor(stat.mtimeMs), stat };}-// ── Materialisation (pdf/docx build text.md + pageMap) ─────────────────+// ── Materialisation (rich docs build text.md + pdf pageMap) ─────────────async function materialise(userId: string,@@ -278,6 +294,18 @@ async function materialise(const md = await docxBufferToMarkdown(buf);fs.writeFileSync(path.join(dir, 'text.md'), md, 'utf8');base.totalChars = md.length;+ } else if (kind === 'spreadsheet') {+ const buf = fs.readFileSync(absPath);+ const md = xlsxBufferToMarkdown(buf);+ fs.writeFileSync(path.join(dir, 'text.md'), md, 'utf8');+ base.totalChars = md.length;+ } else if (kind === 'presentation') {+ const buf = fs.readFileSync(absPath);+ const md = pptxBufferToMarkdown(buf);+ fs.writeFileSync(path.join(dir, 'text.md'), md, 'utf8');+ base.totalChars = md.length;+ } else if (kind === 'legacy_office') {+ throw new UnsupportedFileKindError(absPath, kind);} else if (kind === 'text') {// No text.md for text kind — source IS the text.try {@@ -355,11 +383,12 @@ export function getCachedMeta(userId: string, absPath: string): FileMeta | nullreturn m ? metaToPublic(m) : null;}-/** Force-fresh meta — triggers extract (pdfjs / mammoth) if cache is missing- * or stale. For image kind throws `NoTextError` since image has no text+/** Force-fresh meta — triggers text extraction if cache is missing or stale.+ * For image kind throws `NoTextError` since image has no text* representation (use `readImageAsGrayJpeg` instead). */export async function statFile(userId: string, absPath: string): Promise<FileMeta> {if (kindOf(absPath) === 'image') throw new NoTextError(absPath);+ if (kindOf(absPath) === 'legacy_office') throw new UnsupportedFileKindError(absPath, 'legacy_office');const meta = await ensureFresh(userId, absPath);return metaToPublic(meta);}@@ -369,7 +398,7 @@ export async function statFile(userId: string, absPath: string): Promise<FileMet** Contract by kind:* - text → always works (materialise is cheap: fs.read + .length)- * - pdf / docx → throws `NeedStatError` when no cache exists. Callers+ * - rich docs → throws `NeedStatError` when no cache exists. Callers* must `statFile` first (which extracts) and then retry.* This keeps extract side-effects out of read_file.* - image → throws `NoTextError`. Caller must branch to@@ -381,6 +410,7 @@ export async function readRange(): Promise<TextReadResult> {const kind = kindOf(absPath);if (kind === 'image') throw new NoTextError(absPath);+ if (kind === 'legacy_office') throw new UnsupportedFileKindError(absPath, kind);let meta: OnDiskMeta;if (kind === 'text') {@@ -389,7 +419,7 @@ export async function readRange(// call instead of forcing the model through stat_file first.meta = await ensureFresh(userId, absPath);} else {- // pdf / docx: require an existing fresh cache. Do NOT extract here — the+ // Rich documents require an existing fresh cache. Do NOT extract here — the// model is expected to call stat_file first when the manifest / search// result didn't include total_chars.const peeked = peekMeta(userId, absPath);@@ -435,13 +465,14 @@ export async function readImageAsGrayJpeg(}/** Full extracted text + meta — used by grep_files to scan many files. Text- * kind reads source directly; pdf/docx return cached text.md. Image throws. */+ * kind reads source directly; rich docs return cached text.md. Image throws. */export async function getExtractedText(userId: string,absPath: string,): Promise<{ text: string; meta: FileMeta }> {const meta = await ensureFresh(userId, absPath);if (meta.kind === 'image') throw new Error(`getExtractedText: image not supported: ${absPath}`);+ if (meta.kind === 'legacy_office') throw new UnsupportedFileKindError(absPath, meta.kind);const text = meta.kind === 'text'? fs.readFileSync(absPath, 'utf8'): fs.readFileSync(path.join(cacheDirFor(userId, absPath), 'text.md'), 'utf8');diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.tsindex 25ecb085..6691db7c 100644--- a/src/main/features/group_chat/bus.ts+++ b/src/main/features/group_chat/bus.ts@@ -83,6 +83,14 @@ function escapeHtmlForBubble(s: string): string {.replace(/"/g, '"');}+function escapeXmlAttr(s: string): string {+ return String(s)+ .replace(/&/g, '&')+ .replace(/"/g, '"')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}+function isExistingProducedFile(absPath: string): boolean {try {return fs.statSync(absPath).isFile();@@ -1201,18 +1209,47 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis}// Attach a `<attachments>` manifest block listing files uploaded on this- // user turn (text / pdf / docx / image with absolute paths + kinds).+ // user turn (text / pdf / Office docs / image with absolute paths + kinds).// Library files are intentionally not path-injected; use kb_search/kb_read.// Image bytes ride alongside via ChatOptions.images so the vision model sees// them on the same user turn — the manifest entry carries `attached="inline"`// so the LLM doesn't waste a read_file round-trip re-fetching what it already has.let turnImages: Array<{ data: string; mediaType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' }> = [];+ // Capture the process trail to persist on the end-of-turn message so+ // history reload can rerender the rail (renderer accumulates it live, but+ // without persistence it vanishes on refresh). Cap the array so a runaway+ // tool storm can't bloat the jsonl. Skip `delta` and `assistant` events.+ type ProcessItem =+ | { type: 'progress'; text: string }+ | { type: 'event'; event: { stream: string; data?: unknown } };+ const processItems: ProcessItem[] = [];if (item.attachments && item.attachments.length) {try {const { buildAttachmentManifest } = await import('../chat_attachments');- const { manifest, images } = await buildAttachmentManifest(uid, cid, item.attachments);+ const { manifest, images, skipped } = await buildAttachmentManifest(uid, cid, item.attachments);if (manifest) messageText = `${manifest}\n${messageText}`;if (images.length) turnImages = images;+ if (skipped.length) {+ const skippedEvent = { stream: 'attachment', data: { phase: 'skipped', items: skipped } };+ if (processItems.length < MAX_PROCESS_ITEMS_PER_TURN) {+ processItems.push({ type: 'event', event: skippedEvent });+ }+ emit(state, {+ type: 'process',+ cid,+ actor: actor.id,+ turn_id: item.turnId,+ data: { type: 'event', event: skippedEvent },+ });+ const skippedXml = skipped+ .map((s) => {+ const name = escapeXmlAttr(String(s.name || ''));+ const reason = escapeXmlAttr(String(s.reason || ''));+ return `<file name="${name}" status="skipped" reason="${reason}"/>`;+ })+ .join('\n');+ messageText = `<attachments-skipped>\n${skippedXml}\n</attachments-skipped>\n${messageText}`;+ }} catch (err) {log.warn(`attachments manifest build failed cid=${cid} actor=${actor.id}: ${(err as Error).message}`);}@@ -1350,18 +1387,6 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis// tool-only turns (final empty is normal) from config / auth bugs (the// stream produced literally nothing).let activityEvents = 0;- // Capture the process trail to persist on the end-of-turn message so- // history reload can rerender the rail (renderer accumulates it live, but- // without persistence it vanishes on refresh — `_renderPersistedProcess`- // in conversation.js needs `message.process`). Cap the array so a runaway- // tool storm can't bloat the jsonl. Skip `delta` (token stream — that's- // the final text body) and `assistant` events (`_formatEventLine` would- // drop them anyway). Mirrors the shape used by skills.ts/agents.ts edit- // chats.- type ProcessItem =- | { type: 'progress'; text: string }- | { type: 'event'; event: { stream: string; data?: unknown } };- const processItems: ProcessItem[] = [];// Commander needs to inspect skill / agent specs before mutating them:// `cat .../<id>/SKILL.md` to ground a skill rewrite, `read_file` an// agent.json before emitting an `<agent>` edit container. The ROOTdiff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 24167e26..d4e0cd27 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -85,7 +85,7 @@ type StreamHandler = (const CHAT_PICK_EXTENSIONS = ['md', 'markdown', 'txt', 'csv', 'tsv', 'json', 'yaml', 'yml', 'log',- 'pdf', 'docx',+ 'pdf', 'docx', 'docm', 'xlsx', 'xlsm', 'pptx', 'pptm','png', 'jpg', 'jpeg', 'webp', 'gif','mp4', 'webm', 'mov', 'm4v', 'ogv',];@@ -168,6 +168,187 @@ function _projectFileScopeForUser(userId: string, projectId: string | undefined)return path.resolve(projectFilesDir(userId, projectId));}+function _escapePreviewHtml(s: string): string {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++type OfficePreviewKind = 'word' | 'spreadsheet' | 'presentation';++function _officePreviewKindForExt(ext: string): OfficePreviewKind | null {+ if (ext === '.docx' || ext === '.docm') return 'word';+ if (ext === '.xlsx' || ext === '.xlsm') return 'spreadsheet';+ if (ext === '.pptx' || ext === '.pptm') return 'presentation';+ return null;+}++function _wrapOfficePreviewHtml(kind: OfficePreviewKind, title: string, body: string): string {+ const safeTitle = _escapePreviewHtml(title || 'Office preview');+ return `<!doctype html>+<html>+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>${safeTitle}</title>+ <style>+ :root { color-scheme: light; }+ * { box-sizing: border-box; }+ body {+ margin: 0;+ background: #eef2f7;+ color: #0f172a;+ font: 14px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ }+ .office-preview {+ width: 100%;+ min-height: 100vh;+ margin: 0 auto;+ padding: 24px;+ }+ .office-word {+ max-width: 820px;+ background: #fff;+ min-height: calc(100vh - 48px);+ margin: 20px auto 32px;+ padding: 56px 64px;+ border: 1px solid #e5e7eb;+ box-shadow: 0 1px 8px rgba(15, 23, 42, 0.06);+ }+ .office-spreadsheet {+ max-width: none;+ padding: 18px;+ }+ .office-word h1, .office-word h2, .office-word h3 {+ line-height: 1.3;+ color: #111827;+ }+ .office-word h1 {+ margin: 0 0 22px;+ font-size: 28px;+ font-weight: 700;+ }+ .office-word h2 {+ margin: 26px 0 12px;+ font-size: 21px;+ font-weight: 650;+ }+ .office-word h3 {+ margin: 22px 0 10px;+ font-size: 17px;+ font-weight: 650;+ }+ .office-word p,+ .office-word li {+ margin: 0 0 13px;+ font-size: 15px;+ line-height: 1.72;+ color: #111827;+ }+ .office-word ul,+ .office-word ol {+ margin: 0 0 16px 24px;+ padding: 0;+ }+ .office-word table {+ border-collapse: collapse;+ width: 100%;+ margin: 16px 0;+ }+ .office-word th, .office-word td,+ .office-table-wrap th, .office-table-wrap td {+ border: 1px solid #cbd5e1;+ padding: 7px 9px;+ vertical-align: top;+ }+ .office-sheet {+ margin: 0 0 22px;+ padding: 18px;+ background: #fff;+ border: 1px solid #e2e8f0;+ border-radius: 8px;+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);+ }+ .office-sheet h2 {+ margin: 0 0 12px;+ font-size: 15px;+ }+ .office-table-wrap {+ overflow: auto;+ max-height: 70vh;+ border: 1px solid #e2e8f0;+ border-radius: 6px;+ }+ .office-table-wrap table {+ border-collapse: collapse;+ min-width: 100%;+ background: #fff;+ font-size: 13px;+ }+ .office-table-wrap td {+ min-width: 96px;+ white-space: pre-wrap;+ }+ .office-empty-cell, .office-muted { color: #64748b; }+ .office-presentation {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 24px;+ padding: 24px;+ }+ .office-slide {+ width: min(1120px, calc(100vw - 64px));+ aspect-ratio: 16 / 9;+ margin: 0 auto;+ padding: clamp(32px, 5vw, 64px);+ background: #fff;+ border: 1px solid #e2e8f0;+ border-radius: 6px;+ box-shadow: 0 1px 4px rgba(15, 23, 42, 0.08);+ display: flex;+ align-items: center;+ }+ .office-slide-body p {+ margin: 0 0 18px;+ font-size: clamp(18px, 2vw, 30px);+ line-height: 1.35;+ }+ .office-slide-body p:first-child {+ font-size: clamp(26px, 3vw, 44px);+ font-weight: 600;+ line-height: 1.2;+ }+ @media (max-width: 720px) {+ .office-preview { padding: 12px; }+ .office-word {+ margin: 0 auto;+ min-height: calc(100vh - 24px);+ padding: 32px 24px;+ }+ .office-word h1 { font-size: 24px; }+ .office-word p,+ .office-word li { font-size: 14px; }+ .office-presentation { padding: 12px; gap: 14px; }+ .office-slide {+ width: calc(100vw - 24px);+ padding: 24px;+ }+ .office-slide-body p { font-size: 16px; }+ .office-slide-body p:first-child { font-size: 22px; }+ }+ </style>+</head>+<body>+ <main class="office-preview office-${kind}">+ ${body}+ </main>+</body>+</html>`;+}+/** Build the allowed-roots list for the file-class IPC sandbox: workspace ∪* current cid's attachment dir ∪ payload's project-file dir. The actual* containment check happens via `util/path-sandbox.isPathAllowed`, which@@ -2019,6 +2200,49 @@ const invokeHandlers: Record<string, InvokeHandler> = {return { ok: true, text, size: st.size };},+ // Convert modern Office files into a local, sandboxed HTML preview.+ // This is a content preview, not a high-fidelity Office layout renderer.+ // It shares the same path scope as produced.readText and revealPath.+ 'produced.officePreviewHtml': async (payload, ctx) => {+ const target = payload?.path;+ if (typeof target !== 'string' || !target) {+ throw new Error('missing path');+ }+ const norm = path.resolve(target);+ if (!await _isAllowedFileActionPath(ctx.userId, payload, norm)) {+ throw new Error('path is outside the user workspace');+ }+ const kind = _officePreviewKindForExt(path.extname(norm).toLowerCase());+ if (!kind) return { ok: false, error: 'unsupported' };+ let st: fs.Stats;+ try { st = fs.statSync(norm); }+ catch { return { ok: false, error: 'not_found' }; }+ if (!st.isFile()) return { ok: false, error: 'not_found' };+ const MAX_OFFICE_PREVIEW_BYTES = 50 * 1024 * 1024;+ if (st.size > MAX_OFFICE_PREVIEW_BYTES) {+ return { ok: false, error: 'too_large', size: st.size, cap: MAX_OFFICE_PREVIEW_BYTES };+ }++ try {+ const buf = fs.readFileSync(norm);+ let fragment = '';+ if (kind === 'word') {+ const { docxBufferToHtml } = await import('../util/extract-docx');+ fragment = await docxBufferToHtml(buf);+ } else if (kind === 'spreadsheet') {+ const { xlsxBufferToHtml } = await import('../util/extract-office');+ fragment = xlsxBufferToHtml(buf);+ } else {+ const { pptxBufferToHtml } = await import('../util/extract-office');+ fragment = pptxBufferToHtml(buf);+ }+ const html = _wrapOfficePreviewHtml(kind, path.basename(norm), fragment || '<p class="office-muted">(no previewable content)</p>');+ return { ok: true, html, kind, size: st.size };+ } catch (err) {+ return { ok: false, error: String((err as Error).message || 'preview failed') };+ }+ },+// Write a UTF-8 text file into the workspace (or current cid's attachment// dir). Sandbox parity with `produced.readText`: same scope, same 2MB cap on// the resulting bytes — the chat-md drawer is the sole caller today, anddiff --git a/src/main/model/core-agent/file-tools.ts b/src/main/model/core-agent/file-tools.tsindex eebf7013..679c03b2 100644--- a/src/main/model/core-agent/file-tools.ts+++ b/src/main/model/core-agent/file-tools.ts@@ -3,20 +3,21 @@** - `read_file` — read a slice of a file's text by char offsets. All* kinds use `charStart` / `charEnd` (0-based, half-open);- * the server does not truncate. Text works as-is; pdf/- * docx require a prior `stat_file` call so this tool+ * the server does not truncate. Text works as-is; rich+ * document kinds require a prior `stat_file` call so this tool* never triggers extract side-effects. Image returns an* inline compressed grayscale JPEG (no range).* Overrides core-agent's builtin of the same name.* - `stat_file` — extract (if needed) and return `total_chars` for a- * file. The only tool that triggers pdfjs / mammoth.+ * file. The only tool that triggers pdfjs / mammoth /+ * OOXML extraction.* - `search_files` — locate files by name/glob across the current* conversation's attachment dir + active workspace.* Never triggers extract; `total_chars` is included* only when the cache already has it.* - `grep_files` — cross-file text search in that same scanned scope.- * text/md/code → direct; pdf/docx → extract (cached);- * image skipped.+ * text/md/code → direct; PDF/modern Office → extract+ * (cached); image and unsupported legacy Office skipped.** Scope is enforced via `util/path-sandbox.isPathAllowed`: path-taking tools* first verify the target falls under@@ -42,6 +43,7 @@ import {kindOf,NeedStatError,NoTextError,+ UnsupportedFileKindError,} from '../../features/file_indexer';import { chatAttachmentDir, userMarketplaceSkillsDir, userSkillsDir } from '../../paths';import { getWorkspacePath } from '../../features/user_workspace';@@ -64,7 +66,7 @@ const MAX_SEARCH_RESULTS = 200;/** Max matches returned by grep_files per call. */const MAX_GREP_MATCHES = 200;-/** Concurrent extract workers in grep_files. PDF/DOCX cache miss path. */+/** Concurrent extract workers in grep_files. Rich-document cache miss path. */const GREP_EXTRACT_CONCURRENCY = 4;// ── Opts + scope ─────────────────────────────────────────────────────────@@ -162,6 +164,10 @@ function guardDisabledSkillAccess(opts: FileToolsOpts, abs: string): string | nu);}+function isExtractableRichKind(kind: string): boolean {+ return kind === 'pdf' || kind === 'docx' || kind === 'spreadsheet' || kind === 'presentation';+}+// ── read_file ─────────────────────────────────────────────────────────────function createReadFileTool(opts: FileToolsOpts): AgentTool {@@ -184,8 +190,10 @@ function createReadFileTool(opts: FileToolsOpts): AgentTool {+ ' - Continue: set charStart = previous response\'s covered end.\n'+ ' - total_chars is usually already in the `<attachments>` manifest or in a prior\n'+ ' `search_files` hit — use it to plan charStart/charEnd.\n'- + ' - If a pdf/docx has never been read/stated before, this tool returns E_NEED_STAT.\n'+ + ' - If a PDF or modern Office file has never been read/stated before, this tool returns E_NEED_STAT.\n'+ ' Call `stat_file(path)` first to trigger extraction, then come back.\n'+ + ' - Legacy Office files (.doc/.xls/.ppt) return E_UNSUPPORTED_FILE; ask the user\n'+ + ' for a .docx/.xlsx/.pptx export if the content is required.\n'+ ' - For image kind, no range applies; a compressed grayscale JPEG is returned inline\n'+ ' as a user-turn image.\n'+ '\n'@@ -266,7 +274,7 @@ function createReadFileTool(opts: FileToolsOpts): AgentTool {// skill_invoked attribution: when the LLM read_file's a SKILL.md// body, the body is the progressive-disclosure "use this skill"// signal (per Claude Code conventions). Emit AFTER the successful- // text read — image / pdf / docx SKILL.md is not a real shape.+ // text read — image / rich-document SKILL.md is not a real shape.if (opts.onSkillInvoked) {const parsed = parseSkillPath(abs, opts.userId);if (parsed) {@@ -290,6 +298,16 @@ function createReadFileTool(opts: FileToolsOpts): AgentTool {log.warn(`read_file no-text user=${opts.userId} path=${abs}`);return { content: errText('E_NO_TEXT', `${abs}: image has no text representation`), isError: true };}+ if (err instanceof UnsupportedFileKindError) {+ log.warn(`read_file unsupported user=${opts.userId} kind=${err.kind} path=${abs}`);+ return {+ content: errText(+ 'E_UNSUPPORTED_FILE',+ `${abs}: ${err.kind} cannot be read by the model. Convert it to .docx/.xlsx/.pptx and attach again.`,+ ),+ isError: true,+ };+ }const msg = (err as Error).message;log.warn(`read_file failed user=${opts.userId} path=${abs}: ${msg}`);return { content: errText('E_READ_FAILED', msg), isError: true };@@ -306,18 +324,18 @@ function createStatFileTool(opts: FileToolsOpts): AgentTool {description:'Ensure a file\'s text is extracted and return its `total_chars`. Use this when the\n'+ '`<attachments>` manifest or a `search_files` result did NOT already include\n'- + '`total_chars` for the file — typically for a pdf/docx that has never been read.\n'+ + '`total_chars` for the file — typically for a PDF or modern Office file that has never been read.\n'+ '\n'+ 'Parameters:\n'+ ' path — required. Absolute path inside workspace or current attachment dir.\n'+ '\n'+ 'Response:\n'- + ' <file path="..." kind="text|pdf|docx" total_chars="N"/>\n'+ + ' <file path="..." kind="text|pdf|docx|spreadsheet|presentation" total_chars="N"/>\n'+ '\n'+ 'Notes:\n'+ ' - Skip this call when total_chars is already provided — go straight to read_file.\n'- + ' - This tool does the pdfjs / mammoth extraction; first call on a large pdf may\n'- + ' take a few seconds, subsequent read_file calls hit the cache instantly.\n'+ + ' - This tool does pdfjs / mammoth / OOXML extraction; first call on a large\n'+ + ' document may take a few seconds, subsequent read_file calls hit the cache instantly.\n'+ ' - Returns E_NO_TEXT for image kind; images are displayed via read_file directly.',inputSchema: {type: 'object',@@ -365,6 +383,16 @@ function createStatFileTool(opts: FileToolsOpts): AgentTool {log.warn(`stat_file no-text user=${opts.userId} path=${abs}`);return { content: errText('E_NO_TEXT', `${abs}: image has no text representation`), isError: true };}+ if (err instanceof UnsupportedFileKindError) {+ log.warn(`stat_file unsupported user=${opts.userId} kind=${err.kind} path=${abs}`);+ return {+ content: errText(+ 'E_UNSUPPORTED_FILE',+ `${abs}: ${err.kind} cannot be read by the model. Convert it to .docx/.xlsx/.pptx and attach again.`,+ ),+ isError: true,+ };+ }const msg = (err as Error).message;log.warn(`stat_file failed user=${opts.userId} path=${abs}: ${msg}`);return { content: errText('E_STAT_FAILED', msg), isError: true };@@ -575,9 +603,9 @@ function createGrepFilesTool(opts: FileToolsOpts): AgentTool {'Search for a pattern across files visible to this conversation (workspace + attachment dir).\n'+ 'File type handling:\n'+ ' • text / md / csv / code → searched directly on the source file\n'- + ' • pdf / docx → extracted to text (cached) and searched\n'- + ' • images / binaries → skipped\n'- + 'First cross-file grep on a fresh set of pdfs/docx may be slow (parallel extract);\n'+ + ' • PDF / modern Office → extracted to text (cached) and searched\n'+ + ' • images / legacy Office / binaries → skipped\n'+ + 'First cross-file grep on a fresh set of rich documents may be slow (parallel extract);\n'+ 'subsequent calls in the same session are cached. Use `search_files` to narrow the\n'+ 'set before grepping when the scope is large.',inputSchema: {@@ -646,7 +674,7 @@ function createGrepFilesTool(opts: FileToolsOpts): AgentTool {});const extractTargets = targets.filter((t) => {const k = kindOf(t.abs);- return k === 'pdf' || k === 'docx';+ return isExtractableRichKind(k);});// Images + unknown → skippedskipped += targets.length - textTargets.length - extractTargets.length;diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.tsindex 1efcfc05..6449646c 100644--- a/src/main/model/core-agent/local-tools.ts+++ b/src/main/model/core-agent/local-tools.ts@@ -19,7 +19,7 @@* an existing text file. Sandbox-checked* (workspace + current attachment dir + extraRoots);* does NOT uniquify (semantics are "modify- * existing"); pdf/docx/image kinds rejected; on+ * existing"); non-text/extracted kinds rejected; on* success fires `onFileWritten` so the UI can show* the green chip. Companion to `write_file` for* cheap targeted edits without a full overwrite.@@ -849,7 +849,7 @@ function createWriteFileTool(opts: LocalToolsOpts): AgentTool {/** Wrapped `edit_file` tool — in-place string replacement on existing text files.* Sandbox-checked, permission-gated, no uniquify (semantics is "modify in place").- * pdf/docx/image kinds rejected — those are extracted-only. */+ * Non-text and extracted kinds are rejected. */function createEditFileTool(opts: LocalToolsOpts): AgentTool {return {name: 'edit_file',@@ -867,7 +867,7 @@ function createEditFileTool(opts: LocalToolsOpts): AgentTool {' - Prefer this over `write_file` for targeted edits to existing files.\n' +' - To CREATE a new file, use `write_file` instead — `edit_file` does not create files.\n' +' - Make `old_string` long enough to be unique. On `E_MULTIPLE_MATCHES`, expand `old_string` with surrounding context, or set `replace_all=true` if every occurrence should change.\n' +- ' - Cannot edit pdf / docx / image files (text from those is extracted, not the source). Use `write_file` if you really need to overwrite the binary.\n' ++ ' - Cannot edit pdf / Office / image files in place (text from those is extracted, not the source). Use `write_file` if you really need to overwrite the binary.\n' +'\n' +'Permission: requires local execution permission (same gate as `write_file` / `bash`).',inputSchema: {@@ -919,7 +919,7 @@ function createEditFileTool(opts: LocalToolsOpts): AgentTool {}const kind = kindOf(abs);- if (kind === 'pdf' || kind === 'docx' || kind === 'image') {+ if (kind !== 'text') {return {content: errText('E_NOT_EDITABLE',diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.tsindex c5da4335..39329a21 100644--- a/src/main/model/core-agent/tool-catalog.ts+++ b/src/main/model/core-agent/tool-catalog.ts@@ -62,14 +62,14 @@ export interface ToolCatalogEntry {*/export const TOOL_CATALOG: ToolCatalogEntry[] = [// Files / workspace- { name: 'read_file', group: 'fs', summary: 'Read a slice of text from a workspace or attachment file (PDF/DOCX text or image as multimodal).' },+ { name: 'read_file', group: 'fs', summary: 'Read a slice of text from a workspace or attachment file (PDF/modern Office text or image as multimodal).' },{ name: 'write_file', group: 'fs', permission: 'localExec', summary: 'Write text/code/markdown into the workspace; resolves under $working_dir.' },{ name: 'edit_file', group: 'fs', permission: 'localExec', summary: 'In-place `old_string → new_string` replacement on an existing text file (instead of rewriting the whole file).' },{ name: 'delete_file', group: 'fs', permission: 'localExec', summary: 'Delete a single file from the workspace / current attachment dir / extraRoots. The first call shows an inline confirmation card and returns a token; multiple deletes from the same turn are grouped in one card when possible. Use instead of `bash rm` for removals.' },{ name: 'list_files', group: 'fs', summary: 'List the workspace directory tree.' },- { name: 'stat_file', group: 'fs', summary: 'Trigger PDF/DOCX extraction and return total_chars; call before read_file.' },+ { name: 'stat_file', group: 'fs', summary: 'Trigger PDF/modern Office extraction and return total_chars; call before read_file.' },{ name: 'search_files', group: 'fs', summary: 'Find files by name / glob across the workspace + attachment scope.' },- { name: 'grep_files', group: 'fs', summary: 'Grep text across the workspace + attachment scope (PDF/DOCX auto-extracted, then searched).' },+ { name: 'grep_files', group: 'fs', summary: 'Grep text across the workspace + attachment scope (PDF/modern Office auto-extracted, then searched).' },{ name: 'create_artifact', group: 'fs', permission: 'localExec', summary: 'Build an interactive multi-file app (HTML/CSS/JS) rendered live & clickable inside the chat bubble; for interactive dashboards / calculators / visualizations / mini-tools. Static/read-only dashboards should use :::dashboard; not documents (html_to_pdf) or images (generate_image).' },// Shelldiff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.mdindex b4615b26..333809a3 100644--- a/src/main/prompts/chat_commander.md+++ b/src/main/prompts/chat_commander.md@@ -170,7 +170,7 @@ If a `## Connectors` block exists, use `list_connector_tools({connector_id})` be`<attachments>` file paths are authoritative absolute paths; call `read_file(path=...)` directly, no `search_files` first. For unlisted files, use `search_files` / `grep_files` in `$working_dir` plus this conversation's attachment dir; if not found, ask for a path/upload. Library files use Library tools, not file search.-`read_file` ranges use `charStart` / `charEnd` (0-based half-open). PDF/docx may return `E_NEED_STAT`; call `stat_file` first. Images return vision input for you only; if `attached="inline"`, answer from visible input and do not reread.+`read_file` ranges use `charStart` / `charEnd` (0-based half-open). PDF and modern Office files may return `E_NEED_STAT`; call `stat_file` first. Images return vision input for you only; if `attached="inline"`, answer from visible input and do not reread. If `<attachments-skipped>` is present, do not claim those files were processed.### Resource path constantsdiff --git a/src/main/util/extract-office.ts b/src/main/util/extract-office.tsnew file mode 100644index 00000000..b2f4116a--- /dev/null+++ b/src/main/util/extract-office.ts@@ -0,0 +1,221 @@+import AdmZip from 'adm-zip';++function readZipText(zip: AdmZip, name: string): string {+ const entry = zip.getEntry(name);+ if (!entry) return '';+ return entry.getData().toString('utf8');+}++function decodeXmlText(raw: string): string {+ return raw+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/&/g, '&')+ .replace(/&#x([0-9a-f]+);/gi, (_m, hex) => String.fromCodePoint(parseInt(hex, 16)))+ .replace(/&#(\d+);/g, (_m, dec) => String.fromCodePoint(parseInt(dec, 10)));+}++function textNodes(xml: string): string[] {+ const out: string[] = [];+ const re = /<[^:>]*:?t\b[^>]*>([\s\S]*?)<\/[^:>]*:?t>/g;+ let match: RegExpExecArray | null;+ while ((match = re.exec(xml))) {+ const text = decodeXmlText(match[1] || '').replace(/\s+/g, ' ').trim();+ if (text) out.push(text);+ }+ return out;+}++function stripTags(xml: string): string {+ return decodeXmlText(xml.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim();+}++function columnIndex(cellRef: string): number {+ const letters = (cellRef.match(/^[A-Z]+/i)?.[0] || '').toUpperCase();+ let n = 0;+ for (const ch of letters) n = n * 26 + (ch.charCodeAt(0) - 64);+ return n || 9999;+}++function parseSharedStrings(zip: AdmZip): string[] {+ const xml = readZipText(zip, 'xl/sharedStrings.xml');+ if (!xml) return [];+ const items = xml.match(/<si\b[\s\S]*?<\/si>/g) || [];+ if (!items.length) return textNodes(xml);+ return items.map((item) => {+ const parts = textNodes(item);+ return parts.length ? parts.join('') : stripTags(item);+ });+}++function parseSheetNames(zip: AdmZip): string[] {+ const workbook = readZipText(zip, 'xl/workbook.xml');+ const rels = readZipText(zip, 'xl/_rels/workbook.xml.rels');+ if (!workbook) return [];++ const relNames = new Map<string, string>();+ if (rels) {+ const relRe = /<Relationship\b([^>]*)\/?>/g;+ let relMatch: RegExpExecArray | null;+ while ((relMatch = relRe.exec(rels))) {+ const attrs = relMatch[1] || '';+ const id = attrs.match(/\bId="([^"]+)"/)?.[1];+ const target = attrs.match(/\bTarget="([^"]+)"/)?.[1];+ if (id && target) relNames.set(id, target.replace(/^\/?xl\//, ''));+ }+ }++ const names: string[] = [];+ const sheetRe = /<sheet\b([^>]*)\/?>/g;+ let sheetMatch: RegExpExecArray | null;+ while ((sheetMatch = sheetRe.exec(workbook))) {+ const attrs = sheetMatch[1] || '';+ const displayName = decodeXmlText(attrs.match(/\bname="([^"]*)"/)?.[1] || '');+ const rid = attrs.match(/\br:id="([^"]*)"/)?.[1];+ if (rid) {+ const target = relNames.get(rid);+ const idx = target?.match(/worksheets\/sheet(\d+)\.xml$/)?.[1];+ if (idx) names[Number(idx) - 1] = displayName || `Sheet ${idx}`;+ } else {+ names.push(displayName || `Sheet ${names.length + 1}`);+ }+ }+ return names;+}++function cellValue(cellXml: string, sharedStrings: string[]): string {+ const type = cellXml.match(/\bt="([^"]+)"/)?.[1] || '';+ const inline = cellXml.match(/<is\b[\s\S]*?<\/is>/)?.[0];+ if (inline) return textNodes(inline).join('');+ const value = decodeXmlText(cellXml.match(/<v\b[^>]*>([\s\S]*?)<\/v>/)?.[1] || '').trim();+ if (!value) return '';+ if (type === 's') return sharedStrings[Number(value)] || '';+ if (type === 'b') return value === '1' ? 'TRUE' : 'FALSE';+ return value;+}++function escapeHtml(raw: string): string {+ return String(raw)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++interface SpreadsheetSheet {+ name: string;+ rows: string[][];+}++function parseSpreadsheetSheets(buf: Buffer): SpreadsheetSheet[] {+ if (!buf?.length) throw new Error('empty or invalid spreadsheet');+ const zip = new AdmZip(buf);+ const sharedStrings = parseSharedStrings(zip);+ const sheetNames = parseSheetNames(zip);+ const sheetEntries = zip.getEntries()+ .map((entry) => entry.entryName)+ .filter((name) => /^xl\/worksheets\/sheet\d+\.xml$/i.test(name))+ .sort((a, b) => Number(a.match(/sheet(\d+)\.xml/i)?.[1] || 0) - Number(b.match(/sheet(\d+)\.xml/i)?.[1] || 0));++ if (!sheetEntries.length) throw new Error('spreadsheet contains no worksheets');++ return sheetEntries.map((sheetPath, index) => {+ const sheetNumber = Number(sheetPath.match(/sheet(\d+)\.xml/i)?.[1] || index + 1);+ const sheetName = sheetNames[sheetNumber - 1] || `Sheet ${sheetNumber}`;+ const xml = readZipText(zip, sheetPath);+ const rowXmls = xml.match(/<row\b[\s\S]*?<\/row>/g) || [];+ const rows = rowXmls.map((rowXml) => (rowXml.match(/<c\b[\s\S]*?<\/c>/g) || [])+ .map((cellXml) => ({+ ref: cellXml.match(/\br="([^"]+)"/)?.[1] || '',+ value: cellValue(cellXml, sharedStrings),+ }))+ .filter((cell) => cell.value.trim())+ .sort((a, b) => columnIndex(a.ref) - columnIndex(b.ref))+ .map((cell) => cell.value));+ return { name: sheetName, rows: rows.filter((row) => row.some((cell) => cell.trim())) };+ });+}++interface PresentationSlide {+ number: number;+ texts: string[];+}++function parsePresentationSlides(buf: Buffer): PresentationSlide[] {+ if (!buf?.length) throw new Error('empty or invalid presentation');+ const zip = new AdmZip(buf);+ const slideEntries = zip.getEntries()+ .map((entry) => entry.entryName)+ .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))+ .sort((a, b) => Number(a.match(/slide(\d+)\.xml/i)?.[1] || 0) - Number(b.match(/slide(\d+)\.xml/i)?.[1] || 0));++ if (!slideEntries.length) throw new Error('presentation contains no slides');++ return slideEntries.map((slidePath) => ({+ number: Number(slidePath.match(/slide(\d+)\.xml/i)?.[1] || 0),+ texts: textNodes(readZipText(zip, slidePath)),+ }));+}++export function xlsxBufferToMarkdown(buf: Buffer): string {+ const sheets = parseSpreadsheetSheets(buf);+ const sections: string[] = ['# Spreadsheet'];+ for (const sheet of sheets) {+ sections.push(`\n## ${sheet.name}`);+ for (let i = 0; i < sheet.rows.length; i++) {+ const row = sheet.rows[i];+ if (row.length) {+ sections.push(`Row ${i + 1}: ${row.join('\t')}`);+ }+ }+ }+ return `${sections.join('\n').trim()}\n`;+}++export function xlsxBufferToHtml(buf: Buffer): string {+ const sheets = parseSpreadsheetSheets(buf);+ return sheets.map((sheet) => {+ const maxCols = Math.max(0, ...sheet.rows.map((row) => row.length));+ const rows = sheet.rows.length+ ? sheet.rows.map((row) => (+ `<tr>${Array.from({ length: maxCols }, (_unused, i) => `<td>${escapeHtml(row[i] || '')}</td>`).join('')}</tr>`+ )).join('')+ : '<tr><td class="office-empty-cell">(empty sheet)</td></tr>';+ return [+ '<section class="office-sheet">',+ `<h2>${escapeHtml(sheet.name)}</h2>`,+ '<div class="office-table-wrap">',+ `<table><tbody>${rows}</tbody></table>`,+ '</div>',+ '</section>',+ ].join('');+ }).join('');+}++export function pptxBufferToMarkdown(buf: Buffer): string {+ const slides = parsePresentationSlides(buf);+ const sections: string[] = ['# Presentation'];+ for (const slide of slides) {+ sections.push(`\n## Slide ${slide.number}`);+ sections.push(slide.texts.length ? slide.texts.map((line) => `- ${line}`).join('\n') : '(no text)');+ }+ return `${sections.join('\n').trim()}\n`;+}++export function pptxBufferToHtml(buf: Buffer): string {+ const slides = parsePresentationSlides(buf);+ return slides.map((slide) => {+ const lines = slide.texts.length+ ? slide.texts.map((line) => `<p>${escapeHtml(line)}</p>`).join('')+ : '<p class="office-muted">(no text)</p>';+ return [+ `<section class="office-slide" aria-label="Slide ${slide.number}">`,+ '<div class="office-slide-body">',+ lines,+ '</div>',+ '</section>',+ ].join('');+ }).join('');+}diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.jsindex 2f316b05..26e02186 100644--- a/src/renderer/modules/chat-file-viewer.js+++ b/src/renderer/modules/chat-file-viewer.js@@ -9,6 +9,8 @@// image (.png/.jpg/.jpeg/.webp/.gif) → delegate to openChatImageLightbox// video (.mp4/.webm/.mov/.m4v/.ogv) → <video controls>// pdf (.pdf) → <iframe> + Chromium PDFium+// office(.docx/.docm/.xlsx/.xlsm/.pptx/.pptm)+// → readonly sandboxed HTML iframe// html (.html/.htm) → sandbox="allow-scripts" iframe// md (.md/.markdown) → mountMdViewEdit (markdown toolbar// only fires here — that's the@@ -59,6 +61,7 @@ let _viewerEditController = null;let _viewerDirty = false;let _viewerDiscardConfirmPending = false;let _viewerRenderSeq = 0;+let _viewerBlobUrl = null;const _viewerLog = (typeof createLogger === 'function')? createLogger('chat-file-viewer')@@ -76,6 +79,7 @@ function _viewerTrackError(action, data) {// something useful to do with it; otherwise the fallback is the better UX.const _IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);const _VIDEO_EXTS = new Set(['.mp4', '.webm', '.mov', '.m4v', '.ogv']);+const _OFFICE_EXTS = new Set(['.docx', '.docm', '.xlsx', '.xlsm', '.pptx', '.pptm']);const _MARKDOWN_EXTS = new Set(['.md', '.markdown']);// Text exts: the source-as-text bucket. Keep code-ish exts here too so the// user can peek at a generated script without leaving the app. No syntax@@ -107,6 +111,7 @@ function _kindOf(name) {if (_IMAGE_EXTS.has(ext)) return 'image';if (_VIDEO_EXTS.has(ext)) return 'video';if (ext === '.pdf') return 'pdf';+ if (_OFFICE_EXTS.has(ext)) return 'office';if (ext === '.html' || ext === '.htm') return 'html';if (_MARKDOWN_EXTS.has(ext)) return 'markdown';if (_TEXT_EXTS.has(ext)) return 'text';@@ -173,10 +178,10 @@ function _setSaveAppVisible(visible) {}function _viewerCanAddToLibrary(kind) {- // The Library index supports text/PDF/DOCX/images, but not video. Images- // are delegated to chat-lightbox before this shell opens; the guard here- // keeps the video preview from offering an action the backend rejects.- return kind !== 'video';+ // Images are delegated to chat-lightbox before this shell opens; the guard+ // here keeps unsupported inline previews from offering an action the+ // backend rejects.+ return kind !== 'video' && kind !== 'office';}function _isViewerOpen() {@@ -275,9 +280,18 @@ function _teardownViewerContent() {}_viewerEditController = null;_viewerDirty = false;+ if (_viewerBlobUrl) {+ try {+ if (typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {+ URL.revokeObjectURL(_viewerBlobUrl);+ }+ }+ catch (_) { /* non-fatal */ }+ _viewerBlobUrl = null;+ }if (_viewerBody) _viewerBody.innerHTML = '';if (_viewerMdActions) _viewerMdActions.innerHTML = '';- if (_viewerEl) _viewerEl.classList.remove('is-markdown', 'is-text');+ if (_viewerEl) _viewerEl.classList.remove('is-markdown', 'is-text', 'is-office');}function _typesetViewerMarkdown() {@@ -432,6 +446,7 @@ async function _openViewerShell(displayName, opts) {// for the per-class rules.if (opts && opts.kind === 'markdown') el.classList.add('is-markdown');if (opts && opts.kind === 'text') el.classList.add('is-text');+ if (opts && opts.kind === 'office') el.classList.add('is-office');el.classList.add('is-open');el.setAttribute('aria-hidden', 'false');if (!_viewerKeyHandler) {@@ -495,6 +510,51 @@ async function _renderHtmlBody(absPath, displayName, cid, projectId) {_viewerBody.innerHTML = `<iframe class="chat-file-viewer-html" sandbox="${sandbox}" src="${url}" title="${escapeHtml(displayName || '')}"></iframe>`;}+async function _renderOfficeBody(absPath, displayName, cid, projectId) {+ const seq = await _openViewerShell(displayName, { kind: 'office', absPath, cid, projectId });+ if (!seq) return;+ _viewerBody.innerHTML = `<div class="chat-file-viewer-loading">…</div>`;+ try {+ const payload = { path: absPath };+ if (cid) payload.cid = cid;+ if (projectId) payload.projectId = projectId;+ const res = await window.orkas.invoke('produced.officePreviewHtml', payload);+ if (seq !== _viewerRenderSeq || !_isViewerOpen()) return;+ if (!res || !res.ok) {+ const err = (res && res.error) || 'unknown';+ await closeChatFileViewer({ force: true });+ if (err === 'too_large') {+ const sizeMb = ((res && res.size) || 0) / 1024 / 1024;+ const capMb = ((res && res.cap) || 50 * 1024 * 1024) / 1024 / 1024;+ await _showUnsupportedDialog(absPath, cid, projectId, {+ messageKey: 'chat.preview_too_large_message',+ vars: { name: displayName || absPath.split(/[\\/]/).pop() || absPath, size: sizeMb.toFixed(1), cap: capMb.toFixed(0) },+ fallback: `File is ${sizeMb.toFixed(1)} MB (over the ${capMb.toFixed(0)} MB preview cap). Open the containing folder?`,+ });+ } else {+ await _showUnsupportedDialog(absPath, cid, projectId, {+ messageKey: 'chat.preview_read_failed_message',+ vars: { name: displayName || absPath.split(/[\\/]/).pop() || absPath },+ fallback: 'Could not read this file. Open the containing folder?',+ });+ }+ return;+ }+ const blob = new Blob([String(res.html || '')], { type: 'text/html;charset=utf-8' });+ _viewerBlobUrl = URL.createObjectURL(blob);+ _viewerBody.innerHTML = `<iframe class="chat-file-viewer-office" sandbox="" src="${_viewerBlobUrl}" title="${escapeHtml(displayName || '')}"></iframe>`;+ } catch (err) {+ if (seq !== _viewerRenderSeq) return;+ _viewerLog.warn('office preview threw', { path: absPath, error: String(err && err.message || err) });+ await closeChatFileViewer({ force: true });+ await _showUnsupportedDialog(absPath, cid, projectId, {+ messageKey: 'chat.preview_read_failed_message',+ vars: { name: displayName || absPath.split(/[\\/]/).pop() || absPath },+ fallback: 'Could not read this file. Open the containing folder?',+ });+ }+}+async function _renderVideoBody(absPath, displayName, cid, projectId) {if (!(await _openViewerShell(displayName, { kind: 'video', absPath, cid, projectId }))) return;const url = _chatMediaLocalUrl(absPath);@@ -696,6 +756,7 @@ async function openChatFileViewer(absPath, displayName, opts) {return;}if (kind === 'pdf') return _renderPdfBody(absPath, name, cid, projectId);+ if (kind === 'office') return _renderOfficeBody(absPath, name, cid, projectId);if (kind === 'video') return _renderVideoBody(absPath, name, cid, projectId);if (kind === 'html') return _renderHtmlBody(absPath, name, cid, projectId);if (kind === 'markdown') return _renderMarkdownBody(absPath, name, cid, projectId);diff --git a/src/renderer/modules/conversation-info.js b/src/renderer/modules/conversation-info.jsindex d537acab..8b529fad 100644--- a/src/renderer/modules/conversation-info.js+++ b/src/renderer/modules/conversation-info.js@@ -150,7 +150,10 @@ const ConversationInfo = (() => {if (['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(ext)) return 'image';if (['mp4', 'webm', 'mov', 'm4v', 'ogv'].includes(ext)) return 'video';if (ext === 'pdf') return 'pdf';- if (ext === 'docx') return 'docx';+ if (ext === 'docx' || ext === 'docm') return 'docx';+ if (ext === 'xlsx' || ext === 'xlsm') return 'spreadsheet';+ if (ext === 'pptx' || ext === 'pptm') return 'presentation';+ if (['doc', 'xls', 'ppt'].includes(ext)) return 'legacy_office';return 'text';}@@ -732,7 +735,9 @@ const ConversationInfo = (() => {const n = String(name || '').toLowerCase();if (kind === 'image' || /\.(png|jpe?g|gif|webp|svg)$/i.test(n)) return { cls: 'is-image', label: 'IMG' };if (kind === 'pdf' || /\.pdf$/i.test(n)) return { cls: '', label: 'PDF' };- if (/\.docx?$/i.test(n)) return { cls: 'is-doc', label: 'DOC' };+ if (/\.(docx?|docm)$/i.test(n)) return { cls: 'is-doc', label: 'DOC' };+ if (/\.(xlsx?|xlsm)$/i.test(n)) return { cls: 'is-doc', label: 'XLS' };+ if (/\.(pptx?|pptm)$/i.test(n)) return { cls: 'is-doc', label: 'PPT' };if (/\.(md|markdown|txt|csv|tsv|json|yaml|yml|log)$/i.test(n)) return { cls: 'is-doc', label: (n.split('.').pop() || 'TXT').slice(0, 4).toUpperCase() };return { cls: 'is-doc', label: 'FILE' };}diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex 0434e7b3..b11159ed 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -1850,7 +1850,7 @@ const DRAFT_CID = 'main_chat';const CHAT_ATTACH_ACCEPT = ['.md', '.markdown', '.txt', '.csv', '.tsv', '.json', '.yaml', '.yml', '.log',- '.pdf', '.docx',+ '.pdf', '.docx', '.docm', '.xlsx', '.xlsm', '.pptx', '.pptm','.png', '.jpg', '.jpeg', '.webp', '.gif','.mp4', '.webm', '.mov', '.m4v', '.ogv',];@@ -1873,7 +1873,9 @@ function _chatAttachKindFromExt(ext) {if (CHAT_IMAGE_EXTS.includes(ext)) return 'image';if (CHAT_VIDEO_EXTS.includes(ext)) return 'video';if (ext === '.pdf') return 'pdf';- if (ext === '.docx') return 'docx';+ if (ext === '.docx' || ext === '.docm') return 'docx';+ if (ext === '.xlsx' || ext === '.xlsm') return 'spreadsheet';+ if (ext === '.pptx' || ext === '.pptm') return 'presentation';return 'text';}@@ -1901,7 +1903,9 @@ function _chatAttachPayload(cid, files, source) {total_bytes: totalBytes,image_count: kinds.image || 0,video_count: kinds.video || 0,- document_count: (kinds.pdf || 0) + (kinds.docx || 0),+ document_count:+ (kinds.pdf || 0) + (kinds.docx || 0) + (kinds.spreadsheet || 0)+ + (kinds.presentation || 0),text_count: kinds.text || 0,};}@@ -2401,7 +2405,7 @@ function _renderMessageAttachmentsHtml(names, cid) {// Files written by the LLM via write_file / markdown_to_pdf / html_to_pdf.// Chips use the same visual language as attachments; clicking opens an// in-app preview overlay (chat-file-viewer.js) that renders the file's-// final form (PDF / HTML / markdown / text) or falls through to a dialog+// final form (PDF / Office / HTML / markdown / text) or falls through to a dialog// offering "open the containing folder" for unsupported kinds.function _iconForProduced(name) {@@ -2608,7 +2612,7 @@ function _showFileMissingToast(name) {function _hydrateMessageAttachmentThumbs(msgDiv, cid) {// Image chips have a thumb we want to enlarge via the lightbox; the rest- // (pdf / docx / text / video) get the same kind-aware viewer as produced+ // (pdf / office / text / video) get the same kind-aware viewer as produced// chips. Video chips have inline <video> controls in the bubble already,// so clicking the chip body shouldn't re-open the same playback — skip// them. We rely on `_chatMediaUrl(cid, name)` having loaded the bytes fordiff --git a/src/renderer/modules/icons.js b/src/renderer/modules/icons.jsindex bd4d097e..882bc959 100644--- a/src/renderer/modules/icons.js+++ b/src/renderer/modules/icons.js@@ -8,7 +8,7 @@const VIDEO_EXTS = new Set(['mp4', 'webm', 'mov', 'm4v', 'ogv', 'avi', 'mkv']);const AUDIO_EXTS = new Set(['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac']);const TEXT_EXTS = new Set(['md', 'markdown', 'txt', 'log', 'rst', 'tex']);- const DATA_EXTS = new Set(['json', 'yaml', 'yml', 'toml', 'csv', 'tsv', 'xlsx', 'xls', 'xml', 'ini', 'conf']);+ const DATA_EXTS = new Set(['json', 'yaml', 'yml', 'toml', 'csv', 'tsv', 'xlsx', 'xlsm', 'xls', 'xml', 'ini', 'conf']);const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar']);const CODE_EXTS = new Set(['py', 'pyi', 'ipynb',@@ -121,13 +121,14 @@const raw = String(kind || '').toLowerCase();if (raw === 'docx' || raw === 'doc') return 'doc';if (raw === 'spreadsheet') return 'data';+ if (raw === 'presentation' || raw === 'legacy_office') return 'doc';if (raw === 'binary') return 'file';if (['image', 'video', 'audio', 'pdf', 'doc', 'text', 'data', 'archive', 'code', 'file'].includes(raw)) return raw;if (IMAGE_EXTS.has(ext)) return 'image';if (VIDEO_EXTS.has(ext)) return 'video';if (AUDIO_EXTS.has(ext)) return 'audio';if (ext === 'pdf') return 'pdf';- if (ext === 'docx' || ext === 'doc') return 'doc';+ if (ext === 'docx' || ext === 'docm' || ext === 'doc' || ext === 'pptx' || ext === 'pptm' || ext === 'ppt') return 'doc';if (TEXT_EXTS.has(ext)) return 'text';if (DATA_EXTS.has(ext)) return 'data';if (ARCHIVE_EXTS.has(ext)) return 'archive';diff --git a/src/renderer/style.css b/src/renderer/style.cssindex e1d9bcaa..18a8a7d1 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -5378,15 +5378,19 @@ body.model-not-configured .main-content { flex-direction: column; }overflow: auto;background: #fff;}+.chat-file-viewer.is-office .chat-file-viewer-body {+ background: #eef2f7;+}.chat-file-viewer.is-markdown .chat-file-viewer-body {display: flex;flex-direction: column;overflow: hidden;}-/* iframe-based body (pdf / html) fills the body slot. The body itself+/* iframe-based body (pdf / html / office) fills the body slot. The body itselfhandles scroll for non-iframe bodies (md / text). */.chat-file-viewer-pdf,-.chat-file-viewer-html {+.chat-file-viewer-html,+.chat-file-viewer-office {width: 100%;height: 100%;border: none;diff --git a/test/fixtures/make-minimal-office.ts b/test/fixtures/make-minimal-office.tsnew file mode 100644index 00000000..5caff121--- /dev/null+++ b/test/fixtures/make-minimal-office.ts@@ -0,0 +1,100 @@+import AdmZip from 'adm-zip';++function escapeXml(s: string): string {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function addText(zip: AdmZip, name: string, text: string): void {+ zip.addFile(name, Buffer.from(text, 'utf8'));+}++export function makeMinimalXlsx(opts: { sheetName?: string; rows?: string[][] } = {}): Buffer {+ const sheetName = opts.sheetName ?? 'Sheet1';+ const rows = opts.rows ?? [+ ['Name', 'Score'],+ ['Alice', '42'],+ ];+ const strings = rows.flat();+ const sharedStrings = strings+ .map((s) => `<si><t>${escapeXml(s)}</t></si>`)+ .join('');+ let sharedIndex = 0;+ const rowXml = rows.map((row, rIdx) => {+ const cells = row.map((_, cIdx) => {+ const col = String.fromCharCode(65 + cIdx);+ return `<c r="${col}${rIdx + 1}" t="s"><v>${sharedIndex++}</v></c>`;+ }).join('');+ return `<row r="${rIdx + 1}">${cells}</row>`;+ }).join('');++ const zip = new AdmZip();+ addText(zip, '[Content_Types].xml', `<?xml version="1.0" encoding="UTF-8"?>+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>+ <Default Extension="xml" ContentType="application/xml"/>+ <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>+ <Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>+ <Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>+</Types>`);+ addText(zip, '_rels/.rels', `<?xml version="1.0" encoding="UTF-8"?>+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>+</Relationships>`);+ addText(zip, 'xl/workbook.xml', `<?xml version="1.0" encoding="UTF-8"?>+<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">+ <sheets><sheet name="${escapeXml(sheetName)}" sheetId="1" r:id="rId1"/></sheets>+</workbook>`);+ addText(zip, 'xl/_rels/workbook.xml.rels', `<?xml version="1.0" encoding="UTF-8"?>+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>+</Relationships>`);+ addText(zip, 'xl/sharedStrings.xml', `<?xml version="1.0" encoding="UTF-8"?>+<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${strings.length}" uniqueCount="${strings.length}">+ ${sharedStrings}+</sst>`);+ addText(zip, 'xl/worksheets/sheet1.xml', `<?xml version="1.0" encoding="UTF-8"?>+<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">+ <sheetData>${rowXml}</sheetData>+</worksheet>`);+ return zip.toBuffer();+}++export function makeMinimalPptx(opts: { slides?: string[][] } = {}): Buffer {+ const slides = opts.slides ?? [+ ['Quarterly Review', 'Revenue grew 12%'],+ ];+ const zip = new AdmZip();+ addText(zip, '[Content_Types].xml', `<?xml version="1.0" encoding="UTF-8"?>+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>+ <Default Extension="xml" ContentType="application/xml"/>+ <Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>+ ${slides.map((_, i) => `<Override PartName="/ppt/slides/slide${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>`).join('\n ')}+</Types>`);+ addText(zip, '_rels/.rels', `<?xml version="1.0" encoding="UTF-8"?>+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>+</Relationships>`);+ addText(zip, 'ppt/presentation.xml', `<?xml version="1.0" encoding="UTF-8"?>+<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">+ <p:sldIdLst>${slides.map((_, i) => `<p:sldId id="${256 + i}" r:id="rId${i + 1}"/>`).join('')}</p:sldIdLst>+</p:presentation>`);+ addText(zip, 'ppt/_rels/presentation.xml.rels', `<?xml version="1.0" encoding="UTF-8"?>+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">+ ${slides.map((_, i) => `<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide${i + 1}.xml"/>`).join('\n ')}+</Relationships>`);+ slides.forEach((texts, i) => {+ const runs = texts+ .map((text) => `<a:p><a:r><a:t>${escapeXml(text)}</a:t></a:r></a:p>`)+ .join('');+ addText(zip, `ppt/slides/slide${i + 1}.xml`, `<?xml version="1.0" encoding="UTF-8"?>+<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">+ <p:cSld><p:spTree><p:sp><p:txBody>${runs}</p:txBody></p:sp></p:spTree></p:cSld>+</p:sld>`);+ });+ return zip.toBuffer();+}diff --git a/test/main/features/chat_attachments.test.ts b/test/main/features/chat_attachments.test.tsindex 4e3540a9..a28dea1f 100644--- a/test/main/features/chat_attachments.test.ts+++ b/test/main/features/chat_attachments.test.ts@@ -5,6 +5,7 @@ import * as path from 'node:path';import { makeMinimalPdf } from '../../fixtures/make-minimal-pdf';import { makeMinimalDocx } from '../../fixtures/make-minimal-docx';+import { makeMinimalXlsx, makeMinimalPptx } from '../../fixtures/make-minimal-office';const UID = 'u-attach-001';const CID = 'conv-123';@@ -71,6 +72,39 @@ describe('chat_attachments › uploadAttachment', () => {expect(siblings).toEqual([]);});+ it('stores modern Office files without pre-extracting', async () => {+ const m = await loadMod();+ const docm = await m.uploadAttachment(UID, CID, 'macro.docm', makeMinimalDocx({ heading: 'Macro', paragraphs: ['Docm body.'] }));+ const sheet = await m.uploadAttachment(UID, CID, 'scores.xlsx', makeMinimalXlsx());+ const deck = await m.uploadAttachment(UID, CID, 'slides.pptx', makeMinimalPptx());+ const macroSheet = await m.uploadAttachment(UID, CID, 'scores.xlsm', makeMinimalXlsx({ rows: [['Kind'], ['Macro sheet']] }));+ const macroDeck = await m.uploadAttachment(UID, CID, 'slides.pptm', makeMinimalPptx({ slides: [['Macro deck']] }));++ expect(docm.ok && sheet.ok && deck.ok && macroSheet.ok && macroDeck.ok).toBe(true);+ if (!(docm.ok && sheet.ok && deck.ok && macroSheet.ok && macroDeck.ok)) return;+ expect(docm.info.kind).toBe('docx');+ expect(sheet.info.kind).toBe('spreadsheet');+ expect(deck.info.kind).toBe('presentation');+ expect(macroSheet.info.kind).toBe('spreadsheet');+ expect(macroDeck.info.kind).toBe('presentation');+ const siblings = fs.readdirSync(attDir()).filter((n) => n.startsWith('.'));+ expect(siblings).toEqual([]);+ });++ it('rejects legacy Office binary formats before they enter the attachment pool', async () => {+ const m = await loadMod();+ const doc = await m.uploadAttachment(UID, CID, 'old.doc', Buffer.from('legacy'));+ const xls = await m.uploadAttachment(UID, CID, 'old.xls', Buffer.from('legacy'));+ const ppt = await m.uploadAttachment(UID, CID, 'old.ppt', Buffer.from('legacy'));++ expect(doc.ok).toBe(false);+ expect(xls.ok).toBe(false);+ expect(ppt.ok).toBe(false);+ expect(fs.existsSync(path.join(attDir(), 'old.doc'))).toBe(false);+ expect(fs.existsSync(path.join(attDir(), 'old.xls'))).toBe(false);+ expect(fs.existsSync(path.join(attDir(), 'old.ppt'))).toBe(false);+ });+it('stores image without any sibling cache (preview generated on read)', async () => {const m = await loadMod();const png = await makePng();@@ -683,6 +717,22 @@ describe('chat_attachments › buildAttachmentManifest', () => {expect(r.manifest).not.toContain('chunks=');});+ it('emits modern Office entries WITHOUT total_chars when never extracted', async () => {+ const m = await loadMod();+ await m.uploadAttachment(UID, CID, 'scores.xlsx', makeMinimalXlsx({ rows: [['Name'], ['Ada']] }));+ await m.uploadAttachment(UID, CID, 'slides.pptx', makeMinimalPptx({ slides: [['Roadmap']] }));++ const r = await m.buildAttachmentManifest(UID, CID, ['scores.xlsx', 'slides.pptx']);++ expect(r.manifest).toContain('name="scores.xlsx"');+ expect(r.manifest).toContain('kind="spreadsheet"');+ expect(r.manifest).not.toMatch(/scores\.xlsx[^>]*total_chars=/);+ expect(r.manifest).toContain('name="slides.pptx"');+ expect(r.manifest).toContain('kind="presentation"');+ expect(r.manifest).not.toMatch(/slides\.pptx[^>]*total_chars=/);+ expect(r.skipped).toEqual([]);+ });+it('emits PDF entry WITH total_chars when cache already exists', async () => {const m = await loadMod();const indexer = await import('../../../src/main/features/file_indexer');@@ -695,6 +745,33 @@ describe('chat_attachments › buildAttachmentManifest', () => {expect(r.manifest).toMatch(/cached\.pdf[^>]*total_chars="\d+"/);});+ it('emits modern Office entries WITH total_chars when cache already exists', async () => {+ const m = await loadMod();+ const indexer = await import('../../../src/main/features/file_indexer');+ const { chatAttachmentDir } = await import('../../../src/main/paths');+ await m.uploadAttachment(UID, CID, 'cached.xlsx', makeMinimalXlsx({ rows: [['Name'], ['Ada']] }));+ await m.uploadAttachment(UID, CID, 'cached.pptx', makeMinimalPptx({ slides: [['Roadmap']] }));+ await indexer.statFile(UID, path.join(chatAttachmentDir(UID, CID), 'cached.xlsx'));+ await indexer.statFile(UID, path.join(chatAttachmentDir(UID, CID), 'cached.pptx'));++ const r = await m.buildAttachmentManifest(UID, CID, ['cached.xlsx', 'cached.pptx']);++ expect(r.manifest).toMatch(/cached\.xlsx[^>]*total_chars="\d+"/);+ expect(r.manifest).toMatch(/cached\.pptx[^>]*total_chars="\d+"/);+ });++ it('skips legacy Office names if a stale caller tries to build a manifest for them', async () => {+ const m = await loadMod();++ const r = await m.buildAttachmentManifest(UID, CID, ['old.xls']);++ expect(r.manifest).toBe('');+ expect(r.images).toEqual([]);+ expect(r.skipped).toHaveLength(1);+ expect(r.skipped[0].name).toBe('old.xls');+ expect(r.skipped[0].reason).toMatch(/unsupported|不支持|未対応/i);+ });+it('skips video attachments entirely — manifest empty, images empty, one skipped entry', async () => {const m = await loadMod();await m.uploadAttachment(UID, CID, 'clip.mp4', Buffer.from('fake-bytes'));diff --git a/test/main/model/core-agent/file-tools.test.ts b/test/main/model/core-agent/file-tools.test.tsindex fb319d64..c0d003bb 100644--- a/test/main/model/core-agent/file-tools.test.ts+++ b/test/main/model/core-agent/file-tools.test.ts@@ -5,6 +5,7 @@ import * as path from 'node:path';import { makeMinimalPdf } from '../../../fixtures/make-minimal-pdf';import { makeMinimalDocx } from '../../../fixtures/make-minimal-docx';+import { makeMinimalXlsx, makeMinimalPptx } from '../../../fixtures/make-minimal-office';const UID = 'u-ftools-001';const CID = 'conv-x';@@ -95,7 +96,7 @@ describe('file-tools › read_file (text)', () => {});});-describe('file-tools › read_file (pdf/docx requires stat_file first)', () => {+describe('file-tools › read_file (rich documents require stat_file first)', () => {it('returns E_NEED_STAT when pdf has never been stated', async () => {const { tools, wsDir } = await buildTools();const p = path.join(wsDir, 'fresh.pdf');@@ -105,6 +106,15 @@ describe('file-tools › read_file (pdf/docx requires stat_file first)', () => {expect(r.content).toContain('E_NEED_STAT');});+ it('returns E_NEED_STAT when xlsx has never been stated', async () => {+ const { tools, wsDir } = await buildTools();+ const p = path.join(wsDir, 'fresh.xlsx');+ fs.writeFileSync(p, makeMinimalXlsx({ rows: [['Name'], ['Ada']] }));+ const r = await run(getTool(tools, 'read_file'), { path: p });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_NEED_STAT');+ });+it('reads pdf after stat_file', async () => {const { tools, wsDir } = await buildTools();const p = path.join(wsDir, 'deck.pdf');@@ -132,6 +142,43 @@ describe('file-tools › read_file (pdf/docx requires stat_file first)', () => {expect(r.isError).toBeFalsy();expect(r.content).toContain('covered="0-4"');});++ it('reads xlsx after stat_file', async () => {+ const { tools, wsDir } = await buildTools();+ const p = path.join(wsDir, 'scores.xlsx');+ fs.writeFileSync(p, makeMinimalXlsx({ sheetName: 'Scores', rows: [['Name', 'Score'], ['Ada', '99']] }));+ const s = await run(getTool(tools, 'stat_file'), { path: p });+ expect(s.isError).toBeFalsy();+ expect(s.content).toContain('kind="spreadsheet"');++ const r = await run(getTool(tools, 'read_file'), { path: p });+ expect(r.isError).toBeFalsy();+ expect(r.content).toContain('Row 1: Name\tScore');+ expect(r.content).toContain('Row 2: Ada\t99');+ });++ it('reads pptx after stat_file', async () => {+ const { tools, wsDir } = await buildTools();+ const p = path.join(wsDir, 'slides.pptx');+ fs.writeFileSync(p, makeMinimalPptx({ slides: [['Roadmap', 'Launch in June']] }));+ const s = await run(getTool(tools, 'stat_file'), { path: p });+ expect(s.isError).toBeFalsy();+ expect(s.content).toContain('kind="presentation"');++ const r = await run(getTool(tools, 'read_file'), { path: p });+ expect(r.isError).toBeFalsy();+ expect(r.content).toContain('- Roadmap');+ expect(r.content).toContain('- Launch in June');+ });++ it('returns E_UNSUPPORTED_FILE for legacy Office formats', async () => {+ const { tools, wsDir } = await buildTools();+ const p = path.join(wsDir, 'legacy.xls');+ fs.writeFileSync(p, Buffer.from('legacy'));+ const r = await run(getTool(tools, 'stat_file'), { path: p });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_UNSUPPORTED_FILE');+ });});describe('file-tools › read_file (image)', () => {@@ -255,6 +302,24 @@ describe('file-tools › stat_file', () => {expect(r.content).toMatch(/total_chars="\d+"/);});+ it('extracts xlsx and pptx and returns total_chars', async () => {+ const { tools, wsDir } = await buildTools();+ const sheet = path.join(wsDir, 'scores.xlsx');+ const deck = path.join(wsDir, 'slides.pptx');+ fs.writeFileSync(sheet, makeMinimalXlsx({ rows: [['Name'], ['Ada']] }));+ fs.writeFileSync(deck, makeMinimalPptx({ slides: [['Roadmap']] }));++ const s1 = await run(getTool(tools, 'stat_file'), { path: sheet });+ const s2 = await run(getTool(tools, 'stat_file'), { path: deck });++ expect(s1.isError).toBeFalsy();+ expect(s1.content).toContain('kind="spreadsheet"');+ expect(s1.content).toMatch(/total_chars="\d+"/);+ expect(s2.isError).toBeFalsy();+ expect(s2.content).toContain('kind="presentation"');+ expect(s2.content).toMatch(/total_chars="\d+"/);+ });+it('returns E_NO_TEXT for image kind', async () => {const { tools, wsDir } = await buildTools();const p = path.join(wsDir, 'chart.png');@@ -379,6 +444,17 @@ describe('file-tools › grep_files', () => {expect(r.content).toContain('Termination');});+ it('extracts xlsx/pptx on cache-miss then greps', async () => {+ const { tools, wsDir } = await buildTools();+ fs.writeFileSync(path.join(wsDir, 'scores.xlsx'), makeMinimalXlsx({ rows: [['Name'], ['Banana KPI']] }));+ fs.writeFileSync(path.join(wsDir, 'slides.pptx'), makeMinimalPptx({ slides: [['Roadmap Banana']] }));+ const r = await run(getTool(tools, 'grep_files'), { pattern: 'Banana' });+ expect(r.isError).toBeFalsy();+ expect(r.content).toContain('scores.xlsx');+ expect(r.content).toContain('slides.pptx');+ expect(r.content).toContain('Banana');+ });+it('rejects invalid regex under regex=true', async () => {const { tools } = await buildTools();const r = await run(getTool(tools, 'grep_files'), { pattern: '(', regex: true });diff --git a/test/main/util/extract-office.test.ts b/test/main/util/extract-office.test.tsnew file mode 100644index 00000000..fe4b928e--- /dev/null+++ b/test/main/util/extract-office.test.ts@@ -0,0 +1,84 @@+import { describe, it, expect } from 'vitest';++import {+ xlsxBufferToHtml,+ xlsxBufferToMarkdown,+ pptxBufferToHtml,+ pptxBufferToMarkdown,+} from '../../../src/main/util/extract-office';+import { makeMinimalXlsx, makeMinimalPptx } from '../../fixtures/make-minimal-office';++describe('extract-office › xlsxBufferToMarkdown', () => {+ it('extracts shared-string worksheet rows', () => {+ const md = xlsxBufferToMarkdown(makeMinimalXlsx({+ sheetName: 'Scores',+ rows: [+ ['Name', 'Score'],+ ['Ada', '99'],+ ],+ }));++ expect(md).toContain('# Spreadsheet');+ expect(md).toContain('## Scores');+ expect(md).toContain('Row 1: Name\tScore');+ expect(md).toContain('Row 2: Ada\t99');+ });++ it('rejects empty buffers', () => {+ expect(() => xlsxBufferToMarkdown(Buffer.alloc(0))).toThrow(/empty|invalid/i);+ });+});++describe('extract-office › xlsxBufferToHtml', () => {+ it('renders worksheet rows as escaped table HTML', () => {+ const html = xlsxBufferToHtml(makeMinimalXlsx({+ sheetName: 'Scores & Totals',+ rows: [+ ['Name', 'Score'],+ ['Ada <admin>', '99'],+ ],+ }));++ expect(html).toContain('class="office-sheet"');+ expect(html).toContain('<table>');+ expect(html).toContain('Scores & Totals');+ expect(html).toContain('Ada <admin>');+ });+});++describe('extract-office › pptxBufferToMarkdown', () => {+ it('extracts slide text nodes', () => {+ const md = pptxBufferToMarkdown(makeMinimalPptx({+ slides: [+ ['Roadmap', 'Launch in June'],+ ['Risks', 'Capacity'],+ ],+ }));++ expect(md).toContain('# Presentation');+ expect(md).toContain('## Slide 1');+ expect(md).toContain('- Roadmap');+ expect(md).toContain('- Launch in June');+ expect(md).toContain('## Slide 2');+ expect(md).toContain('- Risks');+ });++ it('rejects empty buffers', () => {+ expect(() => pptxBufferToMarkdown(Buffer.alloc(0))).toThrow(/empty|invalid/i);+ });+});++describe('extract-office › pptxBufferToHtml', () => {+ it('renders slide text as escaped readonly sections', () => {+ const html = pptxBufferToHtml(makeMinimalPptx({+ slides: [+ ['Roadmap', 'Launch <June>'],+ ],+ }));++ expect(html).toContain('class="office-slide"');+ expect(html).toContain('aria-label="Slide 1"');+ expect(html).toContain('<p>Roadmap</p>');+ expect(html).toContain('Launch <June>');+ });+});diff --git a/test/renderer/chat-file-viewer.test.ts b/test/renderer/chat-file-viewer.test.tsindex 682c9e33..b721b016 100644--- a/test/renderer/chat-file-viewer.test.ts+++ b/test/renderer/chat-file-viewer.test.ts@@ -25,6 +25,12 @@ describe('chat-file-viewer › _kindOf', () => {['art.webp', 'image'],['art.gif', 'image'],['report.pdf', 'pdf'],+ ['doc.docx', 'office'],+ ['macro.docm', 'office'],+ ['workbook.xlsx', 'office'],+ ['sheet.xlsm', 'office'],+ ['slides.pptx', 'office'],+ ['deck.pptm', 'office'],['page.html', 'html'],['old.htm', 'html'],['note.md', 'markdown'],@@ -46,9 +52,9 @@ describe('chat-file-viewer › _kindOf', () => {// "html-ish" → html when the actual ext doesn't match.it.each([['archive.zip', 'unsupported'],- ['workbook.xlsx', 'unsupported'],- ['slides.pptx', 'unsupported'],- ['doc.docx', 'unsupported'], // we deliberately don't preview docx in this round+ ['legacy.doc', 'unsupported'],+ ['legacy.xls', 'unsupported'],+ ['legacy.ppt', 'unsupported'],['binary.exe', 'unsupported'],['photo.heic', 'unsupported'], // image-ish but not in the allow-list['no-extension', 'unsupported'],@@ -61,6 +67,7 @@ describe('chat-file-viewer › _kindOf', () => {it('is case-insensitive on the extension portion', () => {expect(_kindOf('REPORT.PDF')).toBe('pdf');+ expect(_kindOf('REPORT.XLSX')).toBe('office');expect(_kindOf('Note.MD')).toBe('markdown');expect(_kindOf('Page.Html')).toBe('html');});@@ -105,8 +112,9 @@ describe('chat-file-viewer › _chatMediaLocalUrl', () => {});describe('chat-file-viewer › _viewerCanAddToLibrary', () => {- it('does not offer Add to Library for video previews', () => {+ it('does not offer Add to Library for video or office previews', () => {expect(_viewerCanAddToLibrary('video')).toBe(false);+ expect(_viewerCanAddToLibrary('office')).toBe(false);});it('keeps Add to Library available for supported preview kinds', () => {