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
Preserve bounded Office extraction and native review rendering
wyt5089e528aa3c
diff --git a/docs/test/office-worker-regression.md b/docs/test/office-worker-regression.mdindex 70ba9cc9..2c0e13db 100644--- a/docs/test/office-worker-regression.md+++ b/docs/test/office-worker-regression.md@@ -28,15 +28,34 @@ Run this checklist when the Office agent, Office skills, built-in Office tools,Run from the repository root:```bash-npm run test:js -- test/main/model/core-agent/office-tools.test.ts test/main/model/core-agent/pdf-tools.test.ts test/main/model/core-agent/office-batch.test.ts test/main/model/core-agent/office-arg.test.ts test/main/features/office/office_engine.test.ts+node scripts/run-tests.mjs run test/main/model/core-agent/office-tools.test.ts test/main/model/core-agent/pdf-tools.test.ts test/main/model/core-agent/office-batch.test.ts test/main/model/core-agent/office-arg.test.ts test/main/features/office/office_engine.test.ts test/main/util/officecli-fetch.test.ts test/main/model/core-agent/tool-catalog.test.ts test/main/avatar-catalogs.test.ts test/renderer/conversation-failed-retry.test.tsnpm run test:office-artifacts+node scripts/run-tests.mjs run test/main/features/office/office-readonly_e2e.test.ts```+`office-tools.test.ts` additionally treats `office_review` as one lifecycle:+unknown actions must invoke neither validation nor rendering; `check_and_render`+must stop before rendering on invalid OpenXML; a multi-page render with one+failed page must retain successful page evidence while returning an overall+failure, so callers can repair or retry without a false all-pages success.++`office-readonly_e2e.test.ts` runs the real bundled engine and embedded Chromium+through `office_review` and `edit_office`. Its five scenarios cover combined+check/render, a missing page followed by a successful retry, cancellation after+a completed issue scan, invalid OpenXML, and an intentional edit followed by+review of the saved copy. They verify source bytes/mtime, receipt hashes, decoded+PNG content, resident/window cleanup, and absence of write registrations during+review. The missing-page and cancellation scenarios each assert one expected+render warning; other application/browser logs and command stderr fail the run.+The fixture replaces only the log sink and observes real command completion+to trigger cancellation; it does not stub engine results or Chromium rendering.+Run these cases after artifact provisioning.+## Real Binary Smoke-`npm run test:office-artifacts` automates steps 1-6, verifies real HTML-path-PNG renders, and generates the seven production-evaluation input fixtures on-the current macOS/Windows host. It checks every fixture source hash before+`npm run test:office-artifacts` automates steps 1-6 and 10, validates browserless+HTML previews, and generates the seven production-evaluation input fixtures on+the current supported host. It checks every fixture source hash beforecleanup. It is a required cross-platform CI gate. Set`ORKAS_KEEP_OFFICE_SMOKE_ARTIFACTS=1` to retain successful output for manualvisual review.@@ -47,17 +66,46 @@ Use a temporary directory and the current-platform binary.2. Create one Chinese DOCX, XLSX, and PPTX through `create` plus a batch file.3. Read each through `view text` or `view outline` and confirm Chinese text and element paths.4. Run a successful multi-operation batch and confirm every change.-5. Run a batch containing one invalid operation and confirm v1.0.139 atomic rollback leaves the file byte-identical.+5. Run a batch containing one invalid operation and confirm atomic rollback leaves the file byte-identical.6. Run `validate` and `view issues --json` on every output.-7. Render representative pages/slides with `view ... screenshot`; inspect for missing CJK glyphs, clipping, and obvious overlap.+7. Render representative pages/slides with `view ... html` and inspect them through the embedded Electron preview for missing CJK glyphs, clipping, and obvious overlap.8. Seed the reviewed DOCX, identifier CSV, XLSM boundary package, reviewedPPTX, mixed-delivery CSV, WPS boundary file, and four-page PDF used byProduction E2E; verify that integrity inspection leaves every sourcebyte-identical.-9. Repeat the artifact and render checks on macOS and Windows before a release that changes the OfficeCLI pin.+9. Repeat the artifact and render checks on macOS, Windows and Linux before a release that changes the OfficeCLI pin. Record platform-specific gaps separately.+10. Build DOCX inputs independently of OfficeCLI, including compressed XML+ and spaced `<w:br />` / `<w:tab />` elements. Run `office_review check`+ twice, `office_read`, and the browserless HTML preview on fresh inputs;+ require unchanged source bytes/mtime and check receipts matching the+ final source hash. Confirm a normal edit still persists after reopen,+ and unversioned batch text newlines remain soft line breaks.Do not use a successful process exit as the only delivery signal. Preserve validation/issue output and visually inspect the rendered image.+## Agent delivery journeys++Exercise the shipped OfficeWorker with isolated workspace fixtures: edit an+existing contract without changing its original, preserve identifier strings+from CSV in an XLSX, prepare and revise an existing presentation, and deliver+mixed document/spreadsheet/presentation outputs. Seed the reviewed DOCX,+identifier CSV, XLSM boundary package, reviewed PPTX, mixed-delivery CSV, WPS+boundary file and four-page PDF. Verify source hashes, expected output count,+package structure and saved content independently of the Agent's final prose.++A failed generation or invalid tool input must remain a failure until the+actual output files have been verified. After a corrected explicit request,+confirm recovery produces usable files and does not publish a placeholder or+mistake seeded input for a new output. Model quality checks require their own+authorized run; these scenarios do not claim a model pass in this build.++For unsupported `.xlsm` and proprietary WPS inputs, the Agent must load the+matching Skill and `stat_file` the actual source before returning the complete+capability boundary through the group handback protocol. The Commander+continuation treats that report as authoritative: it must not search for a+shell/process conversion, publish an empty or placeholder output, or retry the+same unsupported operation through another actor.+## Source-Safety And Fault CasesThe focused Office tool suite must prove all of the following independently:diff --git a/scripts/fetch-officecli.cjs b/scripts/fetch-officecli.cjsindex daa64922..81eefb73 100644--- a/scripts/fetch-officecli.cjs+++ b/scripts/fetch-officecli.cjs@@ -44,7 +44,7 @@ const https = require('node:https');const crypto = require('node:crypto');const { spawnSync } = require('node:child_process');-const VERSION = 'v1.0.139';+const VERSION = 'v1.0.142';const REPO = 'iOfficeAI/OfficeCLI';const RELEASE_BASE_URL = process.env.OFFICECLI_RELEASE_BASE_URL || `https://github.com/${REPO}/releases/download/${VERSION}`;const LICENSE_URL = process.env.OFFICECLI_LICENSE_URL || `https://raw.githubusercontent.com/${REPO}/${VERSION}/LICENSE`;@@ -66,12 +66,12 @@ const ASSETS = {// Pinned sha256 for VERSION (from the release SHA256SUMS). Update with VERSION.const SHA256 = {- 'officecli-linux-x64': 'da07d4f787d7c85724104294ac023c89971ddfaee93ebb183b289282b8f869cc',- 'officecli-linux-arm64': '39008c7f76d202858637810553ef14e2cd3e7f61485fdcf2011f26967a7babd1',- 'officecli-mac-arm64': '393874f79db58222bdbede7f4f942f2536580386923857d1b5ad9754efe80c19',- 'officecli-mac-x64': '6a931d424975dded6ae413c8c1f63d00dfb30a4bd4bd50352964782d13299f5c',- 'officecli-win-x64.exe': '864e0580c8e8c91a6aa4a4c1e8900551c8d4aa648ff10136ceed3a6ba5310888',- 'officecli-win-arm64.exe': '6d80a93ba0c9cafb2b52048efbb403cd761b35126130fa8166383599aa91d96e',+ 'officecli-linux-x64': 'f78563abc13cf70dcd420644019d2f11dc36ea2957ac738613a6911d652b5541',+ 'officecli-linux-arm64': '260cdccd27f2e25902e9436e5e971c0ca5348ae3d36a54a3fbd794c452ba13f7',+ 'officecli-mac-arm64': '684ce214bb8d750003d521eea044a9199bcbdb870817dba5d3191b35715ea38c',+ 'officecli-mac-x64': 'd2d27d8203ec8fc178a6a55eb4ce0ca63696e4ceddb7f85eab359da77f343a91',+ 'officecli-win-x64.exe': '676e0acee691288968a31b9832299ad05599e83140e801c382b6fc4509622fe2',+ 'officecli-win-arm64.exe': '0926428513e15f2d1c6eb726a07b141f7f31d60360226daa7526e518213d3578',};function parseArgs(argv) {diff --git a/scripts/run-office-artifact-smoke.mjs b/scripts/run-office-artifact-smoke.mjsindex 97ae7652..4b7076cf 100644--- a/scripts/run-office-artifact-smoke.mjs+++ b/scripts/run-office-artifact-smoke.mjs@@ -12,9 +12,12 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import AdmZip from 'adm-zip';+import foreignDocxFixture from '../test/fixtures/office/foreign-docx.cjs';import officeCliPin from './fetch-officecli.cjs';import officeCliPolicy from '../bin/officecli-policy-gate.cjs';+const { foreignDocxBytes } = foreignDocxFixture;+const here = path.dirname(fileURLToPath(import.meta.url));const pcRoot = path.resolve(here, '..');const expectedVersion = officeCliPin.VERSION.replace(/^v/, '');@@ -142,6 +145,46 @@ function validateAndInspect(binary, file, expectedText, renderedHtml, renderArgscloseFile(binary, file);}++async function assertReadOnlyDocx(binary, officeReview, officeRead, root) {+ for (const spacedBreaks of [false, true]) {+ const original = foreignDocxBytes(spacedBreaks);+ for (const surface of ['check', 'read', 'preview']) {+ const label = `foreign-${spacedBreaks ? 'spaced-breaks' : 'compressed'}-${surface}`;+ const file = path.join(root, `${label}.docx`);+ fs.writeFileSync(file, original);+ const initialHash = `sha256:${sha256(file)}`;+ const initialMtime = fs.statSync(file, { bigint: true }).mtimeNs;+ try {+ if (surface === 'check') {+ // A second check must keep reviewing the same source revision too.+ for (let round = 0; round < 2; round++) {+ const result = await officeReview.execute({ action: 'check', path: file }, { workingDir: root });+ assert(!result.isError, `${label}: structural check failed: ${result.content}`);+ const receipt = JSON.parse(result.content);+ assert(receipt.valid === true, `${label}: fixture is not valid OpenXML`);+ assert(fs.readFileSync(file).equals(original), `${label}: check changed source bytes`);+ assert(receipt.artifact_sha256 === initialHash, `${label}: receipt identifies a different source revision`);+ assert(receipt.artifact_sha256 === `sha256:${sha256(file)}`, `${label}: receipt differs from final file`);+ }+ } else if (surface === 'read') {+ const result = await officeRead.execute({ mode: 'text', path: file }, { workingDir: root });+ assert(!result.isError, `${label}: read failed: ${result.content}`);+ assertContains(result.content, 'Readonly review fixture', label);+ } else {+ const html = path.join(root, `${label}.html`);+ run(binary, ['view', file, 'html', '--page', '1', '--render', 'html', '-o', html]);+ assertRenderedHtml(html, file);+ }+ } finally {+ closeFile(binary, file);+ }+ assert(fs.readFileSync(file).equals(original), `${label}: read-only lifecycle changed source bytes`);+ assert(fs.statSync(file, { bigint: true }).mtimeNs === initialMtime, `${label}: read-only lifecycle changed source mtime`);+ }+ }+}+const platformKey = `${process.platform}-${process.arch}`;const assetName = assetNames[platformKey];if (!assetName) {@@ -177,8 +220,14 @@ try {await batch(binary, sourceDocx, [{ command: 'add', parent: '/body', type: 'p', props: { text: '季度报告', style: 'Heading1' } },{ command: 'add', parent: '/body', type: 'p', props: { text: '中文内容:进展正常。' } },+ { command: 'add', parent: '/body', type: 'p', props: { text: '第一行\n第二行' } },]);closeFile(binary, sourceDocx);+ // The upgraded engine versions dump/newline semantics, but our unversioned+ // batch contract must retain the existing single-paragraph soft line break.+ const sourceXml = new AdmZip(sourceDocx).readAsText('word/document.xml');+ assert((sourceXml.match(/<w:p[\s>]/g) || []).length === 3, 'DOCX batch newline unexpectedly split a paragraph');+ assert((sourceXml.match(/<w:br[\s/>]/g) || []).length === 1, 'DOCX batch newline did not retain its soft line break');const sourceHash = sha256(sourceDocx);const produced = new Set();const officeTools = createOfficeTools({@@ -190,9 +239,12 @@ try {const editOffice = officeTools.find((tool) => tool.name === 'edit_office');const createXlsx = officeTools.find((tool) => tool.name === 'create_xlsx');const officeRead = officeTools.find((tool) => tool.name === 'office_read');+ const officeReview = officeTools.find((tool) => tool.name === 'office_review');assert(editOffice, 'edit_office tool is missing');assert(createXlsx, 'create_xlsx tool is missing');assert(officeRead, 'office_read tool is missing');+ assert(officeReview, 'office_review tool is missing');+ await assertReadOnlyDocx(binary, officeReview, officeRead, tempDir);const editResult = await editOffice.execute({path: sourceDocx,operations: [@@ -388,7 +440,7 @@ try {);}- console.log(`[office-artifact-smoke] PASS ${platformKey} OfficeCLI=${version} artifacts=3 production-fixtures=${fixtureScenarios.length} native-xlsx-chart=true xlsx-cross-sheet-layout=true xlsx-edit-readback=true tool-copy=true source-preserved=true atomic-rollback=true guarded-html-renders=3`);+ console.log(`[office-artifact-smoke] PASS ${platformKey} OfficeCLI=${version} artifacts=3 production-fixtures=${fixtureScenarios.length} foreign-docx-readonly=true check-receipt-matches-source=true native-xlsx-chart=true xlsx-cross-sheet-layout=true xlsx-edit-readback=true tool-copy=true source-preserved=true atomic-rollback=true guarded-html-renders=3`);} catch (error) {failed = true;console.error(`[office-artifact-smoke] FAIL: ${error instanceof Error ? error.message : String(error)}`);diff --git a/src/main/features/office/office_engine.ts b/src/main/features/office/office_engine.tsindex d68dee4d..ef35a45d 100644--- a/src/main/features/office/office_engine.ts+++ b/src/main/features/office/office_engine.ts@@ -21,6 +21,7 @@ import * as path from 'node:path';import { officeCliBinaryPath } from '../../paths';import { createLogger } from '../../logger';+import { logErrorSummary, logPathRef } from '../../util/log-redact';import { killProcessTree } from '../../../core-agent/src/sandbox/executor';const log = createLogger('office-engine');@@ -93,7 +94,7 @@ export function officeCliAvailable(): boolean {const bin = officeCliBinaryPath();const ok = !!bin && fs.existsSync(bin);if (ok) availableCache = true;- else log.warn(`OfficeCLI binary unavailable (${bin ?? `no asset for ${process.platform}-${process.arch}`})`);+ else log.warn('OfficeCLI binary unavailable', { platform: process.platform, arch: process.arch });return ok;}@@ -219,33 +220,34 @@ export async function closeOfficeFile(file: string, cwd: string): Promise<void>try {await runOfficeCli(['close', file], { cwd, timeoutMs: 10_000 });} catch (err) {- log.warn(`close resident ${file}: ${(err as Error).message}`);+ log.warn('OfficeCLI resident close failed', { file: logPathRef(file), error: logErrorSummary(err) });}}/** Reap ANY lingering OfficeCLI resident daemons. Per-file `closeOfficeFile`* in each tool's `finally` covers the normal path; this is the backstop for a* hard crash that skipped the finally. Call at startup (clean prior-session- * leaks) and on app quit. Synchronous + best-effort; single-instance lock- * guarantees no concurrent legitimate instance to disturb. */+ * leaks) and on app quit. Scope to the exact bundled executable and resident+ * mode: other installations and active document commands must survive. */export function closeAllOfficeResidents(): void {const bin = officeCliBinaryPath();if (!bin) return;try {if (process.platform === 'win32') {- // Match-by-cmdline is unreliable on Windows; at startup/quit killing every- // process of our bundled exe by image name is safe (no concurrent instance).const systemRoot = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';- const taskkill = path.win32.join(systemRoot, 'System32', 'taskkill.exe');- // Use Windows path semantics explicitly. Besides making this branch- // deterministic in cross-host tests, it avoids ever passing a full- // `C:\\...` path to taskkill when the value originated outside the host- // path module (for example packaged metadata or a cross-build step).- spawnSync(taskkill, ['/F', '/T', '/IM', path.win32.basename(bin)], {+ const powershell = path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');+ // Keep the binary path out of executable code. Pin handles and compare+ // creation times so an exited resident's recycled PID is never killed.+ const result = spawnSync(powershell, [+ '-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand',+ Buffer.from(WINDOWS_RESIDENT_CLEANUP, 'utf16le').toString('base64'),+ ], {+ env: { ...process.env, ORKAS_OFFICECLI_SWEEP_BINARY: bin },timeout: 5_000,stdio: 'ignore',windowsHide: true,});+ if (result.error || result.status !== 0) throw new Error('OfficeCLI resident cleanup failed');} else {// Scope strictly to OUR binary's resident daemons, not any other officecli.// `pkill -f` treats the pattern as an extended regex, so escape the binary@@ -255,6 +257,46 @@ export function closeAllOfficeResidents(): void {spawnSync('pkill', ['-f', `${escaped} __resident-serve__`], { timeout: 5_000, stdio: 'ignore' });}} catch (err) {- log.warn(`resident sweep: ${(err as Error).message}`);+ log.warn('OfficeCLI resident sweep failed', { error: logErrorSummary(err) });}}++const WINDOWS_RESIDENT_CLEANUP = String.raw`+$ErrorActionPreference = 'Stop'+$query = $null+$rows = $null+try {+ $binary = [IO.Path]::GetFullPath($env:ORKAS_OFFICECLI_SWEEP_BINARY)+ $name = [IO.Path]::GetFileName($binary).Replace("'", "''")+ $query = [System.Management.ManagementObjectSearcher]::new("SELECT ProcessId,ExecutablePath,CommandLine,CreationDate FROM Win32_Process WHERE Name='$name'")+ $rows = $query.Get()+ $count = 0+ foreach ($row in $rows) {+ $candidate = $null+ try {+ if (++$count -gt 4096) { throw 'resident_limit' }+ if (-not [string]::Equals([string]$row.ExecutablePath, $binary, [StringComparison]::OrdinalIgnoreCase)) { continue }+ # Resident mode must be the first argument, not text in a document path.+ if ([string]$row.CommandLine -notmatch '^\s*(?:"[^"]*"|\S+)\s+__resident-serve__(?:\s|$)') { continue }+ try {+ $candidate = [Diagnostics.Process]::GetProcessById([int]$row.ProcessId)+ $null = $candidate.Handle+ $started = $candidate.StartTime.ToUniversalTime()+ } catch [ArgumentException] { continue }+ catch [InvalidOperationException] { continue }+ $snapshotStarted = [System.Management.ManagementDateTimeConverter]::ToDateTime([string]$row.CreationDate).ToUniversalTime()+ if (($started.Ticks - ($started.Ticks % 10)) -ne $snapshotStarted.Ticks) { continue }+ if (-not $candidate.HasExited) { $candidate.Kill() }+ if (-not $candidate.WaitForExit(500)) { throw 'resident_still_running' }+ } finally {+ if ($null -ne $candidate) { $candidate.Dispose() }+ $row.Dispose()+ }+ }+} catch { exit 1 }+finally {+ if ($null -ne $rows) { $rows.Dispose() }+ if ($null -ne $query) { $query.Dispose() }+}+exit 0+`;diff --git a/src/main/features/office/office_html_security.ts b/src/main/features/office/office_html_security.tsnew file mode 100644index 00000000..78af1506--- /dev/null+++ b/src/main/features/office/office_html_security.ts@@ -0,0 +1,38 @@+/** Shared policy for OfficeCLI HTML; the screenshot session separately+ * restricts file access to its temporary render root and denies permissions. */+export const OFFICE_RENDER_ASSET_HOSTS: readonly string[] = Object.freeze([+ 'd.officecli.ai',+ 'cdn.jsdelivr.net',+ 'fonts.googleapis.com',+ 'fonts.gstatic.com',+]);++export function hardenOfficeHtml(source: string, allowRenderAssets = false): string {+ const assets = allowRenderAssets+ ? ` 'self' ${OFFICE_RENDER_ASSET_HOSTS.map(host => `https://${host}`).join(' ')}`+ : '';+ const csp = [+ "default-src 'none'",+ `img-src data: blob:${assets}`,+ `media-src data: blob:${assets}`,+ `font-src data:${assets}`,+ `style-src 'unsafe-inline' data:${assets}`,+ `script-src 'unsafe-inline'${assets}`,+ "connect-src 'none'",+ "frame-src 'none'",+ "object-src 'none'",+ "base-uri 'none'",+ "form-action 'none'",+ ].join('; ');+ const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}">`;+ const withoutBase = source+ .replace(/<base\b[^>]*>/gi, '')+ .replace(+ /\b(href|src)\s*=\s*(["'])\s*javascript:[\s\S]*?\2/gi,+ (_match, attribute: string, quote: string) => `${attribute}=${quote}#${quote}`,+ );+ if (/<head\b[^>]*>/i.test(withoutBase)) {+ return withoutBase.replace(/<head\b[^>]*>/i, head => `${head}\n${meta}`);+ }+ return `<!doctype html><html><head>${meta}</head><body>${withoutBase}</body></html>`;+}diff --git a/src/main/features/office/office_page_renderer.ts b/src/main/features/office/office_page_renderer.tsindex 87b138ff..ae4eb144 100644--- a/src/main/features/office/office_page_renderer.ts+++ b/src/main/features/office/office_page_renderer.ts@@ -9,18 +9,14 @@ import type { BrowserWindow as ElectronBrowserWindow, Session } from 'electron';import { isPathAllowed } from '../../util/path-sandbox';import { hardenedWebPreferences } from '../../util/window-security';import { runOfficeCli } from './office_engine';+import { hardenOfficeHtml, OFFICE_RENDER_ASSET_HOSTS } from './office_html_security';import { PPTX_TEXT_COLLISION_SCRIPT, unassessedTextCollision, type TextCollisionAudit } from './pptx_text_collision';const OFFICE_RENDER_TIMEOUT_MS = 60_000;const DEFAULT_SCREENSHOT_WIDTH = 1600;const DEFAULT_SCREENSHOT_HEIGHT = 1200;const MAX_SCREENSHOT_DIMENSION = 1920;-const TRUSTED_RENDER_HOSTS = new Set([- 'd.officecli.ai',- 'cdn.jsdelivr.net',- 'fonts.googleapis.com',- 'fonts.gstatic.com',-]);+const TRUSTED_RENDER_HOSTS = new Set(OFFICE_RENDER_ASSET_HOSTS);type ElectronRuntime = {BrowserWindow?: new (options: Record<string, unknown>) => ElectronBrowserWindow;@@ -45,11 +41,26 @@ const READY_SCRIPT = `(async () => {return true;})()`;+// The pinned Word preview skips pagination only for a page-1 screenshot.+// Use its normal paginator after fonts settle so page 1 and later pages share+// the same content partition. The hook schedules one synchronous pagination+// pass; the following timer waits for that pass before measuring/capturing.+const WORD_FIRST_PAGE_SCRIPT = `(async () => {+ const pages = window._requestedPages;+ if (typeof window._wordPaginate !== 'function'+ || !Array.isArray(pages) || pages.length !== 1 || pages[0] !== 1) return;+ window._wordPaginate();+ await new Promise((resolve) => setTimeout(resolve, 0));+})()`;+const CONTENT_SIZE_SCRIPT = `(() => {const visible = (element) => element && element.offsetParent !== null;const slide = Array.from(document.querySelectorAll('.slide')).find(visible);const page = Array.from(document.querySelectorAll('.page')).find(visible);const target = slide || page;+ if (!target && !Array.from(document.querySelectorAll('.sheet-content')).some(visible)) {+ return { missingPage: true };+ }if (!target) return { width: 1600, height: 1200 };return {width: Math.max(1, Math.ceil(target.offsetWidth || 0)),@@ -153,6 +164,12 @@ export async function renderOfficePageToPng(}assertNotAborted(signal);+ // file: responses cannot carry a CSP header. Install the policy before+ // Chromium parses any generated script, preserving Office layout assets.+ const html = await fs.promises.readFile(htmlPath, 'utf8');+ await fs.promises.writeFile(htmlPath, hardenOfficeHtml(html, true));+ assertNotAborted(signal);+const electron = await (deps.loadElectron?.() ?? import('electron') as Promise<ElectronRuntime>);const BrowserWindow = electron.BrowserWindow;if (!BrowserWindow || !electron.session) {@@ -189,7 +206,17 @@ export async function renderOfficePageToPng();assertNotAborted(signal);- const size = normalizeContentSize(await win.webContents.executeJavaScript(CONTENT_SIZE_SCRIPT, true));+ await withTimeout(+ win.webContents.executeJavaScript(WORD_FIRST_PAGE_SCRIPT, true),+ 'E_OFFICE_RENDER_PAGINATION_TIMEOUT: preview pagination did not settle',+ );+ assertNotAborted(signal);++ const layout = await win.webContents.executeJavaScript(CONTENT_SIZE_SCRIPT, true);+ if (layout?.missingPage) {+ throw new Error(`E_OFFICE_RENDER_PAGE_UNAVAILABLE: page ${page} has no visible Office page or worksheet.`);+ }+ const size = normalizeContentSize(layout);win.setContentSize(size.width, size.height, false);await withTimeout(win.webContents.executeJavaScript(READY_SCRIPT, true),diff --git a/src/main/features/office/office_preview_layout.ts b/src/main/features/office/office_preview_layout.tsindex 12fd6e7e..5a81b10a 100644--- a/src/main/features/office/office_preview_layout.ts+++ b/src/main/features/office/office_preview_layout.ts@@ -21,6 +21,7 @@ import {type OfficePreviewResult,} from '../../util/office-preview';import { closeOfficeFile, officeCliAvailable, runOfficeCli } from './office_engine';+import { hardenOfficeHtml } from './office_html_security';const log = createLogger('office-preview');const OFFICE_LAYOUT_PREVIEW_CACHE_MAX_BYTES = 32 * 1024 * 1024;@@ -121,33 +122,10 @@ function stabilizeRenderedPresentationNavigation(source: string): string {}function hardenRenderedOfficeHtml(source: string, kind: OfficePreviewKind): string {- const csp = [- "default-src 'none'",- "img-src data: blob:",- "media-src data: blob:",- "font-src data:",- "style-src 'unsafe-inline' data:",- "script-src 'unsafe-inline'",- "connect-src 'none'",- "frame-src 'none'",- "object-src 'none'",- "base-uri 'none'",- "form-action 'none'",- ].join('; ');- const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}">`;const presentationSafeSource = kind === 'presentation'? stabilizeRenderedPresentationNavigation(source): source;- const withoutBase = presentationSafeSource- .replace(/<base\b[^>]*>/gi, '')- .replace(- /\b(href|src)\s*=\s*(["'])\s*javascript:[\s\S]*?\2/gi,- (_match, attribute: string, quote: string) => `${attribute}=${quote}#${quote}`,- );- if (/<head\b[^>]*>/i.test(withoutBase)) {- return withoutBase.replace(/<head\b[^>]*>/i, (head) => `${head}\n${meta}`);- }- return `<!doctype html><html><head>${meta}</head><body>${withoutBase}</body></html>`;+ return hardenOfficeHtml(presentationSafeSource);}function engineExtensionForKind(kind: OfficePreviewKind): '.docx' | '.xlsx' | '.pptx' {diff --git a/src/main/model/core-agent/office-tools.ts b/src/main/model/core-agent/office-tools.tsindex 30ff5213..e0845096 100644--- a/src/main/model/core-agent/office-tools.ts+++ b/src/main/model/core-agent/office-tools.ts@@ -122,6 +122,11 @@ function officeIssueEntries(value: unknown): Array<Record<string, unknown>> {}function officeIssueSeverity(issue: Record<string, unknown>): OfficeIssueSeverity {+ // Bundled OfficeCLI's IssueSeverity enum serializes as numbers:+ // Error=0, Warning=1, Info=2. Preserve string/subtype compatibility below.+ if (issue.severity === 0) return 'blocker';+ if (issue.severity === 1) return 'warning';+ if (issue.severity === 2) return 'info';const upstream = typeof issue.severity === 'string' ? issue.severity.trim().toLowerCase() : '';if (['blocker', 'error', 'fatal', 'critical'].includes(upstream)) return 'blocker';if (['warning', 'warn', 'advisory'].includes(upstream)) return 'warning';diff --git a/src/main/util/extract-office.ts b/src/main/util/extract-office.tsindex 5b8228d2..54ea8bcb 100644--- a/src/main/util/extract-office.ts+++ b/src/main/util/extract-office.ts@@ -301,7 +301,7 @@ export function xlsxBufferToMarkdown(buf: Buffer): string {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 maxCols = sheet.rows.reduce((max, row) => Math.max(max, row.length), 0);const rows = sheet.rows.map((row) => (`<tr>${Array.from({ length: maxCols }, (_unused, i) => `<td>${escapeHtml(row[i] || '')}</td>`).join('')}</tr>`)).join('');diff --git a/src/main/util/file_to_chunks.ts b/src/main/util/file_to_chunks.tsindex c42bda8b..7d735dcc 100644--- a/src/main/util/file_to_chunks.ts+++ b/src/main/util/file_to_chunks.ts@@ -18,7 +18,7 @@import { pdfBufferToChunks } from './extract-pdf';import { docxBufferToChunks } from './extract-docx';-import { pptxBufferToMarkdown, xlsxBufferToMarkdown } from './extract-office';+import { extractOffice } from './office-extract';import { isZipSpreadsheet, xlsBufferToMarkdown } from './extract-xls';export type ChunkableKind = 'text' | 'pdf' | 'docx' | 'spreadsheet' | 'presentation' | 'image';@@ -71,11 +71,11 @@ export async function fileToChunks(opts: FileToChunksOptions): Promise<Extracted}));}if (opts.kind === 'spreadsheet') {- const text = isZipSpreadsheet(opts.buf) ? xlsxBufferToMarkdown(opts.buf) : await xlsBufferToMarkdown(opts.buf);+ const text = isZipSpreadsheet(opts.buf) ? await extractOffice('xlsx-markdown', opts.buf) : await xlsBufferToMarkdown(opts.buf);return chunkPlainText(text, budget, overlap);}if (opts.kind === 'presentation') {- return chunkPlainText(pptxBufferToMarkdown(opts.buf), budget, overlap);+ return chunkPlainText(await extractOffice('pptx-markdown', opts.buf), budget, overlap);}if (opts.kind === 'image') {if (!opts.imageDescriber) {diff --git a/src/main/util/office-extract-entry.js b/src/main/util/office-extract-entry.jsnew file mode 100644index 00000000..68f0eda4--- /dev/null+++ b/src/main/util/office-extract-entry.js@@ -0,0 +1,3 @@+'use strict';+require('tsx/cjs');+require('./office-extract-worker');diff --git a/src/main/util/office-extract-worker.ts b/src/main/util/office-extract-worker.tsnew file mode 100644index 00000000..37b500b0--- /dev/null+++ b/src/main/util/office-extract-worker.ts@@ -0,0 +1,11 @@+import { parentPort } from 'node:worker_threads';+import { xlsxBufferToMarkdown, xlsxBufferToHtml, pptxBufferToMarkdown, pptxBufferToHtml } from './extract-office';++const extractors = {+ 'xlsx-markdown': xlsxBufferToMarkdown, 'xlsx-html': xlsxBufferToHtml,+ 'pptx-markdown': pptxBufferToMarkdown, 'pptx-html': pptxBufferToHtml,+};+parentPort!.on('message', ({ kind, bytes }: { kind: keyof typeof extractors; bytes: Uint8Array }) => {+ try { parentPort!.postMessage({ ok: true, text: extractors[kind](Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)) }); }+ catch (error) { parentPort!.postMessage({ ok: false, error: error instanceof Error ? error.message : 'Office extraction failed' }); }+});diff --git a/src/main/util/office-extract.ts b/src/main/util/office-extract.tsnew file mode 100644index 00000000..8fe3adff--- /dev/null+++ b/src/main/util/office-extract.ts@@ -0,0 +1,92 @@+/** Preserve the existing extractors while moving OOXML CPU work off main.+ * Admission limits simultaneous work, never supported input or queue length. */+import { Worker } from 'node:worker_threads';+import * as path from 'node:path';+import { isZipSpreadsheet, xlsBufferToMarkdown } from './extract-xls';++export type OfficeExtraction = 'xlsx-markdown' | 'xlsx-html' | 'pptx-markdown' | 'pptx-html' | 'spreadsheet-markdown';+type Input = Buffer | ((signal: AbortSignal) => Promise<Buffer>);+type Job = { kind: OfficeExtraction; input: Input; resolve(value: string): void; reject(error: Error): void };+const queue: Job[] = [];+const active = new Set<{ cancel(): Promise<void> }>();+const idle: Worker[] = [];+let closing: Promise<void> | undefined;++export function extractOffice(kind: OfficeExtraction, input: Input): Promise<string> {+ if (closing) return Promise.reject(new Error('Office extraction closed'));+ return new Promise((resolve, reject) => { queue.push({ kind, input, resolve, reject }); pump(); });+}++function pump(): void {+ while (!closing && active.size < 2 && queue.length) {+ const job = queue.shift()!;+ const controller = new AbortController();+ let worker: Worker | undefined = idle.pop(), settled = false;+ let completion: Promise<void> | undefined;+ const finish = (error?: Error, text?: string): Promise<void> => {+ if (completion) return completion;+ settled = true;+ const reuse = !error && worker && queue.length && !closing;+ if (reuse) {+ worker.removeAllListeners('message');+ worker.removeAllListeners('error');+ worker.removeAllListeners('exit');+ idle.push(worker);+ }+ completion = Promise.resolve(reuse ? undefined : worker?.terminate()).then(() => {}, () => {}).then(() => {+ active.delete(owner);+ if (error) job.reject(error); else job.resolve(text!);+ pump();+ });+ return completion;+ };+ const owner = { cancel: () => {+ controller.abort();+ return finish(new Error('Office extraction closed'));+ } };+ active.add(owner);+ let listening = false;+ const listen = () => {+ if (listening) return;+ listening = true;+ worker!.once('message', message => {+ if (message.ok && typeof message.text === 'string') void finish(undefined, message.text);+ else void finish(new Error(String(message.error || 'Office extraction failed')));+ });+ worker!.once('error', () => { void finish(new Error('Office extraction failed')); });+ worker!.once('exit', () => { if (!settled) void finish(new Error('Office extraction failed')); });+ };+ // A reused worker is already alive while its next lazy input is loading.+ if (worker) listen();+ void (async () => {+ // Lazy inputs are read only after admission, so a burst does not read+ // every file into memory while waiting for a parser slot.+ const input = typeof job.input === 'function' ? await job.input(controller.signal) : job.input;+ if (settled) return;+ if (job.kind === 'spreadsheet-markdown' && !isZipSpreadsheet(input)) {+ // Keep the existing process-wide legacy XLS pool and its contract.+ const text = await xlsBufferToMarkdown(input);+ if (!settled) await finish(undefined, text);+ return;+ }+ worker ||= new Worker(path.join(__dirname, 'office-extract-entry.js'), { execArgv: [] });+ listen();+ // Transfer an owned copy; caller buffers and caches must stay attached.+ const bytes = new Uint8Array(input);+ worker.postMessage({ kind: job.kind === 'spreadsheet-markdown' ? 'xlsx-markdown' : job.kind, bytes }, [bytes.buffer]);+ })().catch(error => { if (!settled) void finish(error instanceof Error ? error : new Error('Office extraction failed')); });+ }+}++export function closeOfficeExtraction(): Promise<void> {+ if (closing) return closing;+ const error = new Error('Office extraction closed');+ for (const job of queue.splice(0)) job.reject(error);+ // Set the barrier before cancellation can synchronously call any consumer.+ closing = Promise.resolve().then(async () => {+ await Promise.all([...active].map(owner => owner.cancel()));+ await Promise.all(idle.splice(0).map(worker => worker.terminate()));+ })+ .finally(() => { closing = undefined; });+ return closing;+}diff --git a/src/main/util/office-preview.ts b/src/main/util/office-preview.tsindex 27f95414..cbccb206 100644--- a/src/main/util/office-preview.ts+++ b/src/main/util/office-preview.ts@@ -1,5 +1,5 @@import { docxBufferToHtml } from './extract-docx';-import { pptxBufferToHtml, xlsxBufferToHtml } from './extract-office';+import { extractOffice } from './office-extract';import { isZipSpreadsheet, xlsBufferToHtml } from './extract-xls';export type OfficePreviewKind = 'word' | 'spreadsheet' | 'presentation';@@ -227,9 +227,9 @@ export async function officeBufferToPreviewHtml(if (kind === 'word') {fragment = await docxBufferToHtml(buf);} else if (kind === 'spreadsheet') {- fragment = isZipSpreadsheet(buf) ? xlsxBufferToHtml(buf) : await xlsBufferToHtml(buf);+ fragment = isZipSpreadsheet(buf) ? await extractOffice('xlsx-html', buf) : await xlsBufferToHtml(buf);} else {- fragment = pptxBufferToHtml(buf);+ fragment = await extractOffice('pptx-html', buf);}const previewHeight = estimateOfficePreviewHeight(kind, fragment);return {diff --git a/test/fixtures/office/foreign-docx.cjs b/test/fixtures/office/foreign-docx.cjsnew file mode 100644index 00000000..37db6c78--- /dev/null+++ b/test/fixtures/office/foreign-docx.cjs@@ -0,0 +1,33 @@+'use strict';+const AdmZip = require('adm-zip');++function foreignDocxBytes(spacedBreaks) {+ // Build independently of OfficeCLI: its own output already uses its ZIP+ // encoding and hid the read-only close-time repack regression upstream.+ const zip = new AdmZip();+ zip.addFile('[Content_Types].xml', Buffer.from(+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ + '<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="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>',+ ));+ zip.addFile('_rels/.rels', Buffer.from(+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ + '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'+ + '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',+ ));+ zip.addFile('word/document.xml', Buffer.from(+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ + '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>'+ + '<w:p><w:r><w:t>Readonly review fixture 检查不应改写原文件</w:t>'+ + (spacedBreaks ? '<w:br /><w:tab />' : '')+ + '<w:t>Stable text 123</w:t></w:r></w:p>'+ + '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>'+ + '</w:body></w:document>',+ ));+ return zip.toBuffer();+}+++module.exports = { foreignDocxBytes };diff --git a/test/fixtures/office/page-selection-render.cjs b/test/fixtures/office/page-selection-render.cjsnew file mode 100644index 00000000..89fbe752--- /dev/null+++ b/test/fixtures/office/page-selection-render.cjs@@ -0,0 +1,60 @@+// Exercise the production renderer in real Chromium with known Office HTML.+const fs = require('node:fs');+const path = require('node:path');+const { app, BrowserWindow, session } = require('electron');+const pc = process.argv[2];+const output = process.argv[3];+app.setPath('userData', path.join(process.env.ORKAS_WORKSPACE_ROOT, 'browser'));+app.disableHardwareAcceleration();+app.on('window-all-closed', () => {});+require(path.join(pc, 'node_modules/tsx/dist/cjs/index.cjs'));+let html = '';+const engine = path.join(pc, 'src/main/features/office/office_engine.ts');+require.cache[engine] = { id: engine, filename: engine, loaded: true, exports: {+ runOfficeCli: async args => {+ fs.writeFileSync(args[args.indexOf('-o') + 1], html);+ return { code: 0, stdout: '', stderr: '' };+ },+} };+const { renderOfficePageToPng } = require(path.join(pc, 'src/main/features/office/office_page_renderer.ts'));+let security;+class ObservedWindow extends BrowserWindow {+ constructor(options) {+ super(options);+ this.webContents.on('console-message', details => security.logs.push({ level: details.level, message: details.message }));+ const capture = this.webContents.capturePage.bind(this.webContents);+ this.webContents.capturePage = async rect => {+ Object.assign(security, await this.webContents.executeJavaScript('window.securityProbe.finished.then(() => window.securityProbe.facts)'));+ return capture(rect);+ };+ }+}+app.whenReady().then(async () => {+ const rows = [];+ try {+ for (const [extension, container] of [['docx', 'page'], ['pptx', 'slide'], ['xlsx', 'sheet-content']]) {+ for (const visible of [true, false]) {+ // A real, empty page is valid. Hidden pages model an out-of-range+ // selection emitted with exit code 0 by the pinned native engine.+ security = { logs: [] };+ html = `<!doctype html><style>body{margin:0}.${container}{width:200px;height:200px;display:${visible ? 'block' : 'none'}}</style><div class="${container}"></div>+<script>+window.securityProbe = { facts: { inlineScript: true, nodeAccess: typeof require !== 'undefined', evalBlocked: false, connectBlocked: false } };+try { eval('window.securityProbe.facts.evalRan = true'); } catch { window.securityProbe.facts.evalBlocked = true; }+window.securityProbe.finished = fetch('data:text/plain,controlled-probe')+ .then(() => {}).catch(() => { window.securityProbe.facts.connectBlocked = true; });+</script>`;+ try {+ const png = await renderOfficePageToPng(path.join(process.env.ORKAS_WORKSPACE_ROOT, `fixture.${extension}`), process.env.ORKAS_WORKSPACE_ROOT, visible ? '1' : '3', undefined, {+ loadElectron: async () => ({ BrowserWindow: ObservedWindow, session }),+ });+ rows.push({ extension, visible, rendered: png.length > 0, security });+ } catch (error) {+ rows.push({ extension, visible, rendered: false, error: error.message });+ }+ }+ }+ fs.writeFileSync(output, JSON.stringify(rows));+ } catch (error) { console.error(error); process.exitCode = 1; }+ finally { app.exit(process.exitCode || 0); }+});diff --git a/test/fixtures/office/readonly-review.cjs b/test/fixtures/office/readonly-review.cjsnew file mode 100644index 00000000..2807b91e--- /dev/null+++ b/test/fixtures/office/readonly-review.cjs@@ -0,0 +1,232 @@+'use strict';+// Real OfficeCLI + Chromium integration. Only the log sink is replaced;+// cancellation is triggered by a completed native issue scan, without timers.+const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const assert = require('node:assert/strict');+const { app, BrowserWindow, nativeImage } = require('electron');+// Electron otherwise turns a module-load exception into a blocking GUI dialog.+process.on('uncaughtException', error => { console.error(error); app.exit(1); });+const { foreignDocxBytes } = require('./foreign-docx.cjs');+const AdmZip = require('adm-zip');+const pc = process.argv[2];+const output = process.argv[3];+const root = process.env.ORKAS_WORKSPACE_ROOT;+app.setPath('userData', path.join(root, 'browser'));+app.disableHardwareAcceleration();+// These hidden capture windows must stay at foreground priority. Avoid+// macOS task-suppression transitions when native suites run concurrently;+// keep stderr strict rather than suppressing Chromium scheduling failures.+app.commandLine.appendSwitch('disable-renderer-backgrounding');+app.on('window-all-closed', () => {});+require(path.join(pc, 'node_modules/tsx/dist/cjs/index.cjs'));+const { makeMinimalPptx, makeNamespacedDirectXlsx } = require(path.join(pc, 'test/fixtures/make-minimal-office.ts'));+let active;+const bootstrapLogs = [];+const logger = path.join(pc, 'src/main/logger.ts');+require.cache[logger] = { id: logger, filename: logger, loaded: true, exports: {+ createLogger: scope => Object.fromEntries(['debug', 'info', 'warn', 'error'].map(level => [level,+ (...args) => (active?.logs || bootstrapLogs).push({ scope, level, args }),+ ])),+} };+app.on('browser-window-created', (_event, win) => {+ const owner = active;+ win.webContents.on('console-message', details => {+ owner?.browserLogs.push({ level: details.level, message: details.message });+ });+});+const enginePath = path.join(pc, 'src/main/features/office/office_engine.ts');+const engine = require(enginePath);+require.cache[enginePath].exports = {+ ...engine,+ runOfficeCli: async (args, opts) => {+ const result = await engine.runOfficeCli(args, opts);+ active?.commands.push({ verb: args[0], code: result.code, stderr: result.stderr, stdoutChars: result.stdout.length });+ if (active?.cancel && args[0] === 'view' && args[2] === 'issues') active.cancel.abort();+ return result;+ },+};+const rendererPath = path.join(pc, 'src/main/features/office/office_page_renderer.ts');+const renderer = require(rendererPath);+require.cache[rendererPath].exports = {+ ...renderer,+ renderOfficePageToPng: async (...args) => {+ try { return await renderer.renderOfficePageToPng(...args); }+ catch (error) {+ active?.renderErrors.push({ page: args[2], message: String(error.message).replaceAll(root, '<fixture>').slice(0, 2048) });+ throw error;+ }+ },+};+const { createOfficeTools } = require(path.join(pc, 'src/main/model/core-agent/office-tools.ts'));+const written = [];+const tools = createOfficeTools({+ userId: 'readonly-fixture', extraRoots: [root],+ hasProducedPath: file => written.includes(file),+ onFileWritten: file => written.push(file),+});+const review = tools.find(tool => tool.name === 'office_review');+const edit = tools.find(tool => tool.name === 'edit_office');+const context = { workingDir: root };+const hash = bytes => `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}`;+function reviewPresentationBytes() {+ // The shared minimal PPTX is an extraction fixture: its text has no shape+ // geometry. Give this rendering fixture an explicitly visible text box.+ const zip = new AdmZip(makeMinimalPptx({ slides: [['Review fixture content']] }));+ zip.updateFile('ppt/slides/slide1.xml', Buffer.from(`<?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:nvSpPr><p:cNvPr id="2" name="Review fixture text"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>+ <p:spPr><a:xfrm><a:off x="914400" y="914400"/><a:ext cx="9144000" cy="914400"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>+ <p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr sz="2400"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:rPr><a:t>Review fixture content</a:t></a:r></a:p></p:txBody>+ </p:sp></p:spTree></p:cSld>+</p:sld>`));+ return zip.toBuffer();+}+function checkReceipt(result, bytes) {+ const block = result.content.match(/<office-check>\n([\s\S]*?)\n<\/office-check>/);+ const receipt = JSON.parse(block ? block[1] : result.content);+ assert.equal(receipt.artifact_sha256, hash(bytes), 'receipt must identify the source bytes');+ for (const observation of result.observations?.fileReads || []) assert.equal(observation.hash, hash(bytes));+ return receipt;+}+function checkImage(image) {+ assert.equal(image.mediaType, 'image/png');+ const png = Buffer.from(image.data, 'base64');+ assert.equal(png.subarray(0, 8).toString('hex'), '89504e470d0a1a0a');+ const decoded = nativeImage.createFromBuffer(png);+ assert.equal(decoded.isEmpty(), false);+ const size = decoded.getSize();+ assert(size.width > 100 && size.height > 100 && Math.max(size.width, size.height) <= 1920);+ // A valid PNG header is insufficient: the known text page must have ink.+ const bitmap = decoded.toBitmap();+ let dark = 0;+ for (let i = 0; i < bitmap.length; i += 4) {+ if (bitmap[i] < 100 && bitmap[i + 1] < 100 && bitmap[i + 2] < 100) dark++;+ }+ assert(dark > 100, 'review image must contain the fixture text, not a blank page');+}+function preserved(file, bytes, mtime) {+ assert.deepEqual(fs.readFileSync(file), bytes, 'read-only operation changed source bytes');+ assert.equal(fs.statSync(file, { bigint: true }).mtimeNs, mtime, 'read-only operation changed source mtime');+}+async function noResident(file) {+ const result = await engine.runOfficeCli(['close', file], { cwd: root, timeoutMs: 10_000 });+ assert.equal(result.code, 0);+ assert.equal(result.stderr, '');+ assert.match(result.stdout, /nothing to close/, 'tool must release its own resident before returning');+}+app.whenReady().then(async () => {+ assert.deepEqual(bootstrapLogs, [], 'unexpected application logs during fixture initialization');+ // Prove that the supported Electron event reaches the audit with its named+ // severity before an empty browserLogs array can establish a clean review.+ const consoleProbe = { browserLogs: [] };+ active = consoleProbe;+ const probeWindow = new BrowserWindow({ show: false });+ try {+ await probeWindow.loadURL('data:text/html,' + encodeURIComponent(+ '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'"><title>Office console capture probe</title>'));+ await probeWindow.webContents.executeJavaScript('console.warn("Office console capture probe")');+ assert.deepEqual(consoleProbe.browserLogs, [{ level: 'warning', message: 'Office console capture probe' }]);+ } finally { probeWindow.destroy(); active = undefined; }+ const rows = [];+ for (const id of ['combined-review', 'partial-page-retry', 'cancel-after-check', 'invalid-document', 'edit-then-review', 'xlsx-render', 'pptx-render']) {+ const row = { id, logs: [], browserLogs: [], commands: [], renderErrors: [] };+ active = row;+ const format = id === 'xlsx-render' ? 'xlsx' : id === 'pptx-render' ? 'pptx' : 'docx';+ const file = path.join(root, `${id}.${format}`);+ // Use a populated worksheet: a single short cell has fewer painted dark+ // pixels than the document-oriented nonblank image oracle below.+ const original = format === 'xlsx' ? makeNamespacedDirectXlsx({+ rows: Array.from({ length: 12 }, (_, i) => ['Review fixture', String(i + 1), '42']),+ })+ : format === 'pptx' ? reviewPresentationBytes() : foreignDocxBytes(true);+ if (id === 'invalid-document') {+ const zip = new AdmZip(original);+ zip.updateFile('word/document.xml', Buffer.from(zip.readAsText('word/document.xml').replace('<w:body>', '<w:body><w:invalidElement/>')));+ fs.writeFileSync(file, zip.toBuffer());+ } else fs.writeFileSync(file, original);+ const before = fs.readFileSync(file);+ const mtime = fs.statSync(file, { bigint: true }).mtimeNs;+ const writtenBefore = written.length;+ try {+ if (format !== 'docx') {+ const readback = await engine.runOfficeCli(['view', file, 'text'], { cwd: root });+ assert.equal(readback.code, 0);+ assert.equal(readback.stderr, '');+ assert(readback.stdout.includes('Review fixture'), 'native fixture must contain the intended text');+ const result = await review.execute({ action: 'render', path: file, pages: ['1'] }, context);+ assert(!result.isError, result.content);+ assert.equal(result.images.length, 1);+ checkImage(result.images[0]);+ } else if (id === 'edit-then-review') {+ const target = path.join(root, 'edited-copy.docx');+ const result = await edit.execute({ path: file, output_path: target,+ operations: [{ action: 'set', path: '/body/p[1]', props: { text: 'Edited content\nSecond line' } }], preview: false,+ }, context);+ assert(!result.isError, result.content);+ assert.deepEqual(written.slice(writtenBefore), [target]);+ const saved = fs.readFileSync(target);+ assert.notEqual(hash(saved), hash(before), 'edit must persist a new revision');+ const xml = new AdmZip(saved).readAsText('word/document.xml');+ assert(xml.includes('Edited content') && xml.includes('Second line'));+ assert.equal((xml.match(/<w:br[\s/>]/g) || []).length, 1, 'edit must preserve the soft-break contract');+ const savedMtime = fs.statSync(target, { bigint: true }).mtimeNs;+ const checked = await review.execute({ action: 'check_and_render', path: target, pages: ['1'] }, context);+ assert(!checked.isError, checked.content);+ assert.equal(checkReceipt(checked, saved).valid, true);+ assert.equal(checked.images.length, 1);+ checkImage(checked.images[0]);+ preserved(target, saved, savedMtime);+ await noResident(target);+ } else if (id === 'invalid-document') {+ const result = await review.execute({ action: 'check_and_render', path: file, pages: ['1'] }, context);+ assert.equal(result.isError, true);+ assert.equal(checkReceipt(result, before).valid, false);+ assert.equal(result.images?.length || 0, 0, 'invalid document must not render');+ } else {+ let signal;+ if (id === 'cancel-after-check') {+ row.cancel = new AbortController();+ signal = row.cancel.signal;+ }+ const result = await review.execute({ action: 'check_and_render', path: file,+ pages: id === 'partial-page-retry' ? ['1', '99'] : ['1'],+ }, { ...context, ...(signal ? { signal } : {}) });+ assert.equal(checkReceipt(result, before).valid, true);+ if (id === 'combined-review') {+ assert(!result.isError, result.content);+ assert.equal(result.images.length, 1);+ checkImage(result.images[0]);+ } else {+ assert.equal(result.isError, true);+ assert.match(result.content, /E_OFFICE_RENDER_FAILED/);+ assert.equal(result.images?.length || 0, id === 'partial-page-retry' ? 1 : 0);+ if (result.images?.length) checkImage(result.images[0]);+ if (signal) assert.equal(signal.aborted, true, 'cancellation must occur after the real issue scan');+ preserved(file, before, mtime);+ await noResident(file);+ delete row.cancel;+ const retry = await review.execute({ action: 'render', path: file, pages: ['1'] }, context);+ assert(!retry.isError, retry.content);+ assert.equal(retry.images.length, 1);+ checkImage(retry.images[0]);+ }+ }+ preserved(file, before, mtime);+ if (id !== 'edit-then-review') assert.equal(written.length, writtenBefore, 'review must not register a write');+ await noResident(file);+ assert.equal(BrowserWindow.getAllWindows().length, 0, 'review must release its preview windows');+ } catch (error) {+ row.error = String(error.stack || error).replaceAll(root, '<fixture>');+ } finally {+ delete row.cancel;+ await engine.closeOfficeFile(file, root);+ for (const win of BrowserWindow.getAllWindows()) win.destroy();+ }+ rows.push(row);+ }+ fs.writeFileSync(output, JSON.stringify(rows));+ app.exit(0);+}).catch(error => { console.error(error); app.exit(1); });diff --git a/test/fixtures/office/word-pagination.cjs b/test/fixtures/office/word-pagination.cjsnew file mode 100644index 00000000..4d2ba4aa--- /dev/null+++ b/test/fixtures/office/word-pagination.cjs@@ -0,0 +1,83 @@+'use strict';+// Independent DOCX and screenshot-time observation through the production renderer.+const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const { app, BrowserWindow, session, nativeImage } = require('electron');+const AdmZip = require('adm-zip');+const { foreignDocxBytes } = require('./foreign-docx.cjs');+const pc = process.argv[2];+const output = process.argv[3];+const root = process.env.ORKAS_WORKSPACE_ROOT;+app.setPath('userData', path.join(root, 'browser'));+app.disableHardwareAcceleration();+app.commandLine.appendSwitch('disable-renderer-backgrounding');+app.on('window-all-closed', () => {});+process.on('uncaughtException', error => { console.error(error); app.exit(1); });+require(path.join(pc, 'node_modules/tsx/dist/cjs/index.cjs'));+const lines = Array.from({ length: 24 }, (_, i) => `Line ${String(i + 1).padStart(3, '0')}: confirmed handover item`);+const zip = new AdmZip(foreignDocxBytes(false));+const xml = zip.readAsText('word/document.xml');+const content = lines.map(text => '<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="280" w:lineRule="exact"/></w:pPr>'+ + '<w:r><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial"/><w:sz w:val="24"/></w:rPr>'+ + `<w:t>${text}</w:t></w:r></w:p>`).join('');+zip.updateFile('word/document.xml', Buffer.from(xml+ .replace(/<w:body>[\s\S]*?<w:sectPr>/, '<w:body>' + content + '<w:sectPr>')+ .replace('w:w="11906" w:h="16838"', 'w:w="8000" w:h="7000"').replaceAll('1440', '720')));+const file = path.join(root, 'handover.docx');+fs.writeFileSync(file, zip.toBuffer());+const hash = () => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');+const before = hash();+const beforeMtime = fs.statSync(file, { bigint: true }).mtimeNs;+const rows = [];+let current;+class ObservedWindow extends BrowserWindow {+ constructor(options) {+ super(options);+ this.webContents.on('console-message', event => current.logs.push({ level: event.level, message: event.message }));+ const capture = this.webContents.capturePage.bind(this.webContents);+ this.webContents.capturePage = async rect => {+ current.paragraphs = await this.webContents.executeJavaScript(`(() => {+ const page = [...document.querySelectorAll('.page')].find(e => e.offsetParent !== null);+ const box = page.getBoundingClientRect();+ return [...page.querySelectorAll('p[data-path]')].filter(e => {+ const r = e.getBoundingClientRect();+ return r.top >= box.top && r.bottom <= box.bottom;+ }).map(e => e.innerText);+ })()`);+ return capture(rect);+ };+ }+}+app.whenReady().then(async () => {+ const { renderOfficePageToPng } = require(path.join(pc, 'src/main/features/office/office_page_renderer.ts'));+ const { runOfficeCli } = require(path.join(pc, 'src/main/features/office/office_engine.ts'));+ try {+ // Page 2 before page 1 also proves the first-page repair does not depend+ // on a preceding preview in the same browser window or resident process.+ for (const page of ['2', '1']) {+ current = { page, logs: [] };+ const png = await renderOfficePageToPng(file, root, page, undefined, {+ loadElectron: async () => ({ BrowserWindow: ObservedWindow, session }),+ });+ current.pngHeader = png.subarray(0, 8).toString('hex');+ const bitmap = nativeImage.createFromBuffer(png).toBitmap();+ current.darkPixels = 0;+ for (let i = 0; i < bitmap.length; i += 4) {+ if (bitmap[i] < 100 && bitmap[i + 1] < 100 && bitmap[i + 2] < 100) current.darkPixels++;+ }+ current.sourcePreserved = hash() === before && fs.statSync(file, { bigint: true }).mtimeNs === beforeMtime;+ rows.push(current);+ }+ fs.writeFileSync(output, JSON.stringify({ rows, remainingWindows: BrowserWindow.getAllWindows().length }));+ } catch (error) { console.error(error); process.exitCode = 1; }+ finally {+ // The direct renderer's caller owns the per-file resident, just as the+ // production Office tool does. Close it before the parent removes cwd.+ try {+ const closed = await runOfficeCli(['close', file], { cwd: root, timeoutMs: 10_000 });+ if (closed.code !== 0 || closed.stderr) throw new Error('Office fixture resident did not close');+ } catch (error) { console.error(error); process.exitCode = 1; }+ app.exit(process.exitCode || 0);+ }+});diff --git a/test/main/features/contexts-office-privacy.test.ts b/test/main/features/contexts-office-privacy.test.tsnew file mode 100644index 00000000..8ac9e01b--- /dev/null+++ b/test/main/features/contexts-office-privacy.test.ts@@ -0,0 +1,146 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { syncBuiltinESMExports } from 'node:module';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { makeMinimalDocx } from '../../fixtures/make-minimal-docx';+import { drainMainRuntimeForTest } from '../../helpers/drain-main-runtime';++const diagnostics = vi.hoisted(() => ({ warn: vi.fn() }));+vi.mock('electron', () => ({ shell: { showItemInFolder: vi.fn() } }));+vi.mock('../../../src/main/logger', () => ({+ createLogger: (name: string) => ({ debug: vi.fn(), info: vi.fn(), error: vi.fn(),+ warn: name === 'contexts' ? diagnostics.warn : vi.fn() }),+}));+vi.mock('../../../src/main/features/office/office_engine', () => ({+ officeCliAvailable: () => false, runOfficeCli: vi.fn(), closeOfficeFile: vi.fn(),+}));+vi.mock('../../../src/main/features/kb_indexer', () => ({+ enqueue: vi.fn(), kbEvents: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+}));+vi.mock('../../../src/main/features/search', () => ({ upsertContext: vi.fn(), dropContext: vi.fn() }));++let workspace = '', previousWorkspace: string | undefined;+const filename = 'private-fixture-document.docx';+beforeEach(async () => {+ previousWorkspace = process.env.ORKAS_WORKSPACE_ROOT;+ workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-office-diagnostics-'));+ process.env.ORKAS_WORKSPACE_ROOT = workspace;+ diagnostics.warn.mockClear(); vi.resetModules();+ const users = await import('../../../src/main/features/users'); users.activateUser('fixture-user');+ fs.mkdirSync(path.join(workspace, 'fixture-user/cloud/contexts'), { recursive: true });+});+afterEach(async () => {+ await drainMainRuntimeForTest();+ if (previousWorkspace === undefined) delete process.env.ORKAS_WORKSPACE_ROOT;+ else process.env.ORKAS_WORKSPACE_ROOT = previousWorkspace;+ fs.rmSync(workspace, { force: true, recursive: true });+});+const absoluteFile = () => path.join(workspace, 'fixture-user/cloud/contexts', filename);+function expectSafeDiagnostics() {+ expect(diagnostics.warn).toHaveBeenCalledExactlyOnceWith('context Office preview failed', {+ path: expect.objectContaining({ path_hash: expect.stringMatching(/^[a-f0-9]{12}$/), ext: '.docx' }),+ error: expect.objectContaining({ message_hash: expect.stringMatching(/^[a-f0-9]{12}$/), message_chars: expect.any(Number) }),+ });+ const saved = JSON.stringify(diagnostics.warn.mock.calls);+ for (const privateValue of [filename, workspace, 'PRIVATE_DIAGNOSTIC_PAYLOAD']) expect(saved).not.toContain(privateValue);+}++describe('context Office failure diagnostics', () => {+ it('retains useful read-error attribution without recording paths or raw errors', async () => {+ fs.writeFileSync(absoluteFile(), makeMinimalDocx({ paragraphs: ['Normal fixture'] }));+ const contexts = await import('../../../src/main/features/contexts');+ const originalRead = fs.readFileSync;+ const failure = Object.assign(new Error(`EACCES: ${absoluteFile()} PRIVATE_DIAGNOSTIC_PAYLOAD`), { code: 'EACCES' });+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((file: any, ...args: any[]) => {+ if (String(file) === absoluteFile()) throw failure;+ return (originalRead as any)(file, ...args);+ }) as any); syncBuiltinESMExports();+ try {+ expect((await contexts.readContextOfficeHtml(filename)).ok).toBe(false);+ } finally { spy.mockRestore(); syncBuiltinESMExports(); }+ expectSafeDiagnostics();+ expect(diagnostics.warn.mock.calls[0][1].error).toMatchObject({ code: 'EACCES', message_chars: failure.message.length });+ });++ it('redacts malformed-document preview failures without losing the failure result', async () => {+ fs.writeFileSync(absoluteFile(), Buffer.from('not a document'));+ const contexts = await import('../../../src/main/features/contexts');+ expect((await contexts.readContextOfficeHtml(filename)).ok).toBe(false);+ expectSafeDiagnostics();+ });++ it('keeps valid lightweight Word preview and the source file intact', async () => {+ const bytes = makeMinimalDocx({ paragraphs: ['Independent preview sentinel'] }); fs.writeFileSync(absoluteFile(), bytes);+ const contexts = await import('../../../src/main/features/contexts');+ const result = await contexts.readContextOfficeHtml(filename);+ expect(result.ok).toBe(true);+ if (!result.ok) throw new Error('Expected a valid preview');+ expect(result.html).toContain('Independent preview sentinel'); expect(result.allowScripts).not.toBe(true);+ expect(fs.readFileSync(absoluteFile())).toEqual(bytes); expect(diagnostics.warn).not.toHaveBeenCalled();+ });+});+++function expectClosedDiagnostic(message: string, rawMessage: string) {+ expect(diagnostics.warn).toHaveBeenCalledExactlyOnceWith(message, {+ message_hash: expect.stringMatching(/^[a-f0-9]{12}$/), message_chars: rawMessage.length,+ });+ for (const value of [workspace, filename, 'PRIVATE_DIAGNOSTIC_PAYLOAD']) {+ expect(JSON.stringify(diagnostics.warn.mock.calls)).not.toContain(value);+ }+}++it('keeps legacy Word-preview failure diagnostics private', async () => {+ fs.writeFileSync(absoluteFile(), Buffer.from('not a document'));+ const contexts = await import('../../../src/main/features/contexts');+ const read = fs.readFileSync;+ const message = `EACCES: ${absoluteFile()} PRIVATE_DIAGNOSTIC_PAYLOAD`;+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((file: any, ...args: any[]) => {+ if (String(file) === absoluteFile()) throw Object.assign(new Error(message), { code: 'EACCES' });+ return (read as any)(file, ...args);+ }) as any); syncBuiltinESMExports();+ try { expect((await contexts.readContextDocxHtml(filename)).ok).toBe(false); }+ finally { spy.mockRestore(); syncBuiltinESMExports(); }+ expectClosedDiagnostic('context Word preview failed', message);+});++it('keeps folder-reveal failure diagnostics private without retrying the OS action', async () => {+ fs.writeFileSync(absoluteFile(), 'Owned fixture source');+ const contexts = await import('../../../src/main/features/contexts');+ const electron = await import('electron');+ const message = `EACCES: ${absoluteFile()} PRIVATE_DIAGNOSTIC_PAYLOAD`;+ const reveal = vi.mocked(electron.shell.showItemInFolder);+ reveal.mockClear(); reveal.mockImplementationOnce(() => { throw new Error(message); });+ expect((await contexts.showContextFileInSystem(filename)).ok).toBe(false);+ expect(reveal).toHaveBeenCalledExactlyOnceWith(absoluteFile());+ expectClosedDiagnostic('context file reveal failed', message);+});++it('retains a successful source write when duplicate lookup fails, without private diagnostics', async () => {+ const contexts = await import('../../../src/main/features/contexts');+ const kb = await import('../../../src/main/features/kb_vector');+ const message = `Database failure ${absoluteFile()} PRIVATE_DIAGNOSTIC_PAYLOAD`;+ const spy = vi.spyOn(kb, 'findBySha1').mockImplementation(() => { throw new Error(message); });+ try { expect(contexts.writeContextFile('note.md', 'Saved owned source')).toMatchObject({ ok: true }); }+ finally { spy.mockRestore(); }+ expect(fs.readFileSync(path.join(workspace, 'fixture-user/cloud/contexts/note.md'), 'utf8')).toBe('Saved owned source');+ expectClosedDiagnostic('duplicate content check skipped', message);+});++it('reports index-rebuild failure privately and rebuilds after the filesystem recovers', async () => {+ const root = path.join(workspace, 'fixture-user/cloud/contexts');+ const source = path.join(root, 'note.md'); fs.writeFileSync(source, '# Preserved owned source');+ const contexts = await import('../../../src/main/features/contexts');+ const mkdir = fs.mkdirSync;+ const message = `EACCES: ${root} PRIVATE_DIAGNOSTIC_PAYLOAD`;+ const spy = vi.spyOn(fs, 'mkdirSync').mockImplementation(((directory: any, ...args: any[]) => {+ if (String(directory) === root) throw Object.assign(new Error(message), { code: 'EACCES' });+ return (mkdir as any)(directory, ...args);+ }) as any); syncBuiltinESMExports();+ try { expect(() => contexts.invalidateIndex()).not.toThrow(); }+ finally { spy.mockRestore(); syncBuiltinESMExports(); }+ expectClosedDiagnostic('context index rebuild failed', message);+ expect(await contexts.getContextIndexMarkdown()).toContain('Preserved owned source');+ expect(fs.readFileSync(source, 'utf8')).toBe('# Preserved owned source');+});diff --git a/test/main/features/office/office-page-selection_e2e.test.ts b/test/main/features/office/office-page-selection_e2e.test.tsnew file mode 100644index 00000000..7e3c9ca8--- /dev/null+++ b/test/main/features/office/office-page-selection_e2e.test.ts@@ -0,0 +1,132 @@+import { execFile } from 'node:child_process';+import { createRequire } from 'node:module';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { promisify } from 'node:util';+import { expect, it, vi } from 'vitest';++const require = createRequire(import.meta.url);++async function checkNativeStderr(stderr: string, platform: NodeJS.Platform = process.platform) {+ const { ELECTRON_MACOS_TASK_POLICY_WARNING_RE } = await import('../../../../scripts/model-eval-log-policy.mjs');+ for (const line of stderr.split(/\r?\n/).filter(Boolean)) {+ expect(platform === 'darwin' && ELECTRON_MACOS_TASK_POLICY_WARNING_RE.test(line),+ 'Unexpected native Chromium stderr').toBe(true);+ console.warn('[native-host-warning]', line);+ }+}++it('renders actual blank Office pages but rejects absent selections in native Chromium', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-page-selection-'));+ const env = { ...process.env, ORKAS_WORKSPACE_ROOT: root };+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const resultPath = path.join(root, 'results.json');+ const logs = await promisify(execFile)(require('electron'), [+ path.resolve('test/fixtures/office/page-selection-render.cjs'), process.cwd(), resultPath,+ ], { env, timeout: 30_000, maxBuffer: 256 * 1024 });+ // Even an otherwise empty Electron app emits one console CRLF on Windows.+ expect(process.platform === 'win32' ? ['', '\r\n'] : ['']).toContain(logs.stdout);+ await checkNativeStderr(logs.stderr);+ const results = JSON.parse(fs.readFileSync(resultPath, 'utf8'));+ expect(results).toHaveLength(6);+ for (const row of results) {+ expect(row.rendered, JSON.stringify(row)).toBe(row.visible);+ if (!row.visible) expect(row.error).toContain('E_OFFICE_RENDER_PAGE_UNAVAILABLE');+ if (row.visible) {+ expect(row.security).toMatchObject({ inlineScript: true, nodeAccess: false, evalBlocked: true, connectBlocked: true });+ expect(row.security.evalRan).toBeUndefined();+ // The attempted data: fetch is an explicit negative control. Keep its+ // CSP diagnostics visible while rejecting unrelated browser output.+ expect(row.security.logs).toHaveLength(2);+ for (const log of row.security.logs) {+ expect(log.level).toBe('error');+ expect(log.message).toContain('Content Security Policy');+ expect(log.message).toContain('data:text/plain,controlled-probe');+ }+ }+ }+ } finally { fs.rmSync(root, { recursive: true, force: true }); }+}, 40_000);++it.skipIf(!['darwin', 'win32'].includes(process.platform))('partitions a Word handover consistently across the first two real preview pages', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-word-pagination-'));+ const env = { ...process.env, ORKAS_WORKSPACE_ROOT: root };+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const resultPath = path.join(root, 'results.json');+ const logs = await promisify(execFile)(require('electron'), [+ path.resolve('test/fixtures/office/word-pagination.cjs'), process.cwd(), resultPath,+ ], { env, timeout: 30_000, maxBuffer: 256 * 1024 });+ // The existing Windows native-test contract permits Electron's sole CRLF.+ expect(process.platform === 'win32' ? ['', '\r\n'] : ['']).toContain(logs.stdout);+ await checkNativeStderr(logs.stderr);+ const result = JSON.parse(fs.readFileSync(resultPath, 'utf8'));+ expect(result.remainingWindows).toBe(0);+ expect(result.rows).toHaveLength(2);+ const rows = result.rows.sort((a: { page: string }, b: { page: string }) => Number(a.page) - Number(b.page));+ for (const row of rows) {+ expect(row.logs).toEqual([]);+ expect(row.pngHeader).toBe('89504e470d0a1a0a');+ expect(row.darkPixels).toBeGreaterThan(100);+ expect(row.sourcePreserved).toBe(true);+ expect(row.paragraphs.length).toBeGreaterThan(0);+ }+ // Independent source enumeration: each visible line appears exactly once,+ // in order, without prescribing the font-dependent page-break position.+ expect(rows.flatMap((row: { paragraphs: string[] }) => row.paragraphs)).toEqual(+ Array.from({ length: 24 }, (_, i) => `Line ${String(i + 1).padStart(3, '0')}: confirmed handover item`),+ );+ } finally { fs.rmSync(root, { recursive: true, force: true }); }+}, 40_000);+++// Synthetic classification controls do not launch Electron or rewrite raw logs.+const categoryWarning = '[12345:1026/194646.769918:ERROR:base/process/process_mac.cc:98] task_policy_set TASK_CATEGORY_POLICY: (os/kern) invalid argument (4)';+const suppressionWarning = '[12346:1026/194646.769919:ERROR:base/process/process_mac.cc:98] task_policy_set TASK_SUPPRESSION_POLICY: (os/kern) invalid argument (4)';++it('retains both exact macOS native policy diagnostics with their original lines', async () => {+ // Only these synthetic warnings are intercepted; real native cases above+ // retain console.warn output for the shared log-analysis gate.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ await checkNativeStderr('', 'darwin');+ expect(warn).not.toHaveBeenCalled();+ await checkNativeStderr(categoryWarning + '\r\n' + suppressionWarning + '\r\n', 'darwin');+ expect(warn.mock.calls).toEqual([+ ['[native-host-warning]', categoryWarning],+ ['[native-host-warning]', suppressionWarning],+ ]);+ } finally { warn.mockRestore(); }+});++it.each([+ ['unknown stderr', 'Unexpected renderer launch failure'],+ ['different kernel code', categoryWarning.replace('(4)', '(5)')],+ ['different native source', categoryWarning.replace('process_mac.cc', 'process_linux.cc')],+ ['additional trailing text', categoryWarning + ' another diagnostic'],+])('rejects %s without classifying it as a native host warning', async (_label, stderr) => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ await expect(checkNativeStderr(stderr, 'darwin')).rejects.toThrow('Unexpected native Chromium stderr');+ expect(warn).not.toHaveBeenCalled();+ } finally { warn.mockRestore(); }+});++it.each(['win32', 'linux'] as const)('rejects the macOS native signature on %s', async platform => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ await expect(checkNativeStderr(categoryWarning, platform)).rejects.toThrow('Unexpected native Chromium stderr');+ expect(warn).not.toHaveBeenCalled();+ } finally { warn.mockRestore(); }+});++it('rejects mixed stderr while retaining the preceding exact native warning', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ await expect(checkNativeStderr(categoryWarning + '\nUnexpected renderer launch failure\n', 'darwin'))+ .rejects.toThrow('Unexpected native Chromium stderr');+ expect(warn.mock.calls).toEqual([['[native-host-warning]', categoryWarning]]);+ } finally { warn.mockRestore(); }+});diff --git a/test/main/features/office/office-readonly_e2e.test.ts b/test/main/features/office/office-readonly_e2e.test.tsnew file mode 100644index 00000000..fd20f890--- /dev/null+++ b/test/main/features/office/office-readonly_e2e.test.ts@@ -0,0 +1,72 @@+import { execFile } from 'node:child_process';+import { createRequire } from 'node:module';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { promisify } from 'node:util';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++const require = createRequire(import.meta.url);+type Row = {+ id: string; error?: string;+ logs: Array<{ scope: string; level: string; args: unknown[] }>;+ browserLogs: Array<{ level: string; message: string }>;+ commands: Array<{ verb: string; code: number; stderr: string; stdoutChars: number }>;+ renderErrors: Array<{ page: string; message: string }>;+};+// OfficeCLI is bundled for desktop macOS/Windows, not Linux hosts.+describe.skipIf(!['darwin', 'win32'].includes(process.platform))('real Office review lifecycle', () => {+ let root: string;+ let rows: Row[];++ beforeAll(async () => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-office-readonly-e2e-'));+ const env = { ...process.env, ORKAS_WORKSPACE_ROOT: path.join(root, 'data') };+ fs.mkdirSync(env.ORKAS_WORKSPACE_ROOT);+ delete env.ELECTRON_RUN_AS_NODE;+ const output = path.join(root, 'results.json');+ const logs = await promisify(execFile)(require('electron'), [+ path.resolve('test/fixtures/office/readonly-review.cjs'), process.cwd(), output,+ ], { env, timeout: 150_000, maxBuffer: 256 * 1024 });+ // Even an otherwise empty Electron app emits one console CRLF on Windows.+ expect(process.platform === 'win32' ? ['', '\r\n'] : ['']).toContain(logs.stdout);+ expect(logs.stderr).toBe('');+ rows = JSON.parse(fs.readFileSync(output, 'utf8'));+ expect(rows.map(row => row.id)).toEqual([+ 'combined-review', 'partial-page-retry', 'cancel-after-check', 'invalid-document', 'edit-then-review',+ 'xlsx-render', 'pptx-render',+ ]);+ }, 160_000);++ afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); });++ it.each([+ ['combined-review', 'checks and renders a foreign DOCX without changing its revision'],+ ['partial-page-retry', 'retains the successful page, preserves the source and recovers after an absent page'],+ ['cancel-after-check', 'preserves the source and can render again after cancellation following a real check'],+ ['invalid-document', 'rejects invalid OpenXML without rendering or changing the source'],+ ['edit-then-review', 'saves an intentional edit, preserves the original and reviews the new revision'],+ ['xlsx-render', 'renders a real workbook with no browser warnings or source mutation'],+ ['pptx-render', 'renders a real presentation with no browser warnings or source mutation'],+ ])('%s: %s', (id) => {+ const row = rows.find(item => item.id === id)!;+ expect(row.error, JSON.stringify({ commands: row.commands, renderErrors: row.renderErrors, logs: row.logs })).toBeUndefined();+ expect(row.commands.length).toBeGreaterThan(0);+ expect(row.commands.every(command => command.stderr === '')).toBe(true);+ expect(row.browserLogs).toEqual([]);+ const warnings = id === 'partial-page-retry' || id === 'cancel-after-check' ? 1 : 0;+ expect(row.logs).toHaveLength(warnings);+ expect(row.renderErrors).toHaveLength(warnings);+ if (id === 'partial-page-retry') expect(row.renderErrors[0]).toMatchObject({ page: '99', message: expect.stringContaining('E_OFFICE_RENDER_PAGE_UNAVAILABLE') });+ if (id === 'cancel-after-check') expect(row.renderErrors[0].message).toContain('E_OFFICE_ABORTED');+ for (const log of row.logs) {+ expect(log).toMatchObject({ scope: 'office-tools', level: 'warn' });+ expect(log.args[0]).toBe('render error');+ }+ const failures = row.commands.filter(command => command.code !== 0);+ if (id === 'invalid-document') {+ expect(failures).toHaveLength(1);+ expect(failures[0].verb).toBe('validate');+ } else expect(failures).toEqual([]);+ });+});diff --git a/test/main/features/office/office_engine.test.ts b/test/main/features/office/office_engine.test.tsindex dc80c011..a46a6239 100644--- a/test/main/features/office/office_engine.test.ts+++ b/test/main/features/office/office_engine.test.ts@@ -1,4 +1,4 @@-import { EventEmitter } from 'node:events';+import { EventEmitter, once } from 'node:events';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({spawn: vi.fn(),spawnSync: vi.fn(),killProcessTree: vi.fn(),+ warn: vi.fn(),}));vi.mock('node:child_process', () => ({@@ -17,7 +18,7 @@ vi.mock('node:child_process', () => ({}));vi.mock('../../../../src/main/paths', () => ({ officeCliBinaryPath: () => mocks.bin || null }));vi.mock('../../../../src/main/logger', () => ({- createLogger: () => ({ warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }),+ createLogger: () => ({ warn: mocks.warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() }),}));vi.mock('../../../../src/core-agent/src/sandbox/executor', () => ({killProcessTree: mocks.killProcessTree,@@ -28,6 +29,7 @@ import {OfficeCliError,_resetOfficeCliAvailableForTest,closeAllOfficeResidents,+ closeOfficeFile,officeCliAvailable,runOfficeCli,} from '../../../../src/main/features/office/office_engine';@@ -55,6 +57,7 @@ describe('OfficeCLI engine', () => {mocks.spawn.mockReset();mocks.spawnSync.mockReset();mocks.killProcessTree.mockReset();+ mocks.warn.mockReset();_resetOfficeCliAvailableForTest();});@@ -68,6 +71,8 @@ describe('OfficeCLI engine', () => {it('does not cache a missing binary but retains a positive availability result', () => {fs.rmSync(mocks.bin);expect(officeCliAvailable()).toBe(false);+ expect(mocks.warn).toHaveBeenCalledOnce();+ expect(JSON.stringify(mocks.warn.mock.calls)).not.toContain(tmpDir);fs.writeFileSync(mocks.bin, 'binary');expect(officeCliAvailable()).toBe(true);fs.rmSync(mocks.bin, { force: true });@@ -201,17 +206,101 @@ describe('OfficeCLI engine', () => {expect(mocks.killProcessTree).toHaveBeenCalledWith(child, 'SIGKILL');});- it('uses a hidden absolute taskkill tree command for the Windows resident sweep', () => {+ it.each(['close', 'sweep'] as const)('keeps %s failure diagnostics without leaking private file or error contents', async (operation) => {+ const file = path.join(tmpDir, 'confidential-acquisition.docx');+ const privateMessage = 'private document text and credentials from a failed native process';+ const failure = new Error(privateMessage);+ mocks.spawn.mockImplementation(() => { throw failure; });+ mocks.spawnSync.mockImplementation(() => { throw failure; });++ if (operation === 'close') await expect(closeOfficeFile(file, tmpDir)).resolves.toBeUndefined();+ else expect(() => closeAllOfficeResidents()).not.toThrow();++ expect(mocks.warn).toHaveBeenCalledOnce();+ const diagnostic = mocks.warn.mock.calls[0][1];+ expect(diagnostic).toMatchObject({+ error: {+ message_hash: expect.stringMatching(/^[a-f0-9]{12}$/),+ message_chars: privateMessage.length,+ },+ });+ const serialized = JSON.stringify(mocks.warn.mock.calls);+ expect(serialized).not.toContain(privateMessage);+ expect(serialized).not.toContain(tmpDir);+ expect(serialized).not.toContain(path.basename(file));+ });++ it('bounds the Windows resident helper, uses an absolute system executable and passes paths as data', () => {vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');vi.stubEnv('SystemRoot', 'D:\\Windows');mocks.bin = 'D:\\Orkas\\resources\\officecli\\officecli-win-x64.exe';+ mocks.spawnSync.mockReturnValue({ status: 0 });closeAllOfficeResidents();expect(mocks.spawnSync).toHaveBeenCalledWith(- 'D:\\Windows\\System32\\taskkill.exe',- ['/F', '/T', '/IM', 'officecli-win-x64.exe'],- { timeout: 5_000, stdio: 'ignore', windowsHide: true },+ 'D:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', expect.any(String)],+ { env: expect.objectContaining({ ORKAS_OFFICECLI_SWEEP_BINARY: mocks.bin }), timeout: 5_000, stdio: 'ignore', windowsHide: true },);+ const source = Buffer.from(mocks.spawnSync.mock.calls[0][1].at(-1), 'base64').toString('utf16le');+ expect(source).not.toContain(mocks.bin);+ expect(mocks.warn).not.toHaveBeenCalled();+ });++ it.each([{ status: 1 }, { status: null, error: new Error('timeout') }])('surfaces an unsuccessful Windows resident sweep without broadening its target: %j', result => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');+ mocks.spawnSync.mockReturnValue(result);+ closeAllOfficeResidents();+ expect(mocks.spawnSync).toHaveBeenCalledTimes(1);+ expect(mocks.warn).toHaveBeenCalledOnce();+ expect(JSON.stringify(mocks.warn.mock.calls)).not.toContain(tmpDir);});++ it.runIf(process.platform === 'win32')('stops only this installation\'s Windows residents, preserving same-name and active commands', async () => {+ const native = await vi.importActual<typeof import('node:child_process')>('node:child_process');+ const binaryName = `orkas-office-fixture-${process.pid}-${Date.now()}.exe`;+ const own = path.join(tmpDir, "Orkas Office 测试 '", binaryName);+ const other = path.join(tmpDir, 'Orkas-other', binaryName);+ for (const binary of [own, other]) {+ fs.mkdirSync(path.dirname(binary), { recursive: true });+ fs.copyFileSync(process.env.ORKAS_TEST_NODE!, binary);+ }+ for (const command of ['__resident-serve__', 'create']) {+ fs.writeFileSync(path.join(tmpDir, command), "console.log('ready');setTimeout(() => {}, 30000);");+ }+ mocks.bin = own;+ mocks.spawnSync.mockImplementation(native.spawnSync);+ const children: import('node:child_process').ChildProcess[] = [];+ const diagnostics: string[] = [];+ const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };+ try {+ for (const [binary, command] of [[own, '__resident-serve__'], [other, '__resident-serve__'], [own, 'create']]) {+ // A resident-mode word later in a document command must not select it.+ const child = native.spawn(binary, [command, '__resident-serve__'], {+ cwd: tmpDir, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined },+ });+ children.push(child);+ child.stderr!.on('data', bytes => diagnostics.push(String(bytes)));+ await once(child.stdout!, 'data', { signal: AbortSignal.timeout(3000) });+ }+ closeAllOfficeResidents();+ expect(alive(children[0].pid!)).toBe(false);+ expect(alive(children[1].pid!), 'another installation with the same executable name must survive').toBe(true);+ expect(alive(children[2].pid!), 'a live document command is not a stale resident').toBe(true);+ closeAllOfficeResidents();+ expect(alive(children[1].pid!)).toBe(true);+ expect(alive(children[2].pid!)).toBe(true);+ expect(mocks.warn).not.toHaveBeenCalled();+ } finally {+ await Promise.all(children.map(async child => {+ if (child.exitCode !== null || child.signalCode !== null) return;+ const closed = once(child, 'close', { signal: AbortSignal.timeout(3000) });+ child.kill();+ await closed;+ }));+ }+ expect(diagnostics).toEqual([]);+ }, 15000);});diff --git a/test/main/features/office/office_page_renderer.test.ts b/test/main/features/office/office_page_renderer.test.tsindex 45c537f1..88d7b12d 100644--- a/test/main/features/office/office_page_renderer.test.ts+++ b/test/main/features/office/office_page_renderer.test.ts@@ -2,6 +2,7 @@ import { EventEmitter } from 'node:events';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';+import { fileURLToPath } from 'node:url';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -34,7 +35,7 @@ class FakeWebContents extends EventEmitter {class FakeBrowserWindow {static instances: FakeBrowserWindow[] = [];webContents = new FakeWebContents();- loadURL = vi.fn(async () => undefined);+ loadURL = vi.fn(async (_url: string) => undefined);setContentSize = vi.fn();destroy = vi.fn();constructor(readonly options: Record<string, unknown>) {@@ -164,4 +165,65 @@ describe('embedded Office page renderer', () => {fs.rmSync(cwd, { recursive: true, force: true });}});++ it('rejects failed pagination without publishing an unpaginated image and releases the renderer', async () => {+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-office-pagination-'));+ const ses = fakeSession();+ mocks.runOfficeCli.mockImplementation(async (args: string[]) => {+ fs.writeFileSync(args[args.indexOf('-o') + 1], '<html></html>');+ return { code: 0, stdout: '', stderr: '' };+ });+ class FailedPaginationWindow extends FakeBrowserWindow {+ constructor(options: Record<string, unknown>) {+ super(options);+ const ordinary = this.webContents.executeJavaScript.getMockImplementation()!;+ this.webContents.executeJavaScript.mockImplementation(async script => {+ if (script.includes('window._wordPaginate')) throw new Error('native pagination failed');+ return ordinary(script);+ });+ }+ }+ try {+ await expect(renderOfficePageToPng(path.join(cwd, 'handover.docx'), cwd, '1', undefined, {+ loadElectron: async () => ({+ BrowserWindow: FailedPaginationWindow as any,+ session: { fromPartition: () => ses as any },+ }),+ })).rejects.toThrow('native pagination failed');+ const win = FakeBrowserWindow.instances[0];+ expect(win.webContents.capturePage).not.toHaveBeenCalled();+ expect(win.destroy).toHaveBeenCalled();+ expect(ses.clearStorageData).toHaveBeenCalled();+ } finally { fs.rmSync(cwd, { recursive: true, force: true }); }+ });++ it('installs the Office policy before generated scripts and preserves the source document', async () => {+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-office-policy-'));+ const source = path.join(cwd, 'fixture.docx');+ fs.writeFileSync(source, 'source must not change');+ const ses = fakeSession();+ mocks.runOfficeCli.mockImplementation(async (args: string[]) => {+ fs.writeFileSync(args[args.indexOf('-o') + 1], '<!doctype html><html><head><script>window.ready=true</script>'+ + '<base href="https://untrusted.example/"></head><body><div class="page"></div></body></html>');+ return { code: 0, stdout: '', stderr: '' };+ });+ class PolicyWindow extends FakeBrowserWindow {+ loadURL = vi.fn(async (url: string) => {+ const html = fs.readFileSync(fileURLToPath(new URL(url)), 'utf8');+ expect(html.indexOf('Content-Security-Policy')).toBeGreaterThan(0);+ expect(html.indexOf('Content-Security-Policy')).toBeLessThan(html.indexOf('<script>'));+ expect(html).toContain("connect-src 'none'");+ expect(html).toContain("object-src 'none'");+ expect(html).not.toContain("'unsafe-eval'");+ expect(html).not.toContain('<base ');+ });+ }+ try {+ await renderOfficePageToPng(source, cwd, '1', undefined, {+ loadElectron: async () => ({ BrowserWindow: PolicyWindow as any, session: { fromPartition: () => ses as any } }),+ });+ expect(fs.readFileSync(source, 'utf8')).toBe('source must not change');+ expect(FakeBrowserWindow.instances[0].webContents.capturePage).toHaveBeenCalledOnce();+ } finally { fs.rmSync(cwd, { recursive: true, force: true }); }+ });});diff --git a/test/main/model/core-agent/office-tools.test.ts b/test/main/model/core-agent/office-tools.test.tsindex 6e42c6fa..5bd9de61 100644--- a/test/main/model/core-agent/office-tools.test.ts+++ b/test/main/model/core-agent/office-tools.test.ts@@ -1192,6 +1192,49 @@ describe('Office built-in tools', () => {});});+ it.each(['docx', 'xlsx', 'pptx'])('preserves native numeric issue severity for %s review', async (extension) => {+ const file = path.join(h.workspace, `numeric-review.${extension}`);+ fs.writeFileSync(file, 'fixture');+ // Pinned OfficeCLI v1.0.139 DocumentIssue.cs: Error=0, Warning=1, Info=2.+ // Native values take precedence over the legacy subtype fallback.+ for (const includeError of [false, true]) {+ h.runOfficeCli.mockReset();+ const issues = [+ { severity: 1, type: 0, message: 'Body paragraph missing first-line indent' },+ { severity: 2, type: 0, message: 'Mixed CJK/Latin punctuation' },+ ...(includeError ? [{ severity: 0, subtype: 'formula_cache_stale' }] : []),+ ];+ h.runOfficeCli.mockImplementation(async (args: string[]) => ({+ code: 0, stderr: '', stdout: JSON.stringify(args[0] === 'validate' ? { valid: true }+ : args[2] === 'issues' ? { success: true, data: { count: issues.length, issues } }+ : args[2] === 'stats' ? { success: true, data: { sheets: 1, totalCells: 1, formulaCells: 0, errorCells: 0 } }+ : { success: true, data: { results: [] } }),+ }));+ const result = await getTool('office_review').execute({ action: 'check', path: file }, ctx());+ expect(result.isError).toBeUndefined();+ expect(JSON.parse(result.content)).toMatchObject({+ valid: true,+ issue_severity_counts: { blocker: includeError ? 1 : 0, warning: 1, info: 1, unknown: 0 },+ structural_review_status: includeError ? 'blockers_found' : 'reviewed',+ });+ expect(fs.readFileSync(file, 'utf8')).toBe('fixture');+ }+ });++ it('keeps unrecognized severity values and unreturned issues indeterminate', async () => {+ const file = path.join(h.workspace, 'unknown-severity.docx');+ fs.writeFileSync(file, 'fixture');+ const issues = [3, -1, 1.5, '1', null, false, {}].map(severity => ({ severity }));+ h.runOfficeCli+ .mockResolvedValueOnce({ code: 0, stdout: '{"valid":true}', stderr: '' })+ .mockResolvedValueOnce({ code: 0, stdout: JSON.stringify({ count: issues.length + 1, issues }), stderr: '' });+ const result = await getTool('office_review').execute({ action: 'check', path: file }, ctx());+ expect(JSON.parse(result.content)).toMatchObject({+ valid: true, issue_severity_counts: { blocker: 0, warning: 0, info: 0, unknown: 8 },+ structural_review_status: 'indeterminate',+ });+ });+it('adds compact XLSX statistics and keeps incomplete issue severity explicit', async () => {const file = path.join(h.workspace, 'formula-review.xlsx');fs.writeFileSync(file, 'fixture');diff --git a/test/main/util/extract-office.test.ts b/test/main/util/extract-office.test.tsindex 845c4002..19f083f6 100644--- a/test/main/util/extract-office.test.ts+++ b/test/main/util/extract-office.test.ts@@ -66,6 +66,16 @@ describe('extract-office › xlsxBufferToMarkdown', () => {});describe('extract-office › xlsxBufferToHtml', () => {+ it('renders every row of a large worksheet without exceeding the argument limit', () => {+ const count = 150000;+ const source = makeMinimalXlsx({ rows: Array.from({ length: count }, (_, i) => [`record-${i + 1}`]) });+ const html = xlsxBufferToHtml(source);++ expect(html.match(/<tr>/g)).toHaveLength(count);+ expect(html).toContain('<td>record-1</td>');+ expect(html).toContain('<td>record-150000</td>');+ }, 15000);+it('renders worksheet rows as escaped table HTML', () => {const html = xlsxBufferToHtml(makeMinimalXlsx({sheetName: 'Scores & Totals',diff --git a/test/main/util/extract-xls-pool.test.ts b/test/main/util/extract-xls-pool.test.tsnew file mode 100644index 00000000..131475dc--- /dev/null+++ b/test/main/util/extract-xls-pool.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it, vi } from 'vitest';++const parser = vi.hoisted(() => {+ const jobs: Array<{ input?: Buffer; close: (error: Error | null, stdout: string) => void }> = [];+ return { jobs, active: 0, maxActive: 0 };+});++// Control only the child protocol and its completion order. Real XLS parsing,+// byte preservation and workbook errors remain covered by extract-xls.test.ts.+vi.mock('../../../src/main/util/bundled-runtime', () => ({+ bundledRuntimeEnv: () => ({ ORKAS_PYTHON: 'controlled-xls-reader' }),+}));+vi.mock('node:child_process', () => ({+ execFile: (_file: string, _args: string[], _options: unknown, callback: (error: Error | null, stdout: string) => void) => {+ parser.active++;+ parser.maxActive = Math.max(parser.maxActive, parser.active);+ const job = {+ input: undefined as Buffer | undefined,+ close(error: Error | null, stdout: string) {+ parser.active--;+ callback(error, stdout);+ },+ };+ parser.jobs.push(job);+ return { stdin: { on() {}, end(input: Buffer) { job.input = input; } } };+ },+}));++import { xlsBufferToMarkdown } from '../../../src/main/util/extract-xls';++describe('XLS reader admission and child lifecycle', () => {+ it('bounds admission at two active and 32 waiting, wakes FIFO and releases every failure', async () => {+ const calls = Array.from({ length: 35 }, (_, index) =>+ xlsBufferToMarkdown(Buffer.from(String(index))).then(+ value => ({ status: 'fulfilled' as const, value }),+ error => ({ status: 'rejected' as const, error: error.message as string }),+ ));+ expect(parser.jobs.map(job => job.input?.toString())).toEqual(['0', '1']);+ expect(parser.active).toBe(2);+ expect(await calls[34]).toEqual({ status: 'rejected', error: expect.stringContaining('busy') });++ for (let index = 0; index < 34; index++) {+ expect(parser.jobs[index].input?.toString()).toBe(String(index));+ if (index === 0) parser.jobs[index].close(new Error('controlled child failure'), '');+ else parser.jobs[index].close(null, JSON.stringify(index === 33+ ? { sheets: [{ name: 'Queued', rows: [{ number: 1, values: ['queued valid workbook'] }] }] }+ : { error: 'format' }));+ const result = await calls[index];+ expect(result).toEqual(index === 33+ ? { status: 'fulfilled', value: expect.stringContaining('queued valid workbook') }+ : { status: 'rejected', error: expect.stringContaining(index === 0 ? 'resource limit' : 'Cannot read') });+ // Each completion admits exactly the oldest waiter, never a third child.+ expect(parser.jobs).toHaveLength(Math.min(34, index + 3));+ expect(parser.active).toBe(Math.min(2, 33 - index));+ }+ expect(parser.maxActive).toBe(2);+ expect(parser.active).toBe(0);+ const after = xlsBufferToMarkdown(Buffer.from('after'));+ expect(parser.jobs[34].input?.toString()).toBe('after');+ parser.jobs[34].close(null, JSON.stringify({ sheets: [{ name: 'After', rows: [{ number: 1, values: ['after valid workbook'] }] }] }));+ await expect(after).resolves.toContain('after valid workbook');+ expect(parser.active).toBe(0);+ });+});diff --git a/test/main/util/extract-xls.test.ts b/test/main/util/extract-xls.test.tsindex 915ba446..2d2da4a6 100644--- a/test/main/util/extract-xls.test.ts+++ b/test/main/util/extract-xls.test.ts@@ -39,15 +39,15 @@ describe('legacy XLS extraction with the bundled reader', () => {await expect(xlsBufferToMarkdown(bytes)).rejects.toThrow('password-protected');});- it('bounds a failure burst and releases reader slots for a queued valid workbook', async () => {- const calls = Array.from({ length: 35 }, (_, i) =>- xlsBufferToMarkdown(i === 33 ? fixture() : Buffer.from('invalid workbook')));- const results = await Promise.allSettled(calls);- expect(results[33].status).toBe('fulfilled');- expect((results[33] as PromiseFulfilledResult<string>).value).toContain('Inventory sentinel 8384');- const reasons = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected').map(r => r.reason.message);- expect(reasons.filter(message => message.includes('busy'))).toHaveLength(1);- expect(reasons.filter(message => message.includes('Cannot read'))).toHaveLength(33);+ it('releases real reader slots after concurrent invalid and valid workbooks', async () => {+ const [invalid, valid] = await Promise.allSettled([+ xlsBufferToMarkdown(Buffer.from('invalid workbook')),+ xlsBufferToMarkdown(fixture()),+ ]);+ expect(invalid.status).toBe('rejected');+ expect((invalid as PromiseRejectedResult).reason.message).toContain('Cannot read');+ expect(valid.status).toBe('fulfilled');+ expect((valid as PromiseFulfilledResult<string>).value).toContain('Inventory sentinel 8384');await expect(xlsBufferToMarkdown(fixture())).resolves.toContain('冷却泵');}, 15_000);diff --git a/test/main/util/office-extract.test.ts b/test/main/util/office-extract.test.tsnew file mode 100644index 00000000..40e441f6--- /dev/null+++ b/test/main/util/office-extract.test.ts@@ -0,0 +1,72 @@+import { afterEach, expect, it } from 'vitest';+import { extractOffice, closeOfficeExtraction } from '../../../src/main/util/office-extract';+import { xlsxBufferToMarkdown, xlsxBufferToHtml, pptxBufferToMarkdown, pptxBufferToHtml } from '../../../src/main/util/extract-office';+import { makeSparseXlsx, makeReorderedPptx, makeMinimalXlsx } from '../../fixtures/make-minimal-office';++afterEach(closeOfficeExtraction);++it('keeps exact extracted content, escaping and caller-owned source bytes', async () => {+ const xlsx = makeSparseXlsx(), pptx = makeReorderedPptx();+ const original = [Buffer.from(xlsx), Buffer.from(pptx)];+ expect(await Promise.all([+ extractOffice('xlsx-markdown', xlsx), extractOffice('xlsx-html', xlsx),+ extractOffice('pptx-markdown', pptx), extractOffice('pptx-html', pptx),+ ])).toEqual([xlsxBufferToMarkdown(xlsx), xlsxBufferToHtml(xlsx), pptxBufferToMarkdown(pptx), pptxBufferToHtml(pptx)]);+ expect([xlsx, pptx]).toEqual(original);+});++it('contains malformed input and lets the next valid document complete', async () => {+ await expect(extractOffice('xlsx-markdown', Buffer.from('not a ZIP'))).rejects.toBeInstanceOf(Error);+ expect(await extractOffice('xlsx-markdown', makeSparseXlsx())).toBe(xlsxBufferToMarkdown(makeSparseXlsx()));+});++it('queues a burst beyond 64 jobs without rejecting it and admits only two input loads', async () => {+ let loads = 0;+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let failures = 0;+ const work = Array.from({ length: 70 }, () => extractOffice('xlsx-markdown', async () => {+ loads++; await gate; return makeSparseXlsx();+ }).catch(error => { failures++; throw error; }));+ const settled = Promise.allSettled(work);+ await new Promise(resolve => setImmediate(resolve));+ expect(loads).toBe(2);+ expect(failures).toBe(0);+ await closeOfficeExtraction();+ release();+ expect((await settled).every(result => result.status === 'rejected')).toBe(true);+ expect(await extractOffice('xlsx-markdown', makeSparseXlsx())).toContain('Left\t\tRight');+ const completed = await Promise.all(Array.from({ length: 70 }, () => extractOffice('xlsx-markdown', makeSparseXlsx())));+ expect(completed).toEqual(Array(70).fill(xlsxBufferToMarkdown(makeSparseXlsx())));+});++it('keeps the main event loop responsive while preserving a complete large spreadsheet', async () => {+ const rows = Array.from({ length: 40000 }, (_, n) => [`row-${n}`, `Full value ${n} <&>`]);+ const source = makeMinimalXlsx({ rows });+ const measure = async (work: () => string | Promise<string>) => {+ let last = performance.now(), maxGapMs = 0, ticks = 0, rss = process.memoryUsage().rss;+ const rssBefore = rss;+ const timer = setInterval(() => {+ const now = performance.now(); maxGapMs = Math.max(maxGapMs, now - last); last = now;+ rss = Math.max(rss, process.memoryUsage().rss); ticks++;+ }, 2);+ try {+ await new Promise(resolve => setTimeout(resolve, 5));+ ticks = 0;+ const start = performance.now();+ const text = await work();+ const elapsedMs = performance.now() - start;+ const workTicks = ticks;+ await new Promise(resolve => setTimeout(resolve, 5));+ return { text, elapsedMs, maxGapMs, workTicks, rssBefore, sampledRss: rss };+ } finally { clearInterval(timer); }+ };+ const baseline = await measure(() => xlsxBufferToMarkdown(source));+ const candidate = await measure(() => extractOffice('xlsx-markdown', source));+ expect(candidate.text).toBe(baseline.text);+ expect(candidate.text).toContain('row-39999\tFull value 39999 <&>');+ expect(candidate.workTicks).toBeGreaterThan(0);+ console.log('Office responsiveness measurement', JSON.stringify({ rows: rows.length, inputBytes: source.length,+ outputBytes: Buffer.byteLength(candidate.text), baseline: { ...baseline, text: undefined },+ candidate: { ...candidate, text: undefined } }));+}, 15000);diff --git a/test/renderer/office-preview-fidelity.test.ts b/test/renderer/office-preview-fidelity.test.tsindex 186c44c3..79df877c 100644--- a/test/renderer/office-preview-fidelity.test.ts+++ b/test/renderer/office-preview-fidelity.test.ts@@ -22,8 +22,8 @@ describe('Office preview fidelity contract', () => {expect(preview).toContain("if (kind === 'word') return '.docx'");expect(preview).toContain("if (kind === 'spreadsheet') return '.xlsx'");expect(preview).toContain('layoutRendered: true');- expect(preview).toContain("connect-src 'none'");- expect(preview).toContain("object-src 'none'");+ // The dynamic rendered-preview owner asserts the actual hardened HTML.+ expect(preview).toContain('hardenOfficeHtml(presentationSafeSource)');expect(ipc).toContain('officeFileToPreviewHtml(kind, path.basename(norm), norm, buf)');expect(contexts).toContain('officeFileToPreviewHtml(kind, path.basename(p), p, buf)');expect(projects).toContain('officeFileToPreviewHtml(kind, path.basename(r.absPath), r.absPath, buf)');