diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b5c43c..00bf387 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,6 +82,17 @@ jobs: fi npm run check:theme-colors + # skills/*/SKILL.md ship to users' agent directories; a body change + # without a metadata.version bump would never be offered as an update. + - name: Check skill versions + env: + FORMAT_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }} + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + FORMAT_BASE_REF=$(git rev-parse HEAD^1) + fi + npm run check:skill-version + # Added lines only: Han text outside locale tables, review-tool tags, # feedback-ledger ids, sample-corpus ids, internal PR numbers, personal # paths/e-mails, credentials, NUL bytes (tools/check-public-hygiene.mjs). @@ -118,6 +129,11 @@ jobs: - name: Check committed fixtures match the generator run: git diff --exit-code -- fixtures/generated + # pptx-engine's OOXML schema gate validates saved decks with xmllint + # (tools/ooxml-validate); the runner image is not guaranteed to have it. + - name: Install xmllint + run: sudo apt-get install -y --no-install-recommends libxml2-utils + - name: Test run: npm test diff --git a/.prettierignore b/.prettierignore index 07fcd29..69c9216 100644 --- a/.prettierignore +++ b/.prettierignore @@ -22,3 +22,6 @@ apps/slides/src/renderer/ai/prompts/*.md # In-page extractor fragments: concatenated into one function body, kept verbatim. packages/html2docx/src/browser/ + +# ISO/IEC 29500 schemas: keep byte-identical to the published files (one marked amendment). +tools/ooxml-validate/schemas/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e56390..fac3231 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,7 +22,7 @@ directly on this repository as usual. ## Repository layout -- `apps/*` — the six Electron apps (docs, sheets, slides, pdf, markdown, shell). +- `apps/*` — the seven Electron apps (docs, sheets, slides, pdf, markdown, html, shell). Each app is an npm workspace with its own `src/main` (Electron main process), `src/renderer` (React UI), and `tests/`. - `packages/*` — pure TypeScript engine and shared packages (no Electron @@ -30,6 +30,48 @@ directly on this repository as usual. i18n, UI kit. - `apps/sheets/native/xlsx-engine` — Rust xlsx engine (runs as a sidecar process) for xlsx import/export. +## Engine packages + +All pure TypeScript, no Electron dependency, unit-tested (except the UI kit): + +- `packages/docx-engine` — docx parsing → block tree (with `docxIndex` + anchors and passthrough), OOXML fragment generation, byte-level paragraph + patching. +- `packages/pptx-engine` / `packages/pptx-render` — pptx model and rendering. +- `packages/pdf2docx` — local PDF → DOCX conversion: PDFium character-level + extraction, pure-geometry layout analysis, rebuild through `docx-engine`; + the same analysis drives the PDF app's PowerPoint and Excel exports. +- `packages/html2docx` — local HTML → DOCX conversion: the page is rendered in + the app's own Chromium, reduced in-browser to a document intent tree, and + written as native OOXML with the `docx` library; only visuals with no Word + counterpart are screenshotted. Drives the HTML app's Export as Word. +- `packages/file-parse` — text extraction for AI attachments (office formats, + text formats). +- `packages/agent-core` — the AI agent loop and skill composition shared by + every app. +- `packages/ai-provider` — provider abstraction and streaming for the model + backends. +- `packages/ai-search` — Genspark auth + web/image search tools. +- `packages/i18n`, `packages/ui`, `packages/project-store`, + `packages/electron-utils` — shared i18n core, React UI kit, recent-files + store, and Electron main-process helpers. + +### Architecture notes (docx round trip) + +``` +open docx ─► archive original by hash (never touched) + ─► docx-engine parses word/document.xml top-level elements (w:p / w:tbl / …) + ─► Block tree, each block anchored by docxIndex + original XML slice + ─► Tiptap streaming editor (manual + AI editing, dirty tracking) +save ─► dirty blocks → OOXML fragments (referencing existing styles only) + ─► splice into original document.xml (untouched blocks keep original bytes) + ─► repack zip; all other entries copied byte-for-byte +``` + +The same philosophy holds in sheets and slides: the original file is the +source of truth, edits are applied as narrow patches, and everything the +editor didn't touch survives the round trip untouched. + ## Getting started Prerequisites: Node 22+, npm 10+, and a Rust toolchain (`cargo` on PATH, @@ -70,7 +112,7 @@ formatting diff. ## Building installers Run these from the repository root — they regenerate the third-party -notices and build all six apps before packaging: +notices and build all seven apps before packaging: ```bash npm run dist:mac # dmg + zip diff --git a/NOTICE b/NOTICE index 5e3319f..9f140d9 100644 --- a/NOTICE +++ b/NOTICE @@ -23,3 +23,11 @@ https://www.unicode.org/Public/17.0.0/ucd/EquivalentUnifiedIdeograph.txt Copyright © 1991-2026 Unicode, Inc. This data is distributed under Unicode License v3. The complete copyright and permission notice is reproduced in LICENSE-UNICODE.txt. + +Office Open XML schemas + +tools/ooxml-validate/schemas contains the ISO/IEC 29500-4:2016 (ECMA-376 +Part 4, Transitional) XML Schema files for PresentationML and DrawingML, as +distributed in the python-docx repository (ref/xsd), with one marked local +amendment (see tools/ooxml-validate/README.md). They are used only by tests +and development tooling and are not shipped in the application. diff --git a/README.md b/README.md index 615db30..09b728b 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Word, Excel, PowerPoint and PDF files, edited by you and your AI, saved back in

Download · + CLI · Website · Community · Privacy @@ -47,6 +48,10 @@ file, makes the change, and shows you exactly what it touched. key for Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty, or any OpenAI-compatible endpoint, local servers included. +- **Scriptable and agent-ready.** The app ships a `genoffice` command line and + a skill for Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode + and Windsurf, so a coding agent can create, convert, read and edit real + Office files on your machine without opening a window. **Get it:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon and Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 and Arm) · @@ -55,8 +60,9 @@ details and requirements in [Download](#download). ## Demo -Six apps, one AI panel. Every screenshot is the real app on macOS, with the -AI driven from the prompt you can read in the panel. +Six apps, one AI panel, and a command line for your coding agent. Every +screenshot is the real app on macOS, with the AI driven from the prompt you +can read in the panel. ### 1 · Docs — open and edit `.docx` with an AI you can review @@ -154,6 +160,26 @@ self-contained `.html` file against those tokens. +### 7 · CLI — your coding agent drives GenOffice, on your machine + +GenOffice ships a `genoffice` command line and an agent skill. Install the +skill and Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode or +Windsurf can create, convert, read and edit real Office files through the +same engines as the apps, without opening a window. + +GenOffice Slides showing an eight-slide Solar System deck that a coding agent built through the genoffice command line: the cover slide on the canvas, eight thumbnails on the left and the AI panel open + + + + + + + + + + +
The eight rendered slides of the Solar System deck side by side: cover, exploration timeline, four key numbers, planet-diameter bar chart, rocky worlds versus giants, the Sun's 99.8% hero number, the four giants grid and takeawaysGenOffice Settings, Integrations page: the genoffice skill installed into Claude Code, with Install buttons next to Codex and Cursor
One prompt to your agent — "Build an eight-slide deck about the Solar System." The agent reads the skill, writes a style sheet, an outline and one page spec per slide, generates the two photos with genoffice image, and lets genoffice slides check reject anything that overflows or overlaps before genoffice create assembles the .pptx and slides render hands back a PNG per slide to look at.Install once, from Settings → Integrations — GenOffice lists the coding agents it finds on this computer and writes the skill into each one you pick. Or download the skill as a zip, or run npx skills add genspark-ai/genoffice. Commands and the full workflow are in Command line and agent skill.
+ ## Why GenOffice - **Open source**, Apache-2.0, built in the open on GitHub. @@ -170,6 +196,9 @@ self-contained `.html` file against those tokens. - **PDF done properly.** Edit text inside the page, and convert PDF to Word, Excel or PowerPoint on-device, with system OCR for scans. - **Markdown and HTML too**, with the same AI panel and local export to Word. +- **Scriptable.** A `genoffice` command line and an agent skill put every + engine at the service of Claude Code, Codex, Cursor and other coding agents, + still on-device. - **Free**, for individuals and teams alike. ## AI backends @@ -191,6 +220,73 @@ The whole suite ships light, dark and system themes. Themes only change what is on screen: exports, prints and saved files always keep the document's own colors. +## Command line and agent skill + +Everything the apps can do to a file, the `genoffice` command line can do from +a terminal: inspect, convert, create, read and edit Word, Excel, PowerPoint, +PDF, Markdown and HTML on the same engines, headless. It installs with +GenOffice, needs no runtime of its own, and never sends a document anywhere. +Paired with the bundled **agent skill**, it turns a coding agent into a +document worker that produces real Office files instead of Markdown +approximations. + +**Works with:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode and Windsurf out of the box, and any other agent that reads skills. + +### Install the skill + +| How | What happens | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Settings → Integrations** in the app | Lists the agents found on this computer; one click writes the skill into each one you choose. An **Update** button appears when a GenOffice release ships a newer skill. | +| **Download as zip** on the same page | The layout claude.ai, the Claude desktop apps and other assistants accept as an uploaded skill. | +| `npx skills add genspark-ai/genoffice` | Installs from this repository into any skills-compatible agent. | + +Then start a new chat and ask for a document. The skill teaches the agent when +to reach for `genoffice`, how to read a file before editing it, and how to +check its own work. + +### Quickstart from the terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Every command prints a one-line summary, or a single JSON object with +`--json`. Edits are atomic: a rejected op leaves the file untouched and comes +back with a guided error. `genoffice help` lists the current command surface; +the full reference is [packages/cli/README.md](packages/cli/README.md). + +### What the agent actually runs + +The Solar System deck in the [demo](#demo) took one prompt in Claude Code. +Behind it, the agent followed the skill's staged workflow and the CLI checked +every stage before the next one started: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +No model call happens inside `genoffice`: the agent does the thinking, the CLI +does the building and the checking, and the result opens in GenOffice or +PowerPoint as an ordinary `.pptx`. + ## Download | Platform | Requirements | Download | @@ -353,6 +449,18 @@ form fields and page backgrounds; only visuals with no Word counterpart +

+Can I drive GenOffice from Claude Code, Codex, Cursor or a script? + +Yes. GenOffice installs a `genoffice` command line that runs the same engines +headless: inspect, convert, create, read and edit documents from a terminal or +a script, with `--json` output for programs. The bundled agent skill teaches +Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf +to use it; install it from **Settings → Integrations**. See +[Command line and agent skill](#command-line-and-agent-skill). + +
+
Does GenOffice collect any data? diff --git a/apps/docs/src/main/docs-main.ts b/apps/docs/src/main/docs-main.ts index 6e96752..94617a0 100644 --- a/apps/docs/src/main/docs-main.ts +++ b/apps/docs/src/main/docs-main.ts @@ -8,8 +8,20 @@ import { unlinkSync, writeFileSync, } from 'node:fs' -import { copyFile, mkdir, readFile, readdir, stat, unlink, writeFile } from 'node:fs/promises' +import { + copyFile, + mkdir, + mkdtemp, + readFile, + readdir, + rm, + stat, + unlink, + writeFile, +} from 'node:fs/promises' +import { tmpdir } from 'node:os' import { basename, join } from 'node:path' +import { pathToFileURL } from 'node:url' import { BrowserWindow, Menu, @@ -30,6 +42,7 @@ import { fetchRemoteImage, installContextMenu, installNavigationGuard, + isHeadlessMode, printHtmlToPdf, safeExternalUrl, saveAsSuggestion, @@ -37,6 +50,11 @@ import { showSaveDialogWithMemory, toggleDevToolsItem, windowMenuTemplate, + type HeadlessExportFormat, + type HeadlessExportTarget, + installRendererProtocol, + registerRendererScheme, + rendererUrl, } from '@genoffice/electron-utils' import { configureMetricsCache, familyVerticalMetrics } from '@genoffice/font-metrics' import { createI18n, getUiLang, normalizeLang, setUiLang } from '@genoffice/i18n' @@ -49,6 +67,8 @@ import type { WebContents, } from 'electron' import { parseFileToText } from '@genoffice/file-parse' +import { convertHtmlToDocx } from '../../../../packages/html2docx/src' +import { ElectronBrowserDriver } from '../../../../packages/html2docx/src/drivers/electron' import { AiCreditsError, AiTimeoutError, @@ -3195,6 +3215,10 @@ export function registerProjectIpc(): void { }) } +/** A4 at 96dpi, as the HTML app exports */ +const ALT_CHUNK_VIEWPORT = { width: 794, height: 1123, deviceScaleFactor: 2 } +const ALT_CHUNK_HTML_MAX_CHARS = 64 * 1024 * 1024 + /** document/attachment/window IPC (everything except the AI proxy above) */ export function registerDocsIpc(): void { registerZoteroIpc() @@ -3223,6 +3247,32 @@ export function registerDocsIpc(): void { ipcMain.handle('docs:open-path', (event, filePath: string) => loadDocx(filePath, event.sender.id)) + // w:altChunk HTML: the same html2docx chain as the HTML app's export, in a + // hidden window; the renderer parses the result and shows its blocks + ipcMain.handle('docs:altchunk-html-to-docx', async (_event, html: unknown) => { + if (typeof html !== 'string' || !html.trim() || html.length > ALT_CHUNK_HTML_MAX_CHARS) { + return null + } + const workDir = await mkdtemp(join(tmpdir(), 'genoffice-altchunk-')) + let driver: ElectronBrowserDriver | null = null + try { + const htmlPath = join(workDir, 'chunk.html') + // the BOM outranks a stale left in the decoded markup + await writeFile(htmlPath, `\ufeff${html}`, 'utf8') + driver = await ElectronBrowserDriver.create(ALT_CHUNK_VIEWPORT) + const { docx } = await convertHtmlToDocx({ url: pathToFileURL(htmlPath).href }, driver, { + naturalTableWidth: true, + }) + return docx + } catch (err) { + console.warn('[docs] altChunk conversion failed:', err) + return null + } finally { + await driver?.close() + await rm(workDir, { recursive: true, force: true }).catch(() => {}) + } + }) + // Review > Protect > Encrypt with Password: set/clear the open password. // Takes effect on the next save (docs:save / save-as / save-new all consult the store). ipcMain.handle( @@ -3313,6 +3363,25 @@ export function registerDocsIpc(): void { return content }) + // ---- headless export mode (--headless-export) ---- + + ipcMain.handle('docs:consume-headless-export', (event): HeadlessExportTarget | null => { + const target = headlessExportTargets.get(event.sender.id) ?? null + headlessExportTargets.delete(event.sender.id) + return target + }) + + ipcMain.on('docs:headless-export-done', (event, result: unknown) => { + const settle = headlessExportWaiters.get(event.sender.id) + if (!settle) return + headlessExportWaiters.delete(event.sender.id) + const state = result as { ok?: unknown; error?: unknown } | null + settle({ + ok: state?.ok === true, + ...(typeof state?.error === 'string' ? { error: state.error } : {}), + }) + }) + ipcMain.handle( 'docs:save', async (event, filePath: string, data: ArrayBuffer, auto?: boolean) => { @@ -3854,6 +3923,9 @@ export function setDocsShellHooks(hooks: DocsShellHooks | null): void { * (shell) or reveal it in the folder (standalone). Tab-opening failure must * not report the write itself as failed — the file is already persisted. */ function openGeneratedFile(path: string): void { + // Headless export has no tab strip and no user: revealing the file in Finder + // would be the only visible effect of a run that must stay silent. + if (isHeadlessMode()) return try { if (shellHooks?.openGeneratedPath?.(path)) return } catch (err) { @@ -4191,6 +4263,73 @@ export function buildDocsMenu(): void { Menu.setApplicationMenu(Menu.buildFromTemplate(template)) } +// ---- headless export ---- + +/** hidden export windows: webContents id -> what the renderer must write */ +const headlessExportTargets = new Map() +/** settled by 'docs:headless-export-done' (or by the renderer dying) */ +const headlessExportWaiters = new Map void>() + +interface HeadlessExportReport { + ok: boolean + error?: string +} + +/** + * Render `input` to `outPath` (as PDF or standalone HTML) with no visible window. + * + * The window is wired exactly like createDocsWindow's (same preload, sandbox + * and `backgroundThrottling: false`) and the document rides the normal + * pending-open queue, so the renderer runs its usual load -> paginate -> + * export pipeline; only the save dialog is skipped, by pre-authorizing + * `outPath` the way a dialog would. Rejects with the renderer's reason when + * the export fails or the deadline passes. + */ +export async function exportDocsHeadless( + input: string, + outPath: string, + format: HeadlessExportFormat = 'pdf', + timeoutMs = 300_000, +): Promise { + const win = new BrowserWindow({ + show: false, + width: 1360, + height: 900, + webPreferences: { + preload: runtime.preloadPath, + contextIsolation: true, + nodeIntegration: false, + sandbox: true, + backgroundThrottling: false, + }, + }) + const wcId = win.webContents.id + pendingWindowOpens.set(wcId, input) + headlessExportTargets.set(wcId, { outPath, format }) + allowPdfWrite(wcId, outPath) + let timer: ReturnType | undefined + try { + const report = await new Promise((resolve) => { + headlessExportWaiters.set(wcId, resolve) + win.webContents.on('render-process-gone', (_event, details) => + resolve({ ok: false, error: `docs renderer stopped (${details.reason})` }), + ) + timer = setTimeout( + () => resolve({ ok: false, error: `docs export timed out after ${timeoutMs}ms` }), + timeoutMs, + ) + void win.webContents.loadURL(rendererUrl(runtime.rendererUrl, 'docs')) + }) + if (!report.ok) throw new Error(report.error ?? 'docs export failed') + } finally { + if (timer) clearTimeout(timer) + headlessExportWaiters.delete(wcId) + headlessExportTargets.delete(wcId) + pendingWindowOpens.delete(wcId) + if (!win.isDestroyed()) win.destroy() + } +} + // ---- window ---- export function createDocsWindow(openPath?: string): BrowserWindow { @@ -4234,11 +4373,7 @@ export function createDocsWindow(openPath?: string): BrowserWindow { return { action: 'deny' } }) - if (runtime.rendererUrl) { - void win.loadURL(runtime.rendererUrl) - } else { - void win.loadFile(runtime.rendererFile) - } + void win.loadURL(rendererUrl(runtime.rendererUrl, 'docs')) // close guard for standalone-window mode (tab mode goes through the same flow via the shell's tab-manager/window-close path) let closeConfirmed = false win.on('close', (event) => { @@ -4457,14 +4592,7 @@ export function createDocsView(openPath?: string): WebContentsView { // mode=tab: the shell's tab strip owns the traffic lights / caption buttons, // so the ribbon must not reserve space for them - if (runtime.rendererUrl) { - // append via URL so a dev URL that already carries query params stays valid - const devUrl = new URL(runtime.rendererUrl) - devUrl.searchParams.set('mode', 'tab') - void view.webContents.loadURL(devUrl.toString()) - } else { - void view.webContents.loadFile(runtime.rendererFile, { query: { mode: 'tab' } }) - } + void view.webContents.loadURL(rendererUrl(runtime.rendererUrl, 'docs', { mode: 'tab' })) // view.webContents becomes undefined after destroy, so grab the id beforehand const wcId = view.webContents.id view.webContents.once('destroyed', () => { @@ -4486,6 +4614,7 @@ export function hasDocsWindow(): boolean { // ---- standalone lifecycle (apps/docs running on its own) ---- export function startDocsStandalone(): void { + registerRendererScheme() installNavigationGuard(app) installContextMenu(app, () => contextMenuLabels(getUiLang())) // dev runs must not share the packaged app's userData (recent files, AI settings) @@ -4518,6 +4647,7 @@ export function startDocsStandalone(): void { registerDocsIpc() app.whenReady().then(() => { + installRendererProtocol({ docs: join(__dirname, '../renderer') }) setUiLang(normalizeLang(process.env.GENOFFICE_LANG ?? app.getLocale())) // packaged builds get the Dock icon from icon.icns; dev shows Electron's default if (isDev && process.platform === 'darwin') { diff --git a/apps/docs/src/main/zotero-ipc.ts b/apps/docs/src/main/zotero-ipc.ts index 5b039e2..c77759d 100644 --- a/apps/docs/src/main/zotero-ipc.ts +++ b/apps/docs/src/main/zotero-ipc.ts @@ -13,10 +13,11 @@ let registered = false function requestRenderer(contents: WebContents, request: ZoteroWireRequest): Promise { return new Promise((resolve, reject) => { const requestId = randomUUID() + // a displayAlert waits on a modal the user may leave open for a while const timer = setTimeout(() => { pending.delete(requestId) reject(new Error(`Timed out handling ${request.command}`)) - }, 120_000) + }, 600_000) pending.set(requestId, { webContentsId: contents.id, resolve: (value) => { diff --git a/apps/docs/src/main/zotero-wire.ts b/apps/docs/src/main/zotero-wire.ts index daf17b6..11db32f 100644 --- a/apps/docs/src/main/zotero-wire.ts +++ b/apps/docs/src/main/zotero-wire.ts @@ -60,10 +60,17 @@ export class ZoteroWireClient { private socket: Socket | null = null private active = false + constructor( + private readonly host = ZOTERO_INTEGRATION_HOST, + private readonly port = ZOTERO_INTEGRATION_PORT, + ) {} + get isActive(): boolean { return this.active } + /** Resolves when Zotero has finished the command (it closes the connection after + * Document_complete), so callers can keep the document busy for the whole run. */ async run( command: string, handleRequest: (request: ZoteroWireRequest) => Promise, @@ -72,12 +79,10 @@ export class ZoteroWireClient { this.active = true const decoder = new ZoteroFrameDecoder() + let socket: Socket try { - const socket = await new Promise((resolve, reject) => { - const candidate = createConnection({ - host: ZOTERO_INTEGRATION_HOST, - port: ZOTERO_INTEGRATION_PORT, - }) + socket = await new Promise((resolve, reject) => { + const candidate = createConnection({ host: this.host, port: this.port }) const onError = (error: Error) => reject(error) candidate.once('error', onError) candidate.once('connect', () => { @@ -85,7 +90,14 @@ export class ZoteroWireClient { resolve(candidate) }) }) - this.socket = socket + } catch (error) { + this.active = false + this.socket = null + throw error + } + this.socket = socket + return new Promise((resolve, reject) => { + let failure: Error | null = null socket.on('data', (chunk) => { let frames: ZoteroWireFrame[] try { @@ -96,19 +108,17 @@ export class ZoteroWireClient { } for (const frame of frames) void this.respondToFrame(socket, frame, handleRequest) }) + socket.once('error', (error) => { + failure = error + }) socket.once('close', () => { if (this.socket === socket) this.socket = null this.active = false - }) - socket.once('error', () => { - // Post-connect errors terminate the socket; request failures are returned as ERR frames. + if (failure) reject(failure) + else resolve() }) socket.write(encodeZoteroFrame(0, JSON.stringify({ command, templateVersion: 1 }))) - } catch (error) { - this.active = false - this.socket = null - throw error - } + }) } close(): void { diff --git a/apps/docs/src/preload/index.ts b/apps/docs/src/preload/index.ts index 6ccedfe..9a60ad6 100644 --- a/apps/docs/src/preload/index.ts +++ b/apps/docs/src/preload/index.ts @@ -57,6 +57,7 @@ const api: DesktopApi = { respondToZotero: (response) => ipcRenderer.send('zotero:response', response), openDocx: () => ipcRenderer.invoke('docs:open'), openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path), + convertAltChunkHtml: (html: string) => ipcRenderer.invoke('docs:altchunk-html-to-docx', html), openDocxDecrypt: (path: string, password: string) => ipcRenderer.invoke('docs:open-decrypt', path, password), setDocPassword: (filePath: string | null, password: string | null) => @@ -72,6 +73,9 @@ const api: DesktopApi = { consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'), consumeNewBlankDoc: () => ipcRenderer.invoke('docs:consume-new-blank'), consumeAiDocContent: () => ipcRenderer.invoke('docs:consume-ai-doc-content'), + consumeHeadlessExport: () => ipcRenderer.invoke('docs:consume-headless-export'), + headlessExportDone: (result: { ok: boolean; error?: string }) => + ipcRenderer.send('docs:headless-export-done', result), createDocument: (request) => ipcRenderer.invoke('docs:create-document', request), onOpenDocx: (handler) => { const listener = (_event: IpcRendererEvent, result: Parameters[0]) => diff --git a/apps/docs/src/renderer/App.tsx b/apps/docs/src/renderer/App.tsx index 261aeef..77fd549 100644 --- a/apps/docs/src/renderer/App.tsx +++ b/apps/docs/src/renderer/App.tsx @@ -1,4 +1,5 @@ import { DOC_CSS_COMMITTED_EVENT } from './editor/cjk-punct-shrink' +import { justifyShrinkPluginKey } from './editor/justify-shrink' import { useCallback, useEffect, @@ -11,12 +12,35 @@ import { import type { CSSProperties, MouseEvent as ReactMouseEvent, SetStateAction } from 'react' import { EditorContent, useEditor } from '@tiptap/react' import type { Editor } from '@tiptap/core' -import { DOMParser as PmDOMParser, type Mark as PmMark } from '@tiptap/pm/model' -import { NodeSelection } from '@tiptap/pm/state' +import { DOMParser as PmDOMParser, type Mark as PmMark, Slice as PmSlice } from '@tiptap/pm/model' +import { NodeSelection, type Transaction } from '@tiptap/pm/state' import { Dropdown, useAutoSavePref } from '@genoffice/ui' import { wordRangeAtCaret } from './editor/comments' import { markdownPasteHtml } from './editor/markdown-paste' import { pasteTextSlice, singleCellPasteText } from './editor/paste-text' +import { + imageFilesFromDataTransfer, + insertImageFilesAtCoords, + isImageFileDrag, +} from './editor/image-drop' +import { + caretFontSlots, + fillMissingRunFonts, + isForeignPasteHtml, + pushDownWebInlineStyles, +} from './editor/paste-web-html' +import { + beginForeignPaste, + caretParaFormat, + caretStyleMark, + consumeForeignPaste, + defaultPasteMode, + lastForeignPasteMode, + mergeFormattingFragment, + stashPastePayload, + takeTextReroute, +} from './editor/paste-options' +import { PasteOptionsChip } from './components/PasteOptionsChip' import { BLANK_BULLET_NUM_ID, BLANK_ORDERED_NUM_ID, @@ -45,6 +69,7 @@ import { AiPanel, AI_REVISION_AUTHOR } from './ai/AiPanel' import type { AiCommentsAccess, AiHeaderFooterAccess } from './ai/tools' import { applyHfText, hfEditText } from './editor/hf-text' import { textColorValue } from './editor/text-color' +import { textOutlineCssValue } from './editor/text-outline' import { AiAskPopover } from './components/AiAskPopover' import { EDIT_QUEUE_MAX, selectionForAnchor, type DocsEditQueueItem } from './ai/edit-queue' import { addQueueAnchor, clearQueueAnchors, removeQueueAnchors } from './editor/ai-queue-anchors' @@ -53,6 +78,7 @@ import { CommentsPanel } from './components/CommentsPanel' import { EquationModal } from './components/EquationModal' import { HeaderFooterArea } from './components/HeaderFooterArea' import { PageFootnotes, PageEndnotes } from './components/PageNoteAreas' +import { noteMarkText, type NoteKind } from './note-format' import { PaginationPreview } from './components/PaginationPreview' import { PrintDialog } from './components/PrintDialog' import { @@ -70,6 +96,7 @@ import { measureBlocks, docGridPitchPt, type LineAnchor, + hfVariantOf, pageNumbers, sliceWithLineSplit, type SliceOutputs, @@ -80,8 +107,17 @@ import { pageAt, singleCutCell, columnLayoutSpecs, + widthPassGate, + newWidthPassState, + resetWidthPassHistory, vAlignShiftSpecs, + verticalTextSpecs, + blockInlineExtraPx, + sectionVertical, + sectionTopMarginSpecs, sectionWidthSpecs, + paperWidthPx, + pageLeftPx, sectionGridPitchPt, sectionGridPitchSpecs, docCharSpacePt, @@ -107,6 +143,8 @@ import { alignGapHfStrips, alignTableGapFills, clearFloatShifts, + floatFlowChangedMeta, + insideFloatTable, setFloatVShifts, setOversizeClips, setPageGaps, @@ -115,11 +153,13 @@ import { syncCutOverlays, syncFloatShifts, syncPageBorders, + syncPageSheets, clampCellBoxTops, pageBorderStyleOf, type PageGapSpec, } from './editor/pagination-gaps' import { setColumnLayout } from './editor/column-layout' +import { syncLineNumbers } from './editor/line-numbers' import { MARKUP_AREA_W, clearMarginAnnotations, @@ -230,6 +270,7 @@ import { type FileActionContext, type PendingPdfExport, } from './file-actions' +import { runHeadlessDocumentExport } from './headless-export' import { allocateListNumId as allocateListNumIdImpl, continueNumbering as continueNumberingImpl, @@ -300,16 +341,43 @@ function posFromAnchor(view: Editor['view'], anchor: LineAnchor): number | undef } } -/** Clean pasted Word/web HTML: mso conditional comments, , and unwrapping
  • x

  • */ +/** Clean pasted Word/web HTML: mso conditional comments, , and unwrapping
  • x

  • ; + * foreign fragments also get block-level font/size/color pushed down onto + * spans so whole-paragraph web copies keep their formatting (r181) */ function cleanPastedHtml(html: string): string { - return unwrapSingleCellTable( + const cleaned = unwrapSingleCellTable( html .replace(//g, '') .replace(/[\s\S]*?<\/o:p>/g, '') .replace(/]*)>\s*]*>([\s\S]*?)<\/p>\s*<\/li>/g, '$2'), ) + return isForeignPasteHtml(html) ? pushDownWebInlineStyles(cleaned) : cleaned } +/** Plain text for a text-mode paste whose clipboard carries no text/plain + * flavor (some apps write HTML only) — the fragment's text content with + * block boundaries as line breaks. */ +function htmlFallbackText(html: string): string { + if (!html) return '' + try { + const body = new window.DOMParser().parseFromString(html, 'text/html').body + for (const block of body.querySelectorAll('p,div,li,tr,h1,h2,h3,h4,h5,h6,br')) { + block.after(body.ownerDocument.createTextNode('\n')) + } + return (body.textContent ?? '').replace(/\n{2,}/g, '\n').trim() + } catch { + return '' + } +} + +// The per-paste foreign-HTML handshake (mode selection, chip payload) lives +// in editor/paste-options.ts: the paste DOM handler and the ribbon Paste +// button arm it (the clipboard is parsed BEFORE handlePaste runs, so the +// mode must be decided when the paste event arrives), transformPasted and +// the handlePaste lanes consume it. Our own clipboard HTML keeps its exact +// run marks, plain-text pastes go through pasteTextSlice, and drops never +// arm anything. + /** * Word parity: pasting a copy of a SINGLE spreadsheet cell inserts its * content as text, not a 1x1 table (alpha ledger r146 — a lone cell copied @@ -365,10 +433,14 @@ function blockNoteScanRuns(b: Block): NonNullable { } /** Note entry content: superscript number + styled runs (shared by the canvas gap area and the hidden height measurer) */ -function appendNoteRuns(row: HTMLElement, it: Omit): void { +function appendNoteRuns( + row: HTMLElement, + it: Omit, + kind: NoteKind, +): void { if (!it.noRefMark) { const sup = document.createElement('sup') - sup.textContent = String(it.no) + sup.textContent = noteMarkText(kind, it.no) row.append(sup) } if (it.richParas) { @@ -388,6 +460,7 @@ function appendNoteRuns(row: HTMLElement, it: Omit, + kind: NoteKind, widthPx: number, lineHeightPx: number, fontSizePt: number, @@ -426,7 +500,7 @@ function measureNoteHeightDom( noteMeasureHost.style.fontSize = `${fontSizePt}pt` noteMeasureHost.style.lineHeight = `${lineHeightPx}px` const row = document.createElement('div') - appendNoteRuns(row, entry) + appendNoteRuns(row, entry, kind) // the renderers' sup style (CSS classes don't reach the detached host) const sup = row.querySelector('sup') if (sup) { @@ -451,6 +525,9 @@ function makeGapNotesEl( const wrap = document.createElement('div') wrap.className = 'page-gap-notes' wrap.style.left = `${leftPx}px` + // paper x: block gaps start at the paper edge, mid-paragraph gaps at their page's + // edge — alignGapHfStrips re-anchors from the actual gap origin + wrap.dataset.paperX = leftPx.toFixed(1) wrap.style.width = `${widthPx}px` wrap.style.height = `${heightPx}px` // same line height as the reservation model; min-height keeps rows at the @@ -465,7 +542,7 @@ function makeGapNotesEl( if (it.lineHeightPx) row.style.lineHeight = `${it.lineHeightPx}px` if (it.fontSizePt) row.style.fontSize = `${it.fontSizePt}pt` if (it.fontFamily) row.style.fontFamily = it.fontFamily - appendNoteRuns(row, it) + appendNoteRuns(row, it, 'footnote') row.addEventListener('dblclick', () => onEdit(it.id)) wrap.appendChild(row) } @@ -707,6 +784,7 @@ export function App() { const [showPagePreview, setShowPagePreview] = useState(false) const [splitHtml, setSplitHtml] = useState('') const [showFind, setShowFind] = useState(false) + const [imageDragOver, setImageDragOver] = useState(false) const [findFocusReplace, setFindFocusReplace] = useState(0) const [showShortcuts, setShowShortcuts] = useState(false) const ribbonActionsRef = useRef<{ @@ -859,12 +937,79 @@ export function App() { // plain-text paste takes the insertion point's formatting like typing // (Word Keep Text Only) — the default parser misses storedMarks (r172) clipboardTextParser: (text, $context, _plain, view) => pasteTextSlice(text, $context, view), + handleDOMEvents: { + paste: (_view, event) => { + const html = event.clipboardData?.getData('text/html') ?? '' + const armed = beginForeignPaste(html) + stashPastePayload( + armed + ? { + html, + text: event.clipboardData?.getData('text/plain') ?? '', + mode: defaultPasteMode(), + } + : null, + ) + return false + }, + }, + // foreign-HTML paste, by the armed mode: 'source' fills runs that still + // have no concrete font after the parse (generic-only family chains + // like `sans-serif`) with the insertion point's font slots (r181); + // 'merge' formats the whole fragment like typing at the insertion + // point, keeping emphasis and structure; 'text' passes through — the + // handlePaste reroute below sends it down the plain-text lane + transformPasted: (slice, view) => { + const mode = consumeForeignPaste() + if (!mode || mode === 'text') return slice + const schema = view.state.schema + const markType = schema.marks.docTextStyle + if (!markType) return slice + const marks = view.state.storedMarks ?? view.state.selection.$from.marks() + if (mode === 'merge') { + return new PmSlice( + mergeFormattingFragment( + slice.content, + schema, + caretStyleMark(marks, schema), + caretParaFormat(view.state.selection.$from, schema), + ), + slice.openStart, + slice.openEnd, + ) + } + const slots = caretFontSlots(marks, markType) + if (!slots) return slice + return new PmSlice( + fillMissingRunFonts(slice.content, slots, schema), + slice.openStart, + slice.openEnd, + ) + }, + // image files dragged from the OS (or a browser) land as inline pictures + // at the drop point, like Word; other drops keep the default handling + handleDrop: (_view, event) => { + const ed = editorRef.current + const files = imageFilesFromDataTransfer(event.dataTransfer) + if (!ed || files.length === 0) return false + return insertImageFilesAtCoords(ed, files, { left: event.clientX, top: event.clientY }) + }, // clipboard images (screenshots/copied images): become inline images; mixed content // with HTML still uses default parsing (text in the HTML takes priority) handlePaste: (view, event) => { const data = event.clipboardData if (!data) return false const html = data.getData('text/html') + // text-mode foreign paste (default setting or chip choice): the whole + // payload goes down the plain-text lane, formatting like typing + if (takeTextReroute()) { + const plain = data.getData('text/plain') || htmlFallbackText(html) + if (plain) { + const slice = pasteTextSlice(plain, view.state.selection.$from, view) + view.dispatch(view.state.tr.replaceSelection(slice).scrollIntoView()) + return true + } + } // a lone unformatted spreadsheet cell is a text paste (the r146 unwrap // turns it into text) and takes the insertion point's formatting like // typing (r172) — the HTML lanes below keep no marks for it and would @@ -917,9 +1062,28 @@ export function App() { const dom = new window.DOMParser().parseFromString(cleanPastedHtml(html), 'text/html') const parsed = PmDOMParser.fromSchema(view.state.schema).parse(dom.body) if (parsed.content.childCount > 0) { - view.dispatch( - view.state.tr.replaceWith($from.before(1), $from.after(1), parsed.content), - ) + // this lane re-parses and dispatches itself, bypassing + // transformPasted — apply the armed paste mode to foreign + // fragments here too (r181; the empty paragraph's pilcrow + // memory lives in storedMarks, caret-marks.ts) + let content = parsed.content + if (isForeignPasteHtml(html)) { + const schema = view.state.schema + const markType = schema.marks.docTextStyle + const marks = view.state.storedMarks ?? $from.marks() + if (lastForeignPasteMode() === 'merge') { + content = mergeFormattingFragment( + content, + schema, + caretStyleMark(marks, schema), + caretParaFormat($from, schema), + ) + } else { + const slots = markType ? caretFontSlots(marks, markType) : null + if (slots) content = fillMissingRunFonts(content, slots, schema) + } + } + view.dispatch(view.state.tr.replaceWith($from.before(1), $from.after(1), content)) return true } } catch { @@ -1049,7 +1213,7 @@ export function App() { }, }) // Blink only respells an editable as a consequence of real (trusted) - // typing of a word-committing character inside it. The r168 retest ruled + // typing of a word-committing character inside it. A retest ruled // everything else out pixel by pixel: attribute flips, focus cycles (the // first attempt at this fix), script or execCommand edits, fresh DOM // nodes, session spellchecker kicks, synthetic clicks and arrow keys — @@ -1069,6 +1233,20 @@ export function App() { respellKickBusy.current = true const sub = getActiveSubEditor() const prev = document.activeElement as HTMLElement | null + // the caret can sit pages away from the viewport (last edit position); + // focusing and typing there scrolls it into view and the toggle + // "jumps to another page". Pin the scroller + // for the whole round trip: the reset runs inside the scroll event, + // before paint, so no jump ever shows. + const scroller = scrollContainerRef.current + const pinTop = scroller?.scrollTop ?? 0 + const pinLeft = scroller?.scrollLeft ?? 0 + const pinScroll = () => { + if (!scroller) return + if (scroller.scrollTop !== pinTop) scroller.scrollTop = pinTop + if (scroller.scrollLeft !== pinLeft) scroller.scrollLeft = pinLeft + } + scroller?.addEventListener('scroll', pinScroll, true) view.focus() // puts the DOM caret where the state says it is const sel = window.getSelection() // typing over a range would replace it — kick from a caret instead; @@ -1080,8 +1258,21 @@ export function App() { const caretText = caretNode instanceof Text ? caretNode : null const caretData = caretText?.data ?? null let sawKick = false + let kickDown = false + let kickPress = false + // shield: PM's keymap must not see the kick, and the user's own keys + // must not mutate the DOM while the observer is paused (the dwell + // below makes that window user-noticeable on Windows) — swallow them. + // Exactly one space keydown and the keypress it produces pass (the + // kick); a later user space would land behind PM's back too const shield = (e: KeyboardEvent) => { - if (e.key === ' ') sawKick = true + let pass = false + if (e.key === ' ') { + if (e.type === 'keydown' && !kickDown) pass = kickDown = true + else if (e.type === 'keypress' && !kickPress) pass = kickPress = true + } + if (pass) sawKick = true + else e.preventDefault() e.stopPropagation() } document.addEventListener('keydown', shield, true) @@ -1126,6 +1317,15 @@ export function App() { while (!sawKick && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 30)) } + // Linux/mac Hunspell respells in the keystroke's wake; the Windows + // OS spellchecker samples the text asynchronously with throttling, + // and a scrub 0.12s after the keystroke erased the mutation before + // the service ever saw it (squiggles only + // returned when repeated toggles happened to straddle a sampling + // window). Let the typed state live long enough to be sampled. + if (sawKick && /win/i.test(navigator.platform)) { + await new Promise((r) => setTimeout(r, 900)) + } scrub() observer.start() document.removeEventListener('keydown', shield, true) @@ -1134,9 +1334,13 @@ export function App() { view.focus() // resync the DOM selection from PM state // ribbon toggle during textbox editing: keep the routing and hand // the keyboard back where it was — typing must not replace the box - if (!sub) return - setActiveSubEditor(sub) - if (prev && prev !== dom) prev.focus({ preventScroll: true }) + if (sub) { + setActiveSubEditor(sub) + if (prev && prev !== dom) prev.focus({ preventScroll: true }) + } + // unpin after the focus resync so its selection scroll is caught too + pinScroll() + scroller?.removeEventListener('scroll', pinScroll, true) }) }) } @@ -1245,6 +1449,14 @@ export function App() { storage.enabled = trackChanges }, [editor, trackChanges]) + // forms protection locks the body but the form's own checkboxes stay + // clickable; Read Mode and a still-loading document keep them read-only + useEffect(() => { + if (!editor) return + editor.storage.checkboxToggle.formsFill = + !writeLocked && editRestriction === 'forms' && !readMode && !docLoading + }, [editor, writeLocked, editRestriction, readMode, docLoading]) + // window title follows the document, so the OS window list and Switch Window show file names useEffect(() => { document.title = doc ? doc.fileName : 'GenOffice Docs' @@ -1904,6 +2116,31 @@ export function App() { setShowPagePreview(true) }, [exportPdf]) + // Headless export mode (--headless-export): this renderer lives in a hidden + // window whose only job is to run the File menu's PDF or HTML export against + // a path the CLI chose, then report back so the main process can quit. + const headlessExportStartedRef = useRef(false) + useEffect(() => { + if (headlessExportStartedRef.current) return + headlessExportStartedRef.current = true + void (async () => { + const target = await window.desktop.consumeHeadlessExport() + if (!target) return + const report = await runHeadlessDocumentExport( + target.outPath, + // A failed open falls back to an untitled blank document (filePath + // null); exporting that would hand the CLI a blank PDF and call it + // success, so only a document that came from disk counts as ready. + () => { + const doc = fileCtxRef.current.doc + return { opened: typeof doc?.filePath === 'string', failed: doc?.filePath === null } + }, + target.format === 'html' ? exportHtml : exportPdf, + ) + window.desktop.headlessExportDone(report) + })() + }, [exportPdf, exportHtml]) + useEffect(() => { const pending = pendingMixedExportRef.current if (pending === false) return @@ -2177,9 +2414,10 @@ export function App() { fn: NoteInfo | undefined, no: number, sec: SectionSettings, + kind: NoteKind, ): { height: number; lineHeightPx: number; fontSizePt: number; fontFamily?: string } => { const contentW = twipsToPx(sec.pageWidth - sec.marginLeft - sec.marginRight) - const key = `${fn?.id ?? ''}|${no}|${Math.round(contentW)}|${fn?.styleId ?? ''}|${fn?.text ?? ''}` + const key = `${kind}|${fn?.id ?? ''}|${no}|${Math.round(contentW)}|${fn?.styleId ?? ''}|${fn?.text ?? ''}` let v = cache.get(key) if (!v) { const style = noteStyleOf(fn) @@ -2194,6 +2432,7 @@ export function App() { ...(fn?.richParas ? { richParas: fn.richParas } : {}), ...(fn?.noRefMark ? { noRefMark: true as const } : {}), }, + kind, contentW, lineHeightPx, fontSizePt, @@ -2217,12 +2456,21 @@ export function App() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [footnotes, endnotes, noteStyleOf]) - // page-bottom heights (px) reserved for footnote references inside a block, one per reference in run order + // display number of a note: the engine's body-order numbering (numStart / eachSect + // applied); notes added in this session are not in the map and count by list position + const noteNo = useCallback( + (kind: 'footnote' | 'endnote', id: string, index: number): number => + doc?.parsed.noteNumbers?.[`${kind}:${id}`] ?? index + 1, + [doc], + ) + + // page-bottom heights (px) reserved for footnote references inside a block, one per + // reference in run order, measured with the marker the page will draw const footnoteBandsOf = useCallback( (b: Block): Array<{ heightPx: number }> => { const runs = blockNoteScanRuns(b) if (runs.length === 0 || footnotes.length === 0) return [] - const noOf = new Map(footnotes.map((f, i) => [f.id, i + 1])) + const noOf = new Map(footnotes.map((f, i) => [f.id, noteNo('footnote', f.id, i)])) const bands: Array<{ heightPx: number }> = [] for (const run of runs) { if (run.noteRef?.kind !== 'footnote') continue @@ -2231,13 +2479,13 @@ export function App() { if (!sec) continue const fn = footnotes.find((f) => f.id === run.noteRef!.id) bands.push({ - heightPx: noteRenderInfoOf(fn, noOf.get(run.noteRef!.id) ?? 0, sec).height, + heightPx: noteRenderInfoOf(fn, noOf.get(run.noteRef!.id) ?? 0, sec, 'footnote').height, }) } // the once-per-page separator is charged by the pagination engine, not per block return bands }, - [footnotes, sections, section, noteRenderInfoOf], + [footnotes, sections, section, noteRenderInfoOf, noteNo], ) // typed w:docGrid line pitch (pt) when every section shares one; null = no snapping @@ -2393,6 +2641,14 @@ export function App() { [doc, header, footer, sectionHfEdits, titlePg, hfVariants, hfMeasureEpoch], ) + // paragraphs without w:pStyle take the default paragraph style's constraints (widowControl off in Normal) + const defaultParaStyle = useMemo( + () => + doc + ? [...doc.parsed.styles.values()].find((s) => s.type === 'paragraph' && s.isDefault) + : undefined, + [doc], + ) // pagination-constraint injection: docxIndex → parse-layer semantics (keepNext/keepLines/widow/table-row flags). // DOM measurement only has geometry; these constraints decide page cut points (no orphan headings / unbreakable lines / repeated table headers). const blockMetaOf = useCallback( @@ -2416,23 +2672,27 @@ export function App() { ...(fnExtra > 0 ? { footnoteExtraPx: fnExtra, footnoteBands: fnBands } : {}), } } - const styleDisplay = b.styleId ? doc?.parsed.styles.get(b.styleId)?.display : undefined + const styleDisplay = (b.styleId ? doc?.parsed.styles.get(b.styleId) : defaultParaStyle) + ?.display const keepNext = b.format?.keepNext ?? styleDisplay?.keepNext const keepLines = b.format?.keepLines ?? styleDisplay?.keepLines const breakBefore = b.format?.pageBreakBefore ?? styleDisplay?.pageBreakBefore - const widowOff = b.format?.widowControl === false + const widowOff = (b.format?.widowControl ?? styleDisplay?.widowControl) === false + const noLineNo = b.format?.suppressLineNumbers ?? styleDisplay?.suppressLineNumbers const fnBands = footnoteBandsOf(b) const fnExtra = fnBands.reduce((s, band) => s + band.heightPx, 0) - if (!keepNext && !keepLines && !breakBefore && !widowOff && fnExtra === 0) return undefined + if (!keepNext && !keepLines && !breakBefore && !widowOff && !noLineNo && fnExtra === 0) + return undefined return { ...(keepNext ? { keepNext: true } : {}), ...(keepLines ? { keepLines: true } : {}), + ...(noLineNo ? { suppressLineNumbers: true } : {}), ...(breakBefore ? { breakBefore: true } : {}), ...(widowOff ? { widowControl: false as const } : {}), ...(fnExtra > 0 ? { footnoteExtraPx: fnExtra, footnoteBands: fnBands } : {}), } }, - [doc, footnoteBandsOf], + [doc, defaultParaStyle, footnoteBandsOf], ) // per-page footnote collection: the page of the referencing block → that page's footnote entries (number/text/estimated height) @@ -2440,7 +2700,7 @@ export function App() { (blocks: BlockBox[], slices: PageSlice[]): PageNoteItem[][] => { const out: PageNoteItem[][] = slices.map(() => []) if (!doc || footnotes.length === 0 || !section) return out - const noOf = new Map(footnotes.map((f, i) => [f.id, i + 1])) + const noOf = new Map(footnotes.map((f, i) => [f.id, noteNo('footnote', f.id, i)])) for (const b of blocks) { if (b.docxIndex === undefined) continue const pb = doc.parsed.blocks.find((bl) => bl.docxIndex === b.docxIndex) @@ -2462,7 +2722,7 @@ export function App() { const page = band ? pageAt(slices, b.top + (b.spaceBeforePx ?? 0) + band.offset + 0.5) - 1 : blockPage - const info = noteRenderInfoOf(fn, noOf.get(id) ?? 0, sec) + const info = noteRenderInfoOf(fn, noOf.get(id) ?? 0, sec, 'footnote') out[page]?.push({ no: noOf.get(id) ?? 0, id, @@ -2478,7 +2738,7 @@ export function App() { } return out }, - [doc, footnotes, sections, section, noteRenderInfoOf], + [doc, footnotes, sections, section, noteRenderInfoOf, noteNo], ) // endnote-area entries (placed together at the document end, shared by pagination preview and page slicing): height measured with the final section's content width @@ -2486,9 +2746,10 @@ export function App() { if (!section || endnotes.length === 0) return [] const sec = sections[sections.length - 1]?.settings ?? section return endnotes.map((n, i) => { - const info = noteRenderInfoOf(n, i + 1, sec) + const no = noteNo('endnote', n.id, i) + const info = noteRenderInfoOf(n, no, sec, 'endnote') return { - no: i + 1, + no, id: n.id, text: n.text, ...(n.richParas ? { richParas: n.richParas } : {}), @@ -2499,7 +2760,7 @@ export function App() { ...(info.fontFamily ? { fontFamily: info.fontFamily } : {}), } }) - }, [endnotes, sections, section, noteRenderInfoOf]) + }, [endnotes, sections, section, noteRenderInfoOf, noteNo]) // canvas column mode: // - 'uniform': every section shares one equal-width multi-column spec (and is LTR) — @@ -2514,9 +2775,12 @@ export function App() { const g0 = sectionColGeom(sections[0]) const uniform = !sections.some(sectionBidi) && - // a same-count nextColumn boundary advances a column — whole-page CSS - // multicol can't paint that, so such documents go through mixed mode - !sections.some((s, i) => i > 0 && s.startType === 'nextColumn') && + // a same-count nextColumn boundary advances a column and a continuous one + // balances the closed columns mid-page — whole-page CSS multicol can't + // paint either, so such documents go through mixed mode + !sections.some( + (s, i) => i > 0 && (s.startType === 'nextColumn' || s.startType === 'continuous'), + ) && sections.every((s) => { const g = sectionColGeom(s) return ( @@ -2542,6 +2806,8 @@ export function App() { () => sections.some((s) => s.settings.vAlign === 'center' || s.settings.vAlign === 'bottom'), [sections], ) + // vertical-text sections (verticalTextSpecs) ride the same translate channel + const hasVertical = useMemo(() => sections.some((s) => sectionVertical(s.settings)), [sections]) // single-flow measuring state for the columned canvas: uniform mode temporarily drops // the CSS columns and sets the width to the column width; mixed mode neutralizes the @@ -2550,7 +2816,7 @@ export function App() { // column flow (synchronous layout round-trip, no visible flicker) const measureSingleFlow = useCallback( function run(pm: HTMLElement, fn: () => T): T { - if ((colMode === 'none' && !hasVAlign) || viewMode !== 'print') return fn() + if ((colMode === 'none' && !hasVAlign && !hasVertical) || viewMode !== 'print') return fn() pm.classList.add('measuring-columns') try { return fn() @@ -2558,7 +2824,7 @@ export function App() { pm.classList.remove('measuring-columns') } }, - [colMode, hasVAlign, viewMode], + [colMode, hasVAlign, hasVertical, viewMode], ) // column-flow geometry gate: when the canvas column layout is inactive, measure as full-width single flow; the geometry must drop cols to match @@ -2583,6 +2849,8 @@ export function App() { const { blocks, totalHeight, sectBreaks } = measureBlocks(pm, origin, factor) const live = liveSections(sections, blocks, sectBreaks, delSectBreaks) let s: PageSlice[] + // same row-split mode as the canvas pass, or TOC page numbers drift + const splitOut: SliceOutputs = { rowSplits: [] } if (live.length > 0) { assignSections(blocks, live) s = sliceWithLineSplit( @@ -2591,6 +2859,7 @@ export function App() { totalHeight, factor, blockMetaOf, + splitOut, ) } else { const contentH = twipsToPx(section.pageHeight) - effTopSingle - effBottomSingle @@ -2608,6 +2877,7 @@ export function App() { totalHeight, factor, blockMetaOf, + splitOut, ) } return { mBlocks: blocks, slices: s, secs: live } @@ -2650,12 +2920,17 @@ export function App() { if (!scroller) return const factor = zoom / 100 const mTopPx = canvasTop + // shared paper = the widest section's page; narrower pages are centered on it + const paperWPx = paperWidthPx(sections, sections[0]?.settings ?? section) + const pageLeftOf = (set: SectionSettings) => pageLeftPx(set, paperWPx) + const mixedPaper = sections.some((s) => pageLeftOf(s.settings) > 0.5) const contentH = twipsToPx(section.pageHeight) - effTopSingle - effBottomSingle let slices: PageSlice[] = [] let timer: number | null = null let suppressSig = '' let secWidthSig = '' let charSpaceSig = '' + const colWidthPass = newWidthPassState() const pmEl = () => document.querySelector('.editor-scroll .ProseMirror') as HTMLElement | null const locate = () => { const pm = pmEl() @@ -2667,8 +2942,17 @@ export function App() { // slices use gapless virtual coordinates; subtract the page-gap height above the midpoint // (including mid-paragraph inline gaps and repeated-header clone rows, which carry // page-repeat-header but not page-gap) + // page-turn gaps only, like the page frames: a split floating table's + // in-table gaps count (they are page turns) while its carry spacer does + // not — the two sums agree past the spacer, and inside the float's pages + // only the former maps the midpoint onto the page shown there. Its + // repeated-header clones are float content (the carry covers only the + // gap bands; the continuation's page starts at the gap's bottom) let gapAbove = 0 - for (const gap of pm.querySelectorAll('.page-gap, .page-repeat-header')) { + for (const gap of pm.querySelectorAll( + '.page-gap:not(.page-gap-carry), .page-repeat-header', + )) { + if (gap.classList.contains('page-repeat-header') && insideFloatTable(gap)) continue const r = gap.getBoundingClientRect() if (r.top < midScreen) gapAbove += Math.min(r.height, midScreen - r.top) } @@ -2681,6 +2965,15 @@ export function App() { ) } const remeasure = () => { + try { + remeasurePass() + } finally { + // a pass that threw between the add and the pre-setPageGaps remove + // must not leave the gap widgets hidden + pmEl()?.classList.remove('measuring-natural') + } + } + const remeasurePass = () => { const pm = pmEl() if (!pm) return const tStart = performance.now() @@ -2689,6 +2982,15 @@ export function App() { // consecutive anchor-paragraph runs collapse onto their band union before // measurement (layout-affecting, idempotent) syncAnchorBands(pm, factor) + // natural-flow measuring state: in-paragraph gap widgets force a line break + // at the PREVIOUS pass's cut, so measuring with them in layout re-confirms + // that cut even after decoration-only reflows (justify space-shrink) moved + // the natural wrap points — a justified page-last line then stayed + // stretched sparse until an at-boundary edit (r177). Hidden, sampling AND + // cut-anchor resolution below see the natural wrap; removed before + // setPageGaps so widget building and later display-state reads (strip + // alignment, cut overlays, locate) run against the real layout. + pm.classList.add('measuring-natural') // a columned canvas measures + slices in the single-flow measuring state (fillLineBoxes // also reads the DOM for line sampling, so it must share the state); display-state DOM // reads like gap positioning happen outside the measuring state @@ -2696,6 +2998,8 @@ export function App() { const t0 = performance.now() const origin = pm.getBoundingClientRect().top + mTopPx * factor const { blocks, totalHeight, floats, sectBreaks } = measureBlocks(pm, origin, factor) + if (hasVertical) + for (const b of blocks) if (b.el && !b.floated) b.inlineExtraPx = blockInlineExtraPx(b.el) tMeasure = performance.now() - t0 // multi-section: assign blocks to sections by docxIndex; each section has its own content height / forced breaks. // liveSections: when a section-break block is deleted, that section merges into the next in real time (effective before saving) @@ -2722,7 +3026,16 @@ export function App() { const flowH = flowWithFloats ?? withEndnotes?.totalHeight ?? totalHeight const hfHs = secList ? hfHeightsOf(secList) : null const t1 = performance.now() - const sliceOut: SliceOutputs = { rowFills: [], floatVShifts: [], oversizeClips: [] } + // rowSplits enables the per-cell row split; the canvas only needs the + // matching row heights (the preview applies the cell shifts) + const sliceOut: SliceOutputs = { + rowFills: [], + rowSplits: [], + floatVShifts: [], + floatFlows: [], + floatSplits: [], + oversizeClips: [], + } const s = secList ? sliceWithLineSplit( blocks, @@ -2757,10 +3070,22 @@ export function App() { floats, rowFills: sliceOut.rowFills ?? [], floatVShifts: sliceOut.floatVShifts ?? [], + floatFlows: sliceOut.floatFlows ?? [], + floatSplits: sliceOut.floatSplits ?? [], oversizeClips: sliceOut.oversizeClips ?? [], } }) - const { blocks, secList, hfHs, floats, rowFills, floatVShifts, oversizeClips } = measured + const { + blocks, + secList, + hfHs, + floats, + rowFills, + floatVShifts, + floatFlows, + floatSplits, + oversizeClips, + } = measured slices = measured.s // document-end footer shows the last page's displayed number, not the physical count if (slices.length > 0) { @@ -2808,6 +3133,9 @@ export function App() { const tGaps0 = performance.now() if (editor) { const gaps: PageGapSpec[] = [] + // in-table gap height per split floating table (its anchor paragraph + // skips the same distance to start beside the last portion) + const carryGaps = new Map() const overlayCutAnchors: LineAnchor[] = [] const lineRectsOf = createLineRectsCache() const gapIds = new Set() @@ -2831,7 +3159,7 @@ export function App() { const pageNo = nums[pageIdx] const split = (imgs?: HfImage[] | null) => ({ images: imgs?.filter((img) => !img.floating), - floats: imgs?.filter((img) => img.floating) ?? [], + floats: imgs?.filter((img) => img.floating && !(watermarkDirty && img.wordArt)) ?? [], }) if (!secList || secList.length <= 1) { if (titlePg && pageIdx === 0) { @@ -2851,12 +3179,7 @@ export function App() { const pageSlice = slices[pageIdx] const sec = secList[Math.min(pageSlice.section, secList.length - 1)] const refs = effRefs![Math.min(pageSlice.section, effRefs!.length - 1)] - const variant = - sec.titlePg && firsts[pageIdx] - ? 'first' - : evenOddHf && pageNo % 2 === 0 - ? 'even' - : 'default' + const variant = hfVariantOf(sec.titlePg, firsts[pageIdx], evenOddHf, pageNo) const ov = variant === 'default' ? sectionHfOverride(pageSlice.section, kind) : null const rId = refs[kind][variant] return { @@ -2877,6 +3200,7 @@ export function App() { marginBottom: effectiveBottomPx(s, hfH.footerPx), headerDist: twipsToPx(s.headerDist ?? 720), sectMarginTop: twipsToPx(s.marginTop), + paperX: pageLeftOf(s), } } const pageNoTextOf = (pageIdx: number) => @@ -2894,7 +3218,7 @@ export function App() { imgs .map( (f) => - `${f.dataUrl.length}:${hashStr(f.dataUrl.slice(0, 1024) + f.dataUrl.slice(-1024))}:${f.posXPx ?? f.posH ?? ''}:${f.posYPx ?? f.posV ?? ''}:${f.posHRel ?? ''}${f.posVRel ?? ''}:${f.widthPx ?? ''}x${f.heightPx ?? ''}${f.washout ? ':w' : ''}`, + `${f.dataUrl.length}:${hashStr(f.dataUrl.slice(0, 1024) + f.dataUrl.slice(-1024))}:${f.posXPx ?? f.posH ?? ''}:${f.posYPx ?? f.posV ?? ''}:${f.posHRel ?? ''}${f.posVRel ?? ''}:${f.widthPx ?? ''}x${f.heightPx ?? ''}${f.washout ? ':w' : ''}${f.rotationDeg ? `:r${f.rotationDeg}` : ''}${f.wordArt ? `:t${f.wordArt.text}` : ''}`, ) .join('|') const visiblePages = visiblePageCount(slices) @@ -2904,14 +3228,16 @@ export function App() { ? twipsToPx(canvasSet.pageWidth - canvasSet.marginLeft - canvasSet.marginRight) : 0 const mixedWidths = - canvasSet != null && - (secList ?? []).some( - (s) => - Math.abs( - twipsToPx(s.settings.pageWidth - s.settings.marginLeft - s.settings.marginRight) - - canvasContentWPx, - ) > 0.5, - ) + mixedPaper || + (canvasSet != null && + (secList ?? []).some( + (s) => + Math.abs( + twipsToPx( + s.settings.pageWidth - s.settings.marginLeft - s.settings.marginRight, + ) - canvasContentWPx, + ) > 0.5, + )) // equal-width docs: strip centered, clamped to the canvas paper. Differing-width // docs: strip gets its section's width and is aligned to the body blocks' left // edge afterwards by measurement (alignGapHfStrips) — gap-box origins vary per @@ -2937,7 +3263,12 @@ export function App() { const stripGeomSig = (set: typeof canvasSet) => { if (!set) return '' const b = sectionPageBox(set) - return [twipsToPx(set.marginLeft), b.contentWidth, b.headerDist, b.footerDist] + return [ + pageLeftOf(set) + twipsToPx(set.marginLeft), + b.contentWidth, + b.headerDist, + b.footerDist, + ] .map((v) => v.toFixed(1)) .join(',') } @@ -2969,12 +3300,15 @@ export function App() { marginBottom: effectiveBottomPx(prevSec, prevHf.footerPx), marginLeft: twipsToPx(nextSec.marginLeft), marginRight: twipsToPx(nextSec.marginRight), - // header/footer strip inset (alignGapHfStrips): survives the inline/ - // in-cell gaps below overriding marginLeft/Right with the host block's - // paper offset (which folds in paragraph indents and cell positions) - sectionMarginLeft: twipsToPx(nextSec.marginLeft), + // header/footer strip inset on the paper (alignGapHfStrips): survives + // the inline/in-cell gaps below overriding marginLeft/Right with the host + // block's paper offset (which folds in paragraph indents and cell positions) + sectionMarginLeft: pageLeftOf(nextSec) + twipsToPx(nextSec.marginLeft), sectionMarginRight: twipsToPx(nextSec.marginRight), sectionMarginTop: twipsToPx(nextSec.marginTop), + ...(mixedPaper + ? { pageLeft: pageLeftOf(nextSec), pageWidth: twipsToPx(nextSec.pageWidth) } + : {}), } // a page ended early (explicit break / section break / keepNext) leaves unused // content height; pad the gap so the canvas paints the full paper height and the @@ -3020,7 +3354,10 @@ export function App() { sizeGapHf(el, box) // the footer belongs to the page ABOVE the gap: its own section's // left margin, not the next section's (alignGapHfStrips) - el.style.setProperty('--hf-ml', `${twipsToPx(prevSec.marginLeft)}px`) + el.style.setProperty( + '--hf-ml', + `${pageLeftOf(prevSec) + twipsToPx(prevSec.marginLeft)}px`, + ) hfEls.push(el) } if (hfHasVisibleContent(gapHeader.value, gapHeader.images)) { @@ -3042,7 +3379,10 @@ export function App() { el.style.bottom = 'auto' el.style.top = `calc(100% - ${metrics.marginTop - headerStripTop}px)` sizeGapHf(el, box) - el.style.setProperty('--hf-ml', `${twipsToPx(nextSec.marginLeft)}px`) + el.style.setProperty( + '--hf-ml', + `${pageLeftOf(nextSec) + twipsToPx(nextSec.marginLeft)}px`, + ) hfEls.push(el) } // next page's floating header images (picture watermarks): behind-text, @@ -3072,7 +3412,7 @@ export function App() { ) notes = makeGapNotesEl( items, - twipsToPx(prevSec.marginLeft), + pageLeftOf(prevSec) + twipsToPx(prevSec.marginLeft), contentW, fnH, footnoteLineHeightPx(prevSec.docGrid), @@ -3082,7 +3422,18 @@ export function App() { notesMetrics = { ...metrics, marginBottom: metrics.marginBottom + fnH } } const markShown = () => items.forEach((n) => gapIds.add(n.id)) - const i = blocks.findIndex((b) => Math.abs(b.top - slice.start) < 0.5) + // split floating table: the boundary is one of its row cuts, so the + // page turn is an in-table gap of the float; the anchor paragraph + // below it shares that top and must not take a block gap + const fsplit = floatSplits.find((f) => + f.cutYs.some((y) => Math.abs(y - slice.start) < 0.5), + ) + const fsBlock = fsplit + ? blocks.find( + (bb) => bb.el && bb.floatTable && Math.abs(bb.top - fsplit.blockTop) < 0.5, + ) + : undefined + const i = fsBlock ? -1 : blocks.findIndex((b) => Math.abs(b.top - slice.start) < 0.5) if (i >= 0 && blocks[i].el) { // footnotes sit at the paper bottom (Word): shift past the padding if (notes && pad > 0) notes.style.top = `${5 + pad}px` @@ -3104,9 +3455,11 @@ export function App() { return } // mid-paragraph page break (line-level cut point): insert an inline gap at the broken line. In-table cut points are not decorated yet - const b = blocks.find( - (bb) => bb.el && bb.top < slice.start && slice.start < bb.top + bb.height - 0.5, - ) + const b = + fsBlock ?? + blocks.find( + (bb) => bb.el && bb.top < slice.start && slice.start < bb.top + bb.height - 0.5, + ) if (!b?.el) { // deliberate trailing blank page (document ends with a page break): no // anchor block exists — hang the gap at the document end so the blank @@ -3127,6 +3480,9 @@ export function App() { } return } + // block-relative Y of the cut (a shifted float's rows start at its --tblp-dy) + const cutOff = + slice.start - b.top - (b.spaceBeforePx ?? 0) - (fsBlock ? fsplit!.dyPx : 0) if (b.el.querySelector('tr')) { // in-table cut point: insert an in-table gap row (display:table-row widget) // before the broken row (next page's first row). Positioning must subtract the @@ -3146,12 +3502,8 @@ export function App() { const gapsAbove = gapRects.reduce((s, g) => (g.top <= trTop ? s + g.height : s), 0) const off = (trTop - elTop - gapsAbove) / factor // last real row starting at/above the cut = the row the cut falls inside - if ( - !tr.classList.contains('page-gap') && - off <= slice.start - b.top - (b.spaceBeforePx ?? 0) + 0.5 - ) - cutRow = tr - if (Math.abs(off - (slice.start - b.top - (b.spaceBeforePx ?? 0))) < 1.5) { + if (!tr.classList.contains('page-gap') && off <= cutOff + 0.5) cutRow = tr + if (Math.abs(off - cutOff) < 1.5) { matched = true try { const $pos = editor.view.state.doc.resolve(editor.view.posAtDOM(tr, 0)) @@ -3221,6 +3573,14 @@ export function App() { } : {}), }) + if (fsplit) { + const gapH = + metrics.marginBottom + tablePad + GAP_BAND + metrics.marginTop + carryGaps.set( + fsplit.blockTop, + (carryGaps.get(fsplit.blockTop) ?? 0) + gapH, + ) + } break } } @@ -3232,12 +3592,7 @@ export function App() { } if (!matched) { // in-row cut point (page break between a cell's lines): anchor at the first line after it - const anchor = nextLineAnchor( - b.el, - slice.start - b.top - (b.spaceBeforePx ?? 0), - factor, - lineRectsOf, - ) + const anchor = nextLineAnchor(b.el, cutOff, factor, lineRectsOf) if (anchor == null) return // anchors inside the read-only nested-table NodeView have no distinct PM // position (posAtDOM collapses them all to the node start): overlay markers @@ -3261,8 +3616,8 @@ export function App() { metrics: { ...metrics, // rect offsets from the paper edge already include the page margins - marginLeft: (r.left - pmRect.left) / factor, - marginRight: (pmRect.right - r.right) / factor, + marginLeft: (r.left - pmRect.left) / factor - pageLeftOf(nextSec), + marginRight: (pmRect.right - r.right) / factor - pageLeftOf(nextSec), }, ...(pullUp > 0.5 ? { pullUp } : {}), ...hfProps, @@ -3277,18 +3632,8 @@ export function App() { // fallback: font-load reflow can leave lineStartAnchor's exact-offset match // just outside tolerance; the first line after the cut still gets the gap const anchor = - lineStartAnchor( - b.el, - slice.start - b.top - (b.spaceBeforePx ?? 0), - factor, - lineRectsOf, - ) ?? - nextLineAnchor( - b.el, - slice.start - b.top - (b.spaceBeforePx ?? 0), - factor, - lineRectsOf, - ) + lineStartAnchor(b.el, cutOff, factor, lineRectsOf) ?? + nextLineAnchor(b.el, cutOff, factor, lineRectsOf) const pos = anchor ? posFromAnchor(editor.view, anchor) : undefined if (pos == null) { console.warn('[pagination] no line anchor at page boundary', slice.start) @@ -3301,8 +3646,8 @@ export function App() { boundaryY: slice.start, metrics: { ...notesMetrics, - marginLeft: (elRect.left - pmRect.left) / factor, - marginRight: (pmRect.right - elRect.right) / factor, + marginLeft: (elRect.left - pmRect.left) / factor - pageLeftOf(nextSec), + marginRight: (pmRect.right - elRect.right) / factor - pageLeftOf(nextSec), }, ...(pullUp > 0.5 ? { pullUp } : {}), ...(notes ? { notes, notesKey } : {}), @@ -3318,7 +3663,7 @@ export function App() { const box = floatBoxOf(0) firstPageFloats = { els: floats.map((img) => makeHfFloatImgEl(img, box, 'lead')), - key: `${floatSig(floats)}·${Math.round(box.pageW)}x${Math.round(box.pageH)}·${Math.round(box.marginTop)}·${Math.round(box.sectMarginTop)}`, + key: `${floatSig(floats)}·${Math.round(box.pageW)}x${Math.round(box.pageH)}·${Math.round(box.marginTop)}·${Math.round(box.sectMarginTop)}·${Math.round(box.paperX ?? 0)}`, } } } @@ -3357,7 +3702,7 @@ export function App() { tGapsBuild = performance.now() - tGaps0 const tSet0 = performance.now() // split declared-height rows: resolve the engine's target heights to tr elements - const rowFillEls: Array<{ el: Element; targetPx: number }> = [] + const rowFillEls: Array<{ el: Element; targetPx: number; extraPx?: number }> = [] for (const f of rowFills) { const b = blocks.find((bb) => bb.tableRows && Math.abs(bb.top - f.blockTop) < 0.5) if (!b?.el) continue @@ -3368,7 +3713,12 @@ export function App() { !tr.classList.contains('page-repeat-header'), ) const tr = trs[f.row] - if (tr) rowFillEls.push({ el: tr, targetPx: f.targetPx }) + if (tr) + rowFillEls.push({ + el: tr, + targetPx: f.targetPx, + ...(f.extraPx ? { extraPx: f.extraPx } : {}), + }) } setRowFills(editor.view, rowFillEls) // oversized single-line blocks: resolve the engine's page-bottom clips to their elements @@ -3381,20 +3731,53 @@ export function App() { } setOversizeClips(editor.view, oversizeEls) // page/margin-anchored floated tables: resolve the engine's Y shifts to table elements - const floatVEls: Array<{ el: Element; dyPx: number }> = [] + const floatVEls: Array<{ + el: Element + dyPx: number + flow?: boolean + carryPx?: number + }> = [] for (const f of floatVShifts) { const b = blocks.find( (bb) => bb.pageRelVyPx !== undefined && Math.abs(bb.top - f.blockTop) < 0.5, ) if (b?.el) floatVEls.push({ el: b.el, dyPx: f.dyPx }) } + for (const f of floatFlows) { + const b = blocks.find((bb) => bb.floatTable && Math.abs(bb.top - f.blockTop) < 0.5) + if (b?.el) floatVEls.push({ el: b.el, dyPx: 0, flow: true }) + } + // split floating table: its anchor paragraph (the next block) starts + // beside the last portion — a flow spacer carries it past the earlier + // portions, a gap-sized spacer past the table's in-table gaps + for (const f of floatSplits) { + const bi = blocks.findIndex( + (bb) => bb.el && bb.floatTable && Math.abs(bb.top - f.blockTop) < 0.5, + ) + const anchor = bi >= 0 ? blocks[bi + 1] : undefined + if (!anchor?.el || anchor.floated) continue + const carry = f.blockTop + f.carryPx - (anchor.top - (anchor.carryAppliedPx ?? 0)) + if (carry > 0.5) floatVEls.push({ el: anchor.el, dyPx: 0, carryPx: carry }) + const gapPx = carryGaps.get(f.blockTop) ?? 0 + if (gapPx > 0.5) + gaps.push({ + el: anchor.el, + carryPx: gapPx, + metrics: { marginTop: 0, marginBottom: 0, marginLeft: 0, marginRight: 0 }, + }) + } setFloatVShifts(editor.view, floatVEls) + pm.classList.remove('measuring-natural') setPageGaps(editor.view, gaps, firstPageFloats) // mixed-column canvas: paint the engine's regions via per-block width/translate decorations const colSpecs = viewMode === 'print' && !readMode && colMode === 'mixed' && secList ? columnLayoutSpecs(blocks, slices, secList) : [] + // unequal columns: a block's width follows the column it lands in, + // which follows its measured height — one more pass per change, and a + // block ping-ponging between columns is pinned to its narrower width + const colGranted = widthPassGate(colWidthPass, colSpecs) // sectPr w:vAlign pages ride the same visual-translate channel const vaSpecs = viewMode === 'print' && !readMode && secList && hfHs @@ -3403,7 +3786,7 @@ export function App() { // sections whose content width differs from the canvas section: per-block wrap widths const secWSpecs = viewMode === 'print' && !readMode && secList && hfHs - ? sectionWidthSpecs(blocks, secList, sectionGeoms(secList, hfHs)) + ? sectionWidthSpecs(blocks, secList, sectionGeoms(secList, hfHs), paperWPx) : [] // sections disagreeing on the typed docGrid pitch: per-block pitch vars const gridSpecs = @@ -3411,10 +3794,24 @@ export function App() { // sections disagreeing on the docGrid charSpace delta: per-block letter-spacing vars const charSpecs = viewMode === 'print' && !readMode && secList ? sectionCharSpaceSpecs(blocks, secList) : [] + // sections disagreeing on the top margin: per-block --doc-margin-top for page-relative anchors + const topSpecs = + viewMode === 'print' && !readMode && secList ? sectionTopMarginSpecs(blocks, secList) : [] + // sectPr w:textDirection sections: writing-mode boxes placed sideways (width wins) + const vertSpecs = + viewMode === 'print' && !readMode && secList && hfHs + ? verticalTextSpecs(blocks, slices, secList, sectionGeoms(secList, hfHs)) + : [] // one spec per block: mixed-column placement wins the width, translates add up - const specLists = [gridSpecs, charSpecs, secWSpecs, colSpecs, vaSpecs].filter( - (l) => l.length > 0, - ) + const specLists = [ + gridSpecs, + charSpecs, + topSpecs, + secWSpecs, + colSpecs, + vaSpecs, + vertSpecs, + ].filter((l) => l.length > 0) let layoutSpecs = specLists.flat() if (specLists.length > 1) { const mergedSpecs = new Map() @@ -3433,7 +3830,7 @@ export function App() { alignTableGapFills(pm, factor) if (secWSpecs.length > 0 && section) { const cSet = secList?.[0]?.settings ?? section - alignGapHfStrips(pm, twipsToPx(cSet.marginLeft), factor) + alignGapHfStrips(pm, pageLeftOf(cSet) + twipsToPx(cSet.marginLeft), factor) } // after setPageGaps: widget insertion is synchronous, so anchor rects are final syncFloatShifts( @@ -3452,7 +3849,18 @@ export function App() { // exclude pages; the border must not run through the page gaps) const pbSec = secList?.[0]?.settings ?? section const borderStyle = pbSec ? pageBorderStyleOf(pbSec) : null - syncPageBorders((pm.closest('.page-wrap') as HTMLElement) ?? pm, borderStyle, factor) + const wrapEl = (pm.closest('.page-wrap') as HTMLElement) ?? pm + const firstFrame = pbSec + ? { left: pageLeftOf(pbSec), width: twipsToPx(pbSec.pageWidth) } + : undefined + syncPageBorders(wrapEl, borderStyle, factor, firstFrame) + syncLineNumbers(wrapEl, pm, blocks, secList ?? [], factor, blockMetaOf, firstFrame) + // differing-width documents paint one sheet per page (the shared paper is transparent) + syncPageSheets( + wrapEl, + factor, + mixedPaper && viewMode === 'print' && !readMode ? (firstFrame ?? null) : null, + ) } syncMarginAnnotations( (pm.closest('.page-wrap') as HTMLElement) ?? pm, @@ -3469,14 +3877,16 @@ export function App() { suppressSig = sig onUpdate() } - // freshly applied wrap widths change line breaks: one follow-up remeasure with them in the DOM - const wSig = secWSpecs + // freshly applied wrap widths (section widths, unequal column widths, + // vertical-text line lengths) change line breaks: one follow-up remeasure with them in the DOM + const wSig = [...secWSpecs, ...colSpecs, ...vertSpecs] .map((s) => `${Math.round(s.widthPx ?? -1)}:${Math.round(s.contentWPx ?? -1)}`) .join(',') if (wSig !== secWidthSig) { secWidthSig = wSig onUpdate() } + if (colGranted) onUpdate() // freshly applied per-block letter-spacing changes line breaks the same way const cSig = charSpecs.length === 0 @@ -3488,7 +3898,7 @@ export function App() { } // the last page paints as a full sheet like the ones above it: // extend the canvas to that page's paper bottom, measured from the last gap - const gapEls = pm.querySelectorAll('.page-gap') + const gapEls = pm.querySelectorAll('.page-gap:not(.page-gap-carry)') const lastGapEl = gapEls[gapEls.length - 1] if (lastGapEl && slices.length > 1) { const last = slices[slices.length - 1] @@ -3595,13 +4005,31 @@ export function App() { const onLoadingDone = () => onFontsChanged(true) document.fonts.addEventListener('loadingdone', onLoadingDone) scroller.addEventListener('scroll', locate, { passive: true }) - editor?.on('update', onUpdate) + const onDocUpdate = () => { + resetWidthPassHistory(colWidthPass) + onUpdate() + } + editor?.on('update', onDocUpdate) + // justify-shrink re-decides via decoration-only transactions that move the + // wrap points of justified paragraphs; tiptap 'update' fires only on doc + // changes, so without this the inline gap widgets keep their pre-shrink cut + // positions and force a stretched-sparse page-last line (r177). The stale + // block re-samples via the shrink fingerprint in lineSampleSig. + const onShrinkTr = (props: { transaction: Transaction }) => { + if ( + props.transaction.getMeta(justifyShrinkPluginKey) || + props.transaction.getMeta(floatFlowChangedMeta) + ) + onUpdate() + } + editor?.on('transaction', onShrinkTr) return () => { if (timer) window.clearTimeout(timer) if (hfTimer) window.clearTimeout(hfTimer) document.fonts.removeEventListener('loadingdone', onLoadingDone) scroller.removeEventListener('scroll', locate) - editor?.off('update', onUpdate) + editor?.off('update', onDocUpdate) + editor?.off('transaction', onShrinkTr) } }, [ doc, @@ -4584,10 +5012,12 @@ export function App() { // canvas geometry is anchored to the first section (stable across cursor moves); // sections with a different content width carry per-block width decorations // the shared paper must cover the widest section or its content lays out past - // the paper edge onto the editor background (a white band down the right side) - const paperW = canvasBox - ? Math.max(canvasBox.width, ...sections.map((s) => twipsToPx(s.settings.pageWidth))) - : 0 + // the paper edge onto the editor background (a white band down the right side); + // narrower pages are centered on it (pageLeftPx) and paint their own sheets + const paperW = canvasBox ? paperWidthPx(sections, canvasSection) : 0 + const pageLeftOf = (set: SectionSettings) => pageLeftPx(set, paperW) + const mixedPaper = + viewMode === 'print' && !readMode && sections.some((s) => pageLeftOf(s.settings) > 0.5) // the trailing footer strip belongs to the LAST page, which is always in the // last section; on differing-width docs the stylesheet centering (50% of the // first-section paper) puts it at the wrong x, so pin it to its own section @@ -4602,7 +5032,7 @@ export function App() { (paperW - lastBox.width > 0.5 || Math.abs(lastBox.contentWidth - canvasBox.contentWidth) > 0.5) ? { width: `${lastBox.contentWidth}px`, - left: `${twipsToPx(lastSection!.marginLeft)}px`, + left: `${pageLeftOf(lastSection!) + twipsToPx(lastSection!.marginLeft)}px`, transform: 'none', bottom: `${lastBox.footerDist}px`, } @@ -4613,7 +5043,7 @@ export function App() { canvasBox && canvasSection && paperW - canvasBox.width > 0.5 ? { width: `${canvasBox.contentWidth}px`, - left: `${twipsToPx(canvasSection.marginLeft)}px`, + left: `${pageLeftOf(canvasSection) + twipsToPx(canvasSection.marginLeft)}px`, transform: 'none', } : undefined @@ -4629,6 +5059,9 @@ export function App() { '--footer-dist': canvasBox ? `${canvasBox.footerDist}px` : undefined, '--page-bg': pageColor ? `#${pageColor}` : undefined, '--page-cols': colFlow && viewMode === 'print' ? colFlow.cols : undefined, + // end-of-document footnote area sits on the last page's sheet + '--last-page-w': mixedPaper && lastBox ? `${lastBox.width}px` : undefined, + '--last-page-x': mixedPaper && lastSection ? `${pageLeftOf(lastSection)}px` : undefined, } as CSSProperties // page-dark: dark paper + remapped colors (styles.css @media screen block); a @@ -4668,7 +5101,7 @@ export function App() { )} {doc && section && ( // over-wide tables may spill into the margins (Word/LO), capped at the paper edge - + )} {/* Theme CSS comes from live state, so a Design ▸ Themes/Fonts/Colors pick shows on the page immediately instead of only in the saved file */} @@ -4706,6 +5139,9 @@ export function App() { inkHighlighter={inkHighlighter} inkCount={inkAnnotations.length} sources={sources} + zoteroNoteFields={ + footnotes.some((note) => note.zoteroField) || endnotes.some((note) => note.zoteroField) + } zoom={Math.round(zoom)} darkPage={darkPage} tabRequest={ribbonTabRequest} @@ -4792,9 +5228,10 @@ export function App() { onQueueRemove={queueRemove} /> )} + {doc && }
    { scrollPosRef.current = { @@ -4802,6 +5239,28 @@ export function App() { top: e.currentTarget.scrollTop, } }} + onDragOver={(e) => { + if (!editor?.isEditable || !isImageFileDrag(e.dataTransfer)) return + e.preventDefault() + if (!imageDragOver) setImageDragOver(true) + }} + onDragLeave={(e) => { + const next = e.relatedTarget as Node | null + if (!next || !e.currentTarget.contains(next)) setImageDragOver(false) + }} + onDrop={(e) => { + setImageDragOver(false) + const files = imageFilesFromDataTransfer(e.dataTransfer) + if (files.length === 0) return + // a drop the editor's own handler did not take (read-only + // islands, the page margin) still must not navigate the window + const handledByEditor = e.isDefaultPrevented() + e.preventDefault() + if (handledByEditor || !editor) return + if (editor.view.dom.contains(e.target as Node)) { + insertImageFilesAtCoords(editor, files, { left: e.clientX, top: e.clientY }) + } + }} > {doc ? (
    )} -
    - {watermark && ( +
    + {watermark && watermarkDirty && ( @@ -4898,12 +5357,14 @@ export function App() { noteNo('footnote', n.id, i)} onEdit={(id) => editNote('footnote', id)} onDelete={(id) => deleteNote('footnote', id)} /> noteNo('endnote', n.id, i)} onEdit={(id) => editNote('endnote', id)} onDelete={(id) => deleteNote('endnote', id)} /> @@ -5146,8 +5607,10 @@ export function App() { }, }} watermark={watermark} + watermarkDirty={watermarkDirty} blockMetaOf={blockMetaOf} pageFootnotesOf={pageFootnotesOf} + footnotesBeneathText={doc.parsed.footnoteProps?.pos === 'beneathText'} endnoteItems={endnoteItems} sectionHfOverride={sectionHfOverride} comments={comments} @@ -5163,6 +5626,8 @@ export function App() { if (wrap) { syncCutOverlays(wrap as HTMLElement, [], 1) syncPageBorders(wrap as HTMLElement, null, 1) + syncLineNumbers(wrap as HTMLElement, wrap as HTMLElement, [], [], 1) + syncPageSheets(wrap as HTMLElement, 1, null) clearMarginAnnotations(wrap as HTMLElement) clearFloatShifts(wrap as HTMLElement) } diff --git a/apps/docs/src/renderer/ai/AiPanel.tsx b/apps/docs/src/renderer/ai/AiPanel.tsx index 75482b1..6a04e6e 100644 --- a/apps/docs/src/renderer/ai/AiPanel.tsx +++ b/apps/docs/src/renderer/ai/AiPanel.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react' import type { Editor } from '@tiptap/core' import type { Block } from '@genoffice/docx-engine' -import { AgentLoop, composeSkills, type AgentImage } from '@genoffice/agent-core' +import { AgentLoop, composeSkills, streamText, type AgentImage } from '@genoffice/agent-core' import { imageGenerationAvailable } from '@genoffice/ai-provider/browser' import type { AiSettings, AttachmentAddResult, AttachmentMeta } from '../../shared/ipc' import { ATTACHMENT_IMAGE_EXTS } from '../../shared/ipc' @@ -11,6 +11,14 @@ import { countWords, findNumId, type NumIds } from './protocol' import { DOC_NAV_SCHEME, navigateToBlock, parseDocNavHref } from './doc-nav' import { markDocSeen, type AiCommentsAccess, type AiHeaderFooterAccess } from './tools' import { createDocsSkill } from './docs-skill' +import { + buildDocWriterRequest, + countFragmentBlocks, + DOC_MAX_CHARS, + extractFragment, + type DocWriteResult, + type DocWriteSpec, +} from './doc-writer' import { EditQueueCard } from './EditQueueCard' import { buildQueueInstruction, @@ -58,6 +66,9 @@ interface ToolActivity { /** Max characters of tool output in the UI expansion panel */ const TOOL_OUTPUT_MAX_CHARS = 2000 +/** progress chip refresh while a write streams */ +const CHIP_UPDATE_MS = 400 + /** Cap on tool args/output persisted in the transcript (the store layer has another 16k truncation fallback) */ const PERSIST_TOOL_FIELD_MAX = 16_000 @@ -325,6 +336,11 @@ export function AiPanel({ /** a send waiting on a phased open's tail; Stop / New chat abort it before it runs */ const pendingSendRef = useRef<{ aborted: boolean } | null>(null) const [chat, setChat] = useState([]) + /** a streamed write stopped early: the draft stays in the document until the user keeps or discards it */ + const [activePartial, setActivePartial] = useState<{ blocks: number } | null>(null) + const partialResolverRef = useRef<((keep: boolean) => void) | null>(null) + /** bumped by New chat / unmount: a writer resuming after its abort must not open the keep card */ + const writerEpochRef = useRef(0) /** Past conversation restored from JSONL (read-only transcript, not fed to the model) */ const [historicChat, setHistoricChat] = useState([]) const [trackChanges, setTrackChanges] = useState( @@ -415,6 +431,15 @@ export function AiPanel({ window.addEventListener('resize', onResize) return () => window.removeEventListener('resize', onResize) }, []) + // a pending keep/discard must not outlive the panel: settle it as discard + useEffect( + () => () => { + writerEpochRef.current++ + partialResolverRef.current?.(false) + partialResolverRef.current = null + }, + [], + ) // bumped on selection/doc changes so the scope hint & quick actions stay fresh const [, setScopeTick] = useState(0) /** the scope chip's expandable preview of the selected text */ @@ -617,6 +642,83 @@ export function AiPanel({ }) } + const transportRef = useRef | null>(null) + if (!transportRef.current) + transportRef.current = createElectronTransport(() => settingsRef.current) + + /** + * Long-form writing: one tool-less request whose reply is the fragment, streamed + * into the document as a draft by the tool. A stream that stops early leaves the + * user a keep-or-discard choice; a stream that produced nothing is retried once. + */ + const runDocWriter = async ( + spec: DocWriteSpec, + onProgress: (html: string) => void, + signal?: AbortSignal, + ): Promise => { + const { system, user } = buildDocWriterRequest(spec, aiLangDirective()) + const epoch = writerEpochRef.current + let closed = false + let chipTimer: ReturnType | null = null + let latest = '' + const updateChip = () => { + chipTimer = null + if (closed) return + const blocks = countFragmentBlocks(latest) + patchLastAssistant((last) => ({ + tools: last.tools?.map((tl) => + tl.running ? { ...tl, summary: tModule('aiWritingDocument', { blocks }) } : tl, + ), + })) + } + const attempt = () => + streamText({ + transport: transportRef.current!, + system, + user, + signal, + maxChars: DOC_MAX_CHARS, + extract: (raw) => ({ text: extractFragment(raw) }), + onProgress: (html) => { + if (closed) return + latest = html + onProgress(html) + if (chipTimer === null) chipTimer = setTimeout(updateChip, CHIP_UPDATE_MS) + }, + }) + let outcome = await attempt() + if (outcome.status === 'empty' && !signal?.aborted) outcome = await attempt() + closed = true + if (chipTimer !== null) clearTimeout(chipTimer) + if (outcome.status === 'complete') return { ok: true, html: outcome.text } + if (outcome.status === 'empty') return { ok: false, error: outcome.error } + if (epoch !== writerEpochRef.current) return { ok: false, error: 'the chat was reset' } + // the draft stays in the document while the user decides + const keep = await new Promise((resolve) => { + partialResolverRef.current = resolve + setActivePartial({ blocks: countFragmentBlocks(outcome.text) }) + }) + return keep + ? { ok: true, html: outcome.text, truncated: true } + : { + ok: false, + error: `${outcome.reason}${outcome.error ? `: ${outcome.error}` : ''}; the user discarded the partial content`, + } + } + const runDocWriterRef = useRef(runDocWriter) + runDocWriterRef.current = runDocWriter + + const decidePartial = (keep: boolean): void => { + partialResolverRef.current?.(keep) + partialResolverRef.current = null + setActivePartial(null) + } + /** New chat / unmount: discard an open keep card and keep a still-settling writer from opening one */ + const abandonWriter = (): void => { + writerEpochRef.current++ + decidePartial(false) + } + const loopRef = useRef | null>(null) if (!loopRef.current) { const numIds = (): NumIds => ({ @@ -624,7 +726,7 @@ export function AiPanel({ ordered: findNumId(blocksRef.current, 'ordered') ?? numIdFallbackRef.current?.ordered ?? null, }) loopRef.current = new AgentLoop({ - transport: createElectronTransport(() => settingsRef.current), + transport: transportRef.current, systemSuffix: aiLangDirective, skill: composeSkills('docs+files', '', [ createDocsSkill( @@ -634,6 +736,9 @@ export function AiPanel({ () => commentsAccessRef.current, () => hfAccessRef.current, () => imageGenerationAvailable(settingsRef.current, gskLoggedInRef.current), + () => ({ + write: (spec, onProgress, signal) => runDocWriterRef.current(spec, onProgress, signal), + }), ), createFilesSkill(availableAttachments), ]), @@ -979,6 +1084,7 @@ export function AiPanel({ pendingSendRef.current.aborted = true pendingSendRef.current = null } + abandonWriter() loopRef.current?.reset() setBusy(false) setChat([]) @@ -1358,6 +1464,28 @@ export function AiPanel({
    {attachNotice &&
    {attachNotice}
    } + {activePartial && ( +
    +
    + {t('aiPartialTitle')} +
    +
    + {t('aiPartialBody', { blocks: activePartial.blocks })} +
    +
    + + +
    +
    + )} void, + signal?: AbortSignal, + ): Promise +} + +const WRITER_SYSTEM = [ + 'You are the document writer of GenOffice Docs, a Word-style editor. You receive a plan (title, sections, key points, tone, length) and reference material, and you write the complete content.', + '', + '## Writing rules', + '- Write the requested content in full: every section in the plan, real prose, no placeholders, no "[to be added]" notes.', + '- Real data only: use the facts, figures, names and quotes from the reference material and the plan; never invent facts or numbers beyond them.', + '- Follow the length the plan asks for; when it gives none, write what the content genuinely needs.', + '', + '## Output', + 'Reply with the restricted HTML fragment only: it starts with the first block tag and ends with the last closing tag. No markdown code fences, no commentary before or after, no / wrapper.', + HTML_RULES, +].join('\n') + +export function buildDocWriterRequest( + spec: DocWriteSpec, + langDirective: string, +): { system: string; user: string } { + const context = spec.context?.trim() + ? `\n\n## Reference material (all names, figures and facts come from here)\n${spec.context.slice(0, CONTEXT_CAP)}` + : '' + const instruction = spec.instruction.trim() + ? `\n\n## The user's request\n${spec.instruction.slice(0, 2000)}` + : '' + return { + system: WRITER_SYSTEM + langDirective, + user: `## Plan\n${spec.title ? `Title: ${spec.title}\n` : ''}${spec.plan.slice(0, 6000)}${context}${instruction}\n\nWrite the content now.`, + } +} + +/** Strip a fence or chatter before the first block tag and a closing fence at the end. */ +export function extractFragment(raw: string): string { + let text = raw.replace(/\r\n/g, '\n') + const start = text.search(/<(?:h[1-6]|p|ul|ol|table|pre|blockquote|formula)[\s>]/i) + if (start > 0) text = text.slice(start) + else if (start < 0) text = text.replace(/^\s*```[a-z]*\n?/i, '') + return text.replace(/\n?```\s*$/, '').trimEnd() +} + +/** rough top-level block count of a fragment, for the progress chip */ +export function countFragmentBlocks(html: string): number { + return (html.match(/<(?:h[1-6]|p|ul|ol|table|pre|blockquote|formula)[\s>]/gi) ?? []).length +} + +export type WritePosition = { kind: 'whole' } | { kind: 'after'; index: number } + +/** meta on every draft transaction: not an edit, not history, not a tracked change */ +export const DRAFT_META = 'aiDraft' + +/** + * Live draft of a streaming fragment inside the document. Each tick re-parses + * the fragment received so far (the HTML parser closes open tags, so a + * half-received block still renders) and swaps only the blocks that changed. + * The draft is outside undo history and Track Changes; `finish()` removes it + * so the caller can land the final fragment through the regular insert path, + * giving one undo step and normal revision marks. + */ +export class DraftLanding { + private from: number + private to: number + /** the text of the last tick that parsed and rendered */ + private rendered: string | null = null + private pending: string | null = null + private timer: ReturnType | null = null + private closed = false + private follow = true + private readonly onTransaction = ({ transaction }: { transaction: Transaction }) => { + if (!transaction.docChanged || transaction.getMeta(DRAFT_META)) return + this.from = transaction.mapping.map(this.from, 1) + this.to = Math.max(this.from, transaction.mapping.map(this.to, -1)) + } + + constructor( + private readonly editor: Editor, + private readonly numIds: NumIds, + position: WritePosition, + ) { + this.from = + position.kind === 'after' && position.index >= 0 + ? blockRangePositions(editor, position.index, position.index).to + : 0 + this.to = this.from + editor.on('transaction', this.onTransaction) + } + + /** latest cumulative fragment; rendered on the next tick */ + update(html: string): void { + if (this.closed) return + this.pending = html + if (this.timer === null) this.timer = setTimeout(() => this.flush(), DRAFT_TICK_MS) + } + + /** the top-level block index the draft sits after (-1 = document start), after any user edits */ + indexBefore(): number { + const doc = this.editor.state.doc + let index = -1 + let i = 0 + doc.forEach((node, offset) => { + if (offset + node.nodeSize <= this.from) index = i + i++ + }) + return index + } + + /** + * Remove the draft; the document is back to what it was around it. Returns the + * text of the last tick that rendered, so a kept stream whose tail no longer + * parses (a half-received formula or table) can still land what the user saw. + */ + finish(): string | null { + if (this.closed) return this.rendered + if (this.timer !== null) clearTimeout(this.timer) + this.timer = null + this.flush() + this.closed = true + this.editor.off('transaction', this.onTransaction) + if (this.to > this.from && !this.editor.isDestroyed) { + this.editor.view.dispatch(this.draftTr().delete(this.from, this.to)) + } + this.to = this.from + return this.rendered + } + + /** live top-level blocks inside the draft range, after any user edits */ + private liveNodes(): Array<{ node: ProseMirrorNode; end: number }> { + const out: Array<{ node: ProseMirrorNode; end: number }> = [] + this.editor.state.doc.forEach((node, offset) => { + if (offset >= this.from && offset + node.nodeSize <= this.to) + out.push({ node, end: offset + node.nodeSize }) + }) + return out + } + + private draftTr(): Transaction { + return this.editor.state.tr + .setMeta(DRAFT_META, true) + .setMeta('addToHistory', false) + .setMeta(TRACK_IGNORE, true) + .setMeta(TABLE_TRAILING_SKIP, true) + } + + private flush(): void { + this.timer = null + if (this.closed || this.pending === null || this.editor.isDestroyed) return + const html = this.pending + this.pending = null + let next: ProseMirrorNode[] + try { + next = parseHtmlFragment(html, this.numIds).map((n) => + this.editor.schema.nodeFromJSON({ ...n, attrs: { ...n.attrs, aiChanged: false } }), + ) + } catch { + return // a half-received formula or table is retried on the next tick + } + this.rendered = html + // compare against the live document: a user edit inside the draft changes sizes and drops that block from the kept prefix + const live = this.liveNodes() + let keep = 0 + while (keep < live.length && keep < next.length && live[keep]!.node.eq(next[keep]!)) keep++ + if (keep === live.length && keep === next.length) return + const at = keep > 0 ? live[keep - 1]!.end : this.from + const wasVisible = this.follow && this.endVisible() + this.editor.view.dispatch(this.draftTr().replaceWith(at, this.to, next.slice(keep))) + this.to = at + next.slice(keep).reduce((size, n) => size + n.nodeSize, 0) + if (wasVisible) this.scrollToEnd() + else this.follow = false + } + + private endVisible(): boolean { + if (this.to === this.from) return true + try { + const { top } = this.editor.view.coordsAtPos(this.to - 1) + return top >= 0 && top <= window.innerHeight + } catch { + return true + } + } + + private scrollToEnd(): void { + if (this.to === this.from) return + try { + const { node } = this.editor.view.domAtPos(this.to - 1) + const el = node instanceof Element ? node : node.parentElement + el?.scrollIntoView?.({ block: 'nearest' }) + } catch { + /* layout not ready */ + } + } +} diff --git a/apps/docs/src/renderer/ai/docs-skill.ts b/apps/docs/src/renderer/ai/docs-skill.ts index 3df0877..bae7f50 100644 --- a/apps/docs/src/renderer/ai/docs-skill.ts +++ b/apps/docs/src/renderer/ai/docs-skill.ts @@ -7,6 +7,7 @@ import { type AiTrack, type NumIds, } from './protocol' +import type { AiDocWriter } from './doc-writer' import { AGENT_TOOLS, executeTool, @@ -32,6 +33,8 @@ export function createDocsSkill( getHf?: () => AiHeaderFooterAccess | undefined, /** live predicate (gsk login && cloud-tools toggle, or a BYOK media key); false hides generate_image */ imageGenAvailable?: () => boolean, + /** streaming long-form writer behind write_document (panel-owned: progress chip, partial keep/discard) */ + getWriter?: () => AiDocWriter | undefined, ): AgentSkill { // Selection frozen per run: tools act on the range the prompt described, // not on wherever the user's live selection has wandered mid-run. The doc @@ -66,6 +69,7 @@ export function createDocsSkill( frozen, getComments?.(), getHf?.(), + getWriter?.(), ), } } diff --git a/apps/docs/src/renderer/ai/protocol.ts b/apps/docs/src/renderer/ai/protocol.ts index fbae82a..3d95519 100644 --- a/apps/docs/src/renderer/ai/protocol.ts +++ b/apps/docs/src/renderer/ai/protocol.ts @@ -83,7 +83,7 @@ export const OPS_GUIDE = [ 'BC-4 Using findReplace sentence by sentence for rewrites such as translation/abbreviation; use replace_blocks (or replace_selection for a selected span) instead;', ].join('\n') -const HTML_RULES = [ +export const HTML_RULES = [ 'The html tool input is a restricted HTML fragment. Rules:', '- Only these tags are allowed: h1 h2 h3 h4 h5 h6 p ul ol li strong em u s a br table thead tbody tr th td pre code blockquote', '- Tables: use for the first (header) row; cells contain plain text only (
    may split lines); nested tables / merged cells are not supported; once inserted the table is protected as a whole, only cell text remains editable', @@ -112,6 +112,7 @@ export const AGENT_SYSTEM_PROMPT = [ '- Every user message carries the latest "document block list" (index|type|content preview; previews may be truncated); after modifications, call get_document_context if you need the latest state;', '- When a list preview is truncated, read the full content with read_blocks before rewriting; never rewrite based on a truncated preview;', '- Content changes: use insert_content for new content, and replace_blocks to rewrite/replace existing blocks (pass a block index range and the new HTML); replaced blocks pass their paragraph and text formatting (font, size, color, indent, spacing, alignment) on to the new blocks automatically, and a rewritten table keeps its widths, borders, shading and cell formatting, so a rewrite never needs follow-up formatting commands;', + '- Long new content (drafting a whole document, a chapter, a full report/article/translation — anything beyond a few paragraphs) goes through write_document: you pass the plan and the reference material, and the system writer streams the text into the document while the user watches; never paste long content into insert_content. When the document is blank and the user asks for content, use write_document;', '- Formatting, structure, and batch operations (color/font size/line spacing/alignment/indent/heading level/find & replace/delete/move/list conversion) go through apply_ops — do not rewrite whole blocks with replace_blocks;', '- Small in-place text fixes (changing a few words inside a sentence) go through apply_ops findReplace with a target — do not rewrite the whole block; styling every occurrence of a phrase (e.g. bold each "TODO") uses setMatchedFont;', '- When the user has text selected, the message includes the selection block indexes and content; rewrite-style requests apply to the selection by default;', diff --git a/apps/docs/src/renderer/ai/tools.ts b/apps/docs/src/renderer/ai/tools.ts index 171b84a..87eaa9b 100644 --- a/apps/docs/src/renderer/ai/tools.ts +++ b/apps/docs/src/renderer/ai/tools.ts @@ -4,6 +4,12 @@ import type { ChartDisplay, CommentInfo, NewChart } from '@genoffice/docx-engine import type { AgentToolCall, AgentToolDef, CreateDocumentType } from '../../shared/ipc' import { t } from '../i18n/locale' import { executeOps, opNames } from './ops' +import { + DraftLanding, + type AiDocWriter, + type DocWriteResult, + type WritePosition, +} from './doc-writer' import { blockRangePositions, buildCommentsContext, @@ -74,6 +80,37 @@ export const AGENT_TOOLS: AgentToolDef[] = [ required: ['html'], }, }, + { + name: 'write_document', + description: + '[For long new content: a whole document, a chapter, a full report, article or translation] Hands the writing to the system writer, which streams restricted HTML straight into the document while the user watches; you never write the text yourself. Give a concrete plan (title, section outline with the key points of each, tone, target length) and put every fact, figure, name and quote the text must use into context — the writer sees only the plan and context, not the conversation. Omit afterBlockIndex on a blank document; on a document with content, pass afterBlockIndex to insert after that block, or replaceDocument=true when the user asked to rewrite everything. Short additions (a paragraph or two) use insert_content instead.', + inputSchema: { + type: 'object', + properties: { + plan: { + type: 'string', + description: 'title, section outline with key points per section, tone, target length', + }, + title: { type: 'string', description: 'document/chapter title, when there is one' }, + context: { + type: 'string', + description: + 'reference material: facts, figures, quotes, sources gathered from the conversation, attachments and web_search', + }, + afterBlockIndex: { + type: 'integer', + description: + 'insert after this block index (-1 = document start); omitted = whole document', + }, + replaceDocument: { + type: 'boolean', + description: + 'true replaces all existing content (only when the user asked for a rewrite)', + }, + }, + required: ['plan'], + }, + }, { name: 'replace_blocks', description: @@ -472,6 +509,7 @@ function editedExternally(editor: Editor): boolean { /** tools addressing the document by block index: refused after an external edit until the model re-reads */ const INDEX_WRITE_SUMMARIES: Record string> = { insert_content: () => t('aiSumInsertContent'), + write_document: () => t('aiSumWriteDocument'), replace_blocks: () => t('aiSumReplaceContent'), replace_selection: () => t('aiSumReplaceSelection'), apply_ops: () => t('aiSumApplyCommands'), @@ -717,6 +755,7 @@ export function executeTool( frozen?: FrozenSelection | null, comments?: AiCommentsAccess, hf?: AiHeaderFooterAccess, + writer?: AiDocWriter, ): ToolExecution | Promise { const scope = frozen && frozen.doc === editor.state.doc ? frozen.scope : null const staleSummary = INDEX_WRITE_SUMMARIES[call.name] @@ -739,9 +778,98 @@ export function executeTool( ) { return executeAsyncTool(editor, call, signal) } + if (call.name === 'write_document') + return writeDocument(editor, call, numIds, track, signal, writer) return settle(executeSyncTool(editor, call, numIds, track, scope, comments, hf)) } +async function writeDocument( + editor: Editor, + call: AgentToolCall, + numIds: NumIds, + track: AiTrack | undefined, + signal: AbortSignal | undefined, + writer: AiDocWriter | undefined, +): Promise { + const summary = t('aiSumWriteDocument') + const plan = String(call.input.plan ?? '').trim() + if (!plan) return fail(summary, 'plan must not be empty') + if (!writer) return fail(summary, 'document writing is not available here') + const count = editor.state.doc.childCount + const afterRaw = call.input.afterBlockIndex + let position: WritePosition + if (afterRaw !== undefined && afterRaw !== null) { + if (!Number.isInteger(afterRaw) || Number(afterRaw) < -1 || Number(afterRaw) >= count) + return fail(summary, rangeError(editor)) + position = { kind: 'after', index: Number(afterRaw) } + } else if (isBlankDocument(editor) || call.input.replaceDocument === true) { + position = { kind: 'whole' } + } else { + return fail( + summary, + 'the document is not blank: pass afterBlockIndex to insert the new content after a block, or replaceDocument=true when the user asked to rewrite the whole document', + ) + } + const str = (v: unknown) => (v === undefined || v === null ? undefined : String(v)) + const draft = new DraftLanding(editor, numIds, position) + let result: DocWriteResult + let rendered: string | null + try { + result = await writer.write( + { + plan, + title: str(call.input.title), + context: str(call.input.context), + instruction: '', + }, + (html) => draft.update(html), + signal, + ) + } finally { + rendered = draft.finish() + } + if (editor.isDestroyed) return fail(summary, 'the document was closed') + if (!result.ok || !result.html) { + return fail( + t('aiSumWriteDocumentFailed'), + `The writer produced nothing (${result.error ?? 'no output'}); the document is unchanged. Tell the user briefly and offer to try again.`, + ) + } + let nodes: ReturnType + try { + nodes = parseHtmlFragment(result.html, numIds) + } catch (e) { + // a kept partial can end mid-formula: land what the user saw rendered instead + if (!result.truncated || !rendered) + return fail(t('aiSumWriteDocumentFailed'), e instanceof Error ? e.message : String(e)) + nodes = parseHtmlFragment(rendered, numIds) + } + if (nodes.length === 0) + return fail( + t('aiSumWriteDocumentFailed'), + 'the writer output did not parse into any content blocks', + ) + // a blank document or an explicit rewrite replaces everything; text the user typed + // into a formerly blank document while the draft streamed is kept, the content goes into the draft's slot + if ( + position.kind === 'whole' && + (isBlankDocument(editor) || call.input.replaceDocument === true) + ) { + replaceBlockRange(editor, 0, editor.state.doc.childCount - 1, nodes, track) + } else { + insertBlocksAfter(editor, draft.indexBefore(), nodes, track) + } + markDocSeen(editor) + const note = result.truncated + ? ' The stream ended early, so the content is INCOMPLETE (the user chose to keep it): the tail is missing. Say so and offer to finish the missing sections with write_document (afterBlockIndex at the end) or insert_content.' + : '' + return { + output: `Content written by the system (${nodes.length} block(s), ${result.html.length} chars). Block indexes have changed; use get_document_context if needed.${note}\nReply with one or two sentences describing what was written; do not paste the content.`, + mutated: true, + summary: result.truncated ? t('aiSumWriteDocumentPartial') : summary, + } +} + function executeSyncTool( editor: Editor, call: AgentToolCall, diff --git a/apps/docs/src/renderer/components/HeaderFooterArea.tsx b/apps/docs/src/renderer/components/HeaderFooterArea.tsx index fc1d07b..298c74d 100644 --- a/apps/docs/src/renderer/components/HeaderFooterArea.tsx +++ b/apps/docs/src/renderer/components/HeaderFooterArea.tsx @@ -17,13 +17,17 @@ import { hfLeadIndentCss, hfRowStyle, hfSegLeftCss, - hfTabSegments, + hfTabLeadNeedsStrut, + hfTabLines, + hfTabOverflowPx, hfBoxAnchorEl, hfTextBoxClass, hfTextBoxStyle, hfUsesLegacyHash, paraBorderCss, + paraBorderPadding, type HfStripGeom, + type HfTabLayout, hfParaLineHeightCss, hfStackedSpacingPx, } from '../editor/hf-dom' @@ -31,6 +35,7 @@ import { applyHfText, hfEditText, hfParasOf, PAGE_TOKEN } from '../editor/hf-tex import { dkStyleProps } from '../editor/dark-page' import { INLINE_RULE_CLASS, inlineRuleStyle } from '../editor/inline-rule' import { textColorValue } from '../editor/text-color' +import { textOutlineCssValue } from '../editor/text-outline' import { cssRunFontFamily, fontKerningCss, runLetterSpacingCss } from '../line-metrics' export interface HfValue { @@ -58,6 +63,7 @@ function runStyle(run: Run): React.CSSProperties { const kerning = fontKerningCss(run) if (kerning) style.fontKerning = kerning if (run.font || run.fontAscii) style.fontFamily = cssRunFontFamily(run.fontAscii, run.font) + if (run.textOutline) style.WebkitTextStroke = textOutlineCssValue(run.textOutline) if (run.caps === 'all') style.textTransform = 'uppercase' else if (run.caps === 'small') style.fontVariantCaps = 'small-caps' else if (run.caps === 'none') { @@ -81,10 +87,11 @@ function paraStyle(para: HfParagraph): React.CSSProperties { } // frame placement wins over the paragraph's own jc (mirrors makeGapHfEl) if (para.frameXAlign) style.textAlign = para.frameXAlign - if (para.shadingFill) { - style.backgroundColor = `#${para.shadingFill}` - Object.assign(style, dkStyleProps({ background: `#${para.shadingFill}` })) - } + const shdBg = para.shadingDisplay ?? para.shadingFill + if (shdBg) { + style.backgroundColor = `#${shdBg}` + Object.assign(style, dkStyleProps({ background: `#${shdBg}` })) + } else if (para.shadingClear) style.backgroundColor = 'transparent' if (para.borders) { const line = (side: 't' | 'b' | 'l' | 'r') => paraBorderCss(para.borderLines?.[side]) const borders: Partial> = {} @@ -93,7 +100,7 @@ function paraStyle(para: HfParagraph): React.CSSProperties { if (para.borders.includes('l')) style.borderLeft = borders.l = line('l') if (para.borders.includes('r')) style.borderRight = borders.r = line('r') Object.assign(style, dkStyleProps({ borders })) - style.padding = '1px 4px' + Object.assign(style, paraBorderPadding(para.borders, para.borderLines)) } return style } @@ -180,14 +187,18 @@ export function HeaderFooterArea({ // preview/export strips lay out like the canvas gaps and the push-down probe const strutPt = hfDeclaredStrutPt(paras) const hasBoxes = boxGeom != null && paras.some((p) => p.box) + const tabOver = Math.max( + 0, + ...paras.map((p) => (p.cells ? 0 : hfTabOverflowPx(hfTabLines(p, display) ?? [], boxGeom))), + ) return (
    0 ? { ['--hf-tab-over' as string]: `${tabOver.toFixed(1)}px` } : {}), + ...style, + }} data-tip={ readOnly ? undefined @@ -365,8 +376,8 @@ function HfContent({
    ) : ( (() => { - const tabbed = hfTabSegments(para, display) - if (!tabbed) { + const tabLines = hfTabLines(para, display) + if (!tabLines) { return (
    ) } - const leadIndent = hfLeadIndentCss(tabbed) - return ( -
    + // tab layout happens in left-aligned space; w:jc becomes an explicit shift + const lineStyle = (tabbed: HfTabLayout): React.CSSProperties => { + const leadIndent = hfLeadIndentCss(tabbed) + return { + ...(tabbed.minHeightPt ? { minHeight: `${tabbed.minHeightPt}pt` } : {}), + textAlign: 'left', + ...(leadIndent ? { textIndent: leadIndent } : {}), + } + } + const lineContent = (tabbed: HfTabLayout) => ( + <> + {hfTabLeadNeedsStrut(tabbed) ? '\u200b' : null} {tabbed.lead.map((run, j) => ( {display(run.text)} @@ -414,6 +423,33 @@ function HfContent({ ))} ))} + + ) + const frame = para.frameXAlign ? ' page-hf-frame' : '' + if (tabLines.length === 1) { + return ( +
    + {lineContent(tabLines[0])} +
    + ) + } + // a w:br paragraph stacks one positioned line per break inside the + // paragraph block (which keeps the spacing and borders) + return ( +
    + {tabLines.map((tabbed, m) => ( +
    + {lineContent(tabbed)} +
    + ))}
    ) })() diff --git a/apps/docs/src/renderer/components/PageNoteAreas.tsx b/apps/docs/src/renderer/components/PageNoteAreas.tsx index c7c61c6..2d5af03 100644 --- a/apps/docs/src/renderer/components/PageNoteAreas.tsx +++ b/apps/docs/src/renderer/components/PageNoteAreas.tsx @@ -1,5 +1,5 @@ import type { NoteInfo } from '@genoffice/docx-engine' -import { toRoman } from '../note-format' +import { noteMarkText } from '../note-format' import { useI18n } from '../i18n/locale' function NoteRow({ @@ -45,11 +45,14 @@ function NoteRow({ export function PageFootnotes({ notes, skipIds, + numberOf, onEdit, onDelete, }: { notes: NoteInfo[] skipIds: ReadonlySet + /** display number of a note (document reference order); default = list position */ + numberOf?: (note: NoteInfo, index: number) => number onEdit: (id: string) => void onDelete: (id: string) => void }) { @@ -61,7 +64,7 @@ export function PageFootnotes({ {shown.map((n) => ( number onEdit: (id: string) => void onDelete: (id: string) => void }) { @@ -101,7 +106,7 @@ export function PageEndnotes({ {notes.map((n, i) => ( { + const si = Math.max(0, Math.min(slice.section, sections.length - 1)) + const mode = sectionVertical(sections[si]?.settings) + const g = geoms[Math.min(si, geoms.length - 1)] + if (!mode || !g || slice.regions) return + const page = `.pv-page[data-pv-page="${i}"]` + // the clip is the full body height (lines span it), so the window pad's + // ride-along neighbours must not show: hide the addressable blocks and + // reveal those intersecting this page (floated frames and other + // horizontal blocks included; blocks without an index stay visible). + // Canvas gap chrome (page / hf / notes gaps, cut marks, float hosts) has + // no index and would paint inside the sheet: hide it too. + rules.push( + `${page} .pv-content > [data-idx],` + + `${page} .pv-content > :is([class*="page-gap"],.page-float-host){visibility:hidden;}`, + ) + for (const b of blocks) { + if (!b.el || b.top >= slice.end - 0.5 || b.top + b.height <= slice.start + 0.5) continue + const idx = b.el.dataset.idx + if (idx === undefined) continue + const sel = `${page} .pv-content > [data-idx="${idx}"]` + if (!b.el.classList.contains('doc-vert-block')) { + rules.push(`${sel}{visibility:visible;}`) + continue + } + const { dx, dy } = verticalBlockShift(mode, g.contentHeight, b.top - slice.start, b.height) + rules.push( + `${sel}{visibility:visible;--pv-vdx:${dx.toFixed(2)}px;--pv-vdy:${dy.toFixed(2)}px;}`, + ) + } + }) + return rules.join('\n') +} + export function pinnedCloneCss(pageCount: number): string { const rules: string[] = [] for (let i = 0; i < pageCount; i++) { @@ -603,6 +673,61 @@ export interface HfSet { * sections is real). Headers/footers render per page by Word variant rules (first page / * odd-even), with real page numbers. */ +/** anchored header/footer picture on a preview page; an a:srcRect crop becomes + * an overflow-hidden window over the scaled image (mirrors hfImgNode) */ +function FloatHfImg({ + img, + pos, +}: { + img: HfImage + pos: ReturnType +}): React.JSX.Element { + const base: React.CSSProperties = { + left: pos.x, + top: pos.y, + transform: hfFloatTransform(img, pos), + ...(img.widthPx ? { width: img.widthPx } : {}), + ...(img.heightPx ? { height: img.heightPx } : {}), + ...(img.washout ? { filter: hfWashoutFilter(img.washout) } : {}), + ...(img.behind ? {} : { zIndex: 1 }), + } + if (img.wordArt) { + return ( +
    + {splitCss && } + {vertCss && } {/* aria-hidden: the cloned page stack is a visual print preview; exposing its full-document DOM to the accessibility tree overflows Blink's AX update queue on long documents and crashes the renderer */} @@ -1186,15 +1353,37 @@ export function PaginationPreview({ hfHeaderGeom(s), ), ) - const mBottom = effectiveBottomPx( - s, - hfReservedHeightPx('footer', parts.footer, secContentW, parts.footerImages), + const footerReservedPx = hfReservedHeightPx( + 'footer', + parts.footer, + secContentW, + parts.footerImages, ) + const mBottom = effectiveBottomPx(s, footerReservedPx) const contentH = pageH - mTop - mBottom + const notes = pageNotes[i] ?? [] + const notesH = + notes.length > 0 + ? notes.reduce((sum, n) => sum + n.height, 0) + FOOTNOTE_SEPARATOR_H + : 0 // page vertical alignment (sectPr w:vAlign): content of non-full pages shifts down as a whole const usedH = Math.min(slice.end - slice.start, contentH) const vSpare = Math.max(0, contentH - usedH) - const vOffset = s.vAlign === 'center' ? vSpare / 2 : s.vAlign === 'bottom' ? vSpare : 0 + // (vertical-text pages: the slice span is the sideways fill, not leftover height) + const vOffset = sectionVertical(s) + ? 0 + : s.vAlign === 'center' + ? vSpare / 2 + : s.vAlign === 'bottom' + ? vSpare + : 0 + const noteArea = noteAreaPlacement(notesH, textEnds[i], slice, { + pageH, + mTop, + mBottom, + headerH: slice.repeatHeader?.height ?? 0, + vOffset, + }) // the window opens up into the top margin: fully on the first page (nothing // precedes the flow there, so a side-wrapped picture anchored above its // paragraph paints into the margin like Word), else by a lifted table's hang @@ -1229,6 +1418,7 @@ export function PaginationPreview({ key={i} className="pv-page" data-pv-page={i} + data-pv-section={slice.section} // inert: cloned pages carry natively focusable nodes (links, // contenteditable cells); keyboard focus must not enter the // aria-hidden subtree. Kept off .pv-scroll so it stays scrollable. @@ -1257,14 +1447,14 @@ export function PaginationPreview({ ...(markupOn ? markupTransform : {}), }} > - {watermark && ( + {watermark && watermarkDirty && ( )} {drawPageBorder && (
    )} - {(pageNotes[i]?.length ?? 0) > 0 && ( - // page-bottom footnotes (Word behavior: placed at the bottom of the page's content area, separator on top) + {notes.length > 0 && (
    sum + n.height, 0) + FOOTNOTE_SEPARATOR_H, + height: notesH, + ...(noteArea.top === null + ? { bottom: twipsToPx(s.marginBottom) } + : { top: noteArea.top }), }} > - {pageNotes[i]!.map((n) => ( + {notes.map((n) => ( // entries get reserved heights (DOM-measured at these exact styles); // min-height lets a residual long entry spill into the bottom margin // instead of overprinting the next entry @@ -1545,7 +1748,7 @@ export function PaginationPreview({ ...(n.fontFamily ? { fontFamily: n.fontFamily } : {}), }} > - {!n.noRefMark && {n.no}} + {!n.noRefMark && {noteMarkText('footnote', n.no)}} {n.richParas ? n.richParas.map((para, pi) => ( @@ -1567,6 +1770,9 @@ export function PaginationPreview({ fontFamily: run.fontAscii ? cssFontFamily(run.fontAscii) : undefined, + WebkitTextStroke: run.textOutline + ? textOutlineCssValue(run.textOutline) + : undefined, textTransform: run.caps === 'all' ? 'uppercase' : undefined, fontVariantCaps: run.caps === 'small' ? 'small-caps' : undefined, @@ -1594,7 +1800,12 @@ export function PaginationPreview({ style={{ left: twipsToPx(s.marginLeft), width: pageW - twipsToPx(s.marginLeft) - twipsToPx(s.marginRight), - top: mTop + (slice.repeatHeader?.height ?? 0) + (rows[0].top - slice.start), + top: + mTop + + (slice.regions ? 0 : vOffset) + + (slice.repeatHeader?.height ?? 0) + + (rows[0].top - slice.start) + + noteArea.endnoteShift, }} > {rows.map(({ item: n, height, withSeparator }) => ( @@ -1609,7 +1820,7 @@ export function PaginationPreview({ }} > {withSeparator &&
    } - {!n.noRefMark && {toRoman(n.no)}} + {!n.noRefMark && {noteMarkText('endnote', n.no)}} {n.richParas ? n.richParas.map((para, pi) => ( @@ -1634,6 +1845,9 @@ export function PaginationPreview({ fontFamily: run.fontAscii ? cssFontFamily(run.fontAscii) : undefined, + WebkitTextStroke: run.textOutline + ? textOutlineCssValue(run.textOutline) + : undefined, textTransform: run.caps === 'all' ? 'uppercase' : undefined, fontVariantCaps: run.caps === 'small' ? 'small-caps' : undefined, diff --git a/apps/docs/src/renderer/components/PasteOptionsChip.tsx b/apps/docs/src/renderer/components/PasteOptionsChip.tsx new file mode 100644 index 0000000..7844cbe --- /dev/null +++ b/apps/docs/src/renderer/components/PasteOptionsChip.tsx @@ -0,0 +1,266 @@ +/** + * Post-paste floating "Paste options" chip (Word parity): after pasting + * foreign HTML (web pages, Word, mail), a small button appears at the end of + * the pasted content offering the three paste modes — keep source formatting, + * merge formatting, keep text only. Choosing one undoes the paste, restores + * the insertion point and re-applies the SAME clipboard payload through the + * editor's full paste pipeline; "always use this choice" persists the mode + * as the default for pasting from other programs (editor/paste-options.ts). + * + * Mounted at the app root with fixed positioning (coordsAtPos speaks viewport + * coordinates, the AiAskPopover pattern); repositions while the document + * scrolls and hides on any other document change. + */ +import React, { useEffect, useRef, useState } from 'react' +import type { Editor } from '@tiptap/core' +import type { EditorState, Transaction } from '@tiptap/pm/state' +import { useI18n, type StringKey } from '../i18n/locale' +import { + beginForeignPaste, + capturePasteRestore, + defaultPasteMode, + forceNextPasteMode, + revertPaste, + setDefaultPasteMode, + takePastePayload, + type PasteMode, + type PastePayload, + type PasteRestore, +} from '../editor/paste-options' +import { IconPaste } from './icons' + +type ChipState = { + payload: PastePayload + from: number + to: number + mode: PasteMode + restore: PasteRestore +} + +type PastedRange = Pick + +const MODE_KEYS: Array<[PasteMode, StringKey]> = [ + ['source', 'appPasteKeepSource'], + ['merge', 'appPasteMergeFormat'], + ['text', 'appPasteTextOnly'], +] + +const GAP = 6 +const EDGE = 8 +const REVERT_META = 'pasteOptionsRevert' + +/** The range a transaction's steps touched, in final-doc coordinates. */ +function changedRangeOf(tr: Transaction): { from: number; to: number } | null { + let from = Infinity + let to = -Infinity + const maps = tr.mapping.maps + maps.forEach((stepMap, index) => { + stepMap.forEach((_oldFrom, _oldTo, newFrom, newTo) => { + let start = newFrom + let end = newTo + for (let later = index + 1; later < maps.length; later++) { + start = maps[later]!.map(start, 1) + end = maps[later]!.map(end, -1) + } + from = Math.min(from, start) + to = Math.max(to, end) + }) + }) + return from <= to ? { from, to } : null +} + +export function PasteOptionsChip({ editor }: { editor: Editor }) { + const { t } = useI18n() + const [chip, setChip] = useState(null) + const [open, setOpen] = useState(false) + const [pos, setPos] = useState<{ left: number; top: number } | null>(null) + // setDefaultPasteMode writes localStorage — bump to re-read it in render + const [, setPrefTick] = useState(0) + const reapplying = useRef(false) + // the state a document-changing transaction started from (editor.state is + // already the new one when 'transaction' fires) and the paste a re-apply + // produced (null when it produced none), read back once pasteHTML returns + const beforeState = useRef(null) + const reapplied = useRef(null) + const rootRef = useRef(null) + + // show on a paste transaction (payload stashed by the paste entry points), + // track re-applies, hide on any other document change + useEffect(() => { + const onBeforeTransaction = ({ transaction }: { transaction: Transaction }) => { + if (transaction.docChanged) beforeState.current = editor.state + } + const onTransaction = ({ + transaction: tr, + appendedTransactions, + }: { + transaction: Transaction + appendedTransactions: Transaction[] + }) => { + if (!tr.docChanged) return + if (tr.getMeta(REVERT_META)) { + reapplied.current = null + return + } + const payload = reapplying.current ? null : takePastePayload() + if (!payload && !reapplying.current) { + setChip(null) + setOpen(false) + return + } + const range = changedRangeOf(tr) + const restore = + range && beforeState.current + ? capturePasteRestore(beforeState.current, [tr, ...appendedTransactions]) + : null + const pasted = range && restore ? { from: range.from, to: range.to, restore } : null + if (reapplying.current) { + reapplied.current = pasted + return + } + setChip(payload && pasted ? { payload, mode: payload.mode, ...pasted } : null) + setOpen(false) + } + editor.on('beforeTransaction', onBeforeTransaction) + editor.on('transaction', onTransaction) + return () => { + editor.off('beforeTransaction', onBeforeTransaction) + editor.off('transaction', onTransaction) + } + }, [editor]) + + // anchor at the end of the pasted content; follow scrolling + useEffect(() => { + if (!chip) { + setPos(null) + return + } + const place = () => { + try { + const max = editor.state.doc.content.size + const coords = editor.view.coordsAtPos(Math.min(chip.to, max)) + const left = Math.min(coords.right + GAP, window.innerWidth - EDGE - 32) + const top = Math.min(coords.bottom + GAP, window.innerHeight - EDGE - 32) + setPos({ left: Math.max(EDGE, left), top: Math.max(EDGE, top) }) + } catch { + setChip(null) + } + } + place() + window.addEventListener('scroll', place, true) + window.addEventListener('resize', place) + return () => { + window.removeEventListener('scroll', place, true) + window.removeEventListener('resize', place) + } + }, [editor, chip]) + + // Esc closes the menu, then the chip; outside clicks close the menu + useEffect(() => { + if (!chip) return + const onKey = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return + if (open) setOpen(false) + else { + setChip(null) + // focus may sit inside the chip (menu buttons, the checkbox) — + // dismissing returns it to the document like Word does + editor.commands.focus() + } + } + const onPointerDown = (event: MouseEvent) => { + if (rootRef.current && !rootRef.current.contains(event.target as Node)) setOpen(false) + } + window.addEventListener('keydown', onKey) + window.addEventListener('mousedown', onPointerDown) + return () => { + window.removeEventListener('keydown', onKey) + window.removeEventListener('mousedown', onPointerDown) + } + }, [editor, chip, open]) + + if (!chip || !pos) return null + + const applyMode = (mode: PasteMode) => { + if (mode === chip.mode) { + setOpen(false) + return + } + const view = editor.view + const revert = revertPaste(view.state, chip.restore) + if (!revert) { + setChip(null) + setOpen(false) + return + } + reapplying.current = true + try { + view.dispatch(revert.setMeta(REVERT_META, true)) + forceNextPasteMode(mode) + beginForeignPaste(chip.payload.html) + const data = new DataTransfer() + data.setData('text/html', chip.payload.html) + if (chip.payload.text) data.setData('text/plain', chip.payload.text) + view.pasteHTML( + chip.payload.html, + new ClipboardEvent('paste', { clipboardData: data }) as ClipboardEvent, + ) + } finally { + reapplying.current = false + } + const pasted = reapplied.current + setChip((prev) => (prev && pasted ? { ...prev, ...pasted, mode } : null)) + setOpen(false) + editor.commands.focus() + } + + const remembered = defaultPasteMode() === chip.mode + + return ( +
    + + {open && ( +
    + {MODE_KEYS.map(([mode, key]) => ( + + ))} +
    + +
    + )} +
    + ) +} diff --git a/apps/docs/src/renderer/components/Ribbon.tsx b/apps/docs/src/renderer/components/Ribbon.tsx index b742e59..d4119ac 100644 --- a/apps/docs/src/renderer/components/Ribbon.tsx +++ b/apps/docs/src/renderer/components/Ribbon.tsx @@ -46,6 +46,7 @@ import { applyCase, type CaseMode } from '../editor/case-transform' import { setParagraphDirection, setSelectionAlign } from '../editor/direction' import { setInactiveSelectionShown } from '../editor/inactive-selection' import { stepParagraphIndent } from '../editor/indent' +import { beginForeignPaste, defaultPasteMode, stashPastePayload } from '../editor/paste-options' import { formatNumber } from '../editor/numbering' import type { InkTool } from '../editor/ink' import type { RibbonFormatState } from './ribbon-format-state' @@ -199,6 +200,8 @@ interface RibbonProps { /** References → footnotes / endnotes / citations */ onInsertNote: (kind: 'footnote' | 'endnote') => void sources: SourceInfo[] + /** footnotes/endnotes hold Zotero citation fields the bridge cannot see yet */ + zoteroNoteFields?: boolean onAddSource: (source: SourceInfo) => void /** TOC page-number backfill: docHeadings in document order → real page numbers (null when not computable) */ headingPages?: () => number[] | null @@ -654,6 +657,7 @@ function RibbonInner({ onInkClearAll, onInsertNote, sources, + zoteroNoteFields, onAddSource, headingPages, zoom, @@ -1835,6 +1839,12 @@ function RibbonInner({ if (item.types.includes('text/html')) { const html = await (await item.getType('text/html')).text() if (html) { + // arm the foreign-paste handshake exactly like a Ctrl+V — the + // synthetic pasteHTML never fires the DOM paste handler, so + // ribbon pastes skipped the paste mode and the r181 fill + if (beginForeignPaste(html)) { + stashPastePayload({ html, text, mode: defaultPasteMode() }) + } ed.view.pasteHTML(html, pasteEvent(html, text)) ed.commands.focus() return @@ -2483,7 +2493,7 @@ function RibbonInner({
    {t('ribbonGroupShading')}
    -
    +
    + +
    +
    + )} {editor && editQueue.length > 0 && ( void, + signal?: AbortSignal, + ): Promise +} + +export function buildDocWriterRequest( + spec: DocWriteSpec, + markdownRules: string, + langDirective: string, +): { system: string; user: string } { + const system = [ + 'You are the document writer of GenOffice Markdown, a markdown editor. You receive a plan (title, sections, key points, tone, length) and reference material, and you write the complete content.', + '', + '## Writing rules', + '- Write the requested content in full: every section in the plan, real prose, no placeholders, no "[to be added]" notes.', + '- Real data only: use the facts, figures, names and quotes from the reference material and the plan; never invent facts or numbers beyond them.', + '- Follow the length the plan asks for; when it gives none, write what the content genuinely needs.', + '- Structure: a single `#` title when the plan has one, `##` sections, short paragraphs; tables for comparisons, task lists for actionable items, blockquotes for important notes.', + '', + '## Output', + 'Reply with the markdown only: it starts with the first heading or paragraph and ends with the last line of content. Do not wrap the whole reply in a code fence and add no commentary before or after.', + markdownRules, + ].join('\n') + const context = spec.context?.trim() + ? `\n\n## Reference material (all names, figures and facts come from here)\n${spec.context.slice(0, CONTEXT_CAP)}` + : '' + return { + system: system + langDirective, + user: `## Plan\n${spec.title ? `Title: ${spec.title}\n` : ''}${spec.plan.slice(0, 6000)}${context}\n\nWrite the content now.`, + } +} + +/** + * Strip a fence the model wrapped the whole reply in. Only a leading + * ```markdown / ```md fence counts: a bare ``` may be real content (a code + * block the document starts with). + */ +export function extractMarkdown(raw: string): string { + let text = raw.replace(/\r\n/g, '\n').replace(/^\s+/, '') + if (/^```(?:markdown|md)\s*\n/i.test(text)) { + text = text.replace(/^```(?:markdown|md)\s*\n/i, '').replace(/\n```\s*$/, '') + } + return text.trimEnd() +} + +/** rough top-level block count of the markdown so far, for the progress chip */ +export function countMarkdownBlocks(markdown: string): number { + return markdown.split(/\n{2,}/).filter((chunk) => chunk.trim()).length +} + +export type WritePosition = { kind: 'whole' } | { kind: 'after'; index: number } + +/** meta on every draft transaction: not an edit of its own, not history */ +export const DRAFT_META = 'aiDraft' + +/** + * Live draft of streaming markdown inside the document. Each tick re-parses + * the markdown received so far (an open fence or table row still renders as + * a block) and swaps only the blocks that changed. The draft is outside undo + * history and carries no op meta, so the AI highlight ignores it; `finish()` + * removes it so the caller can land the final markdown through runOps, giving + * one undo step and the regular highlight. + */ +export class DraftLanding { + private from: number + private to: number + /** the text of the last tick that parsed and rendered */ + private rendered: string | null = null + private pending: string | null = null + private timer: ReturnType | null = null + private closed = false + private follow = true + private readonly onTransaction = ({ transaction }: { transaction: Transaction }) => { + if (!transaction.docChanged || transaction.getMeta(DRAFT_META)) return + this.from = transaction.mapping.map(this.from, 1) + this.to = Math.max(this.from, transaction.mapping.map(this.to, -1)) + } + + constructor( + private readonly editor: Editor, + position: WritePosition, + ) { + this.from = + position.kind === 'after' && position.index >= 0 + ? blockRange(editor.state.doc, position.index, position.index).to + : 0 + this.to = this.from + editor.on('transaction', this.onTransaction) + } + + /** latest cumulative markdown; rendered on the next tick */ + update(markdown: string): void { + if (this.closed) return + this.pending = markdown + if (this.timer === null) this.timer = setTimeout(() => this.flush(), DRAFT_TICK_MS) + } + + /** the top-level block index the draft sits after (-1 = document start), after any user edits */ + indexBefore(): number { + let index = -1 + let i = 0 + this.editor.state.doc.forEach((node, offset) => { + if (offset + node.nodeSize <= this.from) index = i + i++ + }) + return index + } + + /** + * Remove the draft; the document is back to what it was around it. Returns the + * text of the last tick that rendered, so a kept stream whose tail no longer + * parses (a half-received formula or table) can still land what the user saw. + */ + finish(): string | null { + if (this.closed) return this.rendered + if (this.timer !== null) clearTimeout(this.timer) + this.timer = null + this.flush() + this.closed = true + this.editor.off('transaction', this.onTransaction) + if (this.to > this.from && !this.editor.isDestroyed) { + this.editor.view.dispatch(this.draftTr().delete(this.from, this.to)) + } + this.to = this.from + return this.rendered + } + + /** live top-level blocks inside the draft range, after any user edits */ + private liveNodes(): Array<{ node: PmNode; end: number }> { + const out: Array<{ node: PmNode; end: number }> = [] + this.editor.state.doc.forEach((node, offset) => { + if (offset >= this.from && offset + node.nodeSize <= this.to) + out.push({ node, end: offset + node.nodeSize }) + }) + return out + } + + private draftTr(): Transaction { + return this.editor.state.tr.setMeta(DRAFT_META, true).setMeta('addToHistory', false) + } + + private flush(): void { + this.timer = null + if (this.closed || this.pending === null || this.editor.isDestroyed) return + const markdown = this.pending + this.pending = null + let next: PmNode[] + try { + next = parseMarkdownToNodes(this.editor, markdown) + } catch { + return // a half-received block is retried on the next tick + } + this.rendered = markdown + // compare against the live document: a user edit inside the draft changes sizes and drops that block from the kept prefix + const live = this.liveNodes() + let keep = 0 + while (keep < live.length && keep < next.length && live[keep]!.node.eq(next[keep]!)) keep++ + if (keep === live.length && keep === next.length) return + const at = keep > 0 ? live[keep - 1]!.end : this.from + const wasVisible = this.follow && this.endVisible() + this.editor.view.dispatch(this.draftTr().replaceWith(at, this.to, next.slice(keep))) + this.to = at + next.slice(keep).reduce((size, n) => size + n.nodeSize, 0) + if (wasVisible) this.scrollToEnd() + else this.follow = false + } + + private endVisible(): boolean { + if (this.to === this.from) return true + try { + const { top } = this.editor.view.coordsAtPos(this.to - 1) + return top >= 0 && top <= window.innerHeight + } catch { + return true + } + } + + private scrollToEnd(): void { + if (this.to === this.from) return + try { + const { node } = this.editor.view.domAtPos(this.to - 1) + const el = node instanceof Element ? node : node.parentElement + el?.scrollIntoView?.({ block: 'nearest' }) + } catch { + /* layout not ready */ + } + } +} diff --git a/apps/markdown/src/renderer/ai/markdown-skill.ts b/apps/markdown/src/renderer/ai/markdown-skill.ts index 012c2ef..596eeee 100644 --- a/apps/markdown/src/renderer/ai/markdown-skill.ts +++ b/apps/markdown/src/renderer/ai/markdown-skill.ts @@ -1,5 +1,6 @@ import type { AgentSkill } from '@genoffice/agent-core' import type { Editor } from '@tiptap/core' +import type { AiDocWriter } from './doc-writer' import { AGENT_TOOLS, buildDocContext, @@ -8,7 +9,7 @@ import { type FrontmatterAccess, } from './tools' -const MARKDOWN_RULES = [ +export const MARKDOWN_RULES = [ 'All markdown passed to tools must be pure GFM plus math. Rules:', '- Allowed syntax, and nothing else: `#`–`######` headings, paragraphs, `**bold**`, `*italic*`, `~~strikethrough~~`, `` `inline code` ``, `[links](url)`, `![images](path)`, `-` / `1.` lists, `- [ ]` task lists, `>` blockquotes, ``` fenced code blocks, `|` pipe tables, `---` horizontal rules, hard line breaks (two trailing spaces), LaTeX math, and ```mermaid diagrams.', '- Math: `$...$` inline and `$$...$$` blocks are rendered with KaTeX. The content of `$...$` must not start or end with whitespace, and the closing `$` must not be followed by a digit (so currency amounts stay text).', @@ -53,9 +54,9 @@ const AGENT_SYSTEM_PROMPT = [ '- Only cite block indexes that exist in the block list — never guess; prefer heading blocks as citation anchors. Whole-document answers may omit citations.', '', '## Writing a new document', - '- When the document is blank and the user asks for content, write the full document in one insertContent op: start with a single `#` title, use `##` sections, keep paragraphs short.', - '- Use tables for comparisons, task lists for actionable items, blockquotes for important notes.', - '- Never invent facts or numbers; use web_search when the topic needs current information and attribute sources.', + '- Long new content (a whole document, a chapter, a full report/article/translation — anything beyond a few paragraphs) goes through write_document: you pass the plan and the reference material, and the system writer streams the markdown into the document while the user watches; never paste long content into insertContent. When the document is blank and the user asks for content, use write_document.', + '- The plan: a single `#` title, `##` sections with the key points of each, tone and target length; tables for comparisons, task lists for actionable items, blockquotes for important notes.', + '- Never invent facts or numbers; use web_search when the topic needs current information, put the findings into context, and attribute sources.', '', '## Conversation', '- Answer questions about the document directly, without editing it.', @@ -70,6 +71,8 @@ export function createMarkdownSkill( fm?: FrontmatterAccess, /** live predicate (gsk login && cloud-tools toggle, or a BYOK media key); false hides generate_image */ imageGenAvailable?: () => boolean, + /** streaming long-form writer behind write_document (panel-owned: progress chip, partial keep/discard) */ + getWriter?: () => AiDocWriter | undefined, ): AgentSkill { return { id: 'markdown', @@ -95,7 +98,7 @@ export function createMarkdownSkill( if (!editor) { return { output: 'editor not ready', isError: true, summary: call.name } } - return executeTool(editor, call, signal, fm) + return executeTool(editor, call, signal, fm, getWriter?.()) }, } } diff --git a/apps/markdown/src/renderer/ai/tools.ts b/apps/markdown/src/renderer/ai/tools.ts index a112483..6c25696 100644 --- a/apps/markdown/src/renderer/ai/tools.ts +++ b/apps/markdown/src/renderer/ai/tools.ts @@ -6,6 +6,7 @@ import { blockIndexRange, buildOpsGuide, isBlankDoc, + parseMarkdownToNodes, runOps, usesBlockIndexes, validateOps, @@ -13,6 +14,12 @@ import { type MdOp, } from '../editor/ops' import { t } from '../i18n/locale' +import { + DraftLanding, + type AiDocWriter, + type DocWriteResult, + type WritePosition, +} from './doc-writer' export type { FrontmatterAccess } from '../editor/ops' export { blockIndexRange } from '../editor/ops' @@ -143,6 +150,37 @@ export const AGENT_TOOLS: AgentToolDef[] = [ required: ['ops'], }, }, + { + name: 'write_document', + description: + '[For long new content: a whole document, a chapter, a full report, article or translation] Hands the writing to the system writer, which streams markdown straight into the document while the user watches; you never write the text yourself. Give a concrete plan (title, section outline with the key points of each, tone, target length) and put every fact, figure, name and quote the text must use into context — the writer sees only the plan and context, not the conversation. Omit afterIndex on a blank document; on a document with content, pass afterIndex to insert after that block, or replaceDocument=true when the user asked to rewrite everything. Short additions (a paragraph or two) use apply_ops insertContent instead.', + inputSchema: { + type: 'object', + properties: { + plan: { + type: 'string', + description: 'title, section outline with key points per section, tone, target length', + }, + title: { type: 'string', description: 'document/chapter title, when there is one' }, + context: { + type: 'string', + description: + 'reference material: facts, figures, quotes, sources gathered from the conversation and web_search', + }, + afterIndex: { + type: 'integer', + description: + 'insert after this block index (-1 = document start); omitted = whole document', + }, + replaceDocument: { + type: 'boolean', + description: + 'true replaces all existing content (only when the user asked for a rewrite)', + }, + }, + required: ['plan'], + }, + }, { name: 'image_search', description: @@ -316,16 +354,100 @@ async function insertImageFromUrl( } } +async function writeDocument( + editor: Editor, + call: AgentToolCall, + signal: AbortSignal | undefined, + writer: AiDocWriter | undefined, +): Promise { + const label = t('aiToolWriteDoc') + const plan = String(call.input.plan ?? '').trim() + if (!plan) return fail('plan must not be empty', label) + if (!writer) return fail('document writing is not available here', label) + if (editedExternally(editor)) return fail(STALE_DOC_ERROR, label) + const doc = editor.state.doc + const afterRaw = call.input.afterIndex + let position: WritePosition + if (afterRaw !== undefined && afterRaw !== null) { + if (!Number.isInteger(afterRaw) || Number(afterRaw) < -1 || Number(afterRaw) >= doc.childCount) + return fail(`afterIndex out of range; the document has ${doc.childCount} blocks.`, label) + position = { kind: 'after', index: Number(afterRaw) } + } else if (isBlankDoc(doc) || call.input.replaceDocument === true) { + position = { kind: 'whole' } + } else { + return fail( + 'the document is not blank: pass afterIndex to insert the new content after a block, or replaceDocument=true when the user asked to rewrite the whole document', + label, + ) + } + const str = (v: unknown) => (v === undefined || v === null ? undefined : String(v)) + const draft = new DraftLanding(editor, position) + let result: DocWriteResult + let rendered: string | null + try { + result = await writer.write( + { plan, title: str(call.input.title), context: str(call.input.context) }, + (markdown) => draft.update(markdown), + signal, + ) + } finally { + rendered = draft.finish() + } + if (editor.isDestroyed) return fail('the document was closed', label) + if (!result.ok || !result.markdown?.trim()) { + return fail( + `The writer produced nothing (${result.error ?? 'no output'}); the document is unchanged. Tell the user briefly and offer to try again.`, + t('aiToolWriteDocFailed'), + ) + } + // a kept partial whose tail no longer parses lands what the user saw rendered + let parses: boolean + try { + parses = parseMarkdownToNodes(editor, result.markdown).length > 0 + } catch { + parses = false + } + const markdown = !parses && result.truncated && rendered ? rendered : result.markdown + // an explicit rewrite replaces everything; text the user typed into a formerly blank + // document while the draft streamed is kept, the content goes into the draft's slot + const op: MdOp = + position.kind === 'whole' && + !isBlankDoc(editor.state.doc) && + call.input.replaceDocument === true + ? { + op: 'replaceBlocks', + target: { start: 0, end: editor.state.doc.childCount - 1 }, + markdown, + } + : { op: 'insertContent', after: draft.indexBefore(), markdown } + const r = runOps(editor, [op], { source: 'ai' }) + const res = r.results[0]! + if (!res.ok) return fail(res.error, t('aiToolWriteDocFailed')) + markDocSeen(editor) + const note = result.truncated + ? ' The stream ended early, so the content is INCOMPLETE (the user chose to keep it): the tail is missing. Say so and offer to finish the missing sections with write_document (afterIndex at the end) or apply_ops insertContent.' + : '' + return { + output: `Content written by the system (${result.markdown.length} chars). ${res.message} ${INDEX_CHANGE_NOTICE}${note}\nReply with one or two sentences describing what was written; do not paste the content.`, + mutated: true, + summary: result.truncated ? t('aiToolWriteDocPartial') : label, + } +} + export function executeTool( editor: Editor, call: AgentToolCall, signal?: AbortSignal, fm?: FrontmatterAccess, + writer?: AiDocWriter, ): ToolExecution | Promise { const doc = editor.state.doc const maxIndex = doc.childCount - 1 switch (call.name) { + case 'write_document': + return writeDocument(editor, call, signal, writer) + case 'read_frontmatter': { if (!fm) return fail('frontmatter is not available', t('aiToolReadFm')) const inner = fm.read() diff --git a/apps/markdown/src/renderer/components/Ribbon.tsx b/apps/markdown/src/renderer/components/Ribbon.tsx index e0a4626..066773c 100644 --- a/apps/markdown/src/renderer/components/Ribbon.tsx +++ b/apps/markdown/src/renderer/components/Ribbon.tsx @@ -499,7 +499,7 @@ export function Ribbon({ diff --git a/apps/markdown/src/renderer/i18n/strings.ts b/apps/markdown/src/renderer/i18n/strings.ts index 840c4ab..236374e 100644 --- a/apps/markdown/src/renderer/i18n/strings.ts +++ b/apps/markdown/src/renderer/i18n/strings.ts @@ -1,6 +1,14 @@ export const strings = { zh: { aiToolReadFm: '读取文档属性', + aiToolWriteDoc: '撰写文档', + aiToolWriteDocFailed: '文档撰写失败', + aiToolWriteDocPartial: '文档只撰写了一部分', + aiWritingDocument: '正在撰写文档 · {blocks} 块', + aiPartialTitle: '内容只生成了一部分', + aiPartialBody: '已收到 {blocks} 个内容块,生成中断了。采用这部分,还是放弃?', + aiPartialAdopt: '采用', + aiPartialDiscard: '放弃', aiToolSetFm: '更新文档属性', aiScopeSelection: '已选中 {words} 字', aiScopeSelectionTip: '改写类指令默认只作用于选中内容;点击预览', @@ -183,6 +191,15 @@ export const strings = { }, en: { aiToolReadFm: 'Read document properties', + aiToolWriteDoc: 'Wrote the content', + aiToolWriteDocFailed: 'Writing failed', + aiToolWriteDocPartial: 'Wrote part of the content', + aiWritingDocument: 'Writing the document · {blocks} blocks', + aiPartialTitle: 'Only part of the content was written', + aiPartialBody: + '{blocks} blocks arrived before the writing stopped. Keep this part or discard it?', + aiPartialAdopt: 'Keep', + aiPartialDiscard: 'Discard', aiToolSetFm: 'Update document properties', aiScopeSelection: 'Selected: {words} words', aiScopeSelectionTip: @@ -370,6 +387,15 @@ export const strings = { }, ja: { aiToolReadFm: 'ドキュメントのプロパティを読み取り', + aiToolWriteDoc: '本文を作成しました', + aiToolWriteDocFailed: '本文の作成に失敗しました', + aiToolWriteDocPartial: '本文の一部を作成しました', + aiWritingDocument: '文書を作成中 · {blocks} ブロック', + aiPartialTitle: '本文の一部しか作成されませんでした', + aiPartialBody: + '{blocks} ブロックを受信した時点で作成が中断しました。この部分を採用しますか、破棄しますか?', + aiPartialAdopt: '採用', + aiPartialDiscard: '破棄', aiToolSetFm: 'ドキュメントのプロパティを更新', aiScopeSelection: '選択中: {words} 文字', aiScopeSelectionTip: '書き換え系の指示は既定で選択範囲にのみ適用されます。クリックでプレビュー', @@ -555,6 +581,15 @@ export const strings = { }, ko: { aiToolReadFm: '문서 속성 읽기', + aiToolWriteDoc: '본문을 작성했습니다', + aiToolWriteDocFailed: '본문 작성 실패', + aiToolWriteDocPartial: '본문 일부를 작성했습니다', + aiWritingDocument: '문서 작성 중 · {blocks}개 블록', + aiPartialTitle: '본문이 일부만 작성되었습니다', + aiPartialBody: + '{blocks}개 블록을 받은 뒤 작성이 중단되었습니다. 이 부분을 사용할까요, 버릴까요?', + aiPartialAdopt: '사용', + aiPartialDiscard: '버리기', aiToolSetFm: '문서 속성 업데이트', aiScopeSelection: '선택됨: {words}자', aiScopeSelectionTip: @@ -741,6 +776,15 @@ export const strings = { }, fr: { aiToolReadFm: 'Lecture des propriétés du document', + aiToolWriteDoc: 'Contenu rédigé', + aiToolWriteDocFailed: 'Échec de la rédaction', + aiToolWriteDocPartial: 'Contenu partiellement rédigé', + aiWritingDocument: 'Rédaction du document · {blocks} blocs', + aiPartialTitle: "Le contenu n'a été rédigé qu'en partie", + aiPartialBody: + "{blocks} blocs sont arrivés avant l'arrêt de la rédaction. Conserver cette partie ou l'abandonner ?", + aiPartialAdopt: 'Conserver', + aiPartialDiscard: 'Abandonner', aiToolSetFm: 'Mise à jour des propriétés du document', aiScopeSelection: 'Sélection : {words} mots', aiScopeSelectionTip: @@ -932,6 +976,15 @@ export const strings = { }, de: { aiToolReadFm: 'Dokumenteigenschaften lesen', + aiToolWriteDoc: 'Inhalt geschrieben', + aiToolWriteDocFailed: 'Schreiben fehlgeschlagen', + aiToolWriteDocPartial: 'Inhalt teilweise geschrieben', + aiWritingDocument: 'Dokument wird geschrieben · {blocks} Blöcke', + aiPartialTitle: 'Der Inhalt wurde nur teilweise geschrieben', + aiPartialBody: + '{blocks} Blöcke sind angekommen, bevor das Schreiben abbrach. Diesen Teil behalten oder verwerfen?', + aiPartialAdopt: 'Behalten', + aiPartialDiscard: 'Verwerfen', aiToolSetFm: 'Dokumenteigenschaften aktualisieren', aiScopeSelection: 'Ausgewählt: {words} Wörter', aiScopeSelectionTip: @@ -1122,6 +1175,15 @@ export const strings = { }, es: { aiToolReadFm: 'Leer propiedades del documento', + aiToolWriteDoc: 'Contenido redactado', + aiToolWriteDocFailed: 'Falló la redacción', + aiToolWriteDocPartial: 'Contenido redactado parcialmente', + aiWritingDocument: 'Redactando el documento · {blocks} bloques', + aiPartialTitle: 'Solo se redactó parte del contenido', + aiPartialBody: + 'Llegaron {blocks} bloques antes de que la redacción se detuviera. ¿Conservar esta parte o descartarla?', + aiPartialAdopt: 'Conservar', + aiPartialDiscard: 'Descartar', aiToolSetFm: 'Actualizar propiedades del documento', aiScopeSelection: 'Seleccionado: {words} palabras', aiScopeSelectionTip: @@ -1313,6 +1375,14 @@ export const strings = { }, th: { aiToolReadFm: 'อ่านคุณสมบัติเอกสาร', + aiToolWriteDoc: 'เขียนเนื้อหาแล้ว', + aiToolWriteDocFailed: 'เขียนเนื้อหาไม่สำเร็จ', + aiToolWriteDocPartial: 'เขียนเนื้อหาได้บางส่วน', + aiWritingDocument: 'กำลังเขียนเอกสาร · {blocks} บล็อก', + aiPartialTitle: 'เขียนเนื้อหาได้เพียงบางส่วน', + aiPartialBody: 'ได้รับ {blocks} บล็อกก่อนที่การเขียนจะหยุดลง ต้องการเก็บส่วนนี้ไว้หรือทิ้ง?', + aiPartialAdopt: 'เก็บไว้', + aiPartialDiscard: 'ทิ้ง', aiToolSetFm: 'อัปเดตคุณสมบัติเอกสาร', aiScopeSelection: 'เลือกแล้ว {words} คำ', aiScopeSelectionTip: 'คำสั่งเขียนใหม่จะมีผลกับส่วนที่เลือกโดยค่าเริ่มต้น คลิกเพื่อดูตัวอย่าง', @@ -1497,6 +1567,15 @@ export const strings = { }, id: { aiToolReadFm: 'Baca properti dokumen', + aiToolWriteDoc: 'Konten ditulis', + aiToolWriteDocFailed: 'Penulisan gagal', + aiToolWriteDocPartial: 'Sebagian konten ditulis', + aiWritingDocument: 'Menulis dokumen · {blocks} blok', + aiPartialTitle: 'Hanya sebagian konten yang ditulis', + aiPartialBody: + '{blocks} blok diterima sebelum penulisan terhenti. Simpan bagian ini atau buang?', + aiPartialAdopt: 'Simpan', + aiPartialDiscard: 'Buang', aiToolSetFm: 'Perbarui properti dokumen', aiScopeSelection: 'Terpilih: {words} kata', aiScopeSelectionTip: @@ -1683,6 +1762,15 @@ export const strings = { }, ru: { aiToolReadFm: 'Чтение свойств документа', + aiToolWriteDoc: 'Текст написан', + aiToolWriteDocFailed: 'Не удалось написать текст', + aiToolWriteDocPartial: 'Текст написан частично', + aiWritingDocument: 'Пишу документ · {blocks} блоков', + aiPartialTitle: 'Текст написан лишь частично', + aiPartialBody: + 'Получено {blocks} блоков, после чего написание прервалось. Оставить эту часть или отменить?', + aiPartialAdopt: 'Оставить', + aiPartialDiscard: 'Отменить', aiToolSetFm: 'Обновление свойств документа', aiScopeSelection: 'Выделено: {words} слов', aiScopeSelectionTip: @@ -1870,6 +1958,14 @@ export const strings = { }, ar: { aiToolReadFm: 'قراءة خصائص المستند', + aiToolWriteDoc: 'تمت كتابة المحتوى', + aiToolWriteDocFailed: 'فشلت الكتابة', + aiToolWriteDocPartial: 'تمت كتابة جزء من المحتوى', + aiWritingDocument: 'جارٍ كتابة المستند · {blocks} كتلة', + aiPartialTitle: 'لم تتم كتابة سوى جزء من المحتوى', + aiPartialBody: 'وصلت {blocks} كتلة قبل توقف الكتابة. هل تريد الاحتفاظ بهذا الجزء أو تجاهله؟', + aiPartialAdopt: 'احتفاظ', + aiPartialDiscard: 'تجاهل', aiToolSetFm: 'تحديث خصائص المستند', aiScopeSelection: 'المحدد: {words} كلمة', aiScopeSelectionTip: 'تعليمات إعادة الصياغة تُطبق افتراضيًا على التحديد فقط؛ انقر للمعاينة', @@ -2054,6 +2150,15 @@ export const strings = { }, pt: { aiToolReadFm: 'Ler propriedades do documento', + aiToolWriteDoc: 'Conteúdo escrito', + aiToolWriteDocFailed: 'Falha ao escrever', + aiToolWriteDocPartial: 'Conteúdo escrito parcialmente', + aiWritingDocument: 'Escrevendo o documento · {blocks} blocos', + aiPartialTitle: 'Apenas parte do conteúdo foi escrita', + aiPartialBody: + '{blocks} blocos chegaram antes de a escrita parar. Manter esta parte ou descartar?', + aiPartialAdopt: 'Manter', + aiPartialDiscard: 'Descartar', aiToolSetFm: 'Atualizar propriedades do documento', aiScopeSelection: 'Selecionado: {words} palavras', aiScopeSelectionTip: @@ -2243,6 +2348,15 @@ export const strings = { }, it: { aiToolReadFm: 'Lettura delle proprietà del documento', + aiToolWriteDoc: 'Contenuto scritto', + aiToolWriteDocFailed: 'Scrittura non riuscita', + aiToolWriteDocPartial: 'Contenuto scritto in parte', + aiWritingDocument: 'Scrittura del documento · {blocks} blocchi', + aiPartialTitle: 'È stata scritta solo una parte del contenuto', + aiPartialBody: + 'Sono arrivati {blocks} blocchi prima che la scrittura si interrompesse. Conservare questa parte o scartarla?', + aiPartialAdopt: 'Conserva', + aiPartialDiscard: 'Scarta', aiToolSetFm: 'Aggiornamento delle proprietà del documento', aiScopeSelection: 'Selezionato: {words} parole', aiScopeSelectionTip: @@ -2432,6 +2546,15 @@ export const strings = { }, pl: { aiToolReadFm: 'Odczyt właściwości dokumentu', + aiToolWriteDoc: 'Napisano treść', + aiToolWriteDocFailed: 'Pisanie nie powiodło się', + aiToolWriteDocPartial: 'Napisano część treści', + aiWritingDocument: 'Pisanie dokumentu · {blocks} bloków', + aiPartialTitle: 'Napisano tylko część treści', + aiPartialBody: + 'Dotarło {blocks} bloków, zanim pisanie zostało przerwane. Zachować tę część czy odrzucić?', + aiPartialAdopt: 'Zachowaj', + aiPartialDiscard: 'Odrzuć', aiToolSetFm: 'Aktualizacja właściwości dokumentu', aiScopeSelection: 'Zaznaczono: {words} słów', aiScopeSelectionTip: @@ -2619,6 +2742,15 @@ export const strings = { }, cs: { aiToolReadFm: 'Číst vlastnosti dokumentu', + aiToolWriteDoc: 'Obsah napsán', + aiToolWriteDocFailed: 'Psaní se nezdařilo', + aiToolWriteDocPartial: 'Obsah napsán částečně', + aiWritingDocument: 'Píšu dokument · {blocks} bloků', + aiPartialTitle: 'Napsala se jen část obsahu', + aiPartialBody: + 'Dorazilo {blocks} bloků, než se psaní přerušilo. Ponechat tuto část, nebo zahodit?', + aiPartialAdopt: 'Ponechat', + aiPartialDiscard: 'Zahodit', aiToolSetFm: 'Aktualizovat vlastnosti dokumentu', aiScopeSelection: 'Vybráno: {words} slov', aiScopeSelectionTip: @@ -2805,6 +2937,15 @@ export const strings = { }, nl: { aiToolReadFm: 'Documenteigenschappen lezen', + aiToolWriteDoc: 'Inhoud geschreven', + aiToolWriteDocFailed: 'Schrijven mislukt', + aiToolWriteDocPartial: 'Inhoud gedeeltelijk geschreven', + aiWritingDocument: 'Document wordt geschreven · {blocks} blokken', + aiPartialTitle: 'Slechts een deel van de inhoud is geschreven', + aiPartialBody: + '{blocks} blokken kwamen aan voordat het schrijven stopte. Dit deel behouden of weggooien?', + aiPartialAdopt: 'Behouden', + aiPartialDiscard: 'Weggooien', aiToolSetFm: 'Documenteigenschappen bijwerken', aiScopeSelection: 'Geselecteerd: {words} woorden', aiScopeSelectionTip: @@ -2993,6 +3134,15 @@ export const strings = { }, ms: { aiToolReadFm: 'Baca sifat dokumen', + aiToolWriteDoc: 'Kandungan ditulis', + aiToolWriteDocFailed: 'Penulisan gagal', + aiToolWriteDocPartial: 'Sebahagian kandungan ditulis', + aiWritingDocument: 'Menulis dokumen · {blocks} blok', + aiPartialTitle: 'Hanya sebahagian kandungan ditulis', + aiPartialBody: + '{blocks} blok diterima sebelum penulisan terhenti. Simpan bahagian ini atau buang?', + aiPartialAdopt: 'Simpan', + aiPartialDiscard: 'Buang', aiToolSetFm: 'Kemas kini sifat dokumen', aiScopeSelection: 'Dipilih: {words} patah perkataan', aiScopeSelectionTip: @@ -3179,6 +3329,14 @@ export const strings = { }, he: { aiToolReadFm: 'קריאת מאפייני המסמך', + aiToolWriteDoc: 'התוכן נכתב', + aiToolWriteDocFailed: 'הכתיבה נכשלה', + aiToolWriteDocPartial: 'נכתב חלק מהתוכן', + aiWritingDocument: 'כותב את המסמך · {blocks} בלוקים', + aiPartialTitle: 'נכתב רק חלק מהתוכן', + aiPartialBody: 'התקבלו {blocks} בלוקים לפני שהכתיבה נעצרה. לשמור את החלק הזה או להשליך?', + aiPartialAdopt: 'לשמור', + aiPartialDiscard: 'להשליך', aiToolSetFm: 'עדכון מאפייני המסמך', aiScopeSelection: 'נבחרו: {words} מילים', aiScopeSelectionTip: 'הוראות שכתוב חלות כברירת מחדל על הבחירה בלבד; לחץ לתצוגה מקדימה', @@ -3362,6 +3520,14 @@ export const strings = { }, hi: { aiToolReadFm: 'दस्तावेज़ गुण पढ़ें', + aiToolWriteDoc: 'सामग्री लिख दी', + aiToolWriteDocFailed: 'लिखने में विफल', + aiToolWriteDocPartial: 'सामग्री का कुछ हिस्सा लिखा', + aiWritingDocument: 'दस्तावेज़ लिखा जा रहा है · {blocks} ब्लॉक', + aiPartialTitle: 'सामग्री का केवल एक हिस्सा लिखा गया', + aiPartialBody: 'लिखना रुकने से पहले {blocks} ब्लॉक मिले। इस हिस्से को रखें या छोड़ दें?', + aiPartialAdopt: 'रखें', + aiPartialDiscard: 'छोड़ें', aiToolSetFm: 'दस्तावेज़ गुण अपडेट करें', aiScopeSelection: 'चयनित: {words} शब्द', aiScopeSelectionTip: @@ -3549,6 +3715,14 @@ export const strings = { }, 'zh-TW': { aiToolReadFm: '讀取文件屬性', + aiToolWriteDoc: '撰寫文件', + aiToolWriteDocFailed: '文件撰寫失敗', + aiToolWriteDocPartial: '文件只撰寫了一部分', + aiWritingDocument: '正在撰寫文件 · {blocks} 塊', + aiPartialTitle: '內容只產生了一部分', + aiPartialBody: '已收到 {blocks} 個內容區塊,產生中斷了。採用這部分,還是放棄?', + aiPartialAdopt: '採用', + aiPartialDiscard: '放棄', aiToolSetFm: '更新文件屬性', aiScopeSelection: '已選中 {words} 字', aiScopeSelectionTip: '改寫類指令預設只作用於選中內容;點擊預覽', diff --git a/apps/markdown/src/renderer/styles.css b/apps/markdown/src/renderer/styles.css index 3ef27b2..3f9cc2f 100644 --- a/apps/markdown/src/renderer/styles.css +++ b/apps/markdown/src/renderer/styles.css @@ -2877,3 +2877,9 @@ div.tiptap-mathematics-render { .app-toast.success .app-toast-icon { color: var(--md-toast-ok); } + +.ai-partial-card .ai-queue-hint { + padding: 0 10px 4px; + font-size: 12px; + color: var(--color-text-secondary); +} diff --git a/apps/markdown/src/shared/ipc.ts b/apps/markdown/src/shared/ipc.ts index d1792fd..1d98f4c 100644 --- a/apps/markdown/src/shared/ipc.ts +++ b/apps/markdown/src/shared/ipc.ts @@ -23,6 +23,8 @@ export const MARKDOWN_CHANNELS = { exportRequest: 'markdown:export-request', exportDocx: 'markdown:export-docx', exportPdf: 'markdown:export-pdf', + consumeHeadlessExport: 'markdown:consume-headless-export', + headlessExportDone: 'markdown:headless-export-done', printRequest: 'markdown:print-request', aiGenerateImage: 'markdown:ai-generate-image', getLanguage: 'app:get-language', @@ -111,6 +113,8 @@ export interface ExportPdfRequest { /** self-contained print HTML */ html: string suggestedName: string + /** headless export mode only: write here instead of opening the save dialog */ + outPath?: string } export type ExportResult = @@ -125,6 +129,10 @@ export interface ImageData { export interface MarkdownApi { /** Take the md path pending for this view (queued at tab creation); null = new untitled document */ consumePending(): Promise + /** Headless export mode: the PDF path this hidden renderer must export to, null in normal use */ + consumeHeadlessExport(): Promise + /** Headless export mode: report the export outcome so the main process can quit */ + headlessExportDone(result: { ok: boolean; error?: string }): void /** Read the file as UTF-8 text. Only paths granted to this view are allowed */ readFile(path: string): Promise /** diff --git a/apps/markdown/tests/ai-doc-writer.test.ts b/apps/markdown/tests/ai-doc-writer.test.ts new file mode 100644 index 0000000..fddc11d --- /dev/null +++ b/apps/markdown/tests/ai-doc-writer.test.ts @@ -0,0 +1,222 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { Editor } from '@tiptap/core' +import { undoDepth } from '@tiptap/pm/history' +import { buildExtensions } from '../src/renderer/editor/extensions' +import { + buildDocWriterRequest, + countMarkdownBlocks, + DraftLanding, + extractMarkdown, + type AiDocWriter, +} from '../src/renderer/ai/doc-writer' +import { executeTool } from '../src/renderer/ai/tools' +import { MARKDOWN_RULES } from '../src/renderer/ai/markdown-skill' + +const editors: Editor[] = [] +afterEach(() => { + for (const e of editors.splice(0)) e.destroy() +}) + +function createEditor(md = ''): Editor { + const editor = new Editor({ + extensions: buildExtensions({ + slashController: { onOpen() {}, onUpdate() {}, onKeyDown: () => false, onClose() {} }, + slashItems: () => [], + }), + content: '', + }) + if (md) editor.commands.setContent(md, { contentType: 'markdown' }) + editors.push(editor) + return editor +} + +const texts = (editor: Editor) => { + const out: string[] = [] + editor.state.doc.forEach((n) => out.push(n.textContent)) + return out +} + +const tick = () => new Promise((r) => setTimeout(r, 350)) + +describe('extractMarkdown', () => { + it('unwraps a whole-reply markdown fence but keeps a leading code block', () => { + expect(extractMarkdown('```markdown\n# T\n\ntext\n```\n')).toBe('# T\n\ntext') + expect(extractMarkdown('```js\nlet a\n```\n\nafter')).toBe('```js\nlet a\n```\n\nafter') + expect(extractMarkdown('\n\n# T\r\nx')).toBe('# T\nx') + }) + it('counts blank-line separated blocks', () => { + expect(countMarkdownBlocks('# T\n\npara\n\n- a\n- b\n\n')).toBe(3) + }) +}) + +describe('buildDocWriterRequest', () => { + it('carries plan, title and context; the system prompt has the markdown rules and language', () => { + const { system, user } = buildDocWriterRequest( + { plan: 'intro, body', title: 'Guide', context: 'founded 1999' }, + MARKDOWN_RULES, + '\n\nAnswer in French.', + ) + expect(system).toContain('Reply with the markdown only') + expect(system).toContain('pure GFM plus math') + expect(system.endsWith('Answer in French.')).toBe(true) + expect(user).toContain('Title: Guide') + expect(user).toContain('intro, body') + expect(user).toContain('founded 1999') + }) +}) + +describe('DraftLanding', () => { + it('renders the growing markdown in place, keeps unchanged blocks, leaves no trace on finish', async () => { + const editor = createEditor() + const before = editor.state.doc + const depth = undoDepth(editor.state) + const draft = new DraftLanding(editor, { kind: 'whole' }) + draft.update('# Title\n\nfirst para') + await tick() + expect(texts(editor)).toEqual(['Title', 'first para', '']) + const titleNode = editor.state.doc.child(0) + draft.update('# Title\n\nfirst paragraph\n\n- item') + await tick() + expect(texts(editor)).toEqual(['Title', 'first paragraph', 'item', '']) + expect(editor.state.doc.child(0)).toBe(titleNode) + expect(undoDepth(editor.state)).toBe(depth) + draft.finish() + expect(editor.state.doc.eq(before)).toBe(true) + }) + + it("follows the user's edits above the draft and reports the block it sits after", async () => { + const editor = createEditor('one\n\ntwo') + const draft = new DraftLanding(editor, { kind: 'after', index: 0 }) + draft.update('draft') + await tick() + expect(texts(editor)).toEqual(['one', 'draft', 'two']) + editor.view.dispatch(editor.state.tr.insert(0, editor.schema.nodes.paragraph!.create())) + expect(draft.indexBefore()).toBe(1) + draft.update('draft\n\nmore') + await tick() + expect(texts(editor)).toEqual(['', 'one', 'draft', 'more', 'two']) + draft.finish() + expect(texts(editor)).toEqual(['', 'one', 'two']) + }) +}) + +describe('DraftLanding under user edits', () => { + it('re-anchors on the live document when the user edits inside the draft', async () => { + const editor = createEditor('one') + const draft = new DraftLanding(editor, { kind: 'after', index: 0 }) + draft.update('alpha\n\nbeta') + await tick() + expect(texts(editor)).toEqual(['one', 'alpha', 'beta']) + const alphaPos = editor.state.doc.child(0).nodeSize + 1 + 'alpha'.length + editor.view.dispatch(editor.state.tr.insertText(' edited', alphaPos)) + draft.update('alpha\n\nbeta\n\ngamma') + await tick() + expect(texts(editor)).toEqual(['one', 'alpha', 'beta', 'gamma']) + expect(draft.finish()).toBe('alpha\n\nbeta\n\ngamma') + expect(texts(editor)).toEqual(['one']) + }) +}) + +describe('write_document tool', () => { + const writerOf = (markdown: string, truncated = false): AiDocWriter => ({ + write: async (_spec, onProgress) => { + onProgress(markdown.slice(0, 5)) + onProgress(markdown) + return { ok: true, markdown, truncated } + }, + }) + + it('lands the streamed markdown as one regular insert on a blank document', async () => { + const editor = createEditor() + const exec = await executeTool( + editor, + { id: 't', name: 'write_document', input: { plan: 'a title and a paragraph' } }, + undefined, + undefined, + writerOf('# T\n\nbody'), + ) + expect(exec.isError).toBeFalsy() + expect(exec.mutated).toBe(true) + expect(texts(editor)).toEqual(['T', 'body']) + expect(editor.commands.undo()).toBe(true) + expect(texts(editor)).toEqual(['']) + }) + + it('refuses a whole-document write on a non-blank document without replaceDocument', async () => { + const editor = createEditor('keep') + const exec = await executeTool( + editor, + { id: 't', name: 'write_document', input: { plan: 'p' } }, + undefined, + undefined, + writerOf('new'), + ) + expect(exec.isError).toBe(true) + expect(exec.output).toContain('afterIndex') + expect(texts(editor)).toEqual(['keep']) + }) + + it('replaces everything with replaceDocument and inserts after a block with afterIndex', async () => { + const editor = createEditor('one\n\ntwo') + const all = await executeTool( + editor, + { id: 't', name: 'write_document', input: { plan: 'p', replaceDocument: true } }, + undefined, + undefined, + writerOf('# New\n\nbody'), + ) + expect(all.isError).toBeFalsy() + expect(texts(editor)).toEqual(['New', 'body']) + const after = await executeTool( + editor, + { id: 't', name: 'write_document', input: { plan: 'p', afterIndex: 0 } }, + undefined, + undefined, + writerOf('half', true), + ) + expect(after.isError).toBeFalsy() + expect(after.output).toContain('INCOMPLETE') + expect(texts(editor)).toEqual(['New', 'half', 'body']) + }) + + it('keeps text the user typed into a blank document while the draft streamed', async () => { + const editor = createEditor() + const writer: AiDocWriter = { + write: async (_spec, onProgress) => { + onProgress('draft') + await tick() + editor.view.dispatch(editor.state.tr.insertText('mine', editor.state.doc.content.size - 1)) + return { ok: true, markdown: 'draft\n\nmore' } + }, + } + const exec = await executeTool( + editor, + { id: 't', name: 'write_document', input: { plan: 'p' } }, + undefined, + undefined, + writer, + ) + expect(exec.isError).toBeFalsy() + expect(texts(editor)).toEqual(['draft', 'more', 'mine']) + }) + + it('a discarded write leaves the document unchanged', async () => { + const editor = createEditor() + const writer: AiDocWriter = { + write: async (_spec, onProgress) => { + onProgress('draft') + await tick() + return { ok: false, error: 'the user discarded the partial content' } + }, + } + const exec = await executeTool( + editor, + { id: 't', name: 'write_document', input: { plan: 'p' } }, + undefined, + undefined, + writer, + ) + expect(exec.isError).toBe(true) + expect(texts(editor)).toEqual(['']) + }) +}) diff --git a/apps/markdown/tests/close-asset-cleanup.test.ts b/apps/markdown/tests/close-asset-cleanup.test.ts index d34f652..4e60681 100644 --- a/apps/markdown/tests/close-asset-cleanup.test.ts +++ b/apps/markdown/tests/close-asset-cleanup.test.ts @@ -12,6 +12,7 @@ interface FakeWebContents { isDestroyed: ReturnType loadFile: ReturnType loadURL: ReturnType + loadURL: ReturnType once: ReturnType send: ReturnType setWindowOpenHandler: ReturnType @@ -31,6 +32,7 @@ function makeWebContents(): FakeWebContents { isDestroyed: vi.fn(() => false), loadFile: vi.fn(), loadURL: vi.fn(), + loadURL: vi.fn(), once: vi.fn((event: string, listener: () => void) => listeners.set(event, listener)), send: vi.fn(), setWindowOpenHandler: vi.fn(), @@ -75,6 +77,7 @@ vi.mock('@genoffice/electron-utils', () => ({ contextMenuLabels: vi.fn(() => ({})), installContextMenu: vi.fn(), installNavigationGuard: vi.fn(), + rendererUrl: vi.fn(() => 'genoffice-app://markdown/index.html'), safeExternalUrl: vi.fn(() => null), showOpenDialogWithMemory: vi.fn(), showSaveDialogWithMemory: (...args: unknown[]) => showSaveDialogWithMemory(...args), diff --git a/apps/pdf/src/main/pdf-main.ts b/apps/pdf/src/main/pdf-main.ts index d832529..ab0361f 100644 --- a/apps/pdf/src/main/pdf-main.ts +++ b/apps/pdf/src/main/pdf-main.ts @@ -22,6 +22,9 @@ import { printHtmlToPdf, safeExternalUrl, showOpenDialogWithMemory, + installRendererProtocol, + registerRendererScheme, + rendererUrl, } from '@genoffice/electron-utils' import { createI18n, getUiLang } from '@genoffice/i18n' import { generateImageTool } from '@genoffice/ai-search' @@ -1449,13 +1452,13 @@ export function createPdfView(openPath?: string | null): WebContentsView { }, }) grantAndTrack(view.webContents, openPath) - if (runtime.rendererUrl) void view.webContents.loadURL(runtime.rendererUrl) - else if (runtime.rendererFile) void view.webContents.loadFile(runtime.rendererFile) + void view.webContents.loadURL(rendererUrl(runtime.rendererUrl, 'pdf')) return view } /** Standalone window mode: `npm run dev -w @genoffice/pdf`, pdf path passed via argv */ export function startPdfStandalone(): void { + registerRendererScheme() installNavigationGuard(app) installContextMenu(app, () => contextMenuLabels(getUiLang())) configurePdfRuntime({ @@ -1465,6 +1468,7 @@ export function startPdfStandalone(): void { createDocument: createStandaloneDocument, }) void app.whenReady().then(() => { + installRendererProtocol({ pdf: join(__dirname, '../renderer') }) registerPdfIpc() const win = new BrowserWindow({ width: 1200, @@ -1478,8 +1482,7 @@ export function startPdfStandalone(): void { }) const argPath = process.argv.slice(1).find((a) => /\.pdf$/i.test(a) && existsSync(a)) grantAndTrack(win.webContents, argPath) - if (runtime.rendererUrl) void win.loadURL(runtime.rendererUrl) - else if (runtime.rendererFile) void win.loadFile(runtime.rendererFile) + void win.loadURL(rendererUrl(runtime.rendererUrl, 'pdf')) }) app.on('window-all-closed', () => app.quit()) } diff --git a/apps/pdf/src/renderer/App.tsx b/apps/pdf/src/renderer/App.tsx index 3cdecf3..4235aea 100644 --- a/apps/pdf/src/renderer/App.tsx +++ b/apps/pdf/src/renderer/App.tsx @@ -4864,9 +4864,11 @@ export default function App() { void cropPagesOnDisk(pages, crop) } + // currentPage only tracks scroll, so it can outlive a page deletion + const printCurrentPage = Math.max(1, Math.min(currentPage, pageCount)) const openPrintDlg = () => { setPrintMode('all') - setPrintInput(String(currentPage)) + setPrintInput(String(printCurrentPage)) setPrintInvalid(false) setPrintDlg(true) } @@ -4911,7 +4913,7 @@ export default function App() { } if (printMode === 'current') { setPrintDlg(false) - void printDoc([currentPage]) + void printDoc([printCurrentPage]) return } const pages = parsePageRanges(printInput, pageCount) @@ -5382,7 +5384,7 @@ export default function App() { openSearch() } else if (k === 'p' && !e.shiftKey) { e.preventDefault() - void printDoc() + openPrintDlg() } else if (e.key === '=' || e.key === '+') { e.preventDefault() zoomIn() @@ -8405,7 +8407,7 @@ export default function App() { onChange={() => setPrintMode('current')} /> - {t('printRangeCurrent')} ({currentPage}) + {t('printRangeCurrent')} ({printCurrentPage})
    @@ -3042,7 +3045,9 @@ function Ribbon({ } options={[ { value: 'row-height-open', label: `${t('appRowHeight')}…` }, + { value: 'autofit-row-height', label: t('appAutoFitRowHeight') }, { value: 'col-width-open', label: `${t('appColWidth')}…` }, + { value: 'autofit-col-width', label: t('appAutoFitColWidth') }, ]} onPick={(value) => onCommand(value)} /> @@ -3052,6 +3057,37 @@ function Ribbon({
    + + {t('appAutoSum')} + + } + options={autoSumOptions(t)} + onPick={(value) => onCommand(`autofn:${value}`)} + /> + + {t('appGroupSortFilter')} + + } + options={[ + { value: 'sort:asc', label: t('appSortAToZ') }, + { value: 'sort:desc', label: t('appSortZToA') }, + { value: 'sort-custom-open', label: t('appCustomSort') }, + { value: 'filter-toggle', label: t('appFilter') }, + { value: 'filter-clear', label: t('appClearFilterTitle') }, + { value: 'filter-reapply', label: t('appReapplyTitle') }, + ]} + onPick={(value) => onCommand(value)} + /> string): { value: string; label: string }[] { + return [ + { value: 'SUM', label: t('appFnSum') }, + { value: 'AVERAGE', label: t('appFnAverage') }, + { value: 'COUNT', label: t('appFnCountNumbers') }, + { value: 'MAX', label: t('appFnMax') }, + { value: 'MIN', label: t('appFnMin') }, + ] +} + /// Escape-to-close for the ribbon dropdowns; outside-press / blur / shell /// chrome-press dismissal lives in the shared useDismissablePopover. function useEscapeClose(open: boolean, close: () => void): void { diff --git a/apps/sheets/src/renderer/InsertFunctionDialog.tsx b/apps/sheets/src/renderer/InsertFunctionDialog.tsx index 0476b1d..11f0512 100644 --- a/apps/sheets/src/renderer/InsertFunctionDialog.tsx +++ b/apps/sheets/src/renderer/InsertFunctionDialog.tsx @@ -1,21 +1,29 @@ +import type { IFunctionInfo } from '@univerjs/engine-formula' import { useMemo, useState } from 'react' import { Dropdown } from '@genoffice/ui' +import { + buildFunctionCatalog, + FUNCTION_CATEGORIES, + type FunctionCategory, + type FunctionSpec, +} from './function-catalog' import { useI18n, type StringKey } from './i18n/locale' -/// Excel's Insert Function, minimal: browse/search the catalog, read the -/// syntax, finish the formula in the dialog, apply to the active cell. +/// Excel's Insert Function: browse/search the engine's function catalog, +/// read the syntax, finish the formula in the dialog, apply to the active cell. -interface FunctionSpec { +interface FallbackSpec { readonly name: string - /// Stable English id; displayed through CATEGORY_LABELS. - readonly category: string + readonly category: FunctionCategory readonly syntax: string readonly descKey: StringKey } -const FUNCTION_CATALOG: readonly FunctionSpec[] = [ +/// Functions the engine may implement without describing (the app's own +/// executors); only names missing from the live registry are used. +const FALLBACK_CATALOG: readonly FallbackSpec[] = [ { name: 'SUM', category: 'Math', syntax: 'SUM(number1, [number2], …)', descKey: 'dlgFnDescSum' }, { name: 'SUMIF', @@ -284,27 +292,36 @@ const FUNCTION_CATALOG: readonly FunctionSpec[] = [ { name: 'IRR', category: 'Financial', syntax: 'IRR(values, [guess])', descKey: 'dlgFnDescIrr' }, ] -const CATEGORIES = ['All', ...new Set(FUNCTION_CATALOG.map((spec) => spec.category))] - -const CATEGORY_LABELS: Record = { +const CATEGORY_LABELS: Record<'All' | FunctionCategory, StringKey> = { All: 'dlgFnCatAll', + Financial: 'dlgFnCatFinancial', + 'Date & Time': 'dlgFnCatDateTime', Math: 'dlgFnCatMath', Statistical: 'dlgFnCatStatistical', - Logical: 'dlgFnCatLogical', Lookup: 'dlgFnCatLookup', + Database: 'dlgFnCatDatabase', Text: 'dlgFnCatText', - 'Date & Time': 'dlgFnCatDateTime', - Financial: 'dlgFnCatFinancial', + Logical: 'dlgFnCatLogical', + Information: 'dlgFnCatInformation', + Engineering: 'dlgFnCatEngineering', + Cube: 'dlgFnCatCube', + Compatibility: 'dlgFnCatCompatibility', + Web: 'dlgFnCatWeb', + Array: 'dlgFnCatArray', + Other: 'dlgFnCatOther', } export function InsertFunctionDialog({ targetLabel, + functions, onApply, onClose, initialCategory, }: { /// A1 label of the destination cell, for the dialog header. readonly targetLabel: string + /// Descriptions from the running formula engine (already localized). + readonly functions: readonly IFunctionInfo[] /// Returns an error message, or null on success. readonly onApply: (formula: string) => string | null readonly onClose: () => void @@ -312,9 +329,24 @@ export function InsertFunctionDialog({ readonly initialCategory?: string }): React.JSX.Element { const { t, lang } = useI18n() + const catalog = useMemo( + () => + buildFunctionCatalog( + functions, + FALLBACK_CATALOG.map((spec) => { + const description = t(spec.descKey) + return { ...spec, abstract: description, description } + }), + ), + [functions, lang], + ) + const categories = useMemo(() => { + const present = new Set(catalog.map((spec) => spec.category)) + return ['All', ...FUNCTION_CATEGORIES.filter((name) => present.has(name))] + }, [catalog]) const [query, setQuery] = useState('') const [category, setCategory] = useState( - initialCategory && CATEGORIES.includes(initialCategory) ? initialCategory : 'All', + initialCategory && categories.includes(initialCategory) ? initialCategory : 'All', ) const [picked, setPicked] = useState(null) const [formula, setFormula] = useState('') @@ -322,14 +354,14 @@ export function InsertFunctionDialog({ const matches = useMemo(() => { const needle = query.trim().toUpperCase() - return FUNCTION_CATALOG.filter( + return catalog.filter( (spec) => (category === 'All' || spec.category === category) && (needle === '' || spec.name.includes(needle) || - t(spec.descKey).toUpperCase().includes(needle)), + spec.abstract.toUpperCase().includes(needle)), ) - }, [query, category, lang]) + }, [catalog, query, category]) const pick = (spec: FunctionSpec): void => { setPicked(spec) @@ -355,9 +387,9 @@ export function InsertFunctionDialog({ /> ({ + options={categories.map((name) => ({ value: name, - label: CATEGORY_LABELS[name] ? t(CATEGORY_LABELS[name]) : name, + label: t(CATEGORY_LABELS[name as 'All' | FunctionCategory]), }))} onPick={setCategory} /> @@ -372,7 +404,7 @@ export function InsertFunctionDialog({ onClick={() => pick(spec)} > {spec.name} - {t(spec.descKey)} + {spec.abstract} ))} {matches.length === 0 &&

    {t('dlgFnNoMatch')}

    } @@ -380,6 +412,7 @@ export function InsertFunctionDialog({ {picked && (

    {picked.syntax} + {picked.description !== picked.abstract && {picked.description}}

    )}
    +
    +هل يمكنني تشغيل GenOffice من Claude Code أو Codex أو Cursor أو من سكربت؟ + +نعم. يثبّت GenOffice سطر أوامر `genoffice` يشغّل المحرّكات نفسها دون واجهة +رسومية: افحص المستندات وحوّلها وأنشئها واقرأها وحرّرها من الطرفية أو من +سكربت، مع مخرجات `--json` للبرامج. وتعلّم مهارة الوكيل المرفقة Claude Code +وCodex وCursor وGemini CLI وGitHub Copilot وOpenCode وWindsurf استخدامه؛ ثبّتها +من **الإعدادات → التكاملات**. راجع +[سطر الأوامر ومهارة الوكيل](#command-line-and-agent-skill). + +
    +
    هل يجمع GenOffice أي بيانات؟ diff --git a/docs/i18n/README.cs.md b/docs/i18n/README.cs.md index 1b5c328..9df19e2 100644 --- a/docs/i18n/README.cs.md +++ b/docs/i18n/README.cs.md @@ -23,6 +23,7 @@ Soubory Word, Excel, PowerPoint a PDF, upravované vámi a vaší AI, ukládané

    Stažení · + CLI · Web · Komunita · Soukromí @@ -49,6 +50,11 @@ provede požadovanou úpravu a přesně vám ukáže, čeho se dotkl. nebo použijte vlastní klíč pro Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty nebo jakýkoli OpenAI kompatibilní endpoint, včetně lokálních serverů. +- **Skriptovatelný a připravený pro agenty.** Aplikace obsahuje příkazový + řádek `genoffice` a skill pro Claude Code, Codex, Cursor, Gemini CLI, + GitHub Copilot, OpenCode a Windsurf, takže kódovací agent může na vašem + počítači vytvářet, převádět, číst a upravovat skutečné soubory Office, aniž + by otevřel jediné okno. **Stáhnout:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon a Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 a Arm) · @@ -57,8 +63,9 @@ podrobnosti a požadavky najdete v sekci [Stažení](#download). ## Ukázka -Šest aplikací, jeden AI panel. Každý snímek obrazovky je ze skutečné -aplikace na macOS, s AI ovládanou promptem, který si můžete přečíst v panelu. +Šest aplikací, jeden AI panel a příkazový řádek pro vašeho kódovacího agenta. +Každý snímek obrazovky je ze skutečné aplikace na macOS, s AI ovládanou +promptem, který si můžete přečíst v panelu. ### 1 · Docs — otevírejte a upravujte `.docx` s AI, kterou lze zkontrolovat @@ -156,6 +163,26 @@ podle těchto tokenů vytvoří jeden samostatný soubor `.html`. +### 7 · CLI — váš kódovací agent řídí GenOffice, na vašem počítači + +GenOffice obsahuje příkazový řádek `genoffice` a agentní skill. Nainstalujte +skill a Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode nebo +Windsurf mohou vytvářet, převádět, číst a upravovat skutečné soubory Office +přes stejné enginy jako aplikace, aniž by otevřely jediné okno. + +GenOffice Slides zobrazuje osmisnímkovou prezentaci o sluneční soustavě, kterou kódovací agent vytvořil přes příkazový řádek genoffice: titulní snímek na ploše, osm miniatur vlevo a otevřený AI panel + + + + + + + + + + +
    Osm vykreslených snímků prezentace o sluneční soustavě vedle sebe: titul, časová osa průzkumu, čtyři klíčová čísla, sloupcový graf průměrů planet, kamenné světy versus obři, 99,8 % Slunce jako hlavní číslo, mřížka čtyř obrů a závěryNastavení GenOffice, stránka Integrace: skill genoffice nainstalovaný do Claude Code, s tlačítky Instalovat u položek Codex a Cursor
    Jeden prompt vašemu agentovi — „Vytvoř osmisnímkovou prezentaci o sluneční soustavě.“ Agent si přečte skill, napíše stylový list, osnovu a jednu specifikaci stránky na snímek, vygeneruje obě fotografie pomocí genoffice image a nechá genoffice slides check odmítnout vše, co přetéká nebo se překrývá, než genoffice create sestaví soubor .pptx a slides render vrátí ke kontrole jeden PNG na snímek.Nainstalujte jednou, v Nastavení → Integrace — GenOffice vypíše kódovací agenty, které na tomto počítači najde, a zapíše skill do každého, který vyberete. Nebo si skill stáhněte jako zip, případně spusťte npx skills add genspark-ai/genoffice. Příkazy a celý pracovní postup najdete v sekci Příkazový řádek a agentní skill.
    + ## Proč GenOffice - **Open source**, Apache-2.0, vyvíjený otevřeně na GitHubu. @@ -174,6 +201,9 @@ podle těchto tokenů vytvoří jeden samostatný soubor `.html`. - **PDF udělané správně.** Upravujte text přímo na stránce a převádějte PDF do Word, Excel nebo PowerPoint na zařízení, se systémovým OCR pro skeny. - **Také Markdown a HTML**, se stejným panelem AI a místním exportem do Word. +- **Skriptovatelný.** Příkazový řádek `genoffice` a agentní skill dávají + každý engine do služeb agentů Claude Code, Codex, Cursor a dalších, stále + na zařízení. - **Zdarma**, pro jednotlivce i týmy. ## AI backendy @@ -196,6 +226,76 @@ Celý balík nabízí světlý, tmavý a systémový vzhled. Vzhledy mění pouz co je vidět na obrazovce: exporty, tisky a uložené soubory si vždy zachovávají vlastní barvy dokumentu. + + +## Příkazový řádek a agentní skill + +Vše, co aplikace umí se souborem, umí příkazový řádek `genoffice` +z terminálu: prohlížet, převádět, vytvářet, číst a upravovat Word, Excel, +PowerPoint, PDF, Markdown a HTML na stejných enginech, bez grafického +rozhraní. Instaluje se spolu s GenOffice, nepotřebuje vlastní runtime +a nikdy žádný dokument nikam neodesílá. Ve spojení s přibaleným **agentním +skillem** promění kódovacího agenta v dokumentového pracovníka, který +vytváří skutečné soubory Office místo přibližných napodobenin v Markdownu. + +**Funguje s:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode a Windsurf hned po instalaci a s jakýmkoli dalším agentem, který +čte skilly. + +### Instalace skillu + +| Jak | Co se stane | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Nastavení → Integrace** v aplikaci | Vypíše agenty nalezené na tomto počítači; jedním kliknutím zapíše skill do každého, který vyberete. Když nové vydání GenOffice přinese novější skill, objeví se tlačítko **Aktualizovat**. | +| **Stáhnout jako zip** na téže stránce | Rozložení, které claude.ai, desktopové aplikace Claude a další asistenti přijímají jako nahraný skill. | +| `npx skills add genspark-ai/genoffice` | Nainstaluje z tohoto repozitáře do jakéhokoli agenta podporujícího skilly. | + +Pak začněte nový chat a požádejte o dokument. Skill agenta naučí, kdy sáhnout +po `genoffice`, jak si soubor přečíst před úpravou a jak zkontrolovat vlastní +práci. + +### Rychlý start z terminálu + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Každý příkaz vypíše jednořádkové shrnutí, nebo s `--json` jediný objekt JSON. +Úpravy jsou atomické: odmítnutá operace nechá soubor nedotčený a vrátí se +s návodnou chybovou hláškou. `genoffice help` vypíše aktuální sadu příkazů; +úplná reference je v [packages/cli/README.md](../../packages/cli/README.md). + +### Co agent ve skutečnosti spouští + +Prezentace o sluneční soustavě v ukázce výše vznikla z jediného promptu +v Claude Code. Agent za ní postupoval podle fázovaného pracovního postupu ze +skillu a CLI zkontrolovalo každou fázi, než začala další: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Uvnitř `genoffice` neprobíhá žádné volání modelu: agent přemýšlí, CLI staví +a kontroluje a výsledek se otevře v GenOffice nebo PowerPointu jako obyčejný +soubor `.pptx`. + ## Stažení @@ -362,6 +462,19 @@ obrázky.

    +
    +Můžu GenOffice ovládat z nástrojů Claude Code, Codex, Cursor nebo ze skriptu? + +Ano. GenOffice nainstaluje příkazový řádek `genoffice`, který spouští stejné +enginy bez grafického rozhraní: prohlížejte, převádějte, vytvářejte, čtěte +a upravujte dokumenty z terminálu nebo ze skriptu, s výstupem `--json` pro +programy. Přibalený agentní skill naučí Claude Code, Codex, Cursor, Gemini +CLI, GitHub Copilot, OpenCode a Windsurf, jak ho používat; nainstalujte ho +v **Nastavení → Integrace**. Viz +[Příkazový řádek a agentní skill](#command-line-and-agent-skill). + +
    +
    Sbírá GenOffice nějaká data? diff --git a/docs/i18n/README.de.md b/docs/i18n/README.de.md index 80bda01..9f0c4d8 100644 --- a/docs/i18n/README.de.md +++ b/docs/i18n/README.de.md @@ -23,6 +23,7 @@ Word-, Excel-, PowerPoint- und PDF-Dateien, bearbeitet von dir und deiner KI, ge

    Download · + CLI · Website · Community · Datenschutz @@ -52,6 +53,11 @@ er verändert hat. Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty oder jeden OpenAI-kompatiblen Endpunkt mit – auch lokale Server werden unterstützt. +- **Skriptbar und bereit für Agenten.** Die App bringt eine + `genoffice`-Befehlszeile und einen Skill für Claude Code, Codex, Cursor, + Gemini CLI, GitHub Copilot, OpenCode und Windsurf mit, sodass ein + Coding-Agent echte Office-Dateien auf deinem Rechner erstellen, + konvertieren, lesen und bearbeiten kann, ohne ein Fenster zu öffnen. **Los geht's:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon und Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 und Arm) · @@ -60,9 +66,9 @@ Details und Voraussetzungen unter [Download](#download). ## Demo -Sechs Apps, ein KI-Panel. Jeder Screenshot zeigt die echte App auf macOS, -wobei die KI durch den Prompt gesteuert wird, den du im Panel nachlesen -kannst. +Sechs Apps, ein KI-Panel und eine Befehlszeile für deinen Coding-Agenten. +Jeder Screenshot zeigt die echte App auf macOS, wobei die KI durch den +Prompt gesteuert wird, den du im Panel nachlesen kannst. ### 1 · Docs – `.docx` öffnen und bearbeiten mit einer KI, die du überprüfen kannst @@ -161,6 +167,27 @@ nach diesen Vorgaben. +### 7 · CLI – dein Coding-Agent steuert GenOffice, auf deinem Rechner + +GenOffice bringt eine `genoffice`-Befehlszeile und einen Agent-Skill mit. +Installiere den Skill, und Claude Code, Codex, Cursor, Gemini CLI, GitHub +Copilot, OpenCode oder Windsurf können echte Office-Dateien über dieselben +Engines wie die Apps erstellen, konvertieren, lesen und bearbeiten, ohne ein +Fenster zu öffnen. + +GenOffice Slides zeigt eine Sonnensystem-Präsentation mit acht Folien, die ein Coding-Agent über die genoffice-Befehlszeile erstellt hat: die Titelfolie auf der Arbeitsfläche, acht Miniaturansichten links und das geöffnete KI-Panel + + + + + + + + + + +
    Die acht gerenderten Folien der Sonnensystem-Präsentation nebeneinander: Titel, Zeitleiste der Erforschung, vier Kennzahlen, Balkendiagramm der Planetendurchmesser, Gesteinsplaneten gegen Riesen, die 99,8 % der Sonne als Hero-Zahl, das Raster der vier Riesen und die KernaussagenGenOffice-Einstellungen, Seite Integrationen: der genoffice-Skill ist in Claude Code installiert, mit Installieren-Schaltflächen neben Codex und Cursor
    Ein Prompt an deinen Agenten — „Erstelle eine Präsentation mit acht Folien über das Sonnensystem.“ Der Agent liest den Skill, schreibt ein Stylesheet, eine Gliederung und eine Seitenspezifikation pro Folie, generiert die beiden Fotos mit genoffice image und lässt genoffice slides check alles zurückweisen, was überläuft oder sich überlappt, bevor genoffice create die .pptx zusammensetzt und slides render pro Folie ein PNG zum Anschauen zurückgibt.Einmal installieren, unter Einstellungen → Integrationen — GenOffice listet die Coding-Agenten auf, die es auf diesem Rechner findet, und schreibt den Skill in jeden, den du auswählst. Oder lade den Skill als Zip herunter oder führe npx skills add genspark-ai/genoffice aus. Befehle und der vollständige Workflow stehen unter Befehlszeile und Agent-Skill.
    + ## Warum GenOffice - **Open Source**, Apache-2.0, offen entwickelt auf GitHub. @@ -180,6 +207,9 @@ nach diesen Vorgaben. in Word, Excel oder PowerPoint konvertieren, mit System-OCR für Scans. - **Auch Markdown und HTML**, mit demselben KI-Panel und lokalem Export nach Word. +- **Skriptbar.** Eine `genoffice`-Befehlszeile und ein Agent-Skill stellen + jede Engine in den Dienst von Claude Code, Codex, Cursor und anderen + Coding-Agenten – weiterhin auf dem Gerät. - **Kostenlos**, für Einzelpersonen wie für Teams. ## KI-Backends @@ -203,6 +233,79 @@ Systemdesign-Modus mit. Designs ändern nur, was auf dem Bildschirm zu sehen ist: Exporte, Ausdrucke und gespeicherte Dateien behalten immer die eigenen Farben des Dokuments. + + +## Befehlszeile und Agent-Skill + +Alles, was die Apps mit einer Datei tun können, kann die +`genoffice`-Befehlszeile aus einem Terminal heraus: Word, Excel, PowerPoint, +PDF, Markdown und HTML inspizieren, konvertieren, erstellen, lesen und +bearbeiten – auf denselben Engines, ohne Fenster. Sie wird mit GenOffice +installiert, braucht keine eigene Laufzeitumgebung und schickt nie ein +Dokument irgendwohin. Zusammen mit dem mitgelieferten **Agent-Skill** macht +sie aus einem Coding-Agenten einen Dokumentenarbeiter, der echte +Office-Dateien statt Markdown-Näherungen liefert. + +**Funktioniert mit:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode und Windsurf von Haus aus sowie mit jedem anderen Agenten, der +Skills liest. + +### Skill installieren + +| Wie | Was passiert | +| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Einstellungen → Integrationen** in der App | Listet die auf diesem Rechner gefundenen Agenten auf; ein Klick schreibt den Skill in jeden, den du auswählst. Eine **Aktualisieren**-Schaltfläche erscheint, wenn eine GenOffice-Version einen neueren Skill mitbringt. | +| **Als Zip herunterladen** auf derselben Seite | Das Layout, das claude.ai, die Claude-Desktop-Apps und andere Assistenten als hochgeladenen Skill akzeptieren. | +| `npx skills add genspark-ai/genoffice` | Installiert aus diesem Repository in jeden Skills-kompatiblen Agenten. | + +Starte dann einen neuen Chat und bitte um ein Dokument. Der Skill bringt dem +Agenten bei, wann er zu `genoffice` greifen soll, wie er eine Datei vor dem +Bearbeiten liest und wie er seine eigene Arbeit prüft. + +### Schnellstart im Terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Jeder Befehl gibt eine einzeilige Zusammenfassung aus, oder mit `--json` ein +einzelnes JSON-Objekt. Bearbeitungen sind atomar: Eine zurückgewiesene +Operation lässt die Datei unangetastet und kommt mit einer erklärenden +Fehlermeldung zurück. `genoffice help` listet die aktuellen Befehle auf; die +vollständige Referenz steht in +[packages/cli/README.md](../../packages/cli/README.md). + +### Was der Agent tatsächlich ausführt + +Die Sonnensystem-Präsentation in der Demo oben brauchte einen einzigen Prompt +in Claude Code. Dahinter folgte der Agent dem gestuften Workflow des Skills, +und die CLI prüfte jede Stufe, bevor die nächste begann: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Innerhalb von `genoffice` findet kein Modellaufruf statt: Der Agent denkt, +die CLI baut und prüft, und das Ergebnis öffnet sich in GenOffice oder +PowerPoint als gewöhnliche `.pptx`. + ## Download @@ -376,6 +479,19 @@ Boxen) werden als Bilder eingebettet.

    +
    +Kann ich GenOffice aus Claude Code, Codex, Cursor oder einem Skript steuern? + +Ja. GenOffice installiert eine `genoffice`-Befehlszeile, die dieselben +Engines ohne Fenster ausführt: Dokumente aus einem Terminal oder einem Skript +inspizieren, konvertieren, erstellen, lesen und bearbeiten, mit +`--json`-Ausgabe für Programme. Der mitgelieferte Agent-Skill bringt Claude +Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode und Windsurf bei, +sie zu nutzen; installiere ihn unter **Einstellungen → Integrationen**. Siehe +[Befehlszeile und Agent-Skill](#command-line-and-agent-skill). + +
    +
    Erfasst GenOffice irgendwelche Daten? diff --git a/docs/i18n/README.es.md b/docs/i18n/README.es.md index 1e8147a..df0a42d 100644 --- a/docs/i18n/README.es.md +++ b/docs/i18n/README.es.md @@ -23,6 +23,7 @@ Archivos Word, Excel, PowerPoint y PDF, editados por ti y tu IA, guardados de nu

    Descargar · + CLI · Sitio web · Comunidad · Privacidad @@ -49,6 +50,11 @@ hace el cambio y te muestra exactamente qué tocó. claves, o usa tu propia clave para Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty, o cualquier endpoint compatible con OpenAI, servidores locales incluidos. +- **Automatizable y listo para agentes.** La app incluye una línea de comandos + `genoffice` y un skill para Claude Code, Codex, Cursor, Gemini CLI, GitHub + Copilot, OpenCode y Windsurf, de modo que un agente de programación puede + crear, convertir, leer y editar archivos Office reales en tu equipo sin + abrir una ventana. **Consíguelo:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon e Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 y Arm) · @@ -57,8 +63,9 @@ detalles y requisitos en [Download](#download). ## Demo -Seis apps, un solo panel de IA. Cada captura es la app real en macOS, con la -IA impulsada por el prompt que puedes leer en el panel. +Seis apps, un solo panel de IA y una línea de comandos para tu agente de +programación. Cada captura es la app real en macOS, con la IA impulsada por +el prompt que puedes leer en el panel. ### 1 · Docs — abre y edita `.docx` con una IA que puedes revisar @@ -157,6 +164,26 @@ siguiendo esos tokens. +### 7 · CLI — tu agente de programación maneja GenOffice, en tu equipo + +GenOffice incluye una línea de comandos `genoffice` y un skill de agente. +Instala el skill y Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode o Windsurf podrán crear, convertir, leer y editar archivos Office +reales con los mismos motores que las apps, sin abrir una ventana. + +GenOffice Slides mostrando una presentación de ocho diapositivas sobre el Sistema Solar que un agente de programación construyó mediante la línea de comandos genoffice: la diapositiva de portada en el lienzo, ocho miniaturas a la izquierda y el panel de IA abierto + + + + + + + + + + +
    Las ocho diapositivas renderizadas de la presentación del Sistema Solar, una junto a otra: portada, cronología de la exploración, cuatro cifras clave, gráfico de barras con el diámetro de los planetas, mundos rocosos frente a gigantes, la cifra destacada del 99,8 % del Sol, la cuadrícula de los cuatro gigantes y las conclusionesAjustes de GenOffice, página Integraciones: el skill genoffice instalado en Claude Code, con botones Instalar junto a Codex y Cursor
    Un solo prompt a tu agente — «Crea una presentación de ocho diapositivas sobre el Sistema Solar». El agente lee el skill, escribe una hoja de estilos, un esquema y una especificación de página por diapositiva, genera las dos fotos con genoffice image y deja que genoffice slides check rechace todo lo que desborde o se superponga antes de que genoffice create ensamble el .pptx y slides render devuelva un PNG por diapositiva para revisarlo.Instálalo una vez, desde Ajustes → Integraciones — GenOffice muestra los agentes de programación que encuentra en este equipo y escribe el skill en cada uno de los que elijas. O descarga el skill como zip, o ejecuta npx skills add genspark-ai/genoffice. Los comandos y el flujo de trabajo completo están en Línea de comandos y skill de agente.
    + ## Por qué GenOffice - **Código abierto**, Apache-2.0, desarrollado abiertamente en GitHub. @@ -178,6 +205,9 @@ siguiendo esos tokens. sistema para escaneos. - **También Markdown y HTML**, con el mismo panel de IA y exportación local a Word. +- **Automatizable.** Una línea de comandos `genoffice` y un skill de agente + ponen todos los motores al servicio de Claude Code, Codex, Cursor y otros + agentes de programación, siempre en el dispositivo. - **Gratis**, tanto para personas individuales como para equipos. ## Backends de IA @@ -201,6 +231,78 @@ Toda la suite incluye temas claro, oscuro y del sistema. Los temas solo cambian lo que se ve en pantalla: las exportaciones, las impresiones y los archivos guardados siempre conservan los colores propios del documento. + + +## Línea de comandos y skill de agente + +Todo lo que las apps pueden hacer con un archivo, la línea de comandos +`genoffice` puede hacerlo desde una terminal: inspeccionar, convertir, crear, +leer y editar Word, Excel, PowerPoint, PDF, Markdown y HTML con los mismos +motores, sin interfaz gráfica. Se instala con GenOffice, no necesita ningún +runtime propio y nunca envía un documento a ninguna parte. Junto con el +**skill de agente** incluido, convierte a un agente de programación en un +trabajador documental que produce archivos Office reales en lugar de +aproximaciones en Markdown. + +**Funciona con:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode y Windsurf de forma nativa, y con cualquier otro agente que lea +skills. + +### Instalar el skill + +| Cómo | Qué ocurre | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Ajustes → Integraciones** en la app | Muestra los agentes encontrados en este equipo; con un clic escribe el skill en cada uno de los que elijas. Aparece un botón **Actualizar** cuando una versión de GenOffice trae un skill más reciente. | +| **Descargar como zip** en la misma página | El formato que claude.ai, las apps de escritorio de Claude y otros asistentes aceptan como skill subido. | +| `npx skills add genspark-ai/genoffice` | Lo instala desde este repositorio en cualquier agente compatible con skills. | + +Después abre un chat nuevo y pide un documento. El skill enseña al agente +cuándo recurrir a `genoffice`, cómo leer un archivo antes de editarlo y cómo +comprobar su propio trabajo. + +### Inicio rápido desde la terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Cada comando imprime un resumen de una línea, o un único objeto JSON con +`--json`. Las ediciones son atómicas: una operación rechazada deja el archivo +intacto y devuelve un error con indicaciones. `genoffice help` muestra la +lista actual de comandos; la referencia completa está en +[packages/cli/README.md](../../packages/cli/README.md). + +### Lo que el agente ejecuta realmente + +La presentación del Sistema Solar de la demo de arriba llevó un solo prompt +en Claude Code. Por detrás, el agente siguió el flujo de trabajo por etapas +del skill y la CLI comprobó cada etapa antes de iniciar la siguiente: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Dentro de `genoffice` no se hace ninguna llamada a un modelo: el agente +piensa, la CLI construye y comprueba, y el resultado se abre en GenOffice o +en PowerPoint como un `.pptx` normal. + ## Descargar @@ -375,6 +477,19 @@ iconos, cajas decoradas) se incrustan como imágenes.

    +
    +¿Puedo manejar GenOffice desde Claude Code, Codex, Cursor o un script? + +Sí. GenOffice instala una línea de comandos `genoffice` que ejecuta los mismos +motores sin interfaz gráfica: inspecciona, convierte, crea, lee y edita +documentos desde una terminal o un script, con salida `--json` para +programas. El skill de agente incluido enseña a Claude Code, Codex, Cursor, +Gemini CLI, GitHub Copilot, OpenCode y Windsurf a usarla; instálalo desde +**Ajustes → Integraciones**. Consulta +[Línea de comandos y skill de agente](#command-line-and-agent-skill). + +
    +
    ¿GenOffice recopila algún dato? diff --git a/docs/i18n/README.fr.md b/docs/i18n/README.fr.md index c27ef05..80ca4aa 100644 --- a/docs/i18n/README.fr.md +++ b/docs/i18n/README.fr.md @@ -23,6 +23,7 @@ Fichiers Word, Excel, PowerPoint et PDF, modifiés par vous et votre IA, enregis

    Télécharger · + CLI · Site web · Communauté · Confidentialité @@ -52,6 +53,11 @@ modification, et vous montre exactement ce qu'il a touché. clé, ou utilisez votre propre clé pour Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty, ou tout point de terminaison compatible OpenAI, y compris les serveurs locaux. +- **Scriptable et prêt pour les agents.** L'application embarque une ligne de + commande `genoffice` et un skill pour Claude Code, Codex, Cursor, Gemini + CLI, GitHub Copilot, OpenCode et Windsurf, si bien qu'un agent de codage + peut créer, convertir, lire et modifier de vrais fichiers Office sur votre + machine sans ouvrir de fenêtre. **À télécharger :** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon et Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 et Arm) · @@ -60,9 +66,9 @@ détails et prérequis dans la section [Télécharger](#download). ## Démonstration -Six applications, un seul panneau IA. Chaque capture d'écran montre -l'application réelle sur macOS, avec l'IA pilotée par le prompt que vous -pouvez lire dans le panneau. +Six applications, un seul panneau IA, et une ligne de commande pour votre +agent de codage. Chaque capture d'écran montre l'application réelle sur +macOS, avec l'IA pilotée par le prompt que vous pouvez lire dans le panneau. ### 1 · Docs — ouvrez et modifiez des `.docx` avec une IA que vous pouvez vérifier @@ -161,6 +167,27 @@ jetons. +### 7 · CLI — votre agent de codage pilote GenOffice, sur votre machine + +GenOffice embarque une ligne de commande `genoffice` et un skill d'agent. +Installez le skill et Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode ou Windsurf peuvent créer, convertir, lire et modifier de vrais +fichiers Office via les mêmes moteurs que les applications, sans ouvrir de +fenêtre. + +GenOffice Slides affichant un deck de huit diapositives sur le Système solaire qu'un agent de codage a construit via la ligne de commande genoffice : la diapositive de couverture sur le canevas, huit miniatures à gauche et le panneau IA ouvert + + + + + + + + + + +
    Les huit diapositives rendues du deck Système solaire côte à côte : couverture, chronologie de l'exploration, quatre chiffres clés, graphique en barres des diamètres planétaires, mondes rocheux contre géantes, le chiffre phare des 99,8 % du Soleil, la grille des quatre géantes et les points à retenirGenOffice, page Réglages → Intégrations : le skill genoffice installé dans Claude Code, avec des boutons Installer à côté de Codex et Cursor
    Un seul prompt à votre agent — « Construis un deck de huit diapositives sur le Système solaire. » L'agent lit le skill, écrit une feuille de style, un plan et une spécification de page par diapositive, génère les deux photos avec genoffice image, et laisse genoffice slides check rejeter tout ce qui déborde ou se chevauche avant que genoffice create n'assemble le .pptx et que slides render ne renvoie un PNG par diapositive à examiner.Installez une fois, depuis Réglages → Intégrations — GenOffice liste les agents de codage qu'il trouve sur cet ordinateur et écrit le skill dans chacun de ceux que vous choisissez. Ou téléchargez le skill en zip, ou lancez npx skills add genspark-ai/genoffice. Les commandes et le flux de travail complet sont dans Ligne de commande et skill d'agent.
    + ## Pourquoi GenOffice - **Open source**, licence Apache-2.0, développé au grand jour sur GitHub. @@ -182,6 +209,9 @@ jetons. système pour les scans. - **Markdown et HTML aussi**, avec le même panneau IA et un export local vers Word. +- **Scriptable.** Une ligne de commande `genoffice` et un skill d'agent + mettent chaque moteur au service de Claude Code, Codex, Cursor et des + autres agents de codage, toujours en local. - **Gratuit**, pour les particuliers comme pour les équipes. ## Moteurs IA @@ -206,6 +236,79 @@ changent que ce qui est affiché à l'écran : les exports, les impressions et les fichiers enregistrés conservent toujours les couleurs propres au document. + + +## Ligne de commande et skill d'agent + +Tout ce que les applications peuvent faire à un fichier, la ligne de commande +`genoffice` peut le faire depuis un terminal : inspecter, convertir, créer, +lire et modifier du Word, de l'Excel, du PowerPoint, du PDF, du Markdown et +du HTML sur les mêmes moteurs, sans interface graphique. Elle s'installe avec +GenOffice, n'a besoin d'aucun runtime propre et n'envoie jamais un document +où que ce soit. Associée au **skill d'agent** fourni, elle transforme un +agent de codage en un ouvrier documentaire qui produit de vrais fichiers +Office plutôt que des approximations en Markdown. + +**Fonctionne avec :** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode et Windsurf dès l'installation, et tout autre agent qui lit des +skills. + +### Installer le skill + +| Comment | Ce qui se passe | +| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Réglages → Intégrations** dans l'application | Liste les agents trouvés sur cet ordinateur ; un clic écrit le skill dans chacun de ceux que vous choisissez. Un bouton **Mettre à jour** apparaît lorsqu'une version de GenOffice embarque un skill plus récent. | +| **Télécharger en zip** sur la même page | Le format que claude.ai, les applications de bureau Claude et d'autres assistants acceptent comme skill téléversé. | +| `npx skills add genspark-ai/genoffice` | Installe depuis ce dépôt dans tout agent compatible avec les skills. | + +Ouvrez ensuite une nouvelle conversation et demandez un document. Le skill +apprend à l'agent quand recourir à `genoffice`, comment lire un fichier avant +de le modifier, et comment vérifier son propre travail. + +### Démarrage rapide depuis le terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Chaque commande affiche un résumé d'une ligne, ou un seul objet JSON avec +`--json`. Les modifications sont atomiques : une opération rejetée laisse le +fichier intact et renvoie une erreur guidée. `genoffice help` liste les +commandes actuellement disponibles ; la référence complète se trouve dans +[packages/cli/README.md](../../packages/cli/README.md). + +### Ce que l'agent exécute réellement + +Le deck Système solaire de la démonstration ci-dessus a demandé un seul +prompt dans Claude Code. En coulisses, l'agent a suivi le flux de travail par +étapes du skill, et la CLI a vérifié chaque étape avant de passer à la +suivante : + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Aucun appel à un modèle n'a lieu dans `genoffice` : l'agent réfléchit, la CLI +construit et vérifie, et le résultat s'ouvre dans GenOffice ou PowerPoint +comme un `.pptx` ordinaire. + ## Télécharger @@ -383,6 +486,19 @@ icônes, encadrés décorés) sont intégrés sous forme d'images.

    +
    +Puis-je piloter GenOffice depuis Claude Code, Codex, Cursor ou un script ? + +Oui. GenOffice installe une ligne de commande `genoffice` qui exécute les +mêmes moteurs sans interface graphique : inspectez, convertissez, créez, +lisez et modifiez des documents depuis un terminal ou un script, avec une +sortie `--json` pour les programmes. Le skill d'agent fourni apprend à +Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode et Windsurf +à l'utiliser ; installez-le depuis **Réglages → Intégrations**. Voir +[Ligne de commande et skill d'agent](#command-line-and-agent-skill). + +
    +
    GenOffice collecte-t-il des données ? diff --git a/docs/i18n/README.he.md b/docs/i18n/README.he.md index 5f53524..06a47c8 100644 --- a/docs/i18n/README.he.md +++ b/docs/i18n/README.he.md @@ -23,6 +23,7 @@

    הורדה · + CLI · אתר · קהילה · פרטיות @@ -48,6 +49,10 @@ Windows ו-Linux. היא פותחת ושומרת קבצי `.docx`,‏ `.xlsx` ו במפתח, או הביאו מפתח משלכם עבור Claude,‏ OpenAI,‏ Gemini,‏ DeepSeek,‏ Kimi,‏ GLM,‏ Qwen,‏ Doubao,‏ MiniMax,‏ Grok,‏ Mistral,‏ OpenRouter,‏ Requesty, או כל endpoint תואם-OpenAI, כולל שרתים מקומיים. +- **ניתן לסקריפטים ומוכן לסוכנים.** האפליקציה מגיעה עם שורת פקודה `genoffice` + ועם skill עבור Claude Code,‏ Codex,‏ Cursor,‏ Gemini CLI,‏ GitHub Copilot,‏ + OpenCode ו-Windsurf, כך שסוכן קוד יכול ליצור, להמיר, לקרוא ולערוך קבצי + Office אמיתיים על המחשב שלכם בלי לפתוח חלון. **להורדה:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) ‏(Apple Silicon ו-Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) ‏(x64 ו-Arm) · @@ -56,8 +61,8 @@ Windows ו-Linux. היא פותחת ושומרת קבצי `.docx`,‏ `.xlsx` ו ## הדגמה -שש אפליקציות, פאנל AI אחד. כל צילום מסך הוא מהאפליקציה האמיתית ב-macOS, עם -ה-AI מופעל מהפרומפט שאפשר לקרוא בפאנל. +שש אפליקציות, פאנל AI אחד, ושורת פקודה לסוכן הקוד שלכם. כל צילום מסך הוא +מהאפליקציה האמיתית ב-macOS, עם ה-AI מופעל מהפרומפט שאפשר לקרוא בפאנל. ### 1 · Docs — פתחו וערכו `.docx` עם AI שאפשר לבדוק @@ -155,6 +160,26 @@ brief) — משפט פתיחה, פלטת צבעים, טיפוגרפיה וכיו +### 7 · CLI — סוכן הקוד שלכם מפעיל את GenOffice, על המחשב שלכם + +GenOffice מגיעה עם שורת פקודה `genoffice` ועם skill לסוכנים. התקינו את +ה-skill, ו-Claude Code,‏ Codex,‏ Cursor,‏ Gemini CLI,‏ GitHub Copilot,‏ OpenCode +או Windsurf יוכלו ליצור, להמיר, לקרוא ולערוך קבצי Office אמיתיים דרך אותם +מנועים שמפעילים את האפליקציות, בלי לפתוח חלון. + +GenOffice Slides מציג מצגת בת שמונה שקופיות על מערכת השמש שסוכן קוד בנה דרך שורת הפקודה genoffice: שקופית השער על הקנבס, שמונה תמונות ממוזערות בצד שמאל ופאנל ה-AI פתוח + + + + + + + + + + +
    שמונה השקופיות המרונדרות של מצגת מערכת השמש זו לצד זו: שער, ציר זמן של החקר, ארבעה מספרים מרכזיים, תרשים עמודות של קוטרי כוכבי הלכת, עולמות סלעיים מול ענקים, המספר הבולט 99.8% של השמש, רשת ארבעת הענקים ומסקנותהגדרות GenOffice, עמוד Integrations: ה-skill של genoffice מותקן ב-Claude Code, עם כפתורי Install ליד Codex ו-Cursor
    פרומפט אחד לסוכן שלכם — ״בנו מצגת בת שמונה שקופיות על מערכת השמש.״ הסוכן קורא את ה-skill, כותב גיליון סטייל, מתווה ומפרט עמוד אחד לכל שקופית, מייצר את שתי התמונות עם genoffice image, ונותן ל-genoffice slides check לדחות כל דבר שגולש או חופף לפני ש-genoffice create מרכיב את ה-.pptx ו-slides render מחזיר PNG לכל שקופית להתרשמות.התקינו פעם אחת, מתוך הגדרות → שילובים — GenOffice מציגה את סוכני הקוד שהיא מוצאת על המחשב הזה וכותבת את ה-skill לכל אחד שתבחרו. או הורידו את ה-skill כ-zip, או הריצו npx skills add genspark-ai/genoffice. הפקודות ותהליך העבודה המלא נמצאים בשורת הפקודה וה-skill לסוכנים.
    + ## למה GenOffice - **קוד פתוח**, ברישיון Apache-2.0, מפותח בפומבי ב-GitHub. @@ -171,6 +196,8 @@ brief) — משפט פתיחה, פלטת צבעים, טיפוגרפיה וכיו - **PDF שמטופל כמו שצריך.** ערכו טקסט ישירות בתוך העמוד, והמירו PDF ל-Word, Excel או PowerPoint במכשיר עצמו, עם OCR מובנה למסמכים סרוקים. - **גם Markdown ו-HTML**, עם אותו פאנל AI וייצוא מקומי ל-Word. +- **ניתן לסקריפטים.** שורת פקודה `genoffice` ו-skill לסוכנים מעמידים כל מנוע + לרשות Claude Code,‏ Codex,‏ Cursor וסוכני קוד אחרים, עדיין על המכשיר. - **חינם**, גם ליחידים וגם לצוותים. ## ספקי ה-AI @@ -191,6 +218,73 @@ OpenRouter,‏ Requesty ו-OpenCode Zen/Go, ובנוסף שדה מותאם אי את מה שמוצג על המסך: קבצים מיוצאים, מודפסים ונשמרים תמיד שומרים על הצבעים המקוריים של המסמך. + + +## שורת הפקודה וה-skill לסוכנים + +כל מה שהאפליקציות יכולות לעשות לקובץ, שורת הפקודה `genoffice` יכולה לעשות +מהטרמינל: לבדוק, להמיר, ליצור, לקרוא ולערוך Word,‏ Excel,‏ PowerPoint,‏ PDF,‏ +Markdown ו-HTML על אותם מנועים, ללא ממשק גרפי. היא מותקנת יחד עם GenOffice, +לא דורשת סביבת הרצה משלה, ולעולם לא שולחת מסמך לשום מקום. יחד עם **ה-skill +לסוכנים** המצורף, היא הופכת סוכן קוד לעובד מסמכים שמייצר קבצי Office אמיתיים +במקום קירובים ב-Markdown. + +**עובד עם:** Claude Code,‏ Codex,‏ Cursor,‏ Gemini CLI,‏ GitHub Copilot,‏ +OpenCode ו-Windsurf ישר מהקופסה, ועם כל סוכן אחר שקורא skills. + +### התקנת ה-skill + +| איך | מה קורה | +| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| **הגדרות → שילובים** באפליקציה | מציג את הסוכנים שנמצאו על המחשב הזה; לחיצה אחת כותבת את ה-skill לכל אחד שתבחרו. כפתור **Update** מופיע כשגרסת GenOffice חדשה מגיעה עם skill מעודכן. | +| **הורדה כ-zip** באותו העמוד | המבנה ש-claude.ai, אפליקציות Claude לדסקטופ ועוזרים אחרים מקבלים כ-skill שהועלה. | +| `npx skills add genspark-ai/genoffice` | מתקין מהמאגר הזה לכל סוכן שתומך ב-skills. | + +לאחר מכן פתחו צ'אט חדש ובקשו מסמך. ה-skill מלמד את הסוכן מתי לפנות +ל-`genoffice`, איך לקרוא קובץ לפני שעורכים אותו, ואיך לבדוק את העבודה של +עצמו. + +### התחלה מהירה מהטרמינל + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +כל פקודה מדפיסה סיכום בשורה אחת, או אובייקט JSON יחיד עם `--json`. השינויים +אטומיים: פעולה שנדחתה משאירה את הקובץ ללא שינוי וחוזרת עם שגיאה מנחה. +`genoffice help` מציג את מערך הפקודות הנוכחי; התיעוד המלא נמצא +ב-[packages/cli/README.md](../../packages/cli/README.md). + +### מה הסוכן מריץ בפועל + +מצגת מערכת השמש בהדגמה למעלה נוצרה מפרומפט אחד ב-Claude Code. מאחורי +הקלעים, הסוכן עקב אחרי תהליך העבודה המדורג של ה-skill, וה-CLI בדק כל שלב +לפני שהשלב הבא התחיל: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +שום קריאה למודל לא מתבצעת בתוך `genoffice`: הסוכן חושב, ה-CLI בונה ובודק, +והתוצאה נפתחת ב-GenOffice או ב-PowerPoint כקובץ `.pptx` רגיל. + ## הורדה @@ -356,6 +450,18 @@ KPI, שדות טופס ורקעי עמוד; רק אלמנטים ויזואליי

    +
    +האם אפשר להפעיל את GenOffice מתוך Claude Code,‏ Codex,‏ Cursor או מסקריפט? + +כן. GenOffice מתקינה שורת פקודה `genoffice` שמריצה את אותם מנועים ללא ממשק +גרפי: בדיקה, המרה, יצירה, קריאה ועריכה של מסמכים מהטרמינל או מסקריפט, עם +פלט `--json` לתוכנות. ה-skill המצורף לסוכנים מלמד את Claude Code,‏ Codex,‏ +Cursor,‏ Gemini CLI,‏ GitHub Copilot,‏ OpenCode ו-Windsurf להשתמש בה; התקינו +אותו מתוך **הגדרות → שילובים**. ראו +[שורת הפקודה וה-skill לסוכנים](#command-line-and-agent-skill). + +
    +
    האם GenOffice אוספת מידע? diff --git a/docs/i18n/README.hi.md b/docs/i18n/README.hi.md index 4105815..2a454a6 100644 --- a/docs/i18n/README.hi.md +++ b/docs/i18n/README.hi.md @@ -23,6 +23,7 @@ Word, Excel, PowerPoint और PDF फ़ाइलें, आपके और

    डाउनलोड · + CLI · वेबसाइट · कम्युनिटी · गोपनीयता @@ -34,6 +35,7 @@ GenOffice, macOS, Windows और Linux के लिए Microsoft Office का - **AI जिसे आप रिव्यू कर सकते हैं।** एडिट्स ट्रैक्ड चेंजेस और डिफ़ के रूप में आते हैं, जिन्हें एक क्लिक में रोलबैक किया जा सकता है। स्प्रेडशीट में पेस्ट किए गए नंबर नहीं, बल्कि लाइव फ़ॉर्मूला मिलते हैं। डेक और पेज कैनवस पर जनरेट होते हैं और पूरी तरह एडिटेबल बने रहते हैं। - **डिज़ाइन से ही लोकल।** फ़ाइलें आपकी मशीन पर ही खुलती, एडिट होती, सेव होती और कन्वर्ट होती हैं। PDF → Word / Excel / PowerPoint, Markdown → Word और HTML → Word — यह सभी कन्वर्शन ऑन-डिवाइस होते हैं। मशीन से बाहर सिर्फ़ AI कॉल्स जाती हैं, और वह भी आपके चुने हुए प्रोवाइडर तक। - **आपकी कीज़ या कोई कीज़ नहीं।** Genspark से साइन इन करें और कीज़ की झंझट से बचें, या Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty या किसी भी OpenAI-compatible endpoint के लिए अपनी खुद की key लाएँ — लोकल सर्वर भी शामिल हैं। +- **स्क्रिप्ट करने योग्य और एजेंट के लिए तैयार।** ऐप के साथ एक `genoffice` कमांड लाइन और Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode और Windsurf के लिए एक skill आती है, ताकि कोई कोडिंग एजेंट बिना कोई विंडो खोले आपकी मशीन पर असली Office फ़ाइलें बना, कन्वर्ट, पढ़ और एडिट कर सके। **पाएँ:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon और Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 और Arm) · @@ -42,7 +44,7 @@ GenOffice, macOS, Windows और Linux के लिए Microsoft Office का ## डेमो -छह ऐप्स, एक AI पैनल। हर स्क्रीनशॉट macOS पर चल रहे असली ऐप का है, और AI उस प्रॉम्प्ट से चलाया गया है जिसे आप पैनल में पढ़ सकते हैं। +छह ऐप्स, एक AI पैनल, और आपके कोडिंग एजेंट के लिए एक कमांड लाइन। हर स्क्रीनशॉट macOS पर चल रहे असली ऐप का है, और AI उस प्रॉम्प्ट से चलाया गया है जिसे आप पैनल में पढ़ सकते हैं। ### 1 · Docs — ऐसे AI के साथ `.docx` खोलें और एडिट करें जिसे आप रिव्यू कर सकते हैं @@ -138,6 +140,23 @@ GenOffice, macOS, Windows और Linux के लिए Microsoft Office का +### 7 · CLI — आपका कोडिंग एजेंट GenOffice चलाता है, आपकी मशीन पर + +GenOffice के साथ एक `genoffice` कमांड लाइन और एक एजेंट skill आती है। skill इंस्टॉल करें, और Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode या Windsurf उन्हीं इंजनों के ज़रिए, जिन पर ऐप्स चलते हैं, बिना कोई विंडो खोले असली Office फ़ाइलें बना, कन्वर्ट, पढ़ और एडिट कर सकते हैं। + +GenOffice Slides में सोलर सिस्टम पर आठ स्लाइड का एक डेक दिखाया गया है, जिसे एक कोडिंग एजेंट ने genoffice कमांड लाइन के ज़रिए बनाया: कैनवस पर कवर स्लाइड, बाईं ओर आठ थंबनेल और AI पैनल खुला हुआ + + + + + + + + + + +
    सोलर सिस्टम डेक की आठ रेंडर की गई स्लाइड्स एक साथ: कवर, एक्सप्लोरेशन टाइमलाइन, चार मुख्य आँकड़े, ग्रहों के व्यास का बार चार्ट, चट्टानी ग्रह बनाम विशाल ग्रह, सूर्य का 99.8% हीरो नंबर, चार विशाल ग्रहों का ग्रिड और मुख्य निष्कर्षGenOffice Settings का Integrations पेज: genoffice skill Claude Code में इंस्टॉल है, और Codex व Cursor के बगल में Install बटन हैं
    अपने एजेंट को एक प्रॉम्प्ट — "सोलर सिस्टम पर आठ स्लाइड का डेक बनाएँ।" एजेंट skill पढ़ता है, एक स्टाइल शीट, एक आउटलाइन और हर स्लाइड के लिए एक पेज स्पेक लिखता है, genoffice image से दो फ़ोटो जनरेट करता है, और genoffice slides check को ओवरफ़्लो या ओवरलैप करने वाली हर चीज़ रिजेक्ट करने देता है; इसके बाद genoffice create .pptx असेंबल करता है और slides render देखने के लिए हर स्लाइड का एक PNG वापस देता है।एक बार इंस्टॉल करें, सेटिंग्स → इंटीग्रेशन से — GenOffice इस कंप्यूटर पर मिले कोडिंग एजेंट्स की सूची दिखाता है और आपके चुने हुए हर एजेंट में skill लिख देता है। या skill को zip के रूप में डाउनलोड करें, या npx skills add genspark-ai/genoffice चलाएँ। कमांड और पूरा वर्कफ़्लो कमांड लाइन और एजेंट skill में हैं।
    + ## GenOffice क्यों - **ओपन सोर्स**, Apache-2.0, GitHub पर खुले तौर पर बनाया गया। @@ -155,6 +174,9 @@ GenOffice, macOS, Windows और Linux के लिए Microsoft Office का ऑन-डिवाइस Word, Excel या PowerPoint में कन्वर्ट करें, स्कैन के लिए सिस्टम OCR के साथ। - **Markdown और HTML भी**, उसी AI पैनल और Word में लोकल एक्सपोर्ट के साथ। +- **स्क्रिप्ट करने योग्य।** एक `genoffice` कमांड लाइन और एक एजेंट skill हर इंजन को + Claude Code, Codex, Cursor और दूसरे कोडिंग एजेंट्स की सेवा में लगा देती है, वह + भी ऑन-डिवाइस। - **फ़्री**, व्यक्तियों और टीमों दोनों के लिए। ## AI बैकएंड @@ -165,6 +187,76 @@ GenOffice, macOS, Windows और Linux के लिए Microsoft Office का पूरा सूट लाइट, डार्क और सिस्टम थीम के साथ आता है। थीम सिर्फ़ स्क्रीन पर दिखने वाली चीज़ बदलती है: एक्सपोर्ट, प्रिंट और सेव की गई फ़ाइलें हमेशा डॉक्यूमेंट के अपने असली रंग बरकरार रखती हैं। + + +## कमांड लाइन और एजेंट skill + +ऐप्स किसी फ़ाइल के साथ जो कुछ कर सकते हैं, वह सब `genoffice` कमांड लाइन टर्मिनल से +कर सकती है: Word, Excel, PowerPoint, PDF, Markdown और HTML को उन्हीं इंजनों पर, +हेडलेस, इंस्पेक्ट, कन्वर्ट, क्रिएट, रीड और एडिट करना। यह GenOffice के साथ इंस्टॉल +होती है, इसे अपना कोई अलग रनटाइम नहीं चाहिए, और यह कोई डॉक्यूमेंट कहीं नहीं भेजती। +बंडल की गई **एजेंट skill** के साथ मिलकर यह किसी कोडिंग एजेंट को एक ऐसे डॉक्यूमेंट +वर्कर में बदल देती है जो Markdown के अनुमानित रूपांतरणों के बजाय असली Office +फ़ाइलें बनाता है। + +**इनके साथ काम करती है:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode और Windsurf के साथ बिना किसी अतिरिक्त सेटअप के, और skills पढ़ने वाले किसी +भी अन्य एजेंट के साथ। + +### skill इंस्टॉल करें + +| कैसे | क्या होता है | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ऐप में **सेटिंग्स → इंटीग्रेशन** | इस कंप्यूटर पर मिले एजेंट्स की सूची दिखाता है; एक क्लिक में आपके चुने हुए हर एजेंट में skill लिख देता है। जब किसी GenOffice रिलीज़ में नई skill आती है, तो एक **Update** बटन दिखाई देता है। | +| उसी पेज पर **zip के रूप में डाउनलोड** | वह लेआउट जिसे claude.ai, Claude डेस्कटॉप ऐप्स और दूसरे असिस्टेंट अपलोड की गई skill के रूप में स्वीकार करते हैं। | +| `npx skills add genspark-ai/genoffice` | इस रिपॉज़िटरी से किसी भी skills-compatible एजेंट में इंस्टॉल करता है। | + +फिर एक नई चैट शुरू करें और कोई डॉक्यूमेंट माँगें। skill एजेंट को सिखाती है कि +`genoffice` का सहारा कब लेना है, एडिट करने से पहले फ़ाइल कैसे पढ़नी है, और अपना +काम खुद कैसे जाँचना है। + +### टर्मिनल से क्विकस्टार्ट + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +हर कमांड एक लाइन का सारांश प्रिंट करती है, या `--json` के साथ एक सिंगल JSON +ऑब्जेक्ट। एडिट्स एटॉमिक हैं: रिजेक्ट किया गया op फ़ाइल को अछूता छोड़ देता है और +एक गाइडेड एरर के साथ वापस आता है। `genoffice help` मौजूदा कमांड सरफ़ेस की सूची +देता है; पूरा रेफ़रेंस [packages/cli/README.md](../../packages/cli/README.md) में है। + +### एजेंट असल में क्या चलाता है + +ऊपर दिए गए डेमो का सोलर सिस्टम डेक Claude Code में एक ही प्रॉम्प्ट में बना। +पर्दे के पीछे, एजेंट ने skill के चरणबद्ध वर्कफ़्लो का पालन किया और CLI ने अगला +चरण शुरू होने से पहले हर चरण की जाँच की: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +`genoffice` के भीतर कोई मॉडल कॉल नहीं होती: सोचने का काम एजेंट करता है, बनाने +और जाँचने का काम CLI करती है, और नतीजा GenOffice या PowerPoint में एक सामान्य +`.pptx` के रूप में खुलता है। + ## डाउनलोड @@ -326,6 +418,18 @@ Word स्ट्रक्चर में बदला जाता है: ह

    +
    +क्या मैं Claude Code, Codex, Cursor या किसी स्क्रिप्ट से GenOffice चला सकता हूँ? + +हाँ। GenOffice एक `genoffice` कमांड लाइन इंस्टॉल करता है जो उन्हीं इंजनों को +हेडलेस चलाती है: टर्मिनल या स्क्रिप्ट से डॉक्यूमेंट इंस्पेक्ट, कन्वर्ट, क्रिएट, +रीड और एडिट करें, प्रोग्राम्स के लिए `--json` आउटपुट के साथ। बंडल की गई एजेंट +skill Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode और +Windsurf को इसका इस्तेमाल सिखाती है; इसे **सेटिंग्स → इंटीग्रेशन** से इंस्टॉल +करें। देखें [कमांड लाइन और एजेंट skill](#command-line-and-agent-skill)। + +
    +
    क्या GenOffice कोई डेटा कलेक्ट करता है? diff --git a/docs/i18n/README.id.md b/docs/i18n/README.id.md index a506218..174b13c 100644 --- a/docs/i18n/README.id.md +++ b/docs/i18n/README.id.md @@ -23,6 +23,7 @@ File Word, Excel, PowerPoint, dan PDF, diedit oleh Anda dan AI Anda, disimpan ke

    Unduh · + CLI · Situs Web · Komunitas · Privasi @@ -51,6 +52,11 @@ perubahan, dan menunjukkan dengan tepat bagian mana yang diubah. Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty, atau endpoint apa pun yang kompatibel dengan OpenAI, termasuk server lokal. +- **Dapat dijalankan lewat skrip dan siap untuk agen.** Aplikasi ini + menyertakan baris perintah `genoffice` dan sebuah skill untuk Claude Code, + Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode, dan Windsurf, sehingga + coding agent bisa membuat, mengonversi, membaca, dan mengedit file Office + asli di mesin Anda tanpa membuka satu jendela pun. **Unduh di sini:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon dan Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 dan Arm) · @@ -59,8 +65,9 @@ detail dan persyaratan ada di bagian [Download](#download). ## Demo -Enam aplikasi, satu panel AI. Setiap tangkapan layar adalah aplikasi asli di -macOS, dengan AI yang dijalankan dari prompt yang bisa Anda baca di panel. +Enam aplikasi, satu panel AI, dan satu baris perintah untuk coding agent Anda. +Setiap tangkapan layar adalah aplikasi asli di macOS, dengan AI yang dijalankan +dari prompt yang bisa Anda baca di panel. ### 1 · Docs — buka dan edit `.docx` dengan AI yang bisa Anda tinjau @@ -158,6 +165,26 @@ lalu membangun satu file `.html` mandiri berdasarkan token-token tersebut. +### 7 · CLI — coding agent Anda menjalankan GenOffice, di mesin Anda + +GenOffice menyertakan baris perintah `genoffice` dan sebuah skill agen. Pasang +skill itu, dan Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode, +atau Windsurf bisa membuat, mengonversi, membaca, dan mengedit file Office asli +lewat engine yang sama dengan aplikasinya, tanpa membuka satu jendela pun. + +GenOffice Slides menampilkan deck Tata Surya delapan slide yang dibuat coding agent lewat baris perintah genoffice: slide sampul di kanvas, delapan thumbnail di kiri, dan panel AI terbuka + + + + + + + + + + +
    Delapan slide hasil render dari deck Tata Surya berdampingan: sampul, linimasa eksplorasi, empat angka kunci, grafik batang diameter planet, planet berbatu versus planet raksasa, angka utama 99,8% milik Matahari, grid empat planet raksasa, dan kesimpulanGenOffice Settings, halaman Integrations: skill genoffice terpasang di Claude Code, dengan tombol Install di samping Codex dan Cursor
    Satu prompt ke agen Anda — "Buat deck delapan slide tentang Tata Surya." Agen membaca skill, menulis style sheet, outline, dan satu spesifikasi halaman per slide, menghasilkan dua foto dengan genoffice image, dan membiarkan genoffice slides check menolak apa pun yang meluap atau tumpang tindih sebelum genoffice create merakit .pptx dan slides render mengembalikan satu PNG per slide untuk dilihat.Pasang sekali, dari Pengaturan → Integrasi — GenOffice menampilkan coding agent yang ditemukannya di komputer ini dan menulis skill ke setiap agen yang Anda pilih. Atau unduh skill sebagai zip, atau jalankan npx skills add genspark-ai/genoffice. Perintah dan alur kerja lengkapnya ada di Baris perintah dan skill agen.
    + ## Mengapa GenOffice - **Open source**, Apache-2.0, dikembangkan secara terbuka di GitHub. @@ -177,6 +204,9 @@ lalu membangun satu file `.html` mandiri berdasarkan token-token tersebut. sistem untuk hasil pindaian. - **Markdown dan HTML juga**, dengan panel AI yang sama dan ekspor lokal ke Word. +- **Dapat dijalankan lewat skrip.** Baris perintah `genoffice` dan skill agen + menempatkan setiap engine untuk melayani Claude Code, Codex, Cursor, dan + coding agent lainnya, tetap on-device. - **Gratis**, untuk individu maupun tim. ## Backend AI @@ -199,6 +229,78 @@ Seluruh suite mendukung tema terang, gelap, dan sistem. Tema hanya mengubah tampilan di layar: ekspor, cetakan, dan file yang disimpan selalu mempertahankan warna asli dokumen. + + +## Baris perintah dan skill agen + +Semua yang bisa dilakukan aplikasi terhadap sebuah file, bisa dilakukan baris +perintah `genoffice` dari terminal: memeriksa, mengonversi, membuat, membaca, +dan mengedit Word, Excel, PowerPoint, PDF, Markdown, dan HTML dengan engine +yang sama, secara headless. Ia terpasang bersama GenOffice, tidak memerlukan +runtime sendiri, dan tidak pernah mengirim dokumen ke mana pun. Dipadukan +dengan **skill agen** yang disertakan, ia mengubah coding agent menjadi +pekerja dokumen yang menghasilkan file Office asli, bukan tiruan dalam +Markdown. + +**Bekerja dengan:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode, dan Windsurf langsung tanpa konfigurasi, serta agen lain mana pun +yang membaca skill. + +### Memasang skill + +| Cara | Yang terjadi | +| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Pengaturan → Integrasi** di aplikasi | Menampilkan agen yang ditemukan di komputer ini; satu klik menulis skill ke setiap agen yang Anda pilih. Tombol **Update** muncul saat rilis GenOffice membawa skill yang lebih baru. | +| **Unduh sebagai zip** di halaman yang sama | Tata letak yang diterima claude.ai, aplikasi desktop Claude, dan asisten lain sebagai skill yang diunggah. | +| `npx skills add genspark-ai/genoffice` | Memasang dari repositori ini ke agen mana pun yang kompatibel dengan skill. | + +Lalu mulai chat baru dan minta sebuah dokumen. Skill ini mengajari agen kapan +harus menggunakan `genoffice`, bagaimana membaca file sebelum mengeditnya, +dan bagaimana memeriksa hasil kerjanya sendiri. + +### Mulai cepat dari terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Setiap perintah mencetak ringkasan satu baris, atau satu objek JSON dengan +`--json`. Pengeditan bersifat atomik: op yang ditolak membiarkan file tak +tersentuh dan mengembalikan pesan kesalahan berpanduan. `genoffice help` +mencantumkan daftar perintah saat ini; referensi lengkapnya ada di +[packages/cli/README.md](../../packages/cli/README.md). + +### Apa yang sebenarnya dijalankan agen + +Deck Tata Surya di demo di atas hanya butuh satu prompt di Claude Code. Di +baliknya, agen mengikuti alur kerja bertahap dari skill dan CLI memeriksa +setiap tahap sebelum tahap berikutnya dimulai: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Tidak ada panggilan model yang terjadi di dalam `genoffice`: agen yang +berpikir, CLI yang membangun dan memeriksa, dan hasilnya terbuka di GenOffice +atau PowerPoint sebagai `.pptx` biasa. + ## Download @@ -372,6 +474,19 @@ bergaya dekoratif) yang disematkan sebagai gambar.

    +
    +Bisakah saya menjalankan GenOffice dari Claude Code, Codex, Cursor, atau skrip? + +Ya. GenOffice memasang baris perintah `genoffice` yang menjalankan engine yang +sama secara headless: memeriksa, mengonversi, membuat, membaca, dan mengedit +dokumen dari terminal atau skrip, dengan output `--json` untuk program. Skill +agen yang disertakan mengajari Claude Code, Codex, Cursor, Gemini CLI, GitHub +Copilot, OpenCode, dan Windsurf untuk menggunakannya; pasang dari +**Pengaturan → Integrasi**. Lihat +[Baris perintah dan skill agen](#command-line-and-agent-skill). + +
    +
    Apakah GenOffice mengumpulkan data? diff --git a/docs/i18n/README.it.md b/docs/i18n/README.it.md index 074071e..5e1670a 100644 --- a/docs/i18n/README.it.md +++ b/docs/i18n/README.it.md @@ -23,6 +23,7 @@ File Word, Excel, PowerPoint e PDF, modificati da te e dalla tua AI, salvati neg

    Download · + CLI · Sito web · Community · Privacy @@ -49,6 +50,11 @@ applica la modifica e ti mostra esattamente cosa ha toccato. nulla, oppure usa la tua chiave per Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty o qualsiasi endpoint compatibile con OpenAI, inclusi i server locali. +- **Scriptabile e pronto per gli agenti.** L'app include una riga di comando + `genoffice` e uno skill per Claude Code, Codex, Cursor, Gemini CLI, GitHub + Copilot, OpenCode e Windsurf, così un agente di coding può creare, + convertire, leggere e modificare file Office reali sul tuo computer senza + aprire una finestra. **Scaricalo:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon e Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 e Arm) · @@ -57,8 +63,9 @@ dettagli e requisiti nella sezione [Download](#download). ## Demo -Sei app, un solo pannello AI. Ogni screenshot mostra l'app reale su macOS, -con l'AI guidata dal prompt che puoi leggere nel pannello. +Sei app, un solo pannello AI e una riga di comando per il tuo agente di +coding. Ogni screenshot mostra l'app reale su macOS, con l'AI guidata dal +prompt che puoi leggere nel pannello. ### 1 · Docs — apri e modifica `.docx` con un'AI che puoi controllare @@ -156,6 +163,26 @@ costruisce un unico file `.html` autosufficiente basato su quei token. +### 7 · CLI — il tuo agente di coding guida GenOffice, sul tuo computer + +GenOffice include una riga di comando `genoffice` e uno skill per agenti. +Installa lo skill e Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode o Windsurf potranno creare, convertire, leggere e modificare file +Office reali con gli stessi motori delle app, senza aprire una finestra. + +GenOffice Slides mostra una presentazione di otto slide sul Sistema Solare creata da un agente di coding tramite la riga di comando genoffice: la slide di copertina sulla canvas, otto miniature a sinistra e il pannello AI aperto + + + + + + + + + + +
    Le otto slide renderizzate della presentazione sul Sistema Solare una accanto all'altra: copertina, cronologia dell'esplorazione, quattro numeri chiave, grafico a barre dei diametri dei pianeti, mondi rocciosi contro giganti, il numero in evidenza del 99,8% del Sole, la griglia dei quattro giganti e le conclusioniImpostazioni di GenOffice, pagina Integrazioni: lo skill genoffice installato in Claude Code, con pulsanti Installa accanto a Codex e Cursor
    Un solo prompt al tuo agente — "Crea una presentazione di otto slide sul Sistema Solare." L'agente legge lo skill, scrive un foglio di stile, una scaletta e una specifica di pagina per ogni slide, genera le due foto con genoffice image e lascia che genoffice slides check respinga tutto ciò che sborda o si sovrappone prima che genoffice create assembli il .pptx e slides render restituisca un PNG per slide da controllare.Installa una volta sola, da Impostazioni → Integrazioni — GenOffice elenca gli agenti di coding che trova su questo computer e scrive lo skill in ognuno di quelli che scegli. Oppure scarica lo skill come zip, o esegui npx skills add genspark-ai/genoffice. I comandi e il flusso di lavoro completo sono in Riga di comando e skill per agenti.
    + ## Perché GenOffice - **Open source**, Apache-2.0, sviluppato in modo aperto su GitHub. @@ -176,6 +203,9 @@ costruisce un unico file `.html` autosufficiente basato su quei token. scansioni. - **Anche Markdown e HTML**, con lo stesso pannello AI e l'esportazione locale in Word. +- **Scriptabile.** Una riga di comando `genoffice` e uno skill per agenti + mettono ogni motore al servizio di Claude Code, Codex, Cursor e altri + agenti di coding, sempre in locale. - **Gratuito**, per singoli utenti e team. ## Backend AI @@ -199,6 +229,79 @@ L'intera suite include i temi chiaro, scuro e di sistema. I temi cambiano solo ciò che vedi a schermo: esportazioni, stampe e file salvati mantengono sempre i colori originali del documento. + + +## Riga di comando e skill per agenti + +Tutto ciò che le app possono fare a un file, la riga di comando `genoffice` +può farlo da un terminale: ispezionare, convertire, creare, leggere e +modificare Word, Excel, PowerPoint, PDF, Markdown e HTML con gli stessi +motori, senza interfaccia grafica. Si installa insieme a GenOffice, non ha +bisogno di un runtime proprio e non invia mai un documento da nessuna parte. +Abbinata allo **skill per agenti** incluso, trasforma un agente di coding in +un operaio dei documenti che produce file Office reali invece di +approssimazioni in Markdown. + +**Funziona con:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode e Windsurf senza configurazione, e con qualsiasi altro agente che +legga gli skill. + +### Installare lo skill + +| Come | Cosa succede | +| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Impostazioni → Integrazioni** nell'app | Elenca gli agenti trovati su questo computer; un clic scrive lo skill in ognuno di quelli che scegli. Un pulsante **Aggiorna** compare quando una release di GenOffice porta uno skill più recente. | +| **Scarica come zip** nella stessa pagina | Il formato che claude.ai, le app desktop di Claude e altri assistenti accettano come skill caricato. | +| `npx skills add genspark-ai/genoffice` | Installa da questo repository in qualsiasi agente compatibile con gli skill. | + +Poi apri una nuova chat e chiedi un documento. Lo skill insegna all'agente +quando ricorrere a `genoffice`, come leggere un file prima di modificarlo e +come controllare il proprio lavoro. + +### Avvio rapido dal terminale + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Ogni comando stampa un riepilogo di una riga, oppure un singolo oggetto JSON +con `--json`. Le modifiche sono atomiche: un'operazione respinta lascia il +file intatto e restituisce un errore guidato. `genoffice help` elenca i +comandi attualmente disponibili; il riferimento completo è in +[packages/cli/README.md](../../packages/cli/README.md). + +### Cosa esegue davvero l'agente + +La presentazione sul Sistema Solare della demo qui sopra ha richiesto un +solo prompt in Claude Code. Dietro le quinte, l'agente ha seguito il flusso +di lavoro a fasi dello skill e la CLI ha controllato ogni fase prima di +avviare la successiva: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Nessuna chiamata a un modello avviene dentro `genoffice`: l'agente pensa, la +CLI costruisce e controlla, e il risultato si apre in GenOffice o PowerPoint +come un normale `.pptx`. + ## Download @@ -374,6 +477,19 @@ come immagini.

    +
    +Posso guidare GenOffice da Claude Code, Codex, Cursor o da uno script? + +Sì. GenOffice installa una riga di comando `genoffice` che esegue gli stessi +motori senza interfaccia grafica: ispeziona, converti, crea, leggi e modifica +documenti da un terminale o da uno script, con output `--json` per i +programmi. Lo skill per agenti incluso insegna a Claude Code, Codex, Cursor, +Gemini CLI, GitHub Copilot, OpenCode e Windsurf a usarla; installalo da +**Impostazioni → Integrazioni**. Vedi +[Riga di comando e skill per agenti](#command-line-and-agent-skill). + +
    +
    GenOffice raccoglie dati? diff --git a/docs/i18n/README.ja.md b/docs/i18n/README.ja.md index bc2cf08..1095090 100644 --- a/docs/i18n/README.ja.md +++ b/docs/i18n/README.ja.md @@ -2,7 +2,7 @@ - GenOffice — Microsoft Office に代わるオープンソースの AI オフィススイート:Docs、Sheets、Slides、PDF、Markdown、HTML と内蔵 AI パネル + GenOffice — オープンソースの AI オフィススイート:Docs、Sheets、Slides、PDF、Markdown、HTML と内蔵 AI パネル

    @@ -23,6 +23,7 @@ Word、Excel、PowerPoint、PDF ファイルを、あなたとあなたの AI

    ダウンロード · + CLI · ウェブサイト · コミュニティ · プライバシー @@ -34,6 +35,7 @@ GenOffice は、macOS・Windows・Linux で動作する、Microsoft Office に - **レビューできる AI。** 編集内容は変更履歴と差分として反映され、ワンクリックで元に戻せます。スプレッドシートには貼り付けの数値ではなく、実際に機能する数式が入ります。デッキやページはキャンバス上に生成され、そのまま自由に編集できます。 - **設計からローカル動作。** ファイルの開く・編集・保存・変換はすべてお使いのマシン上で行われます。PDF → Word / Excel / PowerPoint、Markdown → Word、HTML → Word の変換もすべてオンデバイスで実行されます。マシンの外に出るのは、選択した AI プロバイダーへの呼び出しだけです。 - **キーを使うか使わないかはあなた次第。** Genspark でサインインすればキーの用意は不要です。あるいは、Claude、OpenAI、Gemini、DeepSeek、Kimi、GLM、Qwen、Doubao、MiniMax、Grok、Mistral、OpenRouter、Requesty、または任意の OpenAI 互換エンドポイント(ローカルサーバーを含む)向けに、自分の API キーを持ち込むこともできます。 +- **スクリプト化でき、エージェントからも使える。** アプリには `genoffice` コマンドラインと、Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode、Windsurf 向けのスキルが同梱されているため、コーディングエージェントはウィンドウを一つも開かずに、お使いのマシン上で本物の Office ファイルを作成・変換・読み取り・編集できます。 **入手方法:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest)(Apple Silicon および Intel)· [Windows](https://github.com/genspark-ai/genoffice/releases/latest)(x64 および Arm)· @@ -42,7 +44,7 @@ GenOffice は、macOS・Windows・Linux で動作する、Microsoft Office に ## デモ -6 つのアプリ、1 つの AI パネル。すべてのスクリーンショットは macOS 上の実際のアプリで撮影したもので、AI はパネル内に表示されているプロンプトそのもので動かしています。 +6 つのアプリ、1 つの AI パネル、そしてコーディングエージェント向けのコマンドライン。すべてのスクリーンショットは macOS 上の実際のアプリで撮影したもので、AI はパネル内に表示されているプロンプトそのもので動かしています。 ### 1 · Docs — `.docx` を開いて、レビューできる AI で編集 @@ -138,6 +140,23 @@ GenOffice は、macOS・Windows・Linux で動作する、Microsoft Office に +### 7 · CLI — コーディングエージェントが、あなたのマシン上で GenOffice を操作 + +GenOffice には `genoffice` コマンドラインとエージェントスキルが同梱されています。スキルをインストールすれば、Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode、Windsurf が、アプリと同じエンジンを通じて本物の Office ファイルを作成・変換・読み取り・編集できます。ウィンドウを開く必要はありません。 + +GenOffice Slides が、コーディングエージェントが genoffice コマンドラインで組み立てた 8 枚構成の太陽系デッキを表示している様子:キャンバスには表紙スライド、左側に 8 枚のサムネイル、AI パネルは開いた状態 + + + + + + + + + + +
    太陽系デッキのレンダリング済みスライド 8 枚を並べたもの:表紙、探査の年表、4 つの重要な数字、惑星の直径の棒グラフ、岩石惑星と巨大惑星の比較、太陽が 99.8% を占めるというヒーロー数字、4 つの巨大惑星のグリッド、まとめGenOffice の設定、連携ページ:genoffice スキルが Claude Code にインストール済みで、Codex と Cursor の横にはインストールボタンが表示されている
    エージェントへのプロンプトは 1 つ — 「太陽系についての 8 枚構成のデッキを作って」。エージェントはスキルを読み、スタイルシート、アウトライン、スライドごとのページ仕様を書き、genoffice image で 2 枚の写真を生成し、genoffice slides check にはみ出しや重なりのある要素を弾かせてから、genoffice create で .pptx を組み立て、slides render でスライドごとの PNG を受け取って確認します。インストールは設定 → 連携から 1 回だけ — GenOffice がこのコンピューター上で見つかったコーディングエージェントを一覧し、選んだそれぞれにスキルを書き込みます。スキルを zip としてダウンロードするか、npx skills add genspark-ai/genoffice を実行しても構いません。コマンドとワークフローの全体は コマンドラインとエージェントスキル にあります。
    + ## GenOffice を選ぶ理由 - **オープンソース**。Apache-2.0 ライセンスで、GitHub 上で公開開発。 @@ -155,6 +174,9 @@ GenOffice は、macOS・Windows・Linux で動作する、Microsoft Office に PDF を Word・Excel・PowerPoint に変換。スキャンにはシステム OCR を使用。 - **Markdown と HTML にも対応**。同じ AI パネルを使い、ローカルで Word に書き出せ る。 +- **スクリプト化できる。** `genoffice` コマンドラインとエージェントスキルにより、 + すべてのエンジンを Claude Code・Codex・Cursor などのコーディングエージェントから + 使える。もちろんオンデバイスのまま。 - **無料**。個人でもチームでも利用できる。 ## AI バックエンド @@ -174,6 +196,71 @@ OpenAI、Gemini、Doubao/Seedream、GLM、Grok、Qwen、MiniMax、または任 スイート全体でライト・ダーク・システムのテーマに対応しています。テーマが変わるのは画面表示 だけで、書き出し・印刷・保存されたファイルは常にドキュメント本来の色を保持します。 + + +## コマンドラインとエージェントスキル + +アプリがファイルに対してできることはすべて、`genoffice` コマンドラインからターミナルで行えます。 +Word、Excel、PowerPoint、PDF、Markdown、HTML の検査・変換・作成・読み取り・編集を、同じエンジンで +ヘッドレスに実行します。GenOffice と一緒にインストールされ、独自のランタイムは不要で、ドキュメント +をどこかへ送信することもありません。同梱の**エージェントスキル**と組み合わせれば、コーディング +エージェントは Markdown による代用品ではなく、本物の Office ファイルを生み出すドキュメント作業者に +なります。 + +**対応エージェント:** Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode、Windsurf +はそのまま使え、スキルを読めるその他のエージェントでも動作します。 + +### スキルをインストールする + +| 方法 | 動作 | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| アプリの **設定 → 連携** | このコンピューター上で見つかったエージェントを一覧し、ワンクリックで選んだそれぞれにスキルを書き込みます。GenOffice のリリースに新しいスキルが含まれていると**更新**ボタンが表示されます。 | +| 同じページの **zip としてダウンロード** | claude.ai、Claude デスクトップアプリ、その他のアシスタントがアップロード用スキルとして受け付ける構成です。 | +| `npx skills add genspark-ai/genoffice` | このリポジトリから、スキルに対応する任意のエージェントにインストールします。 | + +その後、新しいチャットを始めてドキュメントを依頼してください。スキルは、いつ `genoffice` を使うべきか、 +編集前にファイルをどう読むか、自分の成果物をどう確認するかをエージェントに教えます。 + +### ターミナルからのクイックスタート + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +各コマンドは 1 行の要約を出力し、`--json` を付けると単一の JSON オブジェクトを返します。編集はアト +ミックです。拒否された操作はファイルに一切触れず、対処方法を示したエラーとして返ってきます。 +`genoffice help` で現在のコマンド一覧を確認でき、完全なリファレンスは +[packages/cli/README.md](../../packages/cli/README.md) にあります。 + +### エージェントが実際に実行しているもの + +上のデモの太陽系デッキは、Claude Code へのプロンプト 1 つで作られました。その裏では、エージェントが +スキルの段階的なワークフローに従い、CLI が各段階を次に進む前に検査していました。 + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +`genoffice` の内部でモデル呼び出しは一切行われません。考えるのはエージェント、組み立てと検査は CLI +が担い、結果は通常の `.pptx` として GenOffice や PowerPoint で開けます。 + ## ダウンロード @@ -337,6 +424,18 @@ DeepSeek、Kimi、GLM、Qwen、Doubao、MiniMax、Grok、Mistral、OpenRouter、

    +
    +Claude Code、Codex、Cursor、またはスクリプトから GenOffice を操作できますか? + +はい。GenOffice は、同じエンジンをヘッドレスで実行する `genoffice` コマンドラインをインストール +します。ターミナルやスクリプトからドキュメントの検査・変換・作成・読み取り・編集ができ、プログラ +ム向けに `--json` 出力も用意されています。同梱のエージェントスキルは Claude Code、Codex、Cursor、 +Gemini CLI、GitHub Copilot、OpenCode、Windsurf にその使い方を教えます。インストールは +**設定 → 連携** から行えます。詳しくは +[コマンドラインとエージェントスキル](#command-line-and-agent-skill) を参照してください。 + +
    +
    GenOffice はデータを収集しますか? diff --git a/docs/i18n/README.ko.md b/docs/i18n/README.ko.md index 790c4bc..fb8159a 100644 --- a/docs/i18n/README.ko.md +++ b/docs/i18n/README.ko.md @@ -23,6 +23,7 @@ Word, Excel, PowerPoint, PDF 파일을 당신과 당신의 AI가 함께 편집

    다운로드 · + CLI · 웹사이트 · 커뮤니티 · 개인정보 @@ -49,6 +50,11 @@ GenOffice는 macOS, Windows, Linux에서 사용할 수 있는 무료 오픈소 사용할 수 있고, 원한다면 Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty는 물론 OpenAI 호환 엔드포인트(로컬 서버 포함)까지 직접 가져올 수 있습니다. +- **스크립트로 다룰 수 있고, 에이전트가 바로 쓸 수 있습니다.** 앱에는 + `genoffice` 명령줄과 Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, + OpenCode, Windsurf용 스킬이 함께 제공되어, 코딩 에이전트가 창 하나 열지 + 않고도 내 컴퓨터에서 실제 Office 파일을 만들고, 변환하고, 읽고, 편집할 수 + 있습니다. **다운로드:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon 및 Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 및 Arm) · @@ -57,8 +63,9 @@ GenOffice는 macOS, Windows, Linux에서 사용할 수 있는 무료 오픈소 ## 데모 -여섯 개의 앱, 하나의 AI 패널. 모든 스크린샷은 macOS에서 실제로 구동되는 -앱이며, 패널에서 확인할 수 있는 프롬프트로 AI를 직접 실행한 결과입니다. +여섯 개의 앱, 하나의 AI 패널, 그리고 코딩 에이전트를 위한 명령줄. 모든 +스크린샷은 macOS에서 실제로 구동되는 앱이며, 패널에서 확인할 수 있는 +프롬프트로 AI를 직접 실행한 결과입니다. ### 1 · Docs — 검토 가능한 AI로 `.docx`를 열고 편집합니다 @@ -156,6 +163,26 @@ GenOffice는 macOS, Windows, Linux에서 사용할 수 있는 무료 오픈소 +### 7 · CLI — 코딩 에이전트가 내 컴퓨터에서 GenOffice를 움직입니다 + +GenOffice에는 `genoffice` 명령줄과 에이전트 스킬이 함께 제공됩니다. 스킬을 +설치하면 Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode, +Windsurf가 앱과 동일한 엔진을 통해 창을 열지 않고도 실제 Office 파일을 +만들고, 변환하고, 읽고, 편집할 수 있습니다. + +GenOffice Slides가 코딩 에이전트가 genoffice 명령줄로 만든 8장짜리 태양계 덱을 보여주는 화면: 캔버스에는 표지 슬라이드, 왼쪽에는 여덟 개의 축소판, AI 패널은 열려 있음 + + + + + + + + + + +
    태양계 덱의 렌더링된 슬라이드 여덟 장을 나란히 놓은 화면: 표지, 탐사 연표, 네 가지 핵심 수치, 행성 지름 막대 차트, 암석 행성 대 거대 행성, 태양이 99.8%를 차지한다는 헤드라인 숫자, 네 거대 행성 격자, 요약GenOffice 설정의 연동 페이지: genoffice 스킬이 Claude Code에 설치되어 있고, Codex와 Cursor 옆에는 설치 버튼이 표시된 화면
    에이전트에게 프롬프트 하나 — "태양계에 관한 8장짜리 덱을 만들어줘." 에이전트는 스킬을 읽고 스타일 시트, 개요, 슬라이드마다 하나씩의 페이지 스펙을 작성하고, genoffice image로 사진 두 장을 생성하고, genoffice slides check가 넘치거나 겹치는 요소를 걸러낸 뒤, genoffice create로 .pptx를 조립하고 slides render로 슬라이드마다 PNG 한 장을 받아 확인합니다.설정 → 연동에서 한 번만 설치 — GenOffice가 이 컴퓨터에서 찾은 코딩 에이전트를 나열하고, 선택한 각 에이전트에 스킬을 기록합니다. 스킬을 zip으로 내려받거나 npx skills add genspark-ai/genoffice를 실행해도 됩니다. 명령과 전체 워크플로는 명령줄과 에이전트 스킬에 있습니다.
    + ## GenOffice를 선택하는 이유 - **오픈소스**, Apache-2.0 라이선스로 GitHub에서 공개 개발됩니다. @@ -173,6 +200,9 @@ GenOffice는 macOS, Windows, Linux에서 사용할 수 있는 무료 오픈소 Word, Excel, PowerPoint로 변환하며, 스캔 문서는 시스템 OCR을 사용합니다. - **Markdown과 HTML도 지원**하며, 동일한 AI 패널과 로컬 Word 내보내기를 사용합 니다. +- **스크립트로 다룰 수 있습니다.** `genoffice` 명령줄과 에이전트 스킬이 모든 + 엔진을 Claude Code, Codex, Cursor 및 다른 코딩 에이전트가 쓸 수 있게 하며, + 이 역시 기기 내에서 동작합니다. - **무료**로 개인과 팀 모두 사용할 수 있습니다. ## AI 백엔드 @@ -195,6 +225,75 @@ OpenAI 호환 이미지 엔드포인트 중에서 선택합니다. 보이는 모습만 바꿀 뿐입니다: 내보내기, 인쇄, 저장된 파일은 항상 문서 고유의 색상을 그대로 유지합니다. + + +## 명령줄과 에이전트 스킬 + +앱이 파일에 할 수 있는 모든 일을 `genoffice` 명령줄은 터미널에서 할 수 +있습니다: Word, Excel, PowerPoint, PDF, Markdown, HTML을 동일한 엔진으로, +화면 없이 검사하고, 변환하고, 만들고, 읽고, 편집합니다. GenOffice와 함께 +설치되며, 별도의 런타임이 필요 없고, 문서를 어디로도 전송하지 않습니다. +함께 제공되는 **에이전트 스킬**과 결합하면 코딩 에이전트는 Markdown으로 +흉내 낸 결과물 대신 실제 Office 파일을 만들어내는 문서 작업자가 됩니다. + +**지원 대상:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode, Windsurf는 바로 사용할 수 있고, 스킬을 읽을 수 있는 다른 모든 +에이전트에서도 동작합니다. + +### 스킬 설치 + +| 방법 | 동작 | +| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 앱의 **설정 → 연동** | 이 컴퓨터에서 찾은 에이전트를 나열하고, 클릭 한 번으로 선택한 각 에이전트에 스킬을 기록합니다. GenOffice 릴리스에 새 스킬이 포함되면 **업데이트** 버튼이 나타납니다. | +| 같은 페이지의 **zip으로 다운로드** | claude.ai, Claude 데스크톱 앱, 그 밖의 어시스턴트가 업로드 스킬로 받아들이는 구조입니다. | +| `npx skills add genspark-ai/genoffice` | 이 저장소에서 스킬을 지원하는 모든 에이전트에 설치합니다. | + +그런 다음 새 대화를 시작해 문서를 요청하세요. 스킬은 언제 `genoffice`를 +꺼내야 하는지, 편집 전에 파일을 어떻게 읽어야 하는지, 자신의 작업을 +어떻게 검증해야 하는지를 에이전트에게 알려줍니다. + +### 터미널에서 빠르게 시작하기 + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +모든 명령은 한 줄 요약을 출력하며, `--json`을 붙이면 단일 JSON 객체를 +반환합니다. 편집은 원자적입니다: 거부된 작업은 파일을 건드리지 않고, +안내가 담긴 오류로 돌아옵니다. `genoffice help`는 현재 명령 목록을 +보여주며, 전체 레퍼런스는 [packages/cli/README.md](../../packages/cli/README.md)에 있습니다. + +### 에이전트가 실제로 실행하는 것 + +위의 데모에 나온 태양계 덱은 Claude Code에서 프롬프트 하나로 만들어졌습니다. +그 뒤에서 에이전트는 스킬의 단계별 워크플로를 따랐고, CLI는 다음 단계로 +넘어가기 전에 매 단계를 검사했습니다: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +`genoffice` 내부에서는 어떤 모델 호출도 일어나지 않습니다: 생각은 +에이전트가 하고, 만들고 검사하는 일은 CLI가 하며, 결과는 평범한 `.pptx`로 +GenOffice나 PowerPoint에서 열립니다. + ## 다운로드 @@ -363,6 +462,19 @@ OpenRouter, Requesty, OpenCode Zen/Go를 위한 직접 키 사용을 지원하

    +
    +Claude Code, Codex, Cursor 또는 스크립트에서 GenOffice를 제어할 수 있나요? + +네. GenOffice는 동일한 엔진을 화면 없이 실행하는 `genoffice` 명령줄을 +설치합니다: 터미널이나 스크립트에서 문서를 검사하고, 변환하고, 만들고, +읽고, 편집할 수 있으며, 프로그램용 `--json` 출력도 제공합니다. 함께 +제공되는 에이전트 스킬은 Claude Code, Codex, Cursor, Gemini CLI, GitHub +Copilot, OpenCode, Windsurf에 사용법을 알려주며, **설정 → 연동**에서 +설치할 수 있습니다. [명령줄과 에이전트 스킬](#command-line-and-agent-skill)을 +참고하세요. + +
    +
    GenOffice가 데이터를 수집하나요? diff --git a/docs/i18n/README.ms.md b/docs/i18n/README.ms.md index 473f28e..937e342 100644 --- a/docs/i18n/README.ms.md +++ b/docs/i18n/README.ms.md @@ -23,6 +23,7 @@ Fail Word, Excel, PowerPoint dan PDF, disunting oleh anda dan AI anda, disimpan

    Muat Turun · + CLI · Laman Web · Komuniti · Privasi @@ -52,6 +53,11 @@ kepada anda dengan tepat apa yang disentuhnya. OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty, atau mana-mana titik akhir yang serasi dengan OpenAI, termasuk pelayan setempat. +- **Boleh dijalankan melalui skrip dan sedia untuk agen.** Aplikasi ini + disertakan dengan baris arahan `genoffice` dan skill untuk Claude Code, + Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode dan Windsurf, jadi agen + pengekodan boleh mencipta, menukar, membaca dan menyunting fail Office + sebenar pada mesin anda tanpa membuka sebarang tetingkap. **Dapatkan:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon dan Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 dan Arm) · @@ -60,8 +66,9 @@ butiran dan keperluan dalam [Muat Turun](#download). ## Demo -Enam aplikasi, satu panel AI. Setiap tangkapan skrin ialah aplikasi sebenar -pada macOS, dengan AI dipandu oleh gesaan yang boleh anda baca dalam panel. +Enam aplikasi, satu panel AI, dan satu baris arahan untuk agen pengekodan anda. +Setiap tangkapan skrin ialah aplikasi sebenar pada macOS, dengan AI dipandu +oleh gesaan yang boleh anda baca dalam panel. ### 1 · Docs — buka dan sunting `.docx` dengan AI yang boleh anda semak @@ -159,6 +166,27 @@ gaya — sebelum membina satu fail `.html` mandiri berdasarkan token-token itu. +### 7 · CLI — agen pengekodan anda memandu GenOffice, pada mesin anda + +GenOffice disertakan dengan baris arahan `genoffice` dan skill agen. Pasang +skill itu dan Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode +atau Windsurf boleh mencipta, menukar, membaca dan menyunting fail Office +sebenar melalui enjin yang sama seperti aplikasi, tanpa membuka sebarang +tetingkap. + +GenOffice Slides memaparkan deck Sistem Suria lapan slaid yang dibina oleh agen pengekodan melalui baris arahan genoffice: slaid muka depan pada kanvas, lapan lakaran kecil di kiri dan panel AI terbuka + + + + + + + + + + +
    Lapan slaid deck Sistem Suria yang telah dipaparkan bersebelahan: muka depan, garis masa penerokaan, empat angka utama, carta bar diameter planet, dunia berbatu lawan gergasi, angka utama 99.8% milik Matahari, grid empat gergasi dan rumusanGenOffice Settings, halaman Integrations: skill genoffice dipasang ke dalam Claude Code, dengan butang Install di sebelah Codex dan Cursor
    Satu gesaan kepada agen anda — "Build an eight-slide deck about the Solar System." Agen membaca skill, menulis helaian gaya, rangka dan satu spesifikasi halaman bagi setiap slaid, menjana dua foto dengan genoffice image, dan membiarkan genoffice slides check menolak apa-apa yang melimpah atau bertindih sebelum genoffice create memasang .pptx dan slides render memulangkan satu PNG bagi setiap slaid untuk dilihat.Pasang sekali, daripada Tetapan → Integrasi — GenOffice menyenaraikan agen pengekodan yang ditemuinya pada komputer ini dan menulis skill ke dalam setiap satu yang anda pilih. Atau muat turun skill sebagai zip, atau jalankan npx skills add genspark-ai/genoffice. Arahan dan aliran kerja penuh ada dalam Baris arahan dan skill agen.
    + ## Mengapa GenOffice - **Sumber terbuka**, Apache-2.0, dibangunkan secara terbuka di GitHub. @@ -178,6 +206,9 @@ gaya — sebelum membina satu fail `.html` mandiri berdasarkan token-token itu. sistem untuk hasil imbasan. - **Markdown dan HTML juga**, dengan panel AI yang sama dan eksport setempat ke Word. +- **Boleh dijalankan melalui skrip.** Baris arahan `genoffice` dan skill agen + meletakkan setiap enjin di bawah khidmat Claude Code, Codex, Cursor dan agen + pengekodan lain, masih di peranti sendiri. - **Percuma**, untuk individu dan pasukan. ## Bahagian belakang AI @@ -200,6 +231,78 @@ Keseluruhan rangkaian ini disertakan dengan tema terang, gelap dan sistem. Tema hanya mengubah apa yang dipaparkan pada skrin: eksport, cetakan dan fail yang disimpan sentiasa mengekalkan warna sebenar dokumen itu. + + +## Baris arahan dan skill agen + +Segala yang boleh dilakukan aplikasi pada sesuatu fail boleh dilakukan oleh +baris arahan `genoffice` dari terminal: memeriksa, menukar, mencipta, membaca +dan menyunting Word, Excel, PowerPoint, PDF, Markdown dan HTML pada enjin yang +sama, tanpa antara muka (headless). Ia dipasang bersama GenOffice, tidak +memerlukan runtime sendiri, dan tidak pernah menghantar dokumen ke mana-mana. +Digandingkan dengan **skill agen** yang disertakan, ia menjadikan agen +pengekodan sebagai pekerja dokumen yang menghasilkan fail Office sebenar dan +bukan anggaran dalam Markdown. + +**Berfungsi dengan:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode dan Windsurf terus tanpa tetapan tambahan, serta mana-mana agen lain +yang membaca skill. + +### Memasang skill + +| Cara | Apa yang berlaku | +| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Tetapan → Integrasi** dalam aplikasi | Menyenaraikan agen yang ditemui pada komputer ini; satu klik menulis skill ke dalam setiap satu yang anda pilih. Butang **Update** muncul apabila keluaran GenOffice membawa skill yang lebih baharu. | +| **Muat turun sebagai zip** pada halaman yang sama | Susun atur yang diterima oleh claude.ai, aplikasi desktop Claude dan pembantu lain sebagai skill yang dimuat naik. | +| `npx skills add genspark-ai/genoffice` | Memasang daripada repositori ini ke dalam mana-mana agen yang serasi dengan skill. | + +Kemudian mulakan sembang baharu dan minta sesuatu dokumen. Skill itu mengajar +agen bila perlu menggunakan `genoffice`, cara membaca fail sebelum +menyuntingnya, dan cara menyemak hasil kerjanya sendiri. + +### Mula pantas dari terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Setiap arahan mencetak ringkasan satu baris, atau satu objek JSON dengan +`--json`. Suntingan bersifat atomik: op yang ditolak membiarkan fail tidak +tersentuh dan memulangkan ralat berpandu. `genoffice help` menyenaraikan set +arahan semasa; rujukan penuh ada dalam +[packages/cli/README.md](../../packages/cli/README.md). + +### Apa yang sebenarnya dijalankan oleh agen + +Deck Sistem Suria dalam demo di atas hanya memerlukan satu gesaan dalam Claude +Code. Di sebaliknya, agen mengikuti aliran kerja berperingkat skill itu dan +CLI menyemak setiap peringkat sebelum peringkat seterusnya bermula: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Tiada panggilan model berlaku di dalam `genoffice`: agen yang berfikir, CLI +yang membina dan menyemak, dan hasilnya dibuka dalam GenOffice atau PowerPoint +sebagai `.pptx` biasa. + ## Muat Turun @@ -371,6 +474,19 @@ kotak berhias) dibenamkan sebagai gambar.

    +
    +Bolehkah saya memandu GenOffice daripada Claude Code, Codex, Cursor atau skrip? + +Ya. GenOffice memasang baris arahan `genoffice` yang menjalankan enjin yang +sama tanpa antara muka: memeriksa, menukar, mencipta, membaca dan menyunting +dokumen dari terminal atau skrip, dengan output `--json` untuk program. Skill +agen yang disertakan mengajar Claude Code, Codex, Cursor, Gemini CLI, GitHub +Copilot, OpenCode dan Windsurf menggunakannya; pasang daripada +**Tetapan → Integrasi**. Lihat +[Baris arahan dan skill agen](#command-line-and-agent-skill). + +
    +
    Adakah GenOffice mengumpul sebarang data? diff --git a/docs/i18n/README.nl.md b/docs/i18n/README.nl.md index b2c17c5..7b041af 100644 --- a/docs/i18n/README.nl.md +++ b/docs/i18n/README.nl.md @@ -23,6 +23,7 @@ Word-, Excel-, PowerPoint- en PDF-bestanden, bewerkt door jou en je AI, opgeslag

    Download · + CLI · Website · Community · Privacy @@ -50,6 +51,11 @@ aangepast. regelen, of gebruik je eigen key voor Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty, of elk OpenAI-compatibel endpoint, inclusief lokale servers. +- **Scriptbaar en klaar voor agents.** De app levert een + `genoffice`-opdrachtregel en een skill voor Claude Code, Codex, Cursor, + Gemini CLI, GitHub Copilot, OpenCode en Windsurf mee, zodat een coding + agent echte Office-bestanden op je eigen machine kan maken, converteren, + lezen en bewerken zonder een venster te openen. **Haal het hier:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon en Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 en Arm) · @@ -58,8 +64,9 @@ details en vereisten in [Download](#download). ## Demo -Zes apps, één AI-paneel. Elke screenshot toont de echte app op macOS, met de -AI aangestuurd vanuit de prompt die je in het paneel kunt lezen. +Zes apps, één AI-paneel en een opdrachtregel voor je coding agent. Elke +screenshot toont de echte app op macOS, met de AI aangestuurd vanuit de +prompt die je in het paneel kunt lezen. ### 1 · Docs — open en bewerk `.docx` met een AI die je kunt controleren @@ -157,6 +164,27 @@ een **design brief** voor — hook, kleurenpalet, typografie en stijlrichtingen +### 7 · CLI — je coding agent stuurt GenOffice aan, op je eigen machine + +GenOffice levert een `genoffice`-opdrachtregel en een agent-skill mee. +Installeer de skill en Claude Code, Codex, Cursor, Gemini CLI, GitHub +Copilot, OpenCode of Windsurf kunnen echte Office-bestanden maken, +converteren, lezen en bewerken via dezelfde engines als de apps, zonder een +venster te openen. + +GenOffice Slides toont een deck van acht slides over het zonnestelsel dat een coding agent via de genoffice-opdrachtregel heeft gebouwd: de openingsslide op het canvas, acht miniaturen links en het AI-paneel geopend + + + + + + + + + + +
    De acht gerenderde slides van het zonnestelsel-deck naast elkaar: cover, tijdlijn van de ruimteverkenning, vier kerncijfers, staafdiagram van planeetdiameters, rotsplaneten tegenover reuzen, het hoofdcijfer van 99,8% voor de zon, het raster van de vier reuzen en de conclusiesGenOffice-instellingen, pagina Integraties: de genoffice-skill geïnstalleerd in Claude Code, met Installeren-knoppen naast Codex en Cursor
    Eén prompt aan je agent — "Bouw een deck van acht slides over het zonnestelsel." De agent leest de skill, schrijft een stylesheet, een outline en één paginaspecificatie per slide, genereert de twee foto's met genoffice image en laat genoffice slides check alles afwijzen wat overloopt of overlapt, voordat genoffice create de .pptx samenstelt en slides render per slide een PNG teruggeeft om te bekijken.Eén keer installeren, via Instellingen → Integraties — GenOffice toont de coding agents die het op deze computer vindt en schrijft de skill naar elke agent die je kiest. Of download de skill als zip, of voer npx skills add genspark-ai/genoffice uit. Commando's en de volledige workflow staan in Opdrachtregel en agent-skill.
    + ## Waarom GenOffice - **Open source**, Apache-2.0, in het openbaar ontwikkeld op GitHub. @@ -176,6 +204,9 @@ een **design brief** voor — hook, kleurenpalet, typografie en stijlrichtingen naar Word, Excel of PowerPoint on-device, met systeem-OCR voor scans. - **Ook Markdown en HTML**, met hetzelfde AI-paneel en lokale export naar Word. +- **Scriptbaar.** Een `genoffice`-opdrachtregel en een agent-skill stellen + elke engine ter beschikking van Claude Code, Codex, Cursor en andere coding + agents, nog altijd on-device. - **Gratis**, voor individuen en teams. ## AI-backends @@ -198,6 +229,78 @@ De hele suite wordt geleverd met een licht, donker en systeemthema. Thema's veranderen alleen wat er op je scherm te zien is: exports, afdrukken en opgeslagen bestanden behouden altijd de eigen kleuren van het document. + + +## Opdrachtregel en agent-skill + +Alles wat de apps met een bestand kunnen, kan de `genoffice`-opdrachtregel +vanuit een terminal: Word, Excel, PowerPoint, PDF, Markdown en HTML +inspecteren, converteren, maken, lezen en bewerken op dezelfde engines, +headless. Hij wordt samen met GenOffice geïnstalleerd, heeft geen eigen +runtime nodig en stuurt nooit een document ergens naartoe. In combinatie met +de meegeleverde **agent-skill** maakt hij van een coding agent een +documentenwerker die echte Office-bestanden oplevert in plaats van +Markdown-benaderingen. + +**Werkt met:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode en Windsurf direct uit de doos, en met elke andere agent die skills +leest. + +### De skill installeren + +| Hoe | Wat er gebeurt | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Instellingen → Integraties** in de app | Toont de agents die op deze computer zijn gevonden; met één klik wordt de skill naar elke agent geschreven die je kiest. Er verschijnt een knop **Bijwerken** wanneer een GenOffice-release een nieuwere skill meebrengt. | +| **Downloaden als zip** op dezelfde pagina | De indeling die claude.ai, de Claude-desktop-apps en andere assistenten accepteren als geüploade skill. | +| `npx skills add genspark-ai/genoffice` | Installeert vanuit deze repository in elke agent die skills ondersteunt. | + +Start daarna een nieuwe chat en vraag om een document. De skill leert de +agent wanneer hij naar `genoffice` moet grijpen, hoe hij een bestand leest +voordat hij het bewerkt en hoe hij zijn eigen werk controleert. + +### Snelstart vanuit de terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Elk commando print een samenvatting van één regel, of één JSON-object met +`--json`. Bewerkingen zijn atomair: een afgewezen op laat het bestand +onaangeroerd en komt terug met een begeleide foutmelding. `genoffice help` +toont de huidige set commando's; de volledige referentie staat in +[packages/cli/README.md](../../packages/cli/README.md). + +### Wat de agent daadwerkelijk uitvoert + +Het zonnestelsel-deck in de demo hierboven kostte één prompt in Claude Code. +Daarachter volgde de agent de gefaseerde workflow van de skill en +controleerde de CLI elke fase voordat de volgende begon: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Binnen `genoffice` vindt geen enkele modelaanroep plaats: de agent doet het +denkwerk, de CLI het bouwen en controleren, en het resultaat opent in +GenOffice of PowerPoint als een gewone `.pptx`. + ## Download @@ -369,6 +472,19 @@ afbeelding ingevoegd.

    +
    +Kan ik GenOffice aansturen vanuit Claude Code, Codex, Cursor of een script? + +Ja. GenOffice installeert een `genoffice`-opdrachtregel die dezelfde engines +headless draait: documenten inspecteren, converteren, maken, lezen en +bewerken vanuit een terminal of een script, met `--json`-uitvoer voor +programma's. De meegeleverde agent-skill leert Claude Code, Codex, Cursor, +Gemini CLI, GitHub Copilot, OpenCode en Windsurf ermee werken; installeer hem +via **Instellingen → Integraties**. Zie +[Opdrachtregel en agent-skill](#command-line-and-agent-skill). + +
    +
    Verzamelt GenOffice gegevens? diff --git a/docs/i18n/README.pl.md b/docs/i18n/README.pl.md index 5dea778..969fe1e 100644 --- a/docs/i18n/README.pl.md +++ b/docs/i18n/README.pl.md @@ -23,6 +23,7 @@ Pliki Word, Excel, PowerPoint i PDF, edytowane przez Ciebie i Twoją AI, zapisyw

    Pobierz · + CLI · Strona internetowa · Społeczność · Prywatność @@ -50,6 +51,11 @@ i pokazuje precyzyjnie, czego dotknął. użyj własnego klucza dla Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty lub dowolnego endpointu zgodnego z OpenAI, w tym lokalnych serwerów. +- **Skryptowalne i gotowe na agentów.** Aplikacja dostarcza wiersz poleceń + `genoffice` oraz skill dla agentów Claude Code, Codex, Cursor, Gemini CLI, + GitHub Copilot, OpenCode i Windsurf, dzięki czemu agent kodujący może + tworzyć, konwertować, czytać i edytować prawdziwe pliki Office na Twoim + komputerze bez otwierania okna. **Pobierz:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon i Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 i Arm) · @@ -58,8 +64,9 @@ szczegóły i wymagania w sekcji [Pobierz](#download). ## Demo -Sześć aplikacji, jeden panel AI. Każdy zrzut ekranu pochodzi z prawdziwej -aplikacji na macOS, a AI jest prowadzona promptem widocznym w panelu. +Sześć aplikacji, jeden panel AI i wiersz poleceń dla Twojego agenta +kodującego. Każdy zrzut ekranu pochodzi z prawdziwej aplikacji na macOS, a +AI jest prowadzona promptem widocznym w panelu. ### 1 · Docs — otwieraj i edytuj pliki `.docx` z AI, którą możesz zweryfikować @@ -158,6 +165,27 @@ wytycznymi. +### 7 · CLI — Twój agent kodujący steruje GenOffice, na Twoim komputerze + +GenOffice dostarcza wiersz poleceń `genoffice` oraz skill dla agentów. +Zainstaluj skill, a Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode lub Windsurf będą mogły tworzyć, konwertować, czytać i edytować +prawdziwe pliki Office przez te same silniki, co aplikacje, bez otwierania +okna. + +GenOffice Slides pokazuje ośmioslajdową prezentację o Układzie Słonecznym, którą agent kodujący zbudował przez wiersz poleceń genoffice: slajd tytułowy na płótnie, osiem miniatur po lewej i otwarty panel AI + + + + + + + + + + +
    Osiem wyrenderowanych slajdów prezentacji o Układzie Słonecznym obok siebie: okładka, oś czasu eksploracji, cztery kluczowe liczby, wykres słupkowy średnic planet, planety skaliste kontra olbrzymy, 99,8% Słońca jako liczba nagłówkowa, siatka czterech olbrzymów i wnioskiUstawienia GenOffice, strona Integracje: skill genoffice zainstalowany w Claude Code, z przyciskami Zainstaluj przy pozycjach Codex i Cursor
    Jeden prompt do Twojego agenta — „Zbuduj ośmioslajdową prezentację o Układzie Słonecznym”. Agent czyta skill, pisze arkusz stylów, konspekt i jedną specyfikację strony na slajd, generuje dwa zdjęcia za pomocą genoffice image i pozwala, by genoffice slides check odrzuciło wszystko, co wychodzi poza obszar lub nachodzi na siebie, zanim genoffice create złoży plik .pptx, a slides render odda po jednym PNG na slajd do obejrzenia.Zainstaluj raz, w Ustawienia → Integracje — GenOffice wyświetla agentów kodujących, których znajdzie na tym komputerze, i zapisuje skill w każdym, którego wybierzesz. Możesz też pobrać skill jako zip albo uruchomić npx skills add genspark-ai/genoffice. Polecenia i pełny przepływ pracy znajdziesz w sekcji Wiersz poleceń i skill dla agentów.
    + ## Dlaczego GenOffice - **Otwarty kod źródłowy**, Apache-2.0, tworzony w pełni otwarcie na GitHubie. @@ -177,6 +205,9 @@ wytycznymi. Word, Excel lub PowerPoint lokalnie, z systemowym OCR dla skanów. - **Także Markdown i HTML**, z tym samym panelem AI i lokalnym eksportem do Word. +- **Skryptowalne.** Wiersz poleceń `genoffice` i skill dla agentów oddają + każdy silnik do dyspozycji Claude Code, Codex, Cursor i innych agentów + kodujących — nadal lokalnie na urządzeniu. - **Bezpłatne**, dla pojedynczych osób i zespołów. ## Silniki AI @@ -200,6 +231,78 @@ Cały pakiet obsługuje motywy jasny, ciemny i systemowy. Motywy zmieniają tylko to, co widać na ekranie: eksporty, wydruki i zapisane pliki zawsze zachowują oryginalne kolory dokumentu. + + +## Wiersz poleceń i skill dla agentów + +Wszystko, co aplikacje potrafią zrobić z plikiem, wiersz poleceń `genoffice` +potrafi zrobić z terminala: sprawdzać, konwertować, tworzyć, czytać i +edytować pliki Word, Excel, PowerPoint, PDF, Markdown i HTML na tych samych +silnikach, bez interfejsu graficznego. Instaluje się razem z GenOffice, nie +potrzebuje własnego środowiska uruchomieniowego i nigdy nie wysyła dokumentu +poza komputer. W połączeniu z dołączonym **skillem dla agentów** zamienia +agenta kodującego w pracownika biurowego, który tworzy prawdziwe pliki Office +zamiast markdownowych przybliżeń. + +**Działa z:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode i Windsurf od razu po instalacji, a także z każdym innym agentem, +który czyta skille. + +### Instalacja skilla + +| Jak | Co się dzieje | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Ustawienia → Integracje** w aplikacji | Wyświetla agentów znalezionych na tym komputerze; jedno kliknięcie zapisuje skill w każdym, którego wybierzesz. Gdy nowe wydanie GenOffice przynosi nowszy skill, pojawia się przycisk **Aktualizuj**. | +| **Pobierz jako zip** na tej samej stronie | Układ, który claude.ai, aplikacje desktopowe Claude i inni asystenci przyjmują jako przesłany skill. | +| `npx skills add genspark-ai/genoffice` | Instaluje z tego repozytorium w dowolnym agencie obsługującym skille. | + +Następnie zacznij nowy czat i poproś o dokument. Skill uczy agenta, kiedy +sięgać po `genoffice`, jak przeczytać plik przed jego edycją i jak sprawdzać +własną pracę. + +### Szybki start z terminala + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Każde polecenie wypisuje jednowierszowe podsumowanie albo — z `--json` — +pojedynczy obiekt JSON. Edycje są atomowe: odrzucona operacja pozostawia plik +nietknięty i wraca z pomocnym komunikatem błędu. `genoffice help` wypisuje +aktualny zestaw poleceń; pełna dokumentacja znajduje się w +[packages/cli/README.md](../../packages/cli/README.md). + +### Co agent faktycznie uruchamia + +Prezentacja o Układzie Słonecznym z dema powyżej wymagała jednego promptu w +Claude Code. W tle agent podążał za etapowym przepływem pracy ze skilla, a +CLI sprawdzało każdy etap, zanim zaczął się następny: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Wewnątrz `genoffice` nie dochodzi do żadnego wywołania modelu: agent myśli, +CLI buduje i sprawdza, a wynik otwiera się w GenOffice lub PowerPoint jako +zwyczajny plik `.pptx`. + ## Pobierz @@ -374,6 +477,19 @@ osadzane jako obrazy.

    +
    +Czy mogę sterować GenOffice z narzędzi Claude Code, Codex, Cursor albo ze skryptu? + +Tak. GenOffice instaluje wiersz poleceń `genoffice`, który uruchamia te same +silniki bez interfejsu graficznego: sprawdzaj, konwertuj, twórz, czytaj i +edytuj dokumenty z terminala lub skryptu, z wyjściem `--json` dla programów. +Dołączony skill dla agentów uczy Claude Code, Codex, Cursor, Gemini CLI, +GitHub Copilot, OpenCode i Windsurf, jak z niego korzystać; zainstaluj go w +**Ustawienia → Integracje**. Zobacz +[Wiersz poleceń i skill dla agentów](#command-line-and-agent-skill). + +
    +
    Czy GenOffice zbiera jakieś dane? diff --git a/docs/i18n/README.pt-BR.md b/docs/i18n/README.pt-BR.md index 69222eb..2c30ac5 100644 --- a/docs/i18n/README.pt-BR.md +++ b/docs/i18n/README.pt-BR.md @@ -23,6 +23,7 @@ Arquivos do Word, Excel, PowerPoint e PDF, editados por você e sua IA, salvos d

    Download · + CLI · Site · Comunidade · Privacidade @@ -49,6 +50,11 @@ lê o arquivo, faz a alteração e mostra exatamente o que foi tocado. use sua própria chave para Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty, ou qualquer endpoint compatível com OpenAI, incluindo servidores locais. +- **Automatizável e pronto para agentes.** O app inclui uma linha de comando + `genoffice` e um skill para Claude Code, Codex, Cursor, Gemini CLI, GitHub + Copilot, OpenCode e Windsurf, para que um agente de programação possa criar, + converter, ler e editar arquivos reais do Office na sua máquina sem abrir + uma janela. **Baixe:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon e Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 e Arm) · @@ -57,8 +63,9 @@ detalhes e requisitos em [Download](#download). ## Demo -Seis aplicativos, um painel de IA. Cada captura de tela é do aplicativo real -no macOS, com a IA acionada a partir do prompt que você pode ler no painel. +Seis aplicativos, um painel de IA e uma linha de comando para o seu agente de +programação. Cada captura de tela é do aplicativo real no macOS, com a IA +acionada a partir do prompt que você pode ler no painel. ### 1 · Docs — abra e edite `.docx` com uma IA que você pode revisar @@ -157,6 +164,26 @@ tokens. +### 7 · CLI — seu agente de programação comanda o GenOffice, na sua máquina + +O GenOffice inclui uma linha de comando `genoffice` e um skill de agente. +Instale o skill e o Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode ou Windsurf poderão criar, converter, ler e editar arquivos reais do +Office com os mesmos mecanismos dos aplicativos, sem abrir uma janela. + +GenOffice Slides mostrando uma apresentação de oito slides sobre o Sistema Solar que um agente de programação construiu pela linha de comando genoffice: o slide de capa no canvas, oito miniaturas à esquerda e o painel de IA aberto + + + + + + + + + + +
    Os oito slides renderizados da apresentação do Sistema Solar lado a lado: capa, linha do tempo da exploração, quatro números-chave, gráfico de barras com o diâmetro dos planetas, mundos rochosos versus gigantes, o número de destaque de 99,8% do Sol, a grade dos quatro gigantes e as conclusõesConfigurações do GenOffice, página Integrações: o skill genoffice instalado no Claude Code, com botões Instalar ao lado de Codex e Cursor
    Um prompt para o seu agente — "Crie uma apresentação de oito slides sobre o Sistema Solar." O agente lê o skill, escreve uma folha de estilos, um esboço e uma especificação de página por slide, gera as duas fotos com genoffice image e deixa o genoffice slides check rejeitar qualquer coisa que transborde ou se sobreponha antes que o genoffice create monte o .pptx e o slides render devolva um PNG por slide para conferir.Instale uma vez, em Configurações → Integrações — o GenOffice lista os agentes de programação que encontra neste computador e grava o skill em cada um que você escolher. Ou baixe o skill como zip, ou execute npx skills add genspark-ai/genoffice. Os comandos e o fluxo de trabalho completo estão em Linha de comando e skill de agente.
    + ## Por que o GenOffice - **Código aberto**, Apache-2.0, desenvolvido abertamente no GitHub. @@ -177,6 +204,9 @@ tokens. digitalizações. - **Markdown e HTML também**, com o mesmo painel de IA e exportação local para Word. +- **Automatizável.** Uma linha de comando `genoffice` e um skill de agente + colocam todos os mecanismos a serviço do Claude Code, Codex, Cursor e outros + agentes de programação, ainda no dispositivo. - **Gratuito**, para indivíduos e equipes. ## Backends de IA @@ -199,6 +229,78 @@ A suíte completa vem com temas claro, escuro e do sistema. Os temas só mudam o que aparece na tela: exportações, impressões e arquivos salvos sempre mantêm as cores originais do documento. + + +## Linha de comando e skill de agente + +Tudo o que os aplicativos fazem com um arquivo, a linha de comando `genoffice` +faz a partir de um terminal: inspecionar, converter, criar, ler e editar +Word, Excel, PowerPoint, PDF, Markdown e HTML com os mesmos mecanismos, sem +interface gráfica. Ela é instalada junto com o GenOffice, não precisa de +runtime próprio e nunca envia um documento para lugar nenhum. Combinada com +o **skill de agente** incluído, ela transforma um agente de programação em um +operário de documentos que produz arquivos reais do Office em vez de +aproximações em Markdown. + +**Funciona com:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode e Windsurf sem configuração, e com qualquer outro agente que leia +skills. + +### Instalar o skill + +| Como | O que acontece | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Configurações → Integrações** no app | Lista os agentes encontrados neste computador; um clique grava o skill em cada um que você escolher. Um botão **Atualizar** aparece quando uma versão do GenOffice traz um skill mais novo. | +| **Baixar como zip** na mesma página | O formato que o claude.ai, os aplicativos desktop do Claude e outros assistentes aceitam como skill enviado. | +| `npx skills add genspark-ai/genoffice` | Instala a partir deste repositório em qualquer agente compatível com skills. | + +Depois, abra um novo chat e peça um documento. O skill ensina ao agente +quando recorrer ao `genoffice`, como ler um arquivo antes de editá-lo e como +verificar o próprio trabalho. + +### Início rápido no terminal + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Cada comando imprime um resumo de uma linha, ou um único objeto JSON com +`--json`. As edições são atômicas: uma operação rejeitada deixa o arquivo +intocado e volta com um erro orientado. `genoffice help` lista a superfície +de comandos atual; a referência completa está em +[packages/cli/README.md](../../packages/cli/README.md). + +### O que o agente realmente executa + +A apresentação do Sistema Solar da demo acima levou um único prompt no +Claude Code. Por trás, o agente seguiu o fluxo de trabalho em etapas do skill +e a CLI verificou cada etapa antes de começar a seguinte: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Nenhuma chamada a um modelo acontece dentro do `genoffice`: o agente pensa, a +CLI constrói e verifica, e o resultado abre no GenOffice ou no PowerPoint +como um `.pptx` comum. + ## Download @@ -371,6 +473,19 @@ caixas decoradas) são incorporados como imagens.

    +
    +Posso comandar o GenOffice a partir do Claude Code, Codex, Cursor ou de um script? + +Sim. O GenOffice instala uma linha de comando `genoffice` que executa os +mesmos mecanismos sem interface gráfica: inspecione, converta, crie, leia e +edite documentos a partir de um terminal ou de um script, com saída `--json` +para programas. O skill de agente incluído ensina o Claude Code, Codex, +Cursor, Gemini CLI, GitHub Copilot, OpenCode e Windsurf a usá-la; instale-o +em **Configurações → Integrações**. Veja +[Linha de comando e skill de agente](#command-line-and-agent-skill). + +
    +
    O GenOffice coleta algum dado? diff --git a/docs/i18n/README.ru.md b/docs/i18n/README.ru.md index 9fcb0ef..8d1be6d 100644 --- a/docs/i18n/README.ru.md +++ b/docs/i18n/README.ru.md @@ -23,6 +23,7 @@

    Скачать · + CLI · Сайт · Сообщество · Конфиденциальность @@ -51,6 +52,11 @@ AI-агента рядом с каждым документом — не чат- вообще, либо используйте собственный ключ для Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty или любого совместимого с OpenAI эндпоинта, включая локальные серверы. +- **Скриптуемость и готовность к агентам.** В комплекте с приложением идёт + командная строка `genoffice` и скилл для Claude Code, Codex, Cursor, + Gemini CLI, GitHub Copilot, OpenCode и Windsurf, так что кодинг-агент может + создавать, конвертировать, читать и редактировать настоящие файлы Office на + вашем компьютере, не открывая ни одного окна. **Скачать:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon и Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 и Arm) · @@ -59,9 +65,9 @@ AI-агента рядом с каждым документом — не чат- ## Демонстрация -Шесть приложений, одна AI-панель. Каждый скриншот — это реальное приложение -на macOS, а действия AI запускаются промптом, который вы можете прочитать на -панели. +Шесть приложений, одна AI-панель и командная строка для вашего кодинг-агента. +Каждый скриншот — это реальное приложение на macOS, а действия AI запускаются +промптом, который вы можете прочитать на панели. ### 1 · Docs — открывайте и редактируйте `.docx` с AI, чью работу можно проверить @@ -159,6 +165,26 @@ AI-агента рядом с каждым документом — не чат- +### 7 · CLI — ваш кодинг-агент управляет GenOffice на вашем компьютере + +В GenOffice входит командная строка `genoffice` и агентный скилл. Установите +скилл — и Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode или +Windsurf смогут создавать, конвертировать, читать и редактировать настоящие +файлы Office через те же движки, что и приложения, не открывая ни одного окна. + +GenOffice Slides показывает презентацию о Солнечной системе из восьми слайдов, которую кодинг-агент собрал через командную строку genoffice: титульный слайд на холсте, восемь миниатюр слева и открытая AI-панель + + + + + + + + + + +
    Восемь отрисованных слайдов презентации о Солнечной системе рядом друг с другом: обложка, хронология исследований, четыре ключевых числа, столбчатая диаграмма диаметров планет, каменистые миры против гигантов, заголовная цифра 99,8% для Солнца, сетка четырёх гигантов и выводыGenOffice Settings, страница Integrations: скилл genoffice установлен в Claude Code, рядом с Codex и Cursor — кнопки Install
    Один промпт вашему агенту — «Сделай презентацию о Солнечной системе из восьми слайдов». Агент читает скилл, пишет таблицу стилей, план и по одной спецификации страницы на слайд, генерирует две фотографии через genoffice image и даёт genoffice slides check отклонить всё, что выходит за границы или перекрывается, прежде чем genoffice create соберёт .pptx, а slides render вернёт по одному PNG на слайд для просмотра.Установите один раз, через Настройки → Интеграции — GenOffice перечисляет кодинг-агентов, найденных на этом компьютере, и записывает скилл в каждый выбранный вами. Либо скачайте скилл в виде zip или выполните npx skills add genspark-ai/genoffice. Команды и полный рабочий процесс — в разделе Командная строка и агентный скилл.
    + ## Почему GenOffice - **Открытый исходный код**, Apache-2.0, разрабатывается открыто на GitHub. @@ -178,6 +204,9 @@ AI-агента рядом с каждым документом — не чат- в систему OCR для сканов. - **А также Markdown и HTML**, с той же панелью AI и локальным экспортом в Word. +- **Скриптуемость.** Командная строка `genoffice` и агентный скилл отдают + каждый движок в распоряжение Claude Code, Codex, Cursor и других + кодинг-агентов — по-прежнему на устройстве. - **Бесплатно**, как для отдельных пользователей, так и для команд. ## AI-провайдеры @@ -201,6 +230,77 @@ MiniMax или любой совместимый с OpenAI эндпоинт дл то, что видно на экране: экспорт, печать и сохранённые файлы всегда сохраняют собственные цвета документа. + + +## Командная строка и агентный скилл + +Всё, что приложения умеют делать с файлом, командная строка `genoffice` умеет +делать из терминала: инспектировать, конвертировать, создавать, читать и +редактировать Word, Excel, PowerPoint, PDF, Markdown и HTML на тех же движках, +без графического интерфейса. Она устанавливается вместе с GenOffice, не +требует собственной среды выполнения и никогда никуда не отправляет документы. +В паре со встроенным **агентным скиллом** она превращает кодинг-агента в +работника с документами, который выдаёт настоящие файлы Office вместо +Markdown-приближений. + +**Работает с:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode и Windsurf сразу из коробки, а также с любым другим агентом, который +читает скиллы. + +### Установка скилла + +| Как | Что происходит | +| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Настройки → Интеграции** в приложении | Показывает агентов, найденных на этом компьютере; один клик записывает скилл в каждый выбранный. Когда релиз GenOffice приносит более новый скилл, появляется кнопка **Update**. | +| **Скачать как zip** на той же странице | Формат, который claude.ai, десктопные приложения Claude и другие ассистенты принимают как загружаемый скилл. | +| `npx skills add genspark-ai/genoffice` | Устанавливает скилл из этого репозитория в любой агент, поддерживающий скиллы. | + +Затем начните новый чат и попросите документ. Скилл учит агента, когда +обращаться к `genoffice`, как прочитать файл перед редактированием и как +проверять собственную работу. + +### Быстрый старт из терминала + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +Каждая команда выводит однострочную сводку или один JSON-объект с `--json`. +Правки атомарны: отклонённая операция оставляет файл нетронутым и возвращается +с подсказкой об ошибке. `genoffice help` показывает актуальный набор команд; +полный справочник — в [packages/cli/README.md](../../packages/cli/README.md). + +### Что на самом деле запускает агент + +Презентация о Солнечной системе из демо выше потребовала одного промпта в +Claude Code. За кулисами агент следовал поэтапному процессу из скилла, а CLI +проверял каждый этап, прежде чем начинался следующий: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +Внутри `genoffice` не происходит ни одного вызова модели: агент думает, CLI +собирает и проверяет, а результат открывается в GenOffice или PowerPoint как +обычный `.pptx`. + ## Скачать @@ -375,6 +475,19 @@ Chromium и сводится к настоящим структурам Word: з

    +
    +Могу ли я управлять GenOffice из Claude Code, Codex, Cursor или скрипта? + +Да. GenOffice устанавливает командную строку `genoffice`, которая запускает те +же движки без графического интерфейса: инспектируйте, конвертируйте, +создавайте, читайте и редактируйте документы из терминала или скрипта, с +выводом `--json` для программ. Встроенный агентный скилл учит Claude Code, +Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode и Windsurf пользоваться +ею; установите его в разделе **Настройки → Интеграции**. См. +[Командная строка и агентный скилл](#command-line-and-agent-skill). + +
    +
    Собирает ли GenOffice какие-либо данные? diff --git a/docs/i18n/README.th.md b/docs/i18n/README.th.md index 96ab736..06eb02b 100644 --- a/docs/i18n/README.th.md +++ b/docs/i18n/README.th.md @@ -23,6 +23,7 @@

    ดาวน์โหลด · + CLI · เว็บไซต์ · คอมมูนิตี้ · ความเป็นส่วนตัว @@ -49,6 +50,10 @@ Windows และ Linux เปิดและบันทึกไฟล์ `.do Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, Requesty หรือ endpoint ที่รองรับ OpenAI-compatible ใดๆ รวมถึงเซิร์ฟเวอร์โมเดลภายในเครื่องด้วย +- **เขียนสคริปต์ได้และพร้อมสำหรับเอเจนต์** แอปมาพร้อมบรรทัดคำสั่ง `genoffice` + และสกิลสำหรับ Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, + OpenCode และ Windsurf ทำให้เอเจนต์เขียนโค้ดสามารถสร้าง แปลง อ่าน + และแก้ไขไฟล์ Office จริงบนเครื่องของคุณได้โดยไม่ต้องเปิดหน้าต่างใดๆ **ดาวน์โหลด:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest) (Apple Silicon และ Intel) · [Windows](https://github.com/genspark-ai/genoffice/releases/latest) (x64 และ Arm) · @@ -57,8 +62,8 @@ Windows และ Linux เปิดและบันทึกไฟล์ `.do ## เดโม -หกแอป แผง AI เดียว ทุกภาพหน้าจอคือแอปจริงที่รันบน macOS -โดย AI ถูกสั่งงานจากพรอมป์ที่คุณอ่านได้ในแผง +หกแอป แผง AI เดียว และบรรทัดคำสั่งสำหรับเอเจนต์เขียนโค้ดของคุณ +ทุกภาพหน้าจอคือแอปจริงที่รันบน macOS โดย AI ถูกสั่งงานจากพรอมป์ที่คุณอ่านได้ในแผง ### 1 · Docs — เปิดและแก้ไข `.docx` ด้วย AI ที่ตรวจสอบได้ @@ -156,6 +161,26 @@ Windows และ Linux เปิดและบันทึกไฟล์ `.do +### 7 · CLI — เอเจนต์เขียนโค้ดของคุณสั่งงาน GenOffice บนเครื่องของคุณ + +GenOffice มาพร้อมบรรทัดคำสั่ง `genoffice` และสกิลสำหรับเอเจนต์ ติดตั้งสกิลแล้ว +Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode หรือ Windsurf +ก็สร้าง แปลง อ่าน และแก้ไขไฟล์ Office จริงผ่านเอนจินเดียวกับตัวแอปได้ +โดยไม่ต้องเปิดหน้าต่างใดๆ + +GenOffice Slides แสดงเดคเรื่องระบบสุริยะ 8 สไลด์ที่เอเจนต์เขียนโค้ดสร้างผ่านบรรทัดคำสั่ง genoffice: สไลด์หน้าปกบนแคนวาส ภาพย่อ 8 ภาพทางซ้าย และแผง AI ที่เปิดอยู่ + + + + + + + + + + +
    สไลด์ที่เรนเดอร์แล้วทั้ง 8 แผ่นของเดคระบบสุริยะเรียงเคียงกัน: หน้าปก ไทม์ไลน์การสำรวจ ตัวเลขสำคัญ 4 ตัว กราฟแท่งเส้นผ่านศูนย์กลางดาวเคราะห์ ดาวเคราะห์หินเทียบกับดาวยักษ์ ตัวเลขเด่น 99.8% ของดวงอาทิตย์ กริดดาวยักษ์ทั้ง 4 และบทสรุปGenOffice Settings หน้า Integrations: สกิล genoffice ติดตั้งใน Claude Code แล้ว พร้อมปุ่ม Install ข้าง Codex และ Cursor
    พรอมป์เดียวถึงเอเจนต์ของคุณ — "สร้างเดค 8 สไลด์เกี่ยวกับระบบสุริยะ" เอเจนต์อ่านสกิล เขียนสไตล์ชีต โครงร่าง และสเปกหน้าหนึ่งชุดต่อสไลด์ สร้างภาพถ่ายสองภาพด้วย genoffice image และให้ genoffice slides check ปฏิเสธทุกอย่างที่ล้นหรือซ้อนทับกันก่อนที่ genoffice create จะประกอบ .pptx และ slides render ส่ง PNG กลับมาให้ดูหนึ่งภาพต่อสไลด์ติดตั้งครั้งเดียวจาก การตั้งค่า → การเชื่อมต่อ — GenOffice แสดงรายการเอเจนต์เขียนโค้ดที่พบในคอมพิวเตอร์เครื่องนี้และเขียนสกิลลงในแต่ละตัวที่คุณเลือก หรือดาวน์โหลดสกิลเป็น zip หรือรัน npx skills add genspark-ai/genoffice คำสั่งและเวิร์กโฟลว์ฉบับเต็มอยู่ใน บรรทัดคำสั่งและสกิลสำหรับเอเจนต์
    + ## ทำไมต้อง GenOffice - **โอเพนซอร์ส** Apache-2.0 พัฒนาแบบเปิดบน GitHub @@ -171,6 +196,9 @@ Windows และ Linux เปิดและบันทึกไฟล์ `.do - **PDF ที่ทำได้อย่างถูกต้อง** แก้ไขข้อความในตำแหน่งเดิมบนหน้า และแปลง PDF เป็น Word, Excel หรือ PowerPoint ในเครื่อง พร้อม OCR ของระบบสำหรับไฟล์สแกน - **Markdown และ HTML ด้วย** ใช้แผง AI ตัวเดียวกันและส่งออกไปยัง Word ในเครื่อง +- **เขียนสคริปต์ได้** บรรทัดคำสั่ง `genoffice` และสกิลสำหรับเอเจนต์นำทุกเอนจิน + มารับใช้ Claude Code, Codex, Cursor และเอเจนต์เขียนโค้ดอื่นๆ โดยยังคงทำงาน + ในเครื่อง - **ฟรี** สำหรับบุคคลทั่วไปและทีมเช่นเดียวกัน ## แบ็กเอนด์ AI @@ -193,6 +221,73 @@ endpoint ที่รองรับ OpenAI-compatible ใดๆ สำหรั บนหน้าจอเท่านั้น: การส่งออก การพิมพ์ และไฟล์ที่บันทึกจะคงสีของเอกสาร เดิมไว้เสมอ + + +## บรรทัดคำสั่งและสกิลสำหรับเอเจนต์ + +ทุกอย่างที่แอปทำกับไฟล์ได้ บรรทัดคำสั่ง `genoffice` ก็ทำได้จากเทอร์มินัล: +ตรวจสอบ แปลง สร้าง อ่าน และแก้ไข Word, Excel, PowerPoint, PDF, Markdown +และ HTML บนเอนจินเดียวกันแบบ headless มันติดตั้งมาพร้อม GenOffice +ไม่ต้องการรันไทม์ของตัวเอง และไม่เคยส่งเอกสารไปที่ใดเลย เมื่อจับคู่กับ +**สกิลสำหรับเอเจนต์** ที่รวมมาให้ มันเปลี่ยนเอเจนต์เขียนโค้ดให้เป็นผู้ทำงาน +เอกสารที่ผลิตไฟล์ Office จริง ไม่ใช่ของเทียบเคียงในรูป Markdown + +**ใช้งานได้กับ:** Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, +OpenCode และ Windsurf ได้ทันทีโดยไม่ต้องตั้งค่าเพิ่ม รวมถึงเอเจนต์อื่นใดที่อ่านสกิลได้ + +### ติดตั้งสกิล + +| วิธี | สิ่งที่เกิดขึ้น | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **การตั้งค่า → การเชื่อมต่อ** ในแอป | แสดงรายการเอเจนต์ที่พบในคอมพิวเตอร์เครื่องนี้ คลิกเดียวเขียนสกิลลงในแต่ละตัวที่คุณเลือก ปุ่ม **Update** จะปรากฏเมื่อรีลีสของ GenOffice มาพร้อมสกิลเวอร์ชันใหม่กว่า | +| **ดาวน์โหลดเป็น zip** ในหน้าเดียวกัน | โครงสร้างที่ claude.ai แอปเดสก์ท็อป Claude และผู้ช่วยอื่นๆ ยอมรับเป็นสกิลที่อัปโหลด | +| `npx skills add genspark-ai/genoffice` | ติดตั้งจาก repository นี้ลงในเอเจนต์ใดก็ได้ที่รองรับสกิล | + +จากนั้นเริ่มแชทใหม่แล้วขอเอกสารสักฉบับ สกิลจะสอนเอเจนต์ว่าเมื่อใดควรใช้ +`genoffice` วิธีอ่านไฟล์ก่อนแก้ไข และวิธีตรวจสอบงานของตัวเอง + +### เริ่มต้นอย่างรวดเร็วจากเทอร์มินัล + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +ทุกคำสั่งพิมพ์สรุปหนึ่งบรรทัด หรือออบเจ็กต์ JSON เดียวเมื่อใช้ `--json` +การแก้ไขเป็นแบบอะตอมิก: op ที่ถูกปฏิเสธจะไม่แตะไฟล์เลยและส่งกลับพร้อม +ข้อความแนะนำวิธีแก้ `genoffice help` แสดงรายการคำสั่งทั้งหมดในปัจจุบัน +เอกสารอ้างอิงฉบับเต็มอยู่ที่ [packages/cli/README.md](../../packages/cli/README.md) + +### สิ่งที่เอเจนต์รันจริงๆ + +เดคระบบสุริยะในเดโมด้านบนใช้พรอมป์เพียงครั้งเดียวใน Claude Code เบื้องหลังนั้น +เอเจนต์ทำตามเวิร์กโฟลว์เป็นขั้นตอนของสกิล และ CLI ตรวจสอบทุกขั้นตอน +ก่อนที่ขั้นตอนถัดไปจะเริ่ม: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +ไม่มีการเรียกโมเดลเกิดขึ้นภายใน `genoffice`: เอเจนต์เป็นฝ่ายคิด CLI +เป็นฝ่ายสร้างและตรวจสอบ และผลลัพธ์เปิดใน GenOffice หรือ PowerPoint +เป็นไฟล์ `.pptx` ธรรมดา + ## ดาวน์โหลด @@ -358,6 +453,18 @@ Word จริง: หัวเรื่อง พารากราฟ รา

    +
    +สั่งงาน GenOffice จาก Claude Code, Codex, Cursor หรือสคริปต์ได้หรือไม่ + +ได้ GenOffice ติดตั้งบรรทัดคำสั่ง `genoffice` ที่รันเอนจินเดียวกันแบบ headless: +ตรวจสอบ แปลง สร้าง อ่าน และแก้ไขเอกสารจากเทอร์มินัลหรือสคริปต์ พร้อมเอาต์พุต +`--json` สำหรับโปรแกรม สกิลสำหรับเอเจนต์ที่รวมมาให้สอน Claude Code, Codex, +Cursor, Gemini CLI, GitHub Copilot, OpenCode และ Windsurf ให้ใช้งานมัน +ติดตั้งได้จาก **การตั้งค่า → การเชื่อมต่อ** ดู +[บรรทัดคำสั่งและสกิลสำหรับเอเจนต์](#command-line-and-agent-skill) + +
    +
    GenOffice เก็บข้อมูลอะไรบ้างหรือไม่ diff --git a/docs/i18n/README.zh-CN.md b/docs/i18n/README.zh-CN.md index cd957ac..ac3d139 100644 --- a/docs/i18n/README.zh-CN.md +++ b/docs/i18n/README.zh-CN.md @@ -23,6 +23,7 @@ Word、Excel、PowerPoint 和 PDF 文件,由你与你的 AI 共同编辑,并

    下载 · + CLI · 官网 · 社区 · 隐私 @@ -44,6 +45,10 @@ PDF、Markdown 和 HTML,并在每份文档旁边配备一个 AI 智能体 — - **用自己的密钥,或者不用密钥。** 登录 Genspark 即可免配置使用;也可以自带 Claude、OpenAI、Gemini、DeepSeek、Kimi、GLM、Qwen、Doubao、MiniMax、Grok、 Mistral、OpenRouter、Requesty 的密钥,或任何 OpenAI 兼容端点,包括本地模型服务。 +- **可脚本化,随时可供智能体调用。** 应用自带 `genoffice` 命令行和一份面向 + Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode 和 Windsurf + 的 agent skill,让编程智能体无需打开任何窗口,就能在你的电脑上创建、转换、 + 读取和编辑真正的 Office 文件。 **获取:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest)(Apple Silicon 和 Intel)· [Windows](https://github.com/genspark-ai/genoffice/releases/latest)(x64 和 Arm)· @@ -52,8 +57,8 @@ PDF、Markdown 和 HTML,并在每份文档旁边配备一个 AI 智能体 — ## 演示 -六个应用,一个 AI 面板。每张截图都是 macOS 上的真实应用,AI 的操作均由面板中 -可见的提示词驱动。 +六个应用,一个 AI 面板,再加一条供编程智能体使用的命令行。每张截图都是 macOS +上的真实应用,AI 的操作均由面板中可见的提示词驱动。 ### 1 · Docs —— 打开并编辑 `.docx`,AI 改动可审阅 @@ -150,6 +155,26 @@ PDF、Markdown 和 HTML,并在每份文档旁边配备一个 AI 智能体 — +### 7 · CLI —— 让你的编程智能体在本机驱动 GenOffice + +GenOffice 自带 `genoffice` 命令行和一份 agent skill。安装这份 skill 之后, +Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode 或 Windsurf +就能通过与应用相同的引擎创建、转换、读取和编辑真正的 Office 文件,无需打开 +任何窗口。 + +GenOffice Slides 中显示一份由编程智能体通过 genoffice 命令行制作的八页太阳系演示文稿:画布上是封面页,左侧是八张缩略图,AI 面板处于打开状态 + + + + + + + + + + +
    太阳系演示文稿渲染出的八页幻灯片并排展示:封面、探索时间线、四个关键数字、行星直径柱状图、岩质行星与巨行星对比、太阳占 99.8% 的主视觉数字、四大巨行星网格和要点总结GenOffice 设置的「集成」页面:genoffice skill 已安装到 Claude Code,Codex 和 Cursor 旁边显示着「安装」按钮
    给智能体一句提示词 —— “制作一份关于太阳系的八页演示文稿。”智能体读取 skill,依次写出样式表、大纲和每页一份的页面规格,用 genoffice image 生成两张图片,再由 genoffice slides check 拦下所有溢出或重叠的内容,最后由 genoffice create 组装出 .pptx,并用 slides render 为每一页交回一张 PNG 供查看。在设置 → 集成中一次安装 —— GenOffice 会列出在这台电脑上找到的编程智能体,并把 skill 写入你选中的每一个。也可以把 skill 下载为 zip 压缩包,或运行 npx skills add genspark-ai/genoffice。命令和完整工作流见命令行与 agent skill。
    + ## 为什么选择 GenOffice - **开源**,Apache-2.0 协议,在 GitHub 上公开开发。 @@ -164,6 +189,8 @@ PDF、Markdown 和 HTML,并在每份文档旁边配备一个 AI 智能体 — - **认真做好 PDF。** 在页面内直接编辑文字,本机将 PDF 转换为 Word、Excel 或 PowerPoint,扫描件支持系统 OCR。 - **同样支持 Markdown 和 HTML**,共用同一个 AI 面板,并可本机导出为 Word。 +- **可脚本化。** `genoffice` 命令行和 agent skill 让每一个引擎都能为 Claude Code、 + Codex、Cursor 及其他编程智能体所用,且仍然在本机运行。 - **免费**,个人和团队皆可使用。 ## AI 后端 @@ -182,6 +209,70 @@ Grok、Qwen、MiniMax 或任何 OpenAI 兼容的图片端点。 整个套件提供浅色、深色和跟随系统三种主题。主题只改变屏幕上的显示:导出、打印 和保存的文件始终保留文档自身的颜色。 + + +## 命令行与 agent skill + +应用能对文件做的一切,`genoffice` 命令行都能在终端里完成:检查、转换、创建、 +读取和编辑 Word、Excel、PowerPoint、PDF、Markdown 和 HTML,用的是同一套引擎, +无需界面。它随 GenOffice 一起安装,不需要自己的运行时,也绝不会把文档发送到 +任何地方。配合内置的 **agent skill**,它能把编程智能体变成一名文档工作者, +产出真正的 Office 文件,而不是用 Markdown 勉强凑合。 + +**支持:** Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode +和 Windsurf 开箱即用,以及任何其他能读取 skill 的智能体。 + +### 安装 skill + +| 方式 | 效果 | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| 应用内的 **设置 → 集成** | 列出在这台电脑上找到的智能体;一键即可把 skill 写入你选中的每一个。当 GenOffice 新版本附带更新的 skill 时,会出现**更新**按钮。 | +| 同一页面上的 **下载为 zip** | claude.ai、Claude 桌面应用及其他助手可作为上传 skill 接受的目录结构。 | +| `npx skills add genspark-ai/genoffice` | 从本仓库安装到任何兼容 skills 的智能体。 | + +然后开启一个新对话,让它帮你做一份文档。这份 skill 会教智能体何时该用 +`genoffice`、编辑前如何先读取文件,以及如何检查自己的成果。 + +### 从终端快速上手 + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +每条命令都会打印一行摘要,加上 `--json` 则输出单个 JSON 对象。编辑是原子性的: +被拒绝的操作不会改动文件,并会返回带有指引的错误信息。`genoffice help` 列出 +当前的命令集合;完整参考见 [packages/cli/README.md](../../packages/cli/README.md)。 + +### 智能体实际执行了什么 + +上方演示中的太阳系演示文稿,在 Claude Code 里只用了一句提示词。在它背后, +智能体按照 skill 的分阶段工作流推进,而 CLI 在每个阶段开始下一步之前都会先做 +检查: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +`genoffice` 内部不会发起任何模型调用:思考由智能体负责,构建和检查由 CLI +负责,最后的成果会以一份普通的 `.pptx` 在 GenOffice 或 PowerPoint 中打开。 + ## 下载 @@ -337,6 +428,17 @@ OpenCode Zen/Go 的密钥,以及任何 OpenAI 兼容端点 —— 包括本地

    +
    +我可以从 Claude Code、Codex、Cursor 或脚本中驱动 GenOffice 吗? + +可以。GenOffice 会安装一个 `genoffice` 命令行,以无界面方式运行同一套引擎: +在终端或脚本中检查、转换、创建、读取和编辑文档,并可通过 `--json` 输出供程序 +使用。内置的 agent skill 会教 Claude Code、Codex、Cursor、Gemini CLI、GitHub +Copilot、OpenCode 和 Windsurf 使用它;请在 **设置 → 集成** 中安装。详见 +[命令行与 agent skill](#command-line-and-agent-skill)。 + +
    +
    GenOffice 会收集数据吗? diff --git a/docs/i18n/README.zh-TW.md b/docs/i18n/README.zh-TW.md index 182e112..3981ccd 100644 --- a/docs/i18n/README.zh-TW.md +++ b/docs/i18n/README.zh-TW.md @@ -23,6 +23,7 @@ Word、Excel、PowerPoint 與 PDF 檔案,由你與你的 AI 共同編輯,並

    下載 · + CLI · 官網 · 社群 · 隱私權 @@ -46,6 +47,10 @@ Windows 與 Linux。它能開啟並儲存原生的 `.docx`、`.xlsx` 與 `.pptx` 或自行帶入 Claude、OpenAI、Gemini、DeepSeek、Kimi、GLM、Qwen、 Doubao、MiniMax、Grok、Mistral、OpenRouter、Requesty,或任何相容 OpenAI 介面 的服務端點,也支援本機伺服器。 +- **可寫成腳本,也隨時能交給代理。** 應用程式內建 `genoffice` 命令列, + 並附上一份給 Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、 + OpenCode 與 Windsurf 使用的 agent skill,讓程式開發代理不必開啟任何 + 視窗,就能在你的裝置上建立、轉換、讀取與編輯真正的 Office 檔案。 **立即取得:** [macOS](https://github.com/genspark-ai/genoffice/releases/latest)(Apple Silicon 與 Intel)· [Windows](https://github.com/genspark-ai/genoffice/releases/latest)(x64 與 Arm)· @@ -54,8 +59,9 @@ Windows 與 Linux。它能開啟並儲存原生的 `.docx`、`.xlsx` 與 `.pptx` ## Demo -六款應用程式,一個 AI 面板。每張截圖都是在 macOS 上實際操作的真實畫面, -AI 的動作皆由面板中可見的提示詞驅動。 +六款應用程式,一個 AI 面板,再加上一套給程式開發代理使用的命令列。 +每張截圖都是在 macOS 上實際操作的真實畫面,AI 的動作皆由面板中可見的 +提示詞驅動。 ### 1 · Docs — 開啟並編輯 `.docx`,每一步 AI 編輯都能檢視 @@ -182,6 +188,34 @@ GenOffice 會規劃敘事脈絡、研究相關數據,並把每一頁直接生 +### 7 · CLI — 讓你的程式開發代理在本機驅動 GenOffice + +GenOffice 內建 `genoffice` 命令列與一份 agent skill。安裝這份 skill 之後, +Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode 或 Windsurf +就能透過與應用程式相同的引擎,建立、轉換、讀取與編輯真正的 Office 檔案, +完全不必開啟視窗。 + +GenOffice Slides 顯示一份由程式開發代理透過 genoffice 命令列建立的八頁太陽系簡報:畫布上是封面投影片,左側有八張縮圖,AI 面板處於開啟狀態 + + + + + + + + + + +
    太陽系簡報渲染出的八張投影片並排呈現:封面、探索時間線、四個關鍵數字、行星直徑長條圖、岩質行星與巨行星的對比、太陽佔 99.8% 的主視覺數字、四大巨行星的格狀排列與重點整理GenOffice 設定的「整合」頁面:genoffice skill 已安裝到 Claude Code,Codex 與 Cursor 旁邊顯示著「安裝」按鈕
    對代理下一句提示詞——「做一份關於太陽系的八頁簡報。」代理讀取 skill, +寫出一份樣式表、一份大綱與每張投影片各一份的頁面規格,用 +genoffice image 生成兩張照片,再讓 genoffice slides check +擋下所有溢出或重疊的內容,最後由 genoffice create 組裝出 +.pptx,並以 slides render 交回每張投影片各一張 PNG +供你檢視。在設定 → 整合中一次安裝——GenOffice 會列出在這台電腦上找到的 +程式開發代理,並把 skill 寫入你勾選的每一個。也可以把 skill 下載成 zip +壓縮檔,或執行 npx skills add genspark-ai/genoffice。命令與完整 +工作流程請見命令列與 agent skill。
    + ## 為什麼選 GenOffice - **開源**,採用 Apache-2.0 授權,在 GitHub 上公開開發。 @@ -196,6 +230,8 @@ GenOffice 會規劃敘事脈絡、研究相關數據,並把每一頁直接生 - **認真做好 PDF。** 直接在頁面內編輯文字,並在本機將 PDF 轉換為 Word、Excel 或 PowerPoint,掃描檔案支援系統 OCR。 - **同樣支援 Markdown 與 HTML**,共用同一套 AI 面板,並可在本機匯出為 Word。 +- **可寫成腳本。** `genoffice` 命令列與 agent skill 讓每一個引擎都能供 Claude Code、 + Codex、Cursor 及其他程式開發代理使用,而且依然在本機執行。 - **免費**,個人與團隊皆可使用。 ## AI 後端 @@ -215,6 +251,72 @@ Grok、Qwen、MiniMax,或任何相容 OpenAI 的圖片服務端點。 整套軟體支援亮色、深色與跟隨系統三種主題。主題只會改變畫面顯示: 匯出、列印與儲存的檔案永遠保留文件本身的原始色彩。 + + +## 命令列與 agent skill + +應用程式能對檔案做的每一件事,`genoffice` 命令列都能在終端機裡完成: +檢視、轉換、建立、讀取與編輯 Word、Excel、PowerPoint、PDF、Markdown 與 +HTML,用的是同一套引擎,且無需介面。它隨 GenOffice 一起安裝,不需要 +自己的執行環境,也絕不會把文件送到任何地方。搭配內建的 **agent skill**, +它能把程式開發代理變成一位文件工作者,產出真正的 Office 檔案,而不是 +用 Markdown 勉強充數。 + +**支援:** Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、OpenCode +與 Windsurf 開箱即用,以及任何其他能讀取 skill 的代理。 + +### 安裝 skill + +| 方式 | 效果 | +| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| 應用程式內的 **設定 → 整合** | 列出在這台電腦上找到的代理;按一下就把 skill 寫入你選擇的每一個。當 GenOffice 新版本附帶更新的 skill 時,會出現**更新**按鈕。 | +| 同一頁面上的 **下載為 zip** | claude.ai、Claude 桌面版應用程式與其他助理可作為上傳 skill 接受的目錄結構。 | +| `npx skills add genspark-ai/genoffice` | 從本儲存庫安裝到任何相容 skills 的代理。 | + +接著開一個新的對話,請它幫你做一份文件。這份 skill 會教代理何時該使用 +`genoffice`、編輯前如何先讀取檔案,以及如何檢查自己的成果。 + +### 從終端機快速上手 + +```bash +genoffice --version +genoffice info report.docx --json # headings and blocks; or sheets, slides, pages +genoffice convert report.md --to pdf # md/html/docx/xlsx/pptx → pdf, pdf → docx/xlsx/pptx, … +genoffice create --type docx --from notes.md --out notes.docx +genoffice create --type xlsx --from table.json --out sales.xlsx # "=SUM(B2:B9)" cells stay live formulas +genoffice docs read report.docx --range 0-9 --json # then `docs apply --ops edits.json` edits in place +genoffice render report.docx --out shots/ # one PNG per page, to look at what you made +genoffice open sales.xlsx # hand the result to the editor +``` + +每個命令都會印出一行摘要,加上 `--json` 則輸出單一 JSON 物件。編輯是 +原子性的:被拒絕的操作不會動到檔案,並會回傳附有指引的錯誤訊息。 +`genoffice help` 列出目前的命令集合;完整參考請見 +[packages/cli/README.md](../../packages/cli/README.md)。 + +### 代理實際執行了什麼 + +上方 Demo 中的太陽系簡報,在 Claude Code 裡只用了一句提示詞。在它背後, +代理依照 skill 的分階段工作流程逐步進行,而 CLI 會在每個階段開始下一步 +之前先做檢查: + +```bash +genoffice capabilities --json # which cloud tools GenOffice has configured +genoffice guide slides design # the deck workflow and layout library +genoffice image "the eight planets in a row …" --aspect 16:9 --out deck/assets/cover.jpg +genoffice slides check deck/outline.json --json # 8 pages, no findings +genoffice slides check deck/pages/01.json --json # builds one slide, audits overflow and overlap +… # one page file per slide, fixed until each check is clean +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck/solar-system.pptx --json +genoffice slides render deck/solar-system.pptx --out deck/shots --json +genoffice slides audit deck/solar-system.pptx --json # 8 slides, no layout issues +genoffice slides replace deck/solar-system.pptx --slide 4 --spec deck/pages/05.json --json +genoffice open deck/solar-system.pptx +``` + +`genoffice` 內部不會發出任何模型呼叫:思考由代理負責,建置與檢查由 CLI +負責,成品則以一份普通的 `.pptx` 在 GenOffice 或 PowerPoint 中開啟。 + ## 下載 @@ -377,6 +479,17 @@ Word 結構:標題、段落、清單、表格、卡片、KPI 列、表單欄

    +
    +我可以從 Claude Code、Codex、Cursor 或指令碼驅動 GenOffice 嗎? + +可以。GenOffice 會安裝一個 `genoffice` 命令列,以無介面的方式執行同一套 +引擎:在終端機或指令碼中檢視、轉換、建立、讀取與編輯文件,並提供 +`--json` 輸出供程式使用。內建的 agent skill 會教 Claude Code、Codex、Cursor、 +Gemini CLI、GitHub Copilot、OpenCode 與 Windsurf 使用它;請在 **設定 → 整合** +中安裝。詳見[命令列與 agent skill](#command-line-and-agent-skill)。 + +
    +
    GenOffice 會收集任何資料嗎? diff --git a/e2e/assets/justify-pagegap-fr.docx b/e2e/assets/justify-pagegap-fr.docx new file mode 100644 index 0000000..c75f0d3 Binary files /dev/null and b/e2e/assets/justify-pagegap-fr.docx differ diff --git a/e2e/docs-justify-pagegap.spec.ts b/e2e/docs-justify-pagegap.spec.ts new file mode 100644 index 0000000..cb80544 --- /dev/null +++ b/e2e/docs-justify-pagegap.spec.ts @@ -0,0 +1,114 @@ +/** + * A justified paragraph straddling a page boundary must not render its + * page-last line stretched sparse (r177): the inline page-gap + * widget forces the line break at the paginator's cut position, and when + * justify-shrink decorations later move the natural wrap points without a doc + * change, a stale cut leaves a short line that text-align:justify blows up + * with huge word gaps until the user edits at the boundary. + * + * The fixture is compatibilityMode-15 justified French text (space-shrink + * active). Each round edits the FIRST paragraph — shifting every downstream + * wrap point and forcing shrink re-decisions — then asserts that on every + * page-crossing line the largest word gap stays within a few natural space + * widths. + */ +import { test, expect } from '@playwright/test' +import { join } from 'node:path' +import type { Page } from '@playwright/test' +import { launchShell, closeAndSaveVideo, waitForPageWithUrl } from './helpers' + +const FIXTURE = join(__dirname, 'assets/justify-pagegap-fr.docx') + +/** per inline page gap: word count and max word-gap of the line right above + * the widget, as a multiple of the natural space advance */ +async function sparseReport(editor: Page): Promise> { + return editor.evaluate(() => { + const out: Array<{ words: number; ratio: number }> = [] + const canvas = document.createElement('canvas').getContext('2d')! + for (const gap of Array.from(document.querySelectorAll('.page-gap-inline'))) { + const para = gap.closest('p') ?? gap.parentElement + if (!para || gap.closest('table')) continue + const cs = getComputedStyle(para) + canvas.font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}` + const spaceW = canvas.measureText(' ').width + const gapTop = gap.getBoundingClientRect().top + const walker = document.createTreeWalker(para, NodeFilter.SHOW_TEXT) + const boxes: Array<{ l: number; r: number; t: number; b: number }> = [] + let tn: Node | null + while ((tn = walker.nextNode())) { + if (!(gap.compareDocumentPosition(tn) & Node.DOCUMENT_POSITION_PRECEDING)) continue + const text = tn.textContent ?? '' + const re = /[^ ]+/g + let m: RegExpExecArray | null + while ((m = re.exec(text))) { + const r = document.createRange() + r.setStart(tn, m.index) + r.setEnd(tn, m.index + m[0].length) + for (const rect of Array.from(r.getClientRects())) { + if (rect.width > 0.01) + boxes.push({ l: rect.left, r: rect.right, t: rect.top, b: rect.bottom }) + } + } + } + const above = boxes.filter((b) => b.b <= gapTop + 1) + if (above.length === 0) continue + const lowest = above.reduce((a, b) => (b.b > a.b ? b : a)) + const line = above + .filter((b) => b.t < lowest.b - 1 && b.b > lowest.t + 1) + .sort((a, b) => a.l - b.l) + let maxGap = 0 + for (let i = 1; i < line.length; i++) maxGap = Math.max(maxGap, line[i].l - line[i - 1].r) + const zoom = + para instanceof HTMLElement ? para.getBoundingClientRect().width / para.offsetWidth || 1 : 1 + out.push({ words: line.length, ratio: maxGap / zoom / spaceW }) + } + return out + }) +} + +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)) + +test('page-crossing justified lines keep natural word gaps across reflows', async () => { + test.setTimeout(150_000) + const launched = await launchShell({ + onboardingSeen: true, + videoDir: 'justify-pagegap', + openFile: FIXTURE, + }) + const { app } = launched + try { + const editor = await waitForPageWithUrl(app, '://docs/') + await editor.locator('.doc-page .page-gap-inline').first().waitFor({ timeout: 30000 }) + await wait(2500) // pagination + shrink settle + + const baseline = await sparseReport(editor) + expect(baseline.length).toBeGreaterThan(0) // fixture must actually cross pages mid-paragraph + for (const g of baseline) expect(g.ratio).toBeLessThan(3) + + // grow the first paragraph by a full line+ each round: every downstream + // block moves, the page boundary lands in new lines/paragraphs and the + // shrink extension re-decides around each fresh cut (cumulative growth, + // no deletes — per-keystroke Delete rounds blew the CI time budget) + const sentence = + 'Zut alors vraiment ce paragraphe grandit encore un peu plus pour pousser toutes les lignes vers le bas maintenant ' + for (let round = 1; round <= 6; round++) { + await editor.evaluate(() => + document.querySelector('.ProseMirror p')?.scrollIntoView({ block: 'center' }), + ) + await editor + .locator('.ProseMirror p') + .first() + .click({ position: { x: 8, y: 8 } }) + await editor.keyboard.press('Home') + await editor.keyboard.type(sentence, { delay: 2 }) + await wait(1500) // > pagination debounce + shrink RAF rounds + const report = await sparseReport(editor) + expect(report.length, `round ${round}: mid-paragraph cuts vanished`).toBeGreaterThan(0) + for (const g of report) { + expect(g.ratio, `round ${round}: sparse page-last line (${g.words} words)`).toBeLessThan(3) + } + } + } finally { + await closeAndSaveVideo(launched, 'justify-pagegap') + } +}) diff --git a/e2e/docs-paste-options.spec.ts b/e2e/docs-paste-options.spec.ts new file mode 100644 index 0000000..7910107 --- /dev/null +++ b/e2e/docs-paste-options.spec.ts @@ -0,0 +1,156 @@ +import { test, expect } from '@playwright/test' +import { launchShell, closeAndSaveVideo, waitForPageWithUrl } from './helpers' + +/** + * Post-paste "Paste options" chip (Word parity): after pasting foreign web + * HTML the chip appears at the paste point and re-applies the same payload + * in the chosen mode — + * - Merge Formatting: emphasis stays, text formats like typing (caret font); + * - Keep Text Only: plain text, caret font; + * - Keep Source Formatting: the site's concrete font again; + * "Always use this choice" persists the mode for the next paste. + */ + +interface AidocsWindow { + __aidocs?: { editor?: unknown } +} + +const WEB_TWO_PARAS = + `` + + `

    web one strong

    ` + + `

    web two

    ` +const WEB_TEXT = 'web one strong\n\nweb two' + +test.describe('docs paste options chip', () => { + test('chip re-applies merge/text/source modes and remembers the default', async () => { + test.setTimeout(120_000) + const launched = await launchShell({ onboardingSeen: true, videoDir: 'docs-paste-options' }) + const { app, page } = launched + try { + await expect(page.locator('.quick-card').first()).toContainText('AI Docs') + await page.locator('.quick-card').first().click() + const editorPage = await waitForPageWithUrl(app, '://docs/') + await editorPage.waitForFunction( + () => Boolean((window as unknown as AidocsWindow).__aidocs?.editor), + undefined, + { timeout: 30_000 }, + ) + await editorPage.locator('.doc-page').click() + await editorPage.keyboard.type('avant', { delay: 10 }) + await editorPage.evaluate(() => { + const ed = (window as unknown as AidocsWindow).__aidocs!.editor! as { + chain: () => { + selectAll: () => { + setMark: (name: string, attrs: Record) => { run: () => void } + } + } + state: { doc: { content: { size: number } } } + commands: { setTextSelection: (pos: number) => void } + } + ed.chain() + .selectAll() + .setMark('docTextStyle', { font: 'Calibri', fontAscii: 'Calibri' }) + .run() + ed.commands.setTextSelection(ed.state.doc.content.size - 1) + }) + + const runs = async (): Promise> => + editorPage.evaluate(() => { + const ed = (window as unknown as AidocsWindow).__aidocs!.editor! as { + state: { + doc: { + descendants: ( + cb: (node: { + isText: boolean + text?: string + marks: Array<{ type: { name: string }; attrs: Record }> + }) => boolean, + ) => void + } + } + } + const out: Array<{ text: string; font: string | null; bold: boolean }> = [] + ed.state.doc.descendants((node) => { + if (node.isText) { + const style = node.marks.find((m) => m.type.name === 'docTextStyle') + out.push({ + text: node.text ?? '', + font: (style?.attrs.font as string | null) ?? null, + bold: node.marks.some((m) => m.type.name === 'bold'), + }) + } + return true + }) + return out + }) + + const paste = async () => { + await app.evaluate( + ({ clipboard }, payload) => { + clipboard.write({ html: payload.html, text: payload.text }) + }, + { html: WEB_TWO_PARAS, text: WEB_TEXT }, + ) + await editorPage.keyboard.press('Control+v') + await editorPage.waitForTimeout(400) + } + + // default = keep source: the site's concrete font, chip appears + await paste() + let state = await runs() + expect(state.find((r) => r.text.includes('web one'))?.font).toBe('Arial') + expect(state.find((r) => r.text === 'strong')?.bold).toBe(true) + const chip = editorPage.locator('[data-testid="paste-options-chip"]') + await expect(chip).toBeVisible() + + // merge formatting: caret font, emphasis kept + await chip.locator('.paste-chip-btn').click() + await chip.getByRole('menuitemradio', { name: 'Merge Formatting' }).click() + await editorPage.waitForTimeout(300) + state = await runs() + expect(state.find((r) => r.text.includes('web one'))?.font).toBe('Calibri') + expect(state.find((r) => r.text.includes('web two'))?.font).toBe('Calibri') + expect(state.find((r) => r.text === 'strong')?.bold).toBe(true) + + // keep text only: plain caret-formatted text, emphasis gone + await chip.locator('.paste-chip-btn').click() + await chip.getByRole('menuitemradio', { name: 'Keep Text Only' }).click() + await editorPage.waitForTimeout(300) + state = await runs() + expect(state.find((r) => r.text.includes('web one'))?.font).toBe('Calibri') + expect(state.some((r) => r.bold)).toBe(false) + + // back to keep source: the concrete site font returns + await chip.locator('.paste-chip-btn').click() + await chip.getByRole('menuitemradio', { name: 'Keep Source Formatting' }).click() + await editorPage.waitForTimeout(300) + state = await runs() + expect(state.find((r) => r.text.includes('web one'))?.font).toBe('Arial') + + // remember merge as the default: the NEXT paste applies it directly + await chip.locator('.paste-chip-btn').click() + await chip.getByRole('menuitemradio', { name: 'Merge Formatting' }).click() + await editorPage.waitForTimeout(200) + await chip.locator('.paste-chip-btn').click() + await chip.locator('.paste-chip-remember input').check() + await editorPage.keyboard.press('Escape') + await editorPage.keyboard.press('Escape') + await expect(chip).toBeHidden() + // focus back in the document before driving the caret + await editorPage.locator('.doc-page').click() + await editorPage.keyboard.press('Control+End') + await editorPage.keyboard.press('Enter') + await paste() + state = await runs() + const second = state.filter((r) => r.text.includes('web two')) + expect(second[second.length - 1]?.font).toBe('Calibri') + + // typing hides the chip + await expect(chip).toBeVisible() + await editorPage.keyboard.type('x') + await expect(chip).toBeHidden() + } finally { + await closeAndSaveVideo(launched) + } + }) +}) diff --git a/e2e/docs-spellcheck-reenable.spec.ts b/e2e/docs-spellcheck-reenable.spec.ts index 4ae3836..563f975 100644 --- a/e2e/docs-spellcheck-reenable.spec.ts +++ b/e2e/docs-spellcheck-reenable.spec.ts @@ -30,7 +30,7 @@ test('re-enabling spellcheck respells existing text without user input', async ( const { app, page } = launched try { await page.locator('.quick-card').first().click() - const editor = await waitForPageWithUrl(app, 'docs/out') + const editor = await waitForPageWithUrl(app, '://docs/') await editor.locator('.doc-page').waitFor() await wait(1500) @@ -73,3 +73,52 @@ test('re-enabling spellcheck respells existing text without user input', async ( await closeAndSaveVideo(launched, 'spellcheck-reenable') } }) + +test('toggling spellcheck never scrolls the view to the caret', async () => { + test.setTimeout(120_000) + const launched = await launchShell({ onboardingSeen: true, videoDir: 'spellcheck-noscroll' }) + const { app } = launched + try { + await launched.page.locator('.quick-card').first().click() + const editor = await waitForPageWithUrl(app, '://docs/') + await editor.locator('.doc-page').waitFor() + await wait(1500) + + // two pages of short lines, caret ends up on the last page + await editor.locator('.doc-page').click() + for (let i = 0; i < 58; i++) { + await editor.keyboard.type(`ligne ${i}`, { delay: 0 }) + await editor.keyboard.press('Enter') + } + await wait(1000) + const pages = await editor.locator('.page-gap-inline, .page-gap').count() + expect(pages).toBeGreaterThan(0) // the caret really sits pages below the top + + // look at the top of the document while the caret stays at the end + const scrollTo = (y: number) => + editor.evaluate((top) => { + const s = document.querySelector('.editor-scroll') + if (s) s.scrollTop = top + return s?.scrollTop ?? -1 + }, y) + await scrollTo(0) + await wait(300) + + const spelling = editor.getByRole('button', { name: 'Spelling' }) + await editor.getByRole('button', { name: 'Review' }).click() + await spelling.waitFor() + const before = await editor.evaluate( + () => document.querySelector('.editor-scroll')?.scrollTop ?? -1, + ) + await spelling.click() // off + await wait(800) + await spelling.click() // on again → respell kick types at the (off-screen) caret + await wait(2500) + const after = await editor.evaluate( + () => document.querySelector('.editor-scroll')?.scrollTop ?? -1, + ) + expect(Math.abs(after - before)).toBeLessThanOrEqual(2) // no jump to the caret's page + } finally { + await closeAndSaveVideo(launched, 'spellcheck-noscroll') + } +}) diff --git a/e2e/docs-table-gap-flicker.spec.ts b/e2e/docs-table-gap-flicker.spec.ts index ab57361..d09cc61 100644 --- a/e2e/docs-table-gap-flicker.spec.ts +++ b/e2e/docs-table-gap-flicker.spec.ts @@ -24,7 +24,7 @@ test.describe('docs table page-gap stability', () => { try { await expect(page.locator('.quick-card').first()).toContainText('AI Docs') await page.locator('.quick-card').first().click() - const editorPage = await waitForPageWithUrl(app, 'docs/out') + const editorPage = await waitForPageWithUrl(app, '://docs/') await editorPage.waitForFunction( () => Boolean((window as unknown as AidocsWindow).__aidocs?.editor), undefined, diff --git a/e2e/docs-visual.spec.ts b/e2e/docs-visual.spec.ts index 0300f39..3fd91b5 100644 --- a/e2e/docs-visual.spec.ts +++ b/e2e/docs-visual.spec.ts @@ -67,7 +67,7 @@ test.describe('docs visual regression', () => { openFile: resolve(FIXTURES_DIR, doc.file), }) try { - const editorPage = await waitForPageWithUrl(launched.app, 'docs/out') + const editorPage = await waitForPageWithUrl(launched.app, '://docs/') // Keep the default width (narrower clamps zoom below 100% via // width-fit), but grow the height until a whole A4 page fits in the // viewport: capturing beyond the viewport drops the page border and diff --git a/e2e/docs-web-paste-font.spec.ts b/e2e/docs-web-paste-font.spec.ts new file mode 100644 index 0000000..8280fa2 --- /dev/null +++ b/e2e/docs-web-paste-font.spec.ts @@ -0,0 +1,134 @@ +import { test, expect } from '@playwright/test' +import { launchShell, closeAndSaveVideo, waitForPageWithUrl } from './helpers' + +/** + * Web-HTML paste fonts (r181): text copied from a website pasted into a + * document must not land in the theme font. + * - a fragment whose family chain has no concrete face (`sans-serif` — + * generic-only sites) takes the insertion point's font like typing; + * - a whole-paragraph copy carrying the site's styles on the

    keeps its + * concrete font (block styles are pushed down to the spans the mark + * parser reads); + * - our own clipboard HTML (data-pm-slice) keeps its exact marks. + */ + +interface EditorRun { + text: string + font: string | null + color: string | null +} + +interface AidocsWindow { + __aidocs?: { + editor?: { + state: { doc: unknown } + chain: () => unknown + commands: Record unknown> + } + } +} + +const GENERIC_SPAN = `web generic` +const BLOCK_ROBOTO = `

    web roboto block

    ` +const INTERNAL_BARE = `

    internal bare

    ` + +test.describe('docs web-HTML paste fonts', () => { + test('web pastes follow the caret font when generic and keep concrete site fonts', async () => { + const launched = await launchShell({ onboardingSeen: true, videoDir: 'docs-web-paste-font' }) + const { app, page } = launched + try { + await expect(page.locator('.quick-card').first()).toContainText('AI Docs') + await page.locator('.quick-card').first().click() + const editorPage = await waitForPageWithUrl(app, '://docs/') + await editorPage.waitForFunction( + () => Boolean((window as unknown as AidocsWindow).__aidocs?.editor), + undefined, + { timeout: 30_000 }, + ) + await editorPage.locator('.doc-page').click() + await editorPage.keyboard.type('avant apres', { delay: 10 }) + // the field docs this guards: surrounding text carries explicit Calibri + await editorPage.evaluate(() => { + const ed = (window as unknown as AidocsWindow).__aidocs!.editor! as unknown as { + chain: () => { + selectAll: () => { + setMark: (name: string, attrs: Record) => { run: () => void } + } + } + state: { doc: { content: { size: number } } } + commands: { setTextSelection: (pos: number) => void } + } + ed.chain() + .selectAll() + .setMark('docTextStyle', { font: 'Calibri', fontAscii: 'Calibri' }) + .run() + ed.commands.setTextSelection(ed.state.doc.content.size - 1) + }) + for (let i = 0; i < 'apres'.length; i++) await editorPage.keyboard.press('ArrowLeft') + + const runs = async (): Promise => + editorPage.evaluate(() => { + const ed = (window as unknown as AidocsWindow).__aidocs!.editor! as unknown as { + state: { + doc: { + descendants: ( + cb: (node: { + isText: boolean + text?: string + marks: Array<{ type: { name: string }; attrs: Record }> + }) => boolean, + ) => void + } + } + } + const out: Array<{ text: string; font: string | null; color: string | null }> = [] + ed.state.doc.descendants((node) => { + if (node.isText) { + const style = node.marks.find((m) => m.type.name === 'docTextStyle') + out.push({ + text: node.text ?? '', + font: (style?.attrs.font as string | null) ?? null, + color: (style?.attrs.color as string | null) ?? null, + }) + } + return true + }) + return out + }) + + const paste = async (html: string, text: string): Promise => { + await app.evaluate( + ({ clipboard }, payload) => { + clipboard.write({ html: payload.html, text: payload.text }) + }, + { html, text }, + ) + await editorPage.keyboard.press('Control+v') + await editorPage.waitForTimeout(400) + } + + // 1) generic-only chain mid-paragraph: caret font, source color kept + await paste(GENERIC_SPAN, 'web generic') + let state = await runs() + const generic = state.find((r) => r.text === 'web generic') + expect(generic?.font).toBe('Calibri') + expect(generic?.color).toBe('202122') + + // 2) whole-paragraph copy on an empty line: the block's concrete font + await editorPage.keyboard.press('Control+End') + await editorPage.keyboard.press('Enter') + await paste(BLOCK_ROBOTO, 'web roboto block') + state = await runs() + expect(state.find((r) => r.text.includes('web roboto'))?.font).toBe('Roboto') + + // 3) internal clipboard HTML stays untouched (no caret-font fill) + await editorPage.keyboard.press('Control+End') + await editorPage.keyboard.press('Enter') + await paste(INTERNAL_BARE, 'internal bare') + state = await runs() + expect(state.find((r) => r.text.includes('internal bare'))?.font).toBeNull() + } finally { + await closeAndSaveVideo(launched) + } + }) +}) diff --git a/e2e/helpers.ts b/e2e/helpers.ts index 36ca324..1313b1b 100644 --- a/e2e/helpers.ts +++ b/e2e/helpers.ts @@ -68,6 +68,7 @@ export async function launchShell(options: LaunchOptions): Promise env: { ...hostEnv, GENOFFICE_USER_DATA: userDataDir, + GENOFFICE_NO_SPARE_VIEW: '1', GENOFFICE_LANG: options.lang ?? 'en', ...(process.platform === 'linux' ? { ELECTRON_DISABLE_SANDBOX: '1' } : {}), }, diff --git a/e2e/html-insert-drag.spec.ts b/e2e/html-insert-drag.spec.ts new file mode 100644 index 0000000..2fe1c2f --- /dev/null +++ b/e2e/html-insert-drag.spec.ts @@ -0,0 +1,94 @@ +import { mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test, expect } from '@playwright/test' +import { launchShell, closeAndSaveVideo, waitForPageWithUrl, screenshotPath } from './helpers' + +test.describe('html editor: insert, resize, drag', () => { + test('Insert menu adds elements, handles resize, dragging the grip reorders', async () => { + const dir = await mkdtemp(join(tmpdir(), 'genoffice-html-')) + const htmlPath = join(dir, 'layout.html') + const source = + '\n\n\n
    \n

    Hello

    \n

    First line.

    \n

    Second line.

    \n
    \n\n\n' + await writeFile(htmlPath, source) + + const launched = await launchShell({ + onboardingSeen: true, + videoDir: 'html-insert-drag', + openFile: htmlPath, + }) + const { app } = launched + try { + const editorPage = await waitForPageWithUrl(app, '://html/') + await expect(editorPage.locator('.ribbon-body')).toBeVisible() + const frame = editorPage.frameLocator('.preview-frame') + const content = editorPage.locator('.source-editor .cm-content') + await editorPage.locator('.ribbon').getByRole('tab', { name: /Split/ }).click() + + // nothing selected: the new paragraph lands at the end of the body and opens for typing + const ribbon = editorPage.locator('.ribbon') + await ribbon.getByRole('button', { name: 'Paragraph', exact: true }).click() + await expect(content).toContainText(/<\/section>\s*

    Type your text here\.<\/p>\s*<\/body>/) + const fresh = frame.locator('body > p') + await expect(fresh).toHaveText('Type your text here.') + await expect(fresh).toHaveAttribute('contenteditable', 'plaintext-only') + await expect(editorPage.locator('.crumb.current')).toHaveText('p') + await frame.locator('body').press('Escape') + // the split view halves the stage: park the style panel so it does not sit over the page + // (synthetic click: the panel itself may cover the toolbar toggle) + const float = editorPage.locator('.hx-float') + await float.getByRole('button', { name: /Style panel/ }).dispatchEvent('click') + await expect(editorPage.locator('.hx-panel')).toHaveCount(0) + + // with a selection: right after it + await frame.locator('h1#title').click() + await expect(editorPage.locator('.crumb.current')).toHaveText('h1#title') + // the less common kinds sit under "More" + await ribbon.getByRole('button', { name: 'More', exact: true }).click() + await editorPage.getByRole('menuitem', { name: 'Divider' }).click() + await expect(content).toContainText(/

    Hello<\/h1>\s*
    \s*

    /) + await expect(frame.locator('section.hero > hr')).toHaveCount(1) + + // resize: dragging the right handle writes an inline width + await frame.locator('p.lead').click() + await expect(editorPage.locator('.crumb.current')).toHaveText('p.lead') + const handle = frame.locator('[data-gx-inspector-handle="e"]') + await expect(handle).toBeVisible() + const box = (await handle.boundingBox())! + const startWidth = await frame + .locator('p.lead') + .evaluate((el) => el.getBoundingClientRect().width) + await editorPage.mouse.move(box.x + box.width / 2, box.y + box.height / 2) + await editorPage.mouse.down() + await editorPage.mouse.move(box.x + box.width / 2 - 60, box.y + box.height / 2, { steps: 6 }) + await editorPage.mouse.up() + await expect(content).toContainText(/

    /) + const written = Number(/style="width: (\d+)px"/.exec(await content.innerText())![1]) + expect(Math.abs(written - (startWidth - 60))).toBeLessThanOrEqual(2) + await editorPage.screenshot({ path: screenshotPath('html-resize') }) + + // drag: grab the grip beside the selection and drop the note above the lead paragraph + await expect(frame.locator('p.lead')).toHaveAttribute('style', /width/) + await frame.locator('p.note').click() + await expect(editorPage.locator('.crumb.current')).toHaveText('p.note') + await expect(frame.locator('[data-gx-inspector-label]')).toHaveText('p.note') + const grip = frame.locator('[data-gx-inspector-grip]') + await expect(grip).toBeVisible() + const gripBox = (await grip.boundingBox())! + const leadBox = (await frame.locator('p.lead').boundingBox())! + await editorPage.mouse.move(gripBox.x + gripBox.width / 2, gripBox.y + gripBox.height / 2) + await editorPage.mouse.down() + await editorPage.mouse.move(leadBox.x + leadBox.width / 2, leadBox.y + 3, { steps: 8 }) + await expect(frame.locator('[data-gx-inspector-drop]')).toBeVisible() + await editorPage.mouse.up() + await expect(content).toContainText( + /

    Second line\.<\/p>\s*

    { }) const { app } = launched try { - const editorPage = await waitForPageWithUrl(app, 'markdown/out') + const editorPage = await waitForPageWithUrl(app, '://markdown/') const editor = editorPage.locator('.doc-editor') await expect(editor.locator('h1')).toHaveText('Alpha') diff --git a/e2e/new-file-tab.spec.ts b/e2e/new-file-tab.spec.ts index 682fe8b..64c3e29 100644 --- a/e2e/new-file-tab.spec.ts +++ b/e2e/new-file-tab.spec.ts @@ -18,7 +18,7 @@ test.describe('new file from home', () => { // the docs editor loads in a WebContentsView, which surfaces as a new // page — poll for it instead of waitForLoadState, which hangs on Linux // when Playwright attaches mid-navigation and misses lifecycle events - const editorPage = await waitForPageWithUrl(app, 'docs/out') + const editorPage = await waitForPageWithUrl(app, '://docs/') await expect(editorPage.locator('body')).toBeVisible() await editorPage.screenshot({ path: screenshotPath('new-doc-editor') }) } finally { diff --git a/e2e/pdf-fit-zoom.spec.ts b/e2e/pdf-fit-zoom.spec.ts index 5c7ee7d..a04dd74 100644 --- a/e2e/pdf-fit-zoom.spec.ts +++ b/e2e/pdf-fit-zoom.spec.ts @@ -35,7 +35,7 @@ test('image-sized PDF opens at true fit-to-width, not the old 50% zoom floor', a openFile: pdfPath, }) try { - const editorPage = await waitForPageWithUrl(launched.app, 'pdf/out') + const editorPage = await waitForPageWithUrl(launched.app, '://pdf/') await expect(editorPage.locator('.pdf-page').first()).toBeVisible() await expect diff --git a/e2e/pdf-shift-arrow-selection.spec.ts b/e2e/pdf-shift-arrow-selection.spec.ts index ea526ba..06efb4e 100644 --- a/e2e/pdf-shift-arrow-selection.spec.ts +++ b/e2e/pdf-shift-arrow-selection.spec.ts @@ -46,7 +46,7 @@ test('Shift+ArrowRight extends the text selection instead of flipping the page', openFile: pdfPath, }) try { - const editorPage = await waitForPageWithUrl(launched.app, 'pdf/out') + const editorPage = await waitForPageWithUrl(launched.app, '://pdf/') await expect(editorPage.locator('.textLayer span').first()).toBeVisible({ timeout: 30_000 }) // select up to "...000003", like a finished mouse drag that stopped short diff --git a/e2e/sheets-arrow-collapse.spec.ts b/e2e/sheets-arrow-collapse.spec.ts index 64c8bca..6a162bd 100644 --- a/e2e/sheets-arrow-collapse.spec.ts +++ b/e2e/sheets-arrow-collapse.spec.ts @@ -59,7 +59,7 @@ test.describe('sheets: arrow collapses a multi-cell selection to the active cell await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') // the replayed move must not surface as an uncaught command error const commandErrors: string[] = [] sheets.on('pageerror', (err) => { diff --git a/e2e/sheets-csv-export.spec.ts b/e2e/sheets-csv-export.spec.ts index 6f8ae2c..9c11d04 100644 --- a/e2e/sheets-csv-export.spec.ts +++ b/e2e/sheets-csv-export.spec.ts @@ -62,7 +62,7 @@ test.describe('sheets: export the active sheet as CSV', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) // Stub the native dialogs: pick the target path, answer "Continue as @@ -76,7 +76,7 @@ test.describe('sheets: export the active sheet as CSV', () => { // keep re-sending the menu action until the file lands. await expect(async () => { await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'export-csv') }) expect(existsSync(target)).toBe(true) @@ -105,13 +105,13 @@ test.describe('sheets: export the active sheet as CSV', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets, 'Data') await stubDialogs(launched.app, target) await expect(async () => { await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'export-csv') }) expect(existsSync(target)).toBe(true) @@ -128,7 +128,7 @@ test.describe('sheets: export the active sheet as CSV', () => { // the export announces itself with a toast, not just the status bar await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'export-csv') }) await sheets.waitForSelector('.app-toast', { timeout: 10_000 }) @@ -150,13 +150,13 @@ test.describe('sheets: export the active sheet as CSV', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets, 'Data') await stubDialogs(launched.app, target) await expect(async () => { await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save-as') }) expect(existsSync(target)).toBe(true) diff --git a/e2e/sheets-csv-inplace-save.spec.ts b/e2e/sheets-csv-inplace-save.spec.ts index 1cd4f09..876e6a1 100644 --- a/e2e/sheets-csv-inplace-save.spec.ts +++ b/e2e/sheets-csv-inplace-save.spec.ts @@ -38,7 +38,7 @@ test.describe('sheets: a CSV keeps its identity through Save', () => { openFile: csvSource, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) const a1 = await cellA1(sheets) @@ -58,7 +58,7 @@ test.describe('sheets: a CSV keeps its identity through Save', () => { // Save may be refused politely until the preload finishes — retry. await expect(async () => { await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) const bytes = await readFile(csvSource) diff --git a/e2e/sheets-edit-polish.spec.ts b/e2e/sheets-edit-polish.spec.ts index ace5d5f..765fc90 100644 --- a/e2e/sheets-edit-polish.spec.ts +++ b/e2e/sheets-edit-polish.spec.ts @@ -27,7 +27,7 @@ test.describe('sheets: manual visual inserts are undoable', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) await sheets.getByRole('button', { name: 'Insert', exact: true }).click() @@ -72,7 +72,7 @@ test.describe('sheets: freeze journal follows undo', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) await sheets.getByRole('button', { name: 'View', exact: true }).click() @@ -96,7 +96,7 @@ test.describe('sheets: freeze journal follows undo', () => { await sheets.keyboard.press('Enter') await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { @@ -124,7 +124,7 @@ test.describe('sheets: Data → From Text/CSV', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) await sheets.getByRole('button', { name: 'Data', exact: true }).click() @@ -134,7 +134,7 @@ test.describe('sheets: Data → From Text/CSV', () => { await expect(sheets.locator('.workbook-status')).toContainText('A1', { timeout: 15_000 }) await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { @@ -160,7 +160,7 @@ test.describe('sheets: comment navigation', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) await sheets.getByRole('button', { name: 'Review', exact: true }).click() diff --git a/e2e/sheets-edit-save.spec.ts b/e2e/sheets-edit-save.spec.ts index 4dad91d..daca655 100644 --- a/e2e/sheets-edit-save.spec.ts +++ b/e2e/sheets-edit-save.spec.ts @@ -56,7 +56,7 @@ test.describe('sheets: edit and save an external workbook', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(first.app, 'sheets/out') + const sheets = await waitForPageWithUrl(first.app, '://sheets/') await waitForWorkbook(sheets) const a1 = await cellA1(sheets) @@ -74,7 +74,7 @@ test.describe('sheets: edit and save an external workbook', () => { // File > Save, routed to the sheets view the same way the app menu does it await first.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { @@ -93,7 +93,7 @@ test.describe('sheets: edit and save an external workbook', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(second.app, 'sheets/out') + const sheets = await waitForPageWithUrl(second.app, '://sheets/') await waitForWorkbook(sheets) const a1 = await cellA1(sheets) diff --git a/e2e/sheets-filter-outline.spec.ts b/e2e/sheets-filter-outline.spec.ts index 00a2d69..a62cd97 100644 --- a/e2e/sheets-filter-outline.spec.ts +++ b/e2e/sheets-filter-outline.spec.ts @@ -108,7 +108,7 @@ test.describe('sheets: no outline around a filtered range', () => { await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) diff --git a/e2e/sheets-filter-reopen.spec.ts b/e2e/sheets-filter-reopen.spec.ts index 8526a16..a91f825 100644 --- a/e2e/sheets-filter-reopen.spec.ts +++ b/e2e/sheets-filter-reopen.spec.ts @@ -36,7 +36,7 @@ test.describe('sheets: filter criteria survive save and reopen', () => { await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) @@ -74,7 +74,7 @@ test.describe('sheets: filter criteria survive save and reopen', () => { await sheets.waitForTimeout(800) await app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) @@ -101,7 +101,7 @@ test.describe('sheets: filter criteria survive save and reopen', () => { }) try { const { app } = relaunched - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) diff --git a/e2e/sheets-insert-gallery.spec.ts b/e2e/sheets-insert-gallery.spec.ts index 0bc82a7..c842ce0 100644 --- a/e2e/sheets-insert-gallery.spec.ts +++ b/e2e/sheets-insert-gallery.spec.ts @@ -30,7 +30,7 @@ async function gridOrigin(page: Page): Promise<{ x: number; y: number }> { /** center of a cell: ~46px row header, ~24px column header, ~74px × ~23px cells */ function cellPoint(origin: { x: number; y: number }, row: number, column: number) { - return { x: origin.x + 46 + column * 74 + 37, y: origin.y + 24 + row * 23 + 11 } + return { x: origin.x + 46 + column * 74 + 37, y: origin.y + 20 + row * 20 + 10 } } test.describe('sheets: Insert → Recommended Charts and Icons', () => { @@ -45,7 +45,7 @@ test.describe('sheets: Insert → Recommended Charts and Icons', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) const origin = await gridOrigin(sheets) @@ -101,7 +101,7 @@ test.describe('sheets: Insert → Recommended Charts and Icons', () => { await sheets.screenshot({ path: screenshotPath('gallery-inserted') }) await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { diff --git a/e2e/sheets-insert-screenshot.spec.ts b/e2e/sheets-insert-screenshot.spec.ts index fe383b0..edab24f 100644 --- a/e2e/sheets-insert-screenshot.spec.ts +++ b/e2e/sheets-insert-screenshot.spec.ts @@ -27,7 +27,7 @@ test.describe('sheets: Insert → Screenshot', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) // Always stub the OS capturer in the main process: real capture is @@ -65,7 +65,7 @@ test.describe('sheets: Insert → Screenshot', () => { await sheets.screenshot({ path: screenshotPath('screenshot-inserted') }) await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { diff --git a/e2e/sheets-insert-tier2.spec.ts b/e2e/sheets-insert-tier2.spec.ts index b309bfe..82f09c9 100644 --- a/e2e/sheets-insert-tier2.spec.ts +++ b/e2e/sheets-insert-tier2.spec.ts @@ -17,7 +17,7 @@ async function waitForWorkbook(page: Page): Promise { function saveWorkbook(app: Awaited>['app']): Promise { return app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) } @@ -37,7 +37,7 @@ async function gridOrigin(page: Page): Promise<{ x: number; y: number }> { /** center of a cell: ~46px row header, ~24px column header, ~74px × ~23px cells */ function cellPoint(origin: { x: number; y: number }, row: number, column: number) { - return { x: origin.x + 46 + column * 74 + 37, y: origin.y + 24 + row * 23 + 11 } + return { x: origin.x + 46 + column * 74 + 37, y: origin.y + 20 + row * 20 + 10 } } test.describe('sheets: Insert → Equation and Checkbox', () => { @@ -52,7 +52,7 @@ test.describe('sheets: Insert → Equation and Checkbox', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) await sheets.getByRole('button', { name: 'Insert', exact: true }).click() @@ -94,7 +94,7 @@ test.describe('sheets: Insert → Equation and Checkbox', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) await sheets.getByRole('button', { name: 'Insert', exact: true }).click() @@ -126,7 +126,7 @@ test.describe('sheets: Insert → Timeline', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) // Full-load mode arrives within a few seconds on this tiny fixture; // typing the source table below takes longer than that. diff --git a/e2e/sheets-jump-scroll.spec.ts b/e2e/sheets-jump-scroll.spec.ts index 72063d5..26047b9 100644 --- a/e2e/sheets-jump-scroll.spec.ts +++ b/e2e/sheets-jump-scroll.spec.ts @@ -55,7 +55,7 @@ test.describe('sheets: ctrl+shift+arrow scroll follow', () => { await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) diff --git a/e2e/sheets-menu-input-enter.spec.ts b/e2e/sheets-menu-input-enter.spec.ts index cb2704f..3ca0585 100644 --- a/e2e/sheets-menu-input-enter.spec.ts +++ b/e2e/sheets-menu-input-enter.spec.ts @@ -29,7 +29,7 @@ test.describe('sheets: Enter runs the context-menu insert-N action', () => { await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) diff --git a/e2e/sheets-move-rows.spec.ts b/e2e/sheets-move-rows.spec.ts index 35c9046..354e428 100644 --- a/e2e/sheets-move-rows.spec.ts +++ b/e2e/sheets-move-rows.spec.ts @@ -28,11 +28,11 @@ async function gridOrigin(page: Page): Promise<{ x: number; y: number }> { } function cellPoint(origin: { x: number; y: number }, row: number, column: number) { - return { x: origin.x + 46 + column * 86 + 43, y: origin.y + 24 + row * 23 + 11 } + return { x: origin.x + 46 + column * 86 + 43, y: origin.y + 20 + row * 20 + 10 } } function rowHeaderPoint(origin: { x: number; y: number }, row: number) { - return { x: origin.x + 23, y: origin.y + 24 + row * 23 + 11 } + return { x: origin.x + 23, y: origin.y + 20 + row * 20 + 10 } } test.describe('sheets: whole-row move', () => { @@ -47,7 +47,7 @@ test.describe('sheets: whole-row move', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) const origin = await gridOrigin(sheets) @@ -65,14 +65,14 @@ test.describe('sheets: whole-row move', () => { await sheets.mouse.move(header2.x, header2.y) await sheets.mouse.down() const target = rowHeaderPoint(origin, 3) - await sheets.mouse.move(header2.x, header2.y + 12, { steps: 4 }) + await sheets.mouse.move(header2.x, header2.y + 8, { steps: 4 }) await sheets.mouse.move(target.x, target.y + 8, { steps: 12 }) await sheets.mouse.up() await sheets.waitForTimeout(800) } const savedOrder = async (expected: readonly string[]) => { await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { diff --git a/e2e/sheets-new-blank.spec.ts b/e2e/sheets-new-blank.spec.ts index 4b7762c..94b97f8 100644 --- a/e2e/sheets-new-blank.spec.ts +++ b/e2e/sheets-new-blank.spec.ts @@ -24,7 +24,7 @@ test.describe('sheets: new blank workbook', () => { await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) @@ -51,7 +51,7 @@ test.describe('sheets: new blank workbook', () => { await sheets.screenshot({ path: screenshotPath('sheets-new-blank-edited') }) await app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { diff --git a/e2e/sheets-paste-anchor-tile.spec.ts b/e2e/sheets-paste-anchor-tile.spec.ts index 83f2c02..4f48344 100644 --- a/e2e/sheets-paste-anchor-tile.spec.ts +++ b/e2e/sheets-paste-anchor-tile.spec.ts @@ -52,7 +52,7 @@ test.describe('sheets: paste repeats into an anchor-shaped target', () => { await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) diff --git a/e2e/sheets-paste-shared-formula-save.spec.ts b/e2e/sheets-paste-shared-formula-save.spec.ts index 93a644a..661fb52 100644 --- a/e2e/sheets-paste-shared-formula-save.spec.ts +++ b/e2e/sheets-paste-shared-formula-save.spec.ts @@ -31,7 +31,7 @@ test.describe('sheets: tiled paste of formulas survives save', () => { await expect(page.locator('.quick-card').nth(1)).toContainText('AI Sheets') await page.locator('.quick-card').nth(1).click() - const sheets = await waitForPageWithUrl(app, 'sheets/out') + const sheets = await waitForPageWithUrl(app, '://sheets/') await sheets.waitForFunction(() => document.body.textContent?.includes('Sheet1'), null, { timeout: 30_000, }) @@ -92,7 +92,7 @@ test.describe('sheets: tiled paste of formulas survives save', () => { await sheets.waitForTimeout(800) await app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) diff --git a/e2e/sheets-ribbon-batch.spec.ts b/e2e/sheets-ribbon-batch.spec.ts index b5ca8a9..6a5792f 100644 --- a/e2e/sheets-ribbon-batch.spec.ts +++ b/e2e/sheets-ribbon-batch.spec.ts @@ -44,7 +44,7 @@ test.describe('sheets: ribbon batch-1 features', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) const status = sheets.locator('.workbook-status') @@ -52,7 +52,7 @@ test.describe('sheets: ribbon batch-1 features', () => { const origin = await gridOrigin(sheets) await sheets.mouse.move(origin.x + 43, origin.y + 12) await sheets.mouse.down() - await sheets.mouse.move(origin.x + 87 + 43, origin.y + 24 * 2 + 12, { steps: 8 }) + await sheets.mouse.move(origin.x + 87 + 43, origin.y + 20 * 2 + 10, { steps: 8 }) await sheets.mouse.up() await sheets.getByRole('button', { name: 'Formulas' }).click() await sheets.locator('span.styles-row', { hasText: 'Create from Selection' }).click() @@ -91,7 +91,7 @@ test.describe('sheets: ribbon batch-1 features', () => { await expect(status).toContainText('Headings hidden.') await sheets.screenshot({ path: screenshotPath('sheets-headings-hidden') }) await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { @@ -108,7 +108,7 @@ test.describe('sheets: ribbon batch-1 features', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(second.app, 'sheets/out') + const sheets = await waitForPageWithUrl(second.app, '://sheets/') await waitForWorkbook(sheets) await sheets.getByRole('button', { name: 'View', exact: true }).click() const headingsBox = sheets @@ -134,13 +134,13 @@ test.describe('sheets: ribbon batch-2 features', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) const status = sheets.locator('.workbook-status') const origin = await gridOrigin(sheets) const cell = (column: number, row: number): { x: number; y: number } => ({ x: origin.x + 74 * column + 37, - y: origin.y + 24 * row + 12, + y: origin.y + 20 * row + 10, }) // ── seed: D1 = 1/0 (error), D2 = D3*2 (goal-seek target) ── @@ -214,13 +214,13 @@ test.describe('sheets: ribbon batch-3 features', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(launched.app, 'sheets/out') + const sheets = await waitForPageWithUrl(launched.app, '://sheets/') await waitForWorkbook(sheets) const status = sheets.locator('.workbook-status') const origin = await gridOrigin(sheets) // ── Page Layout > Breaks: insert a break at B3 ── - await sheets.mouse.click(origin.x + 87 + 43, origin.y + 24 * 2 + 12) + await sheets.mouse.click(origin.x + 87 + 43, origin.y + 20 * 2 + 10) await sheets.getByRole('button', { name: 'Page Layout' }).click() await sheets.locator('.ribbon-tool', { hasText: 'Breaks' }).click() await sheets.getByRole('option', { name: 'Insert Page Break' }).click() @@ -264,7 +264,7 @@ test.describe('sheets: ribbon batch-3 features', () => { // ── save, then verify every feature landed in the package ── await launched.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { diff --git a/e2e/sheets-xlsm.spec.ts b/e2e/sheets-xlsm.spec.ts index b2e6267..31c5d1a 100644 --- a/e2e/sheets-xlsm.spec.ts +++ b/e2e/sheets-xlsm.spec.ts @@ -55,7 +55,7 @@ test.describe('sheets: macro-enabled workbook (.xlsm)', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(first.app, 'sheets/out') + const sheets = await waitForPageWithUrl(first.app, '://sheets/') await waitForWorkbook(sheets) const a1 = await cellA1(sheets) @@ -67,7 +67,7 @@ test.describe('sheets: macro-enabled workbook (.xlsm)', () => { await sheets.screenshot({ path: screenshotPath('sheets-xlsm-edited') }) await first.app.evaluate(({ webContents }) => { - const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('sheets/out')) + const wc = webContents.getAllWebContents().find((w) => w.getURL().includes('://sheets/')) wc?.send('menu:action', 'save') }) await expect(() => { @@ -92,7 +92,7 @@ test.describe('sheets: macro-enabled workbook (.xlsm)', () => { openFile: workbook, }) try { - const sheets = await waitForPageWithUrl(second.app, 'sheets/out') + const sheets = await waitForPageWithUrl(second.app, '://sheets/') await waitForWorkbook(sheets) const a1 = await cellA1(sheets) diff --git a/e2e/slides-font-manager.spec.ts b/e2e/slides-font-manager.spec.ts index 57e7308..2218516 100644 --- a/e2e/slides-font-manager.spec.ts +++ b/e2e/slides-font-manager.spec.ts @@ -34,7 +34,7 @@ test('font download UI follows CDN configuration', async () => { openFile: await buildRubikFixture(), }) try { - const editorPage = await waitForPageWithUrl(launched.app, 'slides/out') + const editorPage = await waitForPageWithUrl(launched.app, '://slides/') await editorPage.waitForSelector('.stage-wrap canvas', { timeout: 30_000 }) const banner = editorPage.locator('.font-missing-banner') diff --git a/e2e/theme-pipeline.spec.ts b/e2e/theme-pipeline.spec.ts index c0d3939..13bb86a 100644 --- a/e2e/theme-pipeline.spec.ts +++ b/e2e/theme-pipeline.spec.ts @@ -48,7 +48,7 @@ test.describe('theme pipeline', () => { const { app } = launched try { const shellPage = await findShellPage(app) - const editorPage = await waitForPageWithUrl(app, 'markdown/out') + const editorPage = await waitForPageWithUrl(app, '://markdown/') await expect(editorPage.locator('.doc-editor')).toBeVisible() expect(await themeAttr(shellPage)).toBeNull() expect(await themeAttr(editorPage)).toBeNull() diff --git a/e2e/theme-visual-slides.spec.ts b/e2e/theme-visual-slides.spec.ts index f3d2477..7990ed0 100644 --- a/e2e/theme-visual-slides.spec.ts +++ b/e2e/theme-visual-slides.spec.ts @@ -27,7 +27,7 @@ test('slides chrome darkens while the slide canvas stays paper-white', async () try { const shellPage = await findShellPage(launched.app) await shellPage.locator('.quick-card', { hasText: 'AI Slides' }).click() - const editorPage = await waitForPageWithUrl(launched.app, 'slides/out') + const editorPage = await waitForPageWithUrl(launched.app, '://slides/') await editorPage.waitForSelector('.stage-wrap canvas', { timeout: 20_000 }) await shellPage.evaluate(() => diff --git a/e2e/theme-visual.spec.ts b/e2e/theme-visual.spec.ts index 27a247a..983ed4b 100644 --- a/e2e/theme-visual.spec.ts +++ b/e2e/theme-visual.spec.ts @@ -70,7 +70,7 @@ test.describe('theme visual adoption', () => { }) try { const shellPage = await findShellPage(launched.app) - const editorPage = await waitForPageWithUrl(launched.app, 'html/out') + const editorPage = await waitForPageWithUrl(launched.app, '://html/') // preview is the default view; the source pane is what this test measures await editorPage.locator('.rb-view', { hasText: /Source/ }).click() await expect(editorPage.locator('.source-editor .cm-content')).toBeVisible() @@ -102,7 +102,7 @@ test.describe('theme visual adoption', () => { }) try { const shellPage = await findShellPage(launched.app) - const editorPage = await waitForPageWithUrl(launched.app, 'markdown/out') + const editorPage = await waitForPageWithUrl(launched.app, '://markdown/') await expect(editorPage.locator('.doc-editor')).toBeVisible() const lightBg = await bodyBg(editorPage) @@ -126,7 +126,7 @@ test.describe('theme visual adoption', () => { try { const shellPage = await findShellPage(launched.app) await shellPage.locator('.quick-card', { hasText: 'AI Docs' }).click() - const editorPage = await waitForPageWithUrl(launched.app, 'docs/out') + const editorPage = await waitForPageWithUrl(launched.app, '://docs/') const page = editorPage.locator('.doc-page').first() await expect(page).toBeVisible() const pageBg = () => page.evaluate((el) => getComputedStyle(el).backgroundColor) @@ -177,7 +177,7 @@ test.describe('theme visual adoption', () => { try { const shellPage = await findShellPage(launched.app) await shellPage.locator('.quick-card', { hasText: 'AI Sheets' }).click() - const editorPage = await waitForPageWithUrl(launched.app, 'sheets/out') + const editorPage = await waitForPageWithUrl(launched.app, '://sheets/') await editorPage.waitForSelector('canvas', { timeout: 20_000 }) // Univer flags its dark repaint with a class on (ThemeService.darkMode$) @@ -217,7 +217,7 @@ test.describe('theme visual adoption', () => { }) try { const shellPage = await findShellPage(launched.app) - const editorPage = await waitForPageWithUrl(launched.app, 'pdf/out') + const editorPage = await waitForPageWithUrl(launched.app, '://pdf/') await expect(editorPage.locator('.pdf-page').first()).toBeVisible() await setTheme(shellPage, 'dark') diff --git a/e2e/visual-baselines/captable-float-p1.png b/e2e/visual-baselines/captable-float-p1.png index b88109b..1479921 100644 Binary files a/e2e/visual-baselines/captable-float-p1.png and b/e2e/visual-baselines/captable-float-p1.png differ diff --git a/e2e/visual-baselines/captable-inline-p1.png b/e2e/visual-baselines/captable-inline-p1.png index c8739b1..e83dbaa 100644 Binary files a/e2e/visual-baselines/captable-inline-p1.png and b/e2e/visual-baselines/captable-inline-p1.png differ diff --git a/e2e/visual-baselines/captable-pct-p1.png b/e2e/visual-baselines/captable-pct-p1.png index f4e8dfc..eec9856 100644 Binary files a/e2e/visual-baselines/captable-pct-p1.png and b/e2e/visual-baselines/captable-pct-p1.png differ diff --git a/e2e/visual-baselines/kitchen-sink-p1.png b/e2e/visual-baselines/kitchen-sink-p1.png index e7061fb..c98cfea 100644 Binary files a/e2e/visual-baselines/kitchen-sink-p1.png and b/e2e/visual-baselines/kitchen-sink-p1.png differ diff --git a/package-lock.json b/package-lock.json index 1e2153d..42cd5cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -204,6 +204,8 @@ "@genoffice/file-parse": "*", "@genoffice/i18n": "*", "@genoffice/ui": "*", + "@genoffice/pptx-render": "*", + "@genoffice/xlsx-gateway": "*", "@univerjs/core": "^0.25.1", "@univerjs/data-validation": "^0.25.1", "@univerjs/engine-render": "^0.25.1", @@ -243,7 +245,7 @@ }, "apps/shell": { "name": "@genoffice/shell", - "version": "0.9.0", + "version": "0.10.0", "license": "Apache-2.0", "devDependencies": { "@genoffice/agent-core": "*", @@ -252,12 +254,15 @@ "@genoffice/docs": "*", "@genoffice/docx-engine": "*", "@genoffice/electron-utils": "*", + "@genoffice/cli": "*", "@genoffice/i18n": "*", + "@genoffice/pipelines": "*", "@genoffice/pptx-engine": "*", "@genoffice/pptx-render": "*", "@genoffice/sheets": "*", "@genoffice/slides": "*", "@genoffice/ui": "*", + "@genoffice/xlsx-gateway": "*", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^5.0.4", @@ -291,6 +296,7 @@ "@genoffice/file-parse": "*", "@genoffice/i18n": "*", "@genoffice/pptx-engine": "*", + "@genoffice/pptx-ops": "*", "@genoffice/pptx-render": "*", "@genoffice/project-store": "*", "@genoffice/ui": "*", @@ -317,7 +323,6 @@ "version": "0.9.31", "resolved": "https://registry.npmjs.org/@acemir/cssom/-/cssom-0.9.31.tgz", "integrity": "sha512-ZnR3GSaH+/vJ0YlHau21FjfLYjMpYVIzTD8M8vIEQvIGxeOXyXdzCI140rrCY862p/C/BbzWsjc1dgnM9mkoTA==", - "dev": true, "license": "MIT" }, "node_modules/@antfu/install-pkg": { @@ -337,7 +342,6 @@ "version": "5.1.11", "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz", "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==", - "dev": true, "license": "MIT", "dependencies": { "@asamuzakjp/generational-cache": "^1.0.1", @@ -354,7 +358,6 @@ "version": "6.8.1", "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-6.8.1.tgz", "integrity": "sha512-MvRz1nCqW0fsy8Qz4dnLIvhOlMzqDVBabZx6lH+YywFDdjXhMY37SmpV1XFX3JzG5GWHn63j6HX6QPr3lZXHvQ==", - "dev": true, "license": "MIT", "dependencies": { "@asamuzakjp/nwsapi": "^2.3.9", @@ -368,7 +371,6 @@ "version": "11.5.2", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", - "dev": true, "license": "BlueOak-1.0.0", "engines": { "node": "20 || >=22" @@ -378,7 +380,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz", "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==", - "dev": true, "license": "MIT", "engines": { "node": "^20.19.0 || ^22.12.0 || >=24.0.0" @@ -388,7 +389,6 @@ "version": "2.3.9", "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", - "dev": true, "license": "MIT" }, "node_modules/@babel/code-frame": { @@ -708,7 +708,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz", "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==", - "dev": true, "license": "MIT", "dependencies": { "css-tree": "^3.0.0" @@ -863,7 +862,6 @@ "version": "6.1.0", "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.0.tgz", "integrity": "sha512-064IFJdjTfUqnjpCVpMOdbr8FLQBhinbZj6yRv2An2E41O/pLEXqfFRWqGq/SxlE5PEUYTlvWsG2r8MswAVvkg==", - "dev": true, "funding": [ { "type": "github", @@ -883,7 +881,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.2.1.tgz", "integrity": "sha512-DtdHlgXh5ZkA43cwBcAm+huzgJiwx3ZTWVjBs94kwz2xKqSimDA3lBgCjphYgwgVUMWatSM0pDd8TILB1yrVVg==", - "dev": true, "funding": [ { "type": "github", @@ -907,7 +904,6 @@ "version": "4.1.9", "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.1.9.tgz", "integrity": "sha512-paQcIaOO53Rk5+YrBaBjm/SgrV4INImjo2BT1DtQRYr+XeTRbeAYlS+jxXp9drqvKmtFnWRJKIalDLhZZDu42A==", - "dev": true, "funding": [ { "type": "github", @@ -935,7 +931,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==", - "dev": true, "funding": [ { "type": "github", @@ -958,7 +953,6 @@ "version": "1.1.6", "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.6.tgz", "integrity": "sha512-TcJCWFbXLPpJYq6z7bfOyjWYJDiDg2/I4gyUC9pqPNqHFRIey0EB0q0L5cSnQDfWJg8Jd6VadakxdIez/3zkqQ==", - "dev": true, "funding": [ { "type": "github", @@ -983,7 +977,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz", "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==", - "dev": true, "funding": [ { "type": "github", @@ -2060,7 +2053,6 @@ "version": "1.15.1", "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz", "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==", - "dev": true, "license": "MIT", "engines": { "node": "^20.19.0 || ^22.12.0 || >=24.0.0" @@ -2163,6 +2155,10 @@ "resolved": "packages/font-metrics", "link": true }, + "node_modules/@genoffice/cli": { + "resolved": "packages/cli", + "link": true + }, "node_modules/@genoffice/html": { "resolved": "apps/html", "link": true @@ -2187,10 +2183,18 @@ "resolved": "packages/pdf2docx", "link": true }, + "node_modules/@genoffice/pipelines": { + "resolved": "packages/pipelines", + "link": true + }, "node_modules/@genoffice/pptx-engine": { "resolved": "packages/pptx-engine", "link": true }, + "node_modules/@genoffice/pptx-ops": { + "resolved": "packages/pptx-ops", + "link": true + }, "node_modules/@genoffice/pptx-render": { "resolved": "packages/pptx-render", "link": true @@ -2215,6 +2219,10 @@ "resolved": "packages/ui", "link": true }, + "node_modules/@genoffice/xlsx-gateway": { + "resolved": "packages/xlsx-gateway", + "link": true + }, "node_modules/@genspark/cli": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/@genspark/cli/-/cli-1.4.2.tgz", @@ -2875,7 +2883,7 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz", "integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">= 20.19.0" @@ -6553,7 +6561,6 @@ "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, "license": "MIT", "engines": { "node": ">= 14" @@ -7650,7 +7657,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", - "dev": true, "license": "MIT", "dependencies": { "mdn-data": "2.27.1", @@ -7664,7 +7670,6 @@ "version": "6.2.0", "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-6.2.0.tgz", "integrity": "sha512-Fm5NvhYathRnXNVndkUsCCuR63DCLVVwGOOwQw782coXFi5HhkXdu289l59HlXZBawsyNccXfWRYvLzcDCdDig==", - "dev": true, "license": "MIT", "dependencies": { "@asamuzakjp/css-color": "^5.0.1", @@ -7680,7 +7685,6 @@ "version": "11.5.2", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", - "dev": true, "license": "BlueOak-1.0.0", "engines": { "node": "20 || >=22" @@ -8204,7 +8208,6 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", - "dev": true, "license": "MIT", "dependencies": { "whatwg-mimetype": "^5.0.0", @@ -10001,7 +10004,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", - "dev": true, "license": "MIT", "dependencies": { "@exodus/bytes": "^1.6.0" @@ -10021,7 +10023,6 @@ "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, "license": "MIT", "dependencies": { "agent-base": "^7.1.0", @@ -10056,7 +10057,6 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, "license": "MIT", "dependencies": { "agent-base": "^7.1.2", @@ -10216,7 +10216,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true, "license": "MIT" }, "node_modules/is-unsafe": { @@ -10343,7 +10342,6 @@ "version": "28.1.0", "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-28.1.0.tgz", "integrity": "sha512-0+MoQNYyr2rBHqO1xilltfDjV9G7ymYGlAUazgcDLQaUf8JDHbuGwsxN6U9qWaElZ4w1B2r7yEGIL3GdeW3Rug==", - "dev": true, "license": "MIT", "dependencies": { "@acemir/cssom": "^0.9.31", @@ -10384,7 +10382,6 @@ "version": "7.29.0", "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz", "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", - "dev": true, "license": "MIT", "engines": { "node": ">=20.18.1" @@ -10731,7 +10728,6 @@ "version": "2.27.1", "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", - "dev": true, "license": "CC0-1.0" }, "node_modules/mermaid": { @@ -11926,7 +11922,6 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -12451,7 +12446,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", - "dev": true, "license": "ISC", "dependencies": { "xmlchars": "^2.2.0" @@ -12607,7 +12601,6 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -12755,7 +12748,6 @@ "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", - "dev": true, "license": "MIT" }, "node_modules/tailwind-merge": { @@ -12932,7 +12924,6 @@ "version": "7.4.9", "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.9.tgz", "integrity": "sha512-3kZ8wQQ/k5DrChD4X4FVvr2D7E5uoRgAqkPyLpSCGUvqOvqu+JEdr3mwMUaVWb+vMHZaKhF5fp2PBigKsui7hA==", - "dev": true, "license": "MIT", "dependencies": { "tldts-core": "^7.4.9" @@ -12945,7 +12936,6 @@ "version": "7.4.9", "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.9.tgz", "integrity": "sha512-DxKfPBI52p2msTEu7MPhdpdDTBhhVQg1a/8PjQckeyAvO13eMYElX545grIp6nnTGIMZlRvFZPvFhvI/WIz2Vg==", - "dev": true, "license": "MIT" }, "node_modules/tmp": { @@ -12985,7 +12975,6 @@ "version": "6.0.2", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", - "dev": true, "license": "BSD-3-Clause", "dependencies": { "tldts": "^7.0.5" @@ -12998,7 +12987,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", - "dev": true, "license": "MIT", "dependencies": { "punycode": "^2.3.1" @@ -13101,6 +13089,7 @@ "os": [ "aix" ], + "peer": true, "engines": { "node": ">=18" } @@ -13118,6 +13107,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": ">=18" } @@ -13135,6 +13125,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": ">=18" } @@ -13152,6 +13143,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": ">=18" } @@ -13169,6 +13161,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": ">=18" } @@ -13186,6 +13179,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": ">=18" } @@ -13203,6 +13197,7 @@ "os": [ "freebsd" ], + "peer": true, "engines": { "node": ">=18" } @@ -13220,6 +13215,7 @@ "os": [ "freebsd" ], + "peer": true, "engines": { "node": ">=18" } @@ -13237,6 +13233,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13254,6 +13251,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13271,6 +13269,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13288,6 +13287,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13305,6 +13305,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13322,6 +13323,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13339,6 +13341,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13356,6 +13359,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13373,6 +13377,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">=18" } @@ -13390,6 +13395,7 @@ "os": [ "netbsd" ], + "peer": true, "engines": { "node": ">=18" } @@ -13407,6 +13413,7 @@ "os": [ "netbsd" ], + "peer": true, "engines": { "node": ">=18" } @@ -13424,6 +13431,7 @@ "os": [ "openbsd" ], + "peer": true, "engines": { "node": ">=18" } @@ -13441,6 +13449,7 @@ "os": [ "openbsd" ], + "peer": true, "engines": { "node": ">=18" } @@ -13458,6 +13467,7 @@ "os": [ "openharmony" ], + "peer": true, "engines": { "node": ">=18" } @@ -13475,6 +13485,7 @@ "os": [ "sunos" ], + "peer": true, "engines": { "node": ">=18" } @@ -13492,6 +13503,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": ">=18" } @@ -13509,6 +13521,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": ">=18" } @@ -13526,6 +13539,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": ">=18" } @@ -13647,7 +13661,6 @@ "version": "6.28.0", "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz", "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==", - "dev": true, "license": "MIT", "engines": { "node": ">=18.17" @@ -14562,7 +14575,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", - "dev": true, "license": "MIT", "dependencies": { "xml-name-validator": "^5.0.0" @@ -14589,7 +14601,6 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", - "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=20" @@ -14599,7 +14610,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", - "dev": true, "license": "MIT", "engines": { "node": ">=20" @@ -14609,7 +14619,6 @@ "version": "16.0.1", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", - "dev": true, "license": "MIT", "dependencies": { "@exodus/bytes": "^1.11.0", @@ -14752,7 +14761,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", - "dev": true, "license": "Apache-2.0", "engines": { "node": ">=18" @@ -14994,6 +15002,36 @@ "vitest": "^4.1.11" } }, + "packages/cli": { + "name": "@genoffice/cli", + "version": "0.3.0", + "license": "Apache-2.0", + "dependencies": { + "@genoffice/ai-provider": "*", + "@genoffice/ai-search": "*", + "@genoffice/docx-engine": "*", + "@genoffice/pdf2docx": "*", + "@genoffice/pipelines": "*", + "@genoffice/pptx-engine": "*", + "@genoffice/pptx-ops": "*", + "@genoffice/pptx-render": "*", + "@genoffice/xlsx-gateway": "*", + "@tiptap/core": "3.31.0", + "jsdom": "^28.0.0", + "jszip": "^3.10.1", + "numfmt": "^3.2.6", + "undici": "^6.28.0" + }, + "bin": { + "genoffice": "bin/genoffice" + }, + "devDependencies": { + "@types/node": "^24.10.1", + "esbuild": "^0.25.12", + "typescript": "^5.9.3", + "vitest": "^4.1.11" + } + }, "packages/html2docx": { "name": "@genoffice/html2docx", "version": "0.1.0", @@ -15037,6 +15075,20 @@ "vitest": "^4.1.11" } }, + "packages/pipelines": { + "name": "@genoffice/pipelines", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "@genoffice/pptx-engine": "*", + "@genoffice/pptx-render": "*" + }, + "devDependencies": { + "@types/node": "^24.10.1", + "typescript": "^5.9.3", + "vitest": "^4.1.11" + } + }, "packages/pptx-engine": { "name": "@genoffice/pptx-engine", "version": "0.1.0", @@ -15052,6 +15104,18 @@ "vitest": "^4.1.11" } }, + "packages/pptx-ops": { + "name": "@genoffice/pptx-ops", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "@genoffice/pptx-engine": "*" + }, + "devDependencies": { + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, "packages/pptx-render": { "name": "@genoffice/pptx-render", "version": "0.1.0", @@ -15094,6 +15158,20 @@ "peerDependencies": { "react": "^19.0.0" } + }, + "packages/xlsx-gateway": { + "name": "@genoffice/xlsx-gateway", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "jszip": "^3.10.1", + "numfmt": "^3.2.6", + "zod": "^4.3.6" + }, + "devDependencies": { + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } } } } diff --git a/package.json b/package.json index 1a1918c..383daaf 100644 --- a/package.json +++ b/package.json @@ -22,15 +22,16 @@ "format:check": "node tools/format-changed.mjs --check", "check:theme-colors": "node tools/check-theme-colors.mjs", "check:english-comments": "node tools/check-english-comments.mjs", + "check:skill-version": "node tools/check-skill-version.mjs", "lint": "eslint .", "fixtures": "npm run fixtures -w @genoffice/docx-engine", - "test": "npm run test -w @genoffice/i18n && npm run test -w @genoffice/electron-utils && npm run test -w @genoffice/font-metrics && npm run test -w @genoffice/docx-engine && npm run test -w @genoffice/pdf2docx && npm run test -w @genoffice/html2docx && npm run test -w @genoffice/file-parse && npm run test -w @genoffice/pptx-engine && npm run test -w @genoffice/pptx-render && npm run test -w @genoffice/ai-search && npm run test -w @genoffice/agent-core && npm run test -w @genoffice/ai-provider && npm run test -w @genoffice/project-store && npm run test -w @genoffice/ui && npm run test -w @genoffice/docs && npm run test -w @genoffice/sheets && npm run test -w @genoffice/shell && npm run test -w @genoffice/slides && npm run test -w @genoffice/pdf && npm run test -w @genoffice/markdown && npm run test -w @genoffice/html", - "typecheck": "npm run typecheck -w @genoffice/i18n && npm run typecheck -w @genoffice/electron-utils && npm run typecheck -w @genoffice/font-metrics && npm run typecheck -w @genoffice/docx-engine && npm run typecheck -w @genoffice/pdf2docx && npm run typecheck -w @genoffice/html2docx && npm run typecheck -w @genoffice/file-parse && npm run typecheck -w @genoffice/pptx-engine && npm run typecheck -w @genoffice/pptx-render && npm run typecheck -w @genoffice/ai-search && npm run typecheck -w @genoffice/agent-core && npm run typecheck -w @genoffice/ai-provider && npm run typecheck -w @genoffice/project-store && npm run typecheck -w @genoffice/ui && npm run typecheck -w @genoffice/docs && npm run typecheck -w @genoffice/sheets && npm run typecheck -w @genoffice/shell && npm run typecheck -w @genoffice/slides && npm run typecheck -w @genoffice/pdf && npm run typecheck -w @genoffice/markdown && npm run typecheck -w @genoffice/html", + "test": "npm run test -w @genoffice/i18n && npm run test -w @genoffice/electron-utils && npm run test -w @genoffice/font-metrics && npm run test -w @genoffice/docx-engine && npm run test -w @genoffice/pdf2docx && npm run test -w @genoffice/html2docx && npm run test -w @genoffice/file-parse && npm run test -w @genoffice/pptx-engine && npm run test -w @genoffice/pptx-render && npm run test -w @genoffice/pipelines && npm run test -w @genoffice/ai-search && npm run test -w @genoffice/agent-core && npm run test -w @genoffice/ai-provider && npm run test -w @genoffice/project-store && npm run test -w @genoffice/cli && npm run test -w @genoffice/ui && npm run test -w @genoffice/docs && npm run test -w @genoffice/sheets && npm run test -w @genoffice/shell && npm run test -w @genoffice/slides && npm run test -w @genoffice/pdf && npm run test -w @genoffice/markdown && npm run test -w @genoffice/html", + "typecheck": "npm run typecheck -w @genoffice/i18n && npm run typecheck -w @genoffice/electron-utils && npm run typecheck -w @genoffice/font-metrics && npm run typecheck -w @genoffice/docx-engine && npm run typecheck -w @genoffice/pdf2docx && npm run typecheck -w @genoffice/html2docx && npm run typecheck -w @genoffice/file-parse && npm run typecheck -w @genoffice/pptx-engine && npm run typecheck -w @genoffice/xlsx-gateway && npm run typecheck -w @genoffice/pptx-ops && npm run typecheck -w @genoffice/pptx-render && npm run typecheck -w @genoffice/pipelines && npm run typecheck -w @genoffice/ai-search && npm run typecheck -w @genoffice/agent-core && npm run typecheck -w @genoffice/ai-provider && npm run typecheck -w @genoffice/project-store && npm run typecheck -w @genoffice/cli && npm run typecheck -w @genoffice/ui && npm run typecheck -w @genoffice/docs && npm run typecheck -w @genoffice/sheets && npm run typecheck -w @genoffice/shell && npm run typecheck -w @genoffice/slides && npm run typecheck -w @genoffice/pdf && npm run typecheck -w @genoffice/markdown && npm run typecheck -w @genoffice/html", "predev": "node tools/build-stale-preloads.mjs", "dev": "concurrently -k -n docs,sheets,slides,pdf,markdown,html,shell -c blue,green,yellow,red,cyan,white,magenta \"npm run dev:renderer -w @genoffice/docs\" \"npm run dev:renderer -w @genoffice/sheets\" \"npm run dev:renderer -w @genoffice/slides\" \"npm run dev:renderer -w @genoffice/pdf\" \"npm run dev:renderer -w @genoffice/markdown\" \"npm run dev:renderer -w @genoffice/html\" \"DOCS_RENDERER_URL=http://localhost:5173 SHEETS_RENDERER_URL=http://localhost:5174 SLIDES_RENDERER_URL=http://localhost:5175 PDF_RENDERER_URL=http://localhost:5176 MARKDOWN_RENDERER_URL=http://localhost:5177 HTML_RENDERER_URL=http://localhost:5178 npm run dev -w @genoffice/shell\"", "dev:docs": "npm run dev -w @genoffice/docs", "build": "npm run build -w @genoffice/docs", - "build:all": "npm run build -w @genoffice/docs && npm run build -w @genoffice/sheets && npm run build -w @genoffice/slides && npm run build -w @genoffice/pdf && npm run build -w @genoffice/markdown && npm run build -w @genoffice/html && npm run build -w @genoffice/shell", + "build:all": "npm run build -w @genoffice/docs && npm run build -w @genoffice/sheets && npm run build -w @genoffice/slides && npm run build -w @genoffice/pdf && npm run build -w @genoffice/markdown && npm run build -w @genoffice/html && npm run build -w @genoffice/cli && npm run build -w @genoffice/shell", "shell": "npm run build:all && electron apps/shell", "test:e2e": "playwright test --config e2e/playwright.config.ts", "notices": "node tools/gen-third-party-notices.mjs", diff --git a/packages/agent-core/src/index.ts b/packages/agent-core/src/index.ts index daa9dc9..c8fe24f 100644 --- a/packages/agent-core/src/index.ts +++ b/packages/agent-core/src/index.ts @@ -28,4 +28,6 @@ export type { ToolExecutedEvent, } from './loop' export { createIpcTransport, IPC_STREAM_SILENCE_TIMEOUT_MS } from './electron-transport' +export { streamText } from './stream-text' +export type { StreamTextOptions, StreamTextOutcome } from './stream-text' export type { IpcStreamChunk, IpcStreamStart, IpcTransportOptions } from './electron-transport' diff --git a/packages/agent-core/src/loop.ts b/packages/agent-core/src/loop.ts index cf2bea8..45d8cb1 100644 --- a/packages/agent-core/src/loop.ts +++ b/packages/agent-core/src/loop.ts @@ -101,6 +101,13 @@ const MAX_ALL_ERROR_TURNS = 8 * retrying here keeps one gateway hiccup from killing a long multi-tool run. */ const EMPTY_STREAM_RETRY_DELAYS_MS = [1_000, 3_000] +/** + * A stream that closed while a tool's arguments were still streaming (buffered + * server-side, cut by a gateway idle timeout) never delivered a tool call, so + * history is untouched and one replay is safe; it is billed, hence one attempt. + */ +const TOOL_ARGS_DROP_MARK = 'while sending tool arguments' +const TOOL_ARGS_DROP_RETRIES = 1 const TURN_LIMIT_NOTE = '[System] The tool-call turn limit for this request has been reached; no more tools may be called this turn. ' + @@ -559,17 +566,22 @@ export class AgentLoop { onError: (error) => { if (generation !== this.generation || settled) return settled = true - const delay = EMPTY_STREAM_RETRY_DELAYS_MS[retriesUsed] - // The no-partial-output guard keeps the retry idempotent (an empty - // stream never emits deltas, but a mislabeled error must not replay - // a turn whose text/tool calls the UI already saw) - if ( - delay !== undefined && + // The no-partial-output guard keeps the empty-stream retry idempotent (an + // empty stream never emits deltas, but a mislabeled error must not replay + // a turn whose text/tool calls the UI already saw). A dropped tool-argument + // stream may have shown text first; that text is simply re-rendered. + const emptyDelay = EMPTY_STREAM_RETRY_DELAYS_MS[retriesUsed] + const retryEmpty = + emptyDelay !== undefined && error.includes('(empty stream)') && - !this.cancelled && !this.turnText && this.toolCalls.length === 0 - ) { + const retryDrop = + retriesUsed < TOOL_ARGS_DROP_RETRIES && + error.includes(TOOL_ARGS_DROP_MARK) && + this.toolCalls.length === 0 + const delay = retryEmpty ? emptyDelay : EMPTY_STREAM_RETRY_DELAYS_MS[0] + if ((retryEmpty || retryDrop) && !this.cancelled) { setTimeout(() => { if (generation !== this.generation) return // Stopped during the backoff window: finalize like a normal cancel diff --git a/packages/agent-core/src/stream-text.ts b/packages/agent-core/src/stream-text.ts new file mode 100644 index 0000000..1371e36 --- /dev/null +++ b/packages/agent-core/src/stream-text.ts @@ -0,0 +1,89 @@ +import type { AgentTransport } from './types' + +/** + * One tool-less streaming request whose reply body IS the artifact (a page, a + * document fragment). Text deltas arrive immediately, so the caller can mirror + * the draft as it grows and no gateway sees a silent connection — tool + * arguments are buffered server-side until the JSON is complete, and an + * artifact-sized argument exceeds gateway idle cutoffs. + */ +export interface StreamTextOptions { + transport: AgentTransport + system: string + user: string + signal?: AbortSignal + /** the stream is cancelled and reported as partial once the raw reply exceeds this */ + maxChars: number + /** + * Maps the raw reply so far to the artifact. `complete` says the format's own + * terminator arrived (e.g. ``); omit it for formats without one, and + * the stop reason decides (a natural end is complete, `max_tokens` is not). + */ + extract(raw: string): { text: string; complete?: boolean } + /** cumulative extracted text; throttle on the caller's side */ + onProgress?(text: string): void +} + +export type StreamTextOutcome = + | { status: 'complete'; text: string } + | { status: 'partial'; text: string; reason: 'error' | 'stopped' | 'max_tokens'; error?: string } + | { status: 'empty'; error: string } + +/** Resolves with what arrived, never throws. */ +export function streamText(opts: StreamTextOptions): Promise { + return new Promise((resolve) => { + let raw = '' + let stopReason: string | undefined + let settled = false + const finish = (outcome: StreamTextOutcome) => { + if (settled) return + settled = true + opts.signal?.removeEventListener('abort', onAbort) + resolve(outcome) + } + const partialOrEmpty = ( + reason: 'error' | 'stopped' | 'max_tokens', + error?: string, + ): StreamTextOutcome => { + const { text } = opts.extract(raw) + if (!text.trim()) return { status: 'empty', error: error ?? reason } + return error === undefined + ? { status: 'partial', text, reason } + : { status: 'partial', text, reason, error } + } + const handle = opts.transport.stream( + { system: opts.system, messages: [{ role: 'user', text: opts.user }], tools: [] }, + { + onDelta: (delta) => { + if (settled) return + raw += delta + if (raw.length > opts.maxChars) { + handle.cancel() + finish(partialOrEmpty('max_tokens', `output exceeded ${opts.maxChars} chars`)) + return + } + opts.onProgress?.(opts.extract(raw).text) + }, + onToolCall: () => undefined, + onStopReason: (reason) => { + stopReason = reason + }, + onDone: () => { + if (settled) return + const { text, complete } = opts.extract(raw) + const finished = complete ?? (stopReason !== 'max_tokens' && text.trim() !== '') + if (finished) finish({ status: 'complete', text }) + else if (stopReason === 'max_tokens') finish(partialOrEmpty('max_tokens')) + else finish(partialOrEmpty('error', complete === undefined ? 'empty reply' : undefined)) + }, + onError: (error) => finish(partialOrEmpty('error', error)), + }, + ) + const onAbort = () => { + handle.cancel() + finish(partialOrEmpty('stopped')) + } + if (opts.signal?.aborted) onAbort() + else opts.signal?.addEventListener('abort', onAbort, { once: true }) + }) +} diff --git a/packages/agent-core/tests/loop.test.ts b/packages/agent-core/tests/loop.test.ts index ee2a1de..08e5cd8 100644 --- a/packages/agent-core/tests/loop.test.ts +++ b/packages/agent-core/tests/loop.test.ts @@ -728,6 +728,65 @@ describe('AgentLoop', () => { } }) + it('replays a turn once when the stream dropped while sending tool arguments', async () => { + vi.useFakeTimers() + try { + const dropped = (cb: AgentStreamCallbacks) => { + cb.onDelta('Let me plan this.') + cb.onError( + 'Claude stream closed while sending tool arguments (1532 chars received); the connection was dropped', + ) + } + const transport = scriptedTransport([ + dropped, + (cb) => { + cb.onDelta('recovered answer') + cb.onDone() + }, + ]) + const onError = vi.fn() + const onDone = vi.fn() + const loop = new AgentLoop({ transport, skill: makeSkill(), events: { onError, onDone } }) + loop.run('question') + await vi.advanceTimersByTimeAsync(0) + expect(transport.requests).toHaveLength(1) + await vi.advanceTimersByTimeAsync(1_000) + expect(transport.requests).toHaveLength(2) + expect(transport.requests[1].messageCount).toBe(transport.requests[0].messageCount) + expect(onError).not.toHaveBeenCalled() + expect(onDone).toHaveBeenCalledWith({ + text: 'recovered answer', + cancelled: false, + turnLimit: false, + }) + } finally { + vi.useRealTimers() + } + }) + + it('a second tool-argument drop fails the run instead of replaying again', async () => { + vi.useFakeTimers() + try { + const dropped = (cb: AgentStreamCallbacks) => + cb.onError( + 'The model stream closed while sending tool arguments (10 chars received); the connection was dropped', + ) + const transport = scriptedTransport([dropped, dropped, dropped]) + const onError = vi.fn() + const loop = new AgentLoop({ transport, skill: makeSkill(), events: { onError } }) + loop.run('question') + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(1_000) + await vi.advanceTimersByTimeAsync(3_000) + expect(transport.requests).toHaveLength(2) + expect(onError).toHaveBeenCalledTimes(1) + expect(loop.messages).toHaveLength(0) + expect(loop.busy).toBe(false) + } finally { + vi.useRealTimers() + } + }) + it('does not retry an empty-stream error arriving after partial output', async () => { const transport = scriptedTransport([ (cb) => { diff --git a/packages/agent-core/tests/stream-text.test.ts b/packages/agent-core/tests/stream-text.test.ts new file mode 100644 index 0000000..dada24f --- /dev/null +++ b/packages/agent-core/tests/stream-text.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStreamCallbacks, AgentTransport } from '../src/types' +import { streamText } from '../src/stream-text' + +function fakeTransport( + script: (cb: AgentStreamCallbacks) => void, + onCancel?: () => void, +): AgentTransport { + return { + stream: (_req, cb) => { + queueMicrotask(() => script(cb)) + return { cancel: () => onCancel?.() } + }, + } +} + +const passthrough = (raw: string) => ({ text: raw.trim() }) + +describe('streamText', () => { + it('sends a tool-less request and reports cumulative progress', async () => { + const progress: string[] = [] + let request: { tools: unknown[]; messages: unknown[] } | undefined + const outcome = await streamText({ + transport: { + stream: (req, cb) => { + request = req + queueMicrotask(() => { + cb.onDelta('# Title\n\n') + cb.onDelta('body') + cb.onStopReason?.('end_turn') + cb.onDone() + }) + return { cancel: () => undefined } + }, + }, + system: 's', + user: 'u', + maxChars: 1000, + extract: passthrough, + onProgress: (text) => progress.push(text), + }) + expect(request?.tools).toEqual([]) + expect(request?.messages).toEqual([{ role: 'user', text: 'u' }]) + expect(outcome).toEqual({ status: 'complete', text: '# Title\n\nbody' }) + expect(progress).toEqual(['# Title', '# Title\n\nbody']) + }) + + it('without a terminator, max_tokens makes the reply partial and end_turn complete', async () => { + const cut = await streamText({ + transport: fakeTransport((cb) => { + cb.onDelta('half') + cb.onStopReason?.('max_tokens') + cb.onDone() + }), + system: 's', + user: 'u', + maxChars: 1000, + extract: passthrough, + }) + expect(cut).toEqual({ status: 'partial', text: 'half', reason: 'max_tokens' }) + const nothing = await streamText({ + transport: fakeTransport((cb) => { + cb.onStopReason?.('end_turn') + cb.onDone() + }), + system: 's', + user: 'u', + maxChars: 1000, + extract: passthrough, + }) + expect(nothing).toEqual({ status: 'empty', error: 'empty reply' }) + }) + + it('an explicit terminator decides completeness over the stop reason', async () => { + const extract = (raw: string) => ({ text: raw, complete: raw.endsWith('END') }) + const done = await streamText({ + transport: fakeTransport((cb) => { + cb.onDelta('abc END') + cb.onStopReason?.('max_tokens') + cb.onDone() + }), + system: 's', + user: 'u', + maxChars: 1000, + extract, + }) + expect(done).toEqual({ status: 'complete', text: 'abc END' }) + const open = await streamText({ + transport: fakeTransport((cb) => { + cb.onDelta('abc') + cb.onStopReason?.('end_turn') + cb.onDone() + }), + system: 's', + user: 'u', + maxChars: 1000, + extract, + }) + expect(open).toEqual({ status: 'partial', text: 'abc', reason: 'error' }) + }) + + it('a dropped connection keeps the partial text; an empty one is empty', async () => { + const partial = await streamText({ + transport: fakeTransport((cb) => { + cb.onDelta('half') + cb.onError('connection dropped') + }), + system: 's', + user: 'u', + maxChars: 1000, + extract: passthrough, + }) + expect(partial).toEqual({ + status: 'partial', + text: 'half', + reason: 'error', + error: 'connection dropped', + }) + const empty = await streamText({ + transport: fakeTransport((cb) => cb.onError('gateway 502')), + system: 's', + user: 'u', + maxChars: 1000, + extract: passthrough, + }) + expect(empty).toEqual({ status: 'empty', error: 'gateway 502' }) + }) + + it('stop cancels the transport and keeps what arrived; later deltas are ignored', async () => { + let cancelled = false + const progress: string[] = [] + const controller = new AbortController() + let callbacks!: AgentStreamCallbacks + const promise = streamText({ + transport: { + stream: (_req, cb) => { + callbacks = cb + queueMicrotask(() => cb.onDelta('first')) + return { + cancel: () => { + cancelled = true + }, + } + }, + }, + system: 's', + user: 'u', + signal: controller.signal, + maxChars: 1000, + extract: passthrough, + onProgress: (text) => progress.push(text), + }) + await new Promise((r) => setTimeout(r, 0)) + controller.abort() + callbacks.onDelta(' late') + callbacks.onDone() + expect(await promise).toEqual({ status: 'partial', text: 'first', reason: 'stopped' }) + expect(cancelled).toBe(true) + expect(progress).toEqual(['first']) + }) + + it('the size cap cancels the stream and reports max_tokens', async () => { + let cancelled = false + const outcome = await streamText({ + transport: fakeTransport( + (cb) => cb.onDelta('x'.repeat(20)), + () => { + cancelled = true + }, + ), + system: 's', + user: 'u', + maxChars: 10, + extract: passthrough, + }) + expect(outcome).toMatchObject({ status: 'partial', reason: 'max_tokens' }) + expect(cancelled).toBe(true) + }) +}) diff --git a/packages/ai-provider/src/protocols/anthropic.ts b/packages/ai-provider/src/protocols/anthropic.ts index b3b8e6a..f657e52 100644 --- a/packages/ai-provider/src/protocols/anthropic.ts +++ b/packages/ai-provider/src/protocols/anthropic.ts @@ -1,7 +1,7 @@ import type { AgentMessage, AgentToolCall, AgentToolDef } from '@genoffice/agent-core' import { aiFetch } from '../fetch' import { httpBodyDetail } from '../http-error' -import { gensparkAttributionHeaders } from '../providers' +import { gensparkAttributionHeaders, opencodeSessionHeaders } from '../providers' import type { AiChatResponse, AiProviderConfig } from '../types' import { createStreamWatchdog, type StreamWatchdog } from '../watchdog' import { @@ -138,6 +138,7 @@ async function anthropicTurn( // allowed". This header is the official opt-in for browser/Electron environments. 'anthropic-dangerous-direct-browser-access': 'true', ...gensparkAttributionHeaders(baseUrl), + ...opencodeSessionHeaders(baseUrl, cb.sessionId), }, body: JSON.stringify({ model: config.model, @@ -267,6 +268,7 @@ export async function chatAnthropic( // Fetch in the Electron main process goes through Chromium's network stack; this header avoids 403. 'anthropic-dangerous-direct-browser-access': 'true', ...gensparkAttributionHeaders(baseUrl), + ...opencodeSessionHeaders(baseUrl), }, body: JSON.stringify({ model: config.model, diff --git a/packages/ai-provider/src/protocols/gemini.ts b/packages/ai-provider/src/protocols/gemini.ts index c40fa2d..a73df28 100644 --- a/packages/ai-provider/src/protocols/gemini.ts +++ b/packages/ai-provider/src/protocols/gemini.ts @@ -1,7 +1,7 @@ import type { AgentMessage, AgentToolDef } from '@genoffice/agent-core' import { aiFetch } from '../fetch' import { httpBodyDetail } from '../http-error' -import { gensparkAttributionHeaders } from '../providers' +import { gensparkAttributionHeaders, opencodeSessionHeaders } from '../providers' import type { AiChatResponse, AiProviderConfig } from '../types' import { createStreamWatchdog, type StreamWatchdog } from '../watchdog' import { toGeminiSchema } from './gemini-schema' @@ -154,6 +154,7 @@ async function geminiTurn( 'Content-Type': 'application/json', 'x-goog-api-key': config.apiKey, ...gensparkAttributionHeaders(baseUrl), + ...opencodeSessionHeaders(baseUrl, cb.sessionId), }, body: JSON.stringify({ systemInstruction: { parts: [{ text: system }] }, @@ -272,6 +273,7 @@ export async function chatGemini( 'Content-Type': 'application/json', 'x-goog-api-key': config.apiKey, ...gensparkAttributionHeaders(baseUrl), + ...opencodeSessionHeaders(baseUrl), }, body: JSON.stringify({ systemInstruction: { parts: [{ text: system }] }, diff --git a/packages/ai-provider/src/protocols/openai-compatible.ts b/packages/ai-provider/src/protocols/openai-compatible.ts index 9704e76..54d839b 100644 --- a/packages/ai-provider/src/protocols/openai-compatible.ts +++ b/packages/ai-provider/src/protocols/openai-compatible.ts @@ -1,7 +1,7 @@ import type { AgentMessage, AgentToolCall, AgentToolDef } from '@genoffice/agent-core' import { aiFetch } from '../fetch' import { httpBodyDetail } from '../http-error' -import { gensparkAttributionHeaders } from '../providers' +import { gensparkAttributionHeaders, opencodeSessionHeaders } from '../providers' import { modelEchoesReasoning } from '../registry' import type { AiChatResponse, AiProviderConfig } from '../types' import { createStreamWatchdog, type StreamWatchdog } from '../watchdog' @@ -156,6 +156,7 @@ async function openAiCompatibleTurn( 'Content-Type': 'application/json', ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}), ...gensparkAttributionHeaders(baseUrl), + ...opencodeSessionHeaders(baseUrl, cb.sessionId), }, body: JSON.stringify({ model: config.model, @@ -320,6 +321,7 @@ export async function chatOpenAiCompatible( 'Content-Type': 'application/json', ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}), ...gensparkAttributionHeaders(baseUrl), + ...opencodeSessionHeaders(baseUrl), }, body: JSON.stringify({ model: config.model, diff --git a/packages/ai-provider/src/providers.ts b/packages/ai-provider/src/providers.ts index 843a69d..198518c 100644 --- a/packages/ai-provider/src/providers.ts +++ b/packages/ai-provider/src/providers.ts @@ -25,6 +25,20 @@ export function gensparkAttributionHeaders(baseUrl?: string): Record { + return baseUrl?.startsWith('https://opencode.ai/') + ? { 'x-opencode-session': sessionId || crypto.randomUUID() } + : {} +} + export const AI_PROVIDERS: AiProviderMeta[] = [ { id: 'genspark', diff --git a/packages/ai-provider/tests/chat.test.ts b/packages/ai-provider/tests/chat.test.ts index 611b15d..9826864 100644 --- a/packages/ai-provider/tests/chat.test.ts +++ b/packages/ai-provider/tests/chat.test.ts @@ -161,6 +161,23 @@ describe('chatForProvider', () => { ).toBeUndefined() }) + it('opencode: a one-shot call gets its own x-opencode-session', async () => { + const fetchMock = vi + .fn() + .mockImplementation(async () => jsonResponse({ choices: [{ message: { content: 'ok' } }] })) + vi.stubGlobal('fetch', fetchMock) + await chatForProvider('opencode-go', { apiKey: 'k', model: 'kimi-k2.7-code' }, 'sys', 'hi') + await chatForProvider('opencode-go', { apiKey: 'k', model: 'kimi-k2.7-code' }, 'sys', 'hi') + const first = (fetchMock.mock.calls[0]![1].headers as Record)[ + 'x-opencode-session' + ] + const second = (fetchMock.mock.calls[1]![1].headers as Record)[ + 'x-opencode-session' + ] + expect(first).toMatch(/^[0-9a-f-]{36}$/) + expect(second).not.toBe(first) + }) + it('treats an empty response body as an error', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ choices: [{ message: {} }] }))) const result = await chatForProvider( diff --git a/packages/ai-provider/tests/stream.test.ts b/packages/ai-provider/tests/stream.test.ts index 469fbbc..50d74bd 100644 --- a/packages/ai-provider/tests/stream.test.ts +++ b/packages/ai-provider/tests/stream.test.ts @@ -895,6 +895,52 @@ describe('streamForProvider: genspark', () => { expect(headers['X-Agent-Type']).toBeUndefined() } }) + + it('opencode: sends the renderer session id as x-opencode-session on every route', async () => { + for (const [provider, model] of [ + ['opencode-go', 'kimi-k2.7-code'], + ['opencode-go', 'minimax-m3'], + ['opencode-zen', 'claude-sonnet-5'], + ['opencode-zen', 'gemini-3.7-flash'], + ] as const) { + const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream([]))) + vi.stubGlobal('fetch', fetchMock) + const { cb } = collector() + await streamForProvider(provider, { apiKey: 'k', model }, 'sys', [], [], 100, { + ...cb, + sessionId: 'tab-42', + }).catch(() => {}) + const headers = fetchMock.mock.calls[0]![1].headers as Record + expect(headers['x-opencode-session']).toBe('tab-42') + } + }) + + it('opencode: a turn without a renderer session id still carries a session header', async () => { + const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream([]))) + vi.stubGlobal('fetch', fetchMock) + await streamForProvider( + 'opencode-go', + { apiKey: 'k', model: 'kimi-k2.7-code' }, + 'sys', + [], + [], + 100, + collector().cb, + ).catch(() => {}) + const headers = fetchMock.mock.calls[0]![1].headers as Record + expect(headers['x-opencode-session']).toMatch(/^[0-9a-f-]{36}$/) + }) + + it('never sends x-opencode-session to other gateways', async () => { + const fetchMock = vi.fn().mockResolvedValue(okResponse(sseStream([]))) + vi.stubGlobal('fetch', fetchMock) + await streamForProvider('kimi', { apiKey: 'k', model: 'kimi-k3' }, 'sys', [], [], 100, { + ...collector().cb, + sessionId: 'tab-42', + }).catch(() => {}) + const headers = fetchMock.mock.calls[0]![1].headers as Record + expect(headers['x-opencode-session']).toBeUndefined() + }) }) describe('streamForProvider: 200 + non-stream JSON instead of SSE', () => { diff --git a/packages/ai-search/src/media-tools.ts b/packages/ai-search/src/media-tools.ts index 79608a4..f14a5d2 100644 --- a/packages/ai-search/src/media-tools.ts +++ b/packages/ai-search/src/media-tools.ts @@ -20,12 +20,10 @@ import { type LegacyAiSettings, type MediaBlob, } from '@genoffice/ai-provider' -import { - fetchRemoteImage, - fetchWithSsrfGuard, - readGeneratedImage, - storeGeneratedImage, -} from '@genoffice/electron-utils' +// deep imports: the package root re-exports Electron-bound modules, and this file also runs in the genoffice CLI +import { readGeneratedImage, storeGeneratedImage } from '@genoffice/electron-utils/generated-images' +import { fetchRemoteImage } from '@genoffice/electron-utils/remote-image' +import { fetchWithSsrfGuard } from '@genoffice/electron-utils/safe-remote-url' import { gskAnalyzeMedia, gskGenerateImage, hasGskAuth, type GskGenerateImageOptions } from './gsk' export const GSK_NOT_LOGGED_IN_ERROR = diff --git a/packages/cli/README.md b/packages/cli/README.md new file mode 100644 index 0000000..ff2c4c5 --- /dev/null +++ b/packages/cli/README.md @@ -0,0 +1,123 @@ +# @genoffice/cli + +`genoffice` is the GenOffice command line. It exposes the suite's document engines +to scripts and AI agents without opening a window: the packaged app runs the +bundled CLI on its own Node runtime (`ELECTRON_RUN_AS_NODE`), so nothing extra +has to be installed. + +``` +genoffice info report.docx +genoffice convert scan.pdf --to docx +genoffice convert data.csv --to xlsx --out out/data.xlsx +genoffice open report.docx +genoffice convert scan.pdf --to pptx --json +genoffice guide slides # op groups; `genoffice guide slides insert` for one group +genoffice slides read deck.pptx [--full] --json # durable ids + geometry an agent targets ops at; --full: whole text, tables, notes +genoffice create --type pptx --ops deck.json --out deck.pptx +genoffice create --type pptx --spec deck/pages --outline deck/outline.json --out deck.pptx # one page spec file per slide (`genoffice guide slides design|spec`) +genoffice slides check deck/outline.json | deck/pages/03.json # outline rules (exit 1 on errors) / build + audit one page file +genoffice slides replace deck.pptx --slide 2 --spec deck/pages/03.json # rebuild one slide from its page file +genoffice slides apply deck.pptx --ops edit.json [--dry-run] [--out copy.pptx] +genoffice slides audit deck.pptx [--slide 0] --json # out-of-bounds / text overflow / overlap per slide, durable ids +genoffice slides render deck.pptx --out shots/ [--scale 2] # one PNG per slide through the app's PDF export +genoffice render report.docx|book.xlsx|page.html|file.pdf --out shots/ [--page 3] [--scale 2] # one PNG per page of any document, to look at what was made +genoffice create --type xlsx --from table.json --out book.xlsx # 2-D array or {sheets:[{name,rows}]}; "=..." cells are formulas +genoffice create --type xlsx --from data.csv --out data.xlsx +genoffice sheet read book.xlsx [--sheet Data] [--range A1:D20] [--formats] --json # values, formulas, sheet features; --formats adds styles, widths, heights +genoffice sheet apply book.xlsx --cells cells.json # [{cell:"B2", value|formula, style?, sheet?}] +genoffice sheet apply book.xlsx --ops ops.json [--dry-run] # workbook DSL: cells, formats, charts, tables, filters, conditional formats, validation, links, notes, panes, page setup, sheets (`genoffice guide sheets`) +genoffice create --type docx --from report.md --out report.docx # or --from fragment.html (restricted HTML) +genoffice convert notes.md --to docx|html +genoffice convert report.docx --to html # the Word editor's standalone-HTML export +genoffice convert page.html --to docx # html2docx, same as the HTML app's Export as Word +genoffice convert report.docx --to md # GFM via the markdown editor's serializer +genoffice convert book.xlsx --to csv [--sheet Data] # one sheet, cell text as displayed, UTF-8 BOM, CRLF +genoffice capabilities --json # which cloud features GenOffice has configured (no network call) +genoffice search "electron headless export" [--images] [--max 6] --json +genoffice image "isometric office, soft light" --aspect 16:9 --out hero.png +genoffice media photo.jpg --ask "What text is in this picture?" --json +genoffice docs read report.docx [--range 0-9] [--html] [--full] [--comments] [--revisions] [--header-footer] --json # blocks (--full: whole text), comment threads, tracked changes, header/footer text +genoffice docs apply report.docx --ops ops.json [--dry-run] # apply_ops entries + insert_content / replace_blocks / insert_image / insert_chart / edit_chart / set_header_footer / reply_comment / resolve_comment +genoffice guide docs # op signatures + restricted-HTML rules +``` + +Word and Markdown commands run the docs and markdown editors under jsdom (installed once per process, loaded lazily). Those modules are imported from the app renderers by relative path until they move into packages of their own. + +Workbook writes go through `@genoffice/xlsx-gateway` (the app's save path). The in-memory workbook validates and applies the cell, format and structure ops; ops the snapshot cannot hold (charts, images, tables, filters, conditional formats, validation, hyperlinks, notes, panes, page setup, protection, defined names, tab order) become the gateway's declarative save payloads, as the app's edit journal does. Pivots, sparklines and edits to editor-session objects stay app-only. After writing formulas genoffice evaluates them with the xlsx sidecar and stores the results as cached values, so `sheet read` and plain readers see numbers, not blanks. + +`create`/`slides apply` take the same ops the in-app AI uses (`@genoffice/pptx-ops`), as a JSON array or `{ "ops": [...] }`; `--ops -` reads stdin. Image ops accept a local file path in their `bytes` field. A rejected op comes back with the guided error and its usage line so the caller can fix and retry; atomic transactions leave the file untouched. + +`create --type pptx --spec` is the CLI end of the app's deck generation pipeline (`@genoffice/pipelines`): the caller's agent does the design work following `genoffice guide slides design`, writing the style sheet, the outline and one page spec file per slide (`genoffice guide slides spec`), and the same page builder the app uses turns them into a pptx, measuring every text box and growing it to its content. Where the app separates the stages into model calls, the CLI separates them into files: `slides check` validates the outline against the planning rules and builds and audits a single page file, then checks it against its outline entry and the style sheet's palette (both found beside the page files), `create --spec

    ` runs the same checks on every file and refuses to assemble a deck with pages missing or disagreeing with the outline, and `slides replace` rebuilds one slide from its file. `slides audit` runs the app's deterministic layout audit; `slides render` gives the agent PNGs to look at. No model call happens inside genoffice. + +Every command prints a one-line human summary by default or a single JSON +object with `--json` (`{ status, command, summary, output_path?, detail? }`). +Exit codes: `0` ok, `1` usage, `2` file, `3` conversion failed, `4` app not +available. + +## Putting genoffice on the PATH + +- **macOS**: the app tries to symlink `/usr/local/bin/genoffice` (or `/opt/homebrew/bin/genoffice`) on every launch until one succeeds. If neither directory is writable it stays silent; run `genoffice install-cli` from the launcher, or `sudo mkdir -p /usr/local/bin && sudo ln -sf "/Applications/GenOffice.app/Contents/Resources/cli/genoffice" /usr/local/bin/genoffice`. +- **Windows**: the installer appends `\resources\cli` to the user PATH (`apps/shell/build/installer.nsh`, REG_EXPAND_SZ preserved, removed on uninstall) and the app re-checks once per version; new terminals see `genoffice`. The directory holds `genoffice.cmd` for cmd / PowerShell and the extension-less `genoffice` for Git Bash. +- **Linux**: the deb/rpm post-install links `/usr/bin/genoffice`; the AppImage relies on the first-launch symlink into `/usr/local/bin` when it is writable. + +`genoffice install-cli` repeats the attempt and prints the manual command when it cannot finish. jsdom (for Word/Markdown) ships beside the bundle as `Resources/cli/node_modules`, collected by `collect-deps.mjs` at build time. + +Independently of the PATH, every launch of the packaged app writes the launcher directory to `~/.genoffice/launcher` (`GENOFFICE_AUTH_DIR` overrides the directory, as for `auth.json`). The `genoffice` agent skill (`skills/genoffice/SKILL.md`) reads it when `genoffice` is not on the PATH. `genoffice --version` prints this package's version, inlined by `build.mjs`. + +## Layout + +- `src/cli.ts` — argv parsing, dispatch, output; `runCli()` is embeddable. +- `src/registry.ts` — `CommandDef` table (`name`, `usage`, `run`), the single + place future entry points (in-app AI, MCP) dispatch through. +- `src/commands/` — `info`, `convert`, `create`, `render`, `slides`, `sheet`, `docs`, + `guide`, `open`, `capabilities`, `search`, `image`, `media`, `install-cli`. +- `src/dom.ts` — the jsdom bootstrap the Word/Markdown paths need. +- `src/formats/` — thin adapters over `@genoffice/pdf2docx`, the xlsx sidecar + and the sheets CSV importer. +- `src/resources.ts` — locates pdfium wasm, the xlsx sidecar and the OCR + helper in both the packaged `Resources/` layout and the dev checkout. +- `bin/genoffice`, `bin/genoffice.cmd` — launchers copied next to `genoffice.cjs` in the + packaged app. + +## Path policy and audit log + +- `GENOFFICE_ALLOWED_ROOTS` (PATH-style list of directories) confines every file genoffice + reads or writes to those trees; symlinks are resolved before the check. A path + outside exits 2 with the roots in `detail.allowed_roots`. Unset means + unrestricted. +- `apply --out` onto another existing file needs `--force`, like `create` / `convert`; + editing in place never does. Unknown options are rejected instead of ignored. +- A file the running GenOffice shell has open in a tab is not rewritten in place + (exit 2, `detail.gui_pid`): the shell publishes its open tabs to + `userData/open-documents.json` and genoffice reads it (`GENOFFICE_USER_DATA` + overrides the location). `--force` writes anyway; the editor then warns about + the on-disk change at its next save (Word, Excel) or may overwrite it (PowerPoint). +- Every executed command appends one JSON line (`ts`, `command`, `argv`, + `status`, `code`, `output_path`, `ms`, `cwd`) to + `~/.genoffice/cli-audit.jsonl`, rotated at 2 MB. `GENOFFICE_AUDIT_LOG=` + redirects it, `GENOFFICE_AUDIT_LOG=off` disables it. + +## Cloud commands + +`search`, `image` and `media` reuse the editors' provider routing: Genspark +when signed in (`~/.genoffice/auth.json`) and cloud tools are on, otherwise the +Serper / Tavily or BYOK image / media provider chosen in the app's AI settings +(`GenOffice/ai-settings.json` in the platform config directory, override with +`GENOFFICE_AI_SETTINGS`). `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY` are honoured. +Search results, image bytes and analysis text come back in the JSON `detail`; +`image` also writes the file. These are the only commands that send data off +the machine. + +## Build and run in a checkout + +``` +npm run build -w @genoffice/cli # esbuild → dist/genoffice.cjs +packages/cli/bin/genoffice info file.docx # falls back to the system node +``` + +Conversions that need an app renderer (Word/PowerPoint/Excel/HTML/Markdown → PDF, +Word → HTML, HTML → Word, `create --type pdf`) run inside the GenOffice binary +through its hidden `--headless-export` mode: genoffice spawns it (Dock hidden, no +window), reads the JSON envelope it prints and maps its exit code. Set +`GENOFFICE_APP_BIN` to point at a specific executable; in a checkout the dev Electron +plus `apps/shell` is used, so `npm run build:all` first. diff --git a/packages/cli/bin/genoffice b/packages/cli/bin/genoffice new file mode 100755 index 0000000..05fb8de --- /dev/null +++ b/packages/cli/bin/genoffice @@ -0,0 +1,36 @@ +#!/bin/sh +# genoffice launcher. Inside a packaged GenOffice it runs the bundled CLI on the +# app's own Node runtime (ELECTRON_RUN_AS_NODE); in a dev checkout it falls +# back to the system node and the local build output. Usually reached through +# a symlink on the PATH, so the real location is resolved first. +self="$0" +while [ -L "$self" ]; do + target=$(readlink "$self") + case "$target" in + /*) self="$target" ;; + *) self="$(dirname "$self")/$target" ;; + esac +done +here=$(cd "$(dirname "$self")" && pwd) + +if [ -n "$GENOFFICE_NODE" ]; then + exec "$GENOFFICE_NODE" "$here/genoffice.cjs" "$@" +fi + +case "$here" in + */Contents/Resources/cli) app="$here/../../MacOS/GenOffice" ;; + */resources/cli) + # Linux install, or the Windows install reached from Git Bash / MSYS + if [ -x "$here/../../GenOffice.exe" ]; then app="$here/../../GenOffice.exe"; else app="$here/../../genoffice"; fi + ;; + *) app="" ;; +esac + +if [ -n "$app" ] && [ -x "$app" ]; then + ELECTRON_RUN_AS_NODE=1 exec "$app" "$here/genoffice.cjs" "$@" +fi + +if [ -f "$here/genoffice.cjs" ]; then + exec node "$here/genoffice.cjs" "$@" +fi +exec node "$here/../dist/genoffice.cjs" "$@" diff --git a/packages/cli/bin/genoffice.cmd b/packages/cli/bin/genoffice.cmd new file mode 100644 index 0000000..e37c7a8 --- /dev/null +++ b/packages/cli/bin/genoffice.cmd @@ -0,0 +1,6 @@ +@echo off +rem genoffice launcher for the packaged Windows app: \resources\cli\genoffice.cmd +setlocal +set ELECTRON_RUN_AS_NODE=1 +"%~dp0..\..\GenOffice.exe" "%~dp0genoffice.cjs" %* +endlocal diff --git a/packages/cli/build.mjs b/packages/cli/build.mjs new file mode 100644 index 0000000..a61ea4e --- /dev/null +++ b/packages/cli/build.mjs @@ -0,0 +1,55 @@ +// Bundles the CLI into one CommonJS file so the packaged app can run it with +// ELECTRON_RUN_AS_NODE (no node_modules ship with the app). Runtime assets +// (pdfium wasm, xlsx sidecar, OCR helper) are located by src/resources.ts. +import { build } from 'esbuild' +import { readFile } from 'node:fs/promises' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) +const { version } = JSON.parse(await readFile(join(here, 'package.json'), 'utf8')) + +// Vite's `?raw` text imports (the pptx op guides are markdown files) +const rawText = { + name: 'raw-text', + setup(b) { + b.onResolve({ filter: /\?raw$/ }, (args) => ({ + path: resolve(args.resolveDir, args.path.replace(/\?raw$/, '')), + namespace: 'raw-text', + })) + b.onLoad({ filter: /.*/, namespace: 'raw-text' }, async (args) => ({ + contents: await readFile(args.path, 'utf8'), + loader: 'text', + })) + }, +} + +await build({ + entryPoints: [join(here, 'src/cli.ts')], + outfile: join(here, 'dist/genoffice.cjs'), + bundle: true, + platform: 'node', + target: 'node22', + format: 'cjs', + logLevel: 'info', + // esbuild leaves import.meta empty in cjs output; deps use import.meta.url + // for asset lookups, so give them the bundle's own location. + define: { + 'import.meta.url': '__cliImportMetaUrl', + __GENOFFICE_VERSION__: JSON.stringify(version), + }, + banner: { js: "const __cliImportMetaUrl = require('node:url').pathToFileURL(__filename).href;" }, + jsx: 'automatic', + // jsdom reads its own stylesheet from disk and cannot be inlined; it ships beside the bundle + // mermaid is only reached by the markdown editor's lazy diagram renderer, which never runs headless + external: ['electron', 'jsdom', 'mermaid'], + loader: { + '.css': 'empty', + '.ttf': 'empty', + '.woff': 'empty', + '.woff2': 'empty', + '.svg': 'empty', + '.png': 'empty', + }, + plugins: [rawText], +}) diff --git a/packages/cli/collect-deps.mjs b/packages/cli/collect-deps.mjs new file mode 100644 index 0000000..7ee6ea1 --- /dev/null +++ b/packages/cli/collect-deps.mjs @@ -0,0 +1,53 @@ +// Copies the runtime dependencies the bundle leaves external (jsdom and its +// tree) into dist/node_modules, mirroring their layout under the checkout's +// node_modules so nested versions keep resolving. The packaged app ships the +// result beside genoffice.cjs (Resources/cli/node_modules); src/dom.ts resolves +// jsdom from there. +import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' +import { dirname, join, relative, resolve, sep } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) +const rootModules = resolve(here, '../../node_modules') +const out = join(here, 'dist', 'node_modules') +const EXTERNALS = ['jsdom'] + +function resolvePkg(name, from) { + let dir = from + for (;;) { + const candidate = join(dir, 'node_modules', name) + if (existsSync(join(candidate, 'package.json'))) return candidate + const parent = dirname(dir) + if (parent === dir) return null + dir = parent + } +} + +const seen = new Set() +function walk(name, from) { + const dir = resolvePkg(name, from) + if (!dir) throw new Error(`genoffice deps: cannot resolve ${name} from ${from}`) + if (seen.has(dir)) return + seen.add(dir) + const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) + for (const dep of Object.keys(pkg.dependencies ?? {})) walk(dep, dir) + for (const dep of Object.keys(pkg.optionalDependencies ?? {})) { + if (resolvePkg(dep, dir)) walk(dep, dir) + } +} +for (const name of EXTERNALS) walk(name, resolve(here, '..', '..')) + +rmSync(out, { recursive: true, force: true }) +mkdirSync(out, { recursive: true }) +for (const dir of seen) { + const rel = relative(rootModules, dir) + if (rel.startsWith('..')) + throw new Error(`genoffice deps: ${dir} is outside the root node_modules`) + cpSync(dir, join(out, rel), { + recursive: true, + dereference: true, + // nested node_modules are copied by their own closure entries + filter: (src) => !relative(dir, src).split(sep).includes('node_modules'), + }) +} +console.log(`genoffice deps: ${seen.size} packages → ${relative(here, out)}`) diff --git a/packages/cli/package.json b/packages/cli/package.json new file mode 100644 index 0000000..9232dd8 --- /dev/null +++ b/packages/cli/package.json @@ -0,0 +1,43 @@ +{ + "name": "@genoffice/cli", + "version": "0.6.0", + "license": "Apache-2.0", + "private": true, + "type": "module", + "description": "genoffice: the GenOffice command line (create, convert, read, edit and render documents) built on the same engines as the app; runs headless on the app's bundled Node runtime", + "exports": { + ".": "./src/index.ts", + "./install": "./src/install.ts" + }, + "bin": { + "genoffice": "./bin/genoffice" + }, + "scripts": { + "build": "node build.mjs && node collect-deps.mjs", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@genoffice/ai-provider": "*", + "@genoffice/ai-search": "*", + "@genoffice/docx-engine": "*", + "@genoffice/pdf2docx": "*", + "@genoffice/pipelines": "*", + "@genoffice/pptx-engine": "*", + "@genoffice/pptx-ops": "*", + "@genoffice/pptx-render": "*", + "@genoffice/xlsx-gateway": "*", + "@tiptap/core": "3.31.0", + "jsdom": "^28.0.0", + "jszip": "^3.10.1", + "numfmt": "^3.2.6", + "undici": "^6.28.0" + }, + "devDependencies": { + "@types/node": "^24.10.1", + "esbuild": "^0.25.12", + "typescript": "^5.9.3", + "vitest": "^4.1.11" + } +} diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts new file mode 100644 index 0000000..0a89a37 --- /dev/null +++ b/packages/cli/src/args.ts @@ -0,0 +1,55 @@ +export interface ParsedArgs { + positionals: string[] + flags: Record +} + +/** + * `--key value`, `--key=value`, `--flag`, `-h`; a lone `--` ends flag parsing. + * Names in `booleans` never take a value, so `genoffice --json info a.docx` keeps + * `info` as the command. + */ +export function parseArgs( + argv: readonly string[], + booleans: ReadonlySet = new Set(), +): ParsedArgs { + const positionals: string[] = [] + const flags: Record = {} + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] + if (arg === '--') { + positionals.push(...argv.slice(i + 1)) + break + } + if (arg === '-h') { + flags.help = true + continue + } + if (!arg.startsWith('--') || arg.length === 2) { + positionals.push(arg) + continue + } + const eq = arg.indexOf('=') + if (eq !== -1) { + flags[arg.slice(2, eq)] = arg.slice(eq + 1) + continue + } + const key = arg.slice(2) + const next = argv[i + 1] + if (!booleans.has(key) && next !== undefined && !next.startsWith('--')) { + flags[key] = next + i++ + } else { + flags[key] = true + } + } + return { positionals, flags } +} + +export function flagString(args: ParsedArgs, name: string): string | undefined { + const v = args.flags[name] + return typeof v === 'string' ? v : undefined +} + +export function flagBool(args: ParsedArgs, name: string): boolean { + return args.flags[name] !== undefined +} diff --git a/packages/cli/src/audit.ts b/packages/cli/src/audit.ts new file mode 100644 index 0000000..0f7474d --- /dev/null +++ b/packages/cli/src/audit.ts @@ -0,0 +1,41 @@ +import { appendFileSync, mkdirSync, renameSync, statSync } from 'node:fs' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' + +/** + * One JSON line per executed command, so the person who let an agent loose + * with genoffice can see afterwards what it touched. Default location + * ~/.genoffice/cli-audit.jsonl; GENOFFICE_AUDIT_LOG= redirects, `off` + * disables. Never throws: a failed audit write must not fail the command. + */ +export interface AuditRecord { + command: string + argv: readonly string[] + status: 'ok' | 'error' + code: number + output_path?: string + ms: number + cwd: string +} + +const MAX_BYTES = 2_000_000 + +export function auditLogPath(env: NodeJS.ProcessEnv): string | null { + const raw = env.GENOFFICE_AUDIT_LOG?.trim() + if (raw?.toLowerCase() === 'off') return null + if (raw) return raw + return join(env.GENOFFICE_AUTH_DIR || join(homedir(), '.genoffice'), 'cli-audit.jsonl') +} + +export function appendAudit(env: NodeJS.ProcessEnv, record: AuditRecord): void { + const path = auditLogPath(env) + if (!path) return + try { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }) + try { + if (statSync(path).size > MAX_BYTES) renameSync(path, `${path}.1`) + } catch {} + const line = JSON.stringify({ ts: new Date().toISOString(), pid: process.pid, ...record }) + appendFileSync(path, line + '\n', { mode: 0o600 }) + } catch {} +} diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts new file mode 100644 index 0000000..9435962 --- /dev/null +++ b/packages/cli/src/cli.ts @@ -0,0 +1,213 @@ +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { flagBool, parseArgs } from './args' +import { appendAudit } from './audit' +import { capabilitiesCommand } from './commands/capabilities' +import { convertCommand } from './commands/convert' +import { docsCommand } from './commands/docs' +import { createCommand } from './commands/create' +import { guideCommand } from './commands/guide' +import { imageCommand } from './commands/image' +import { mediaCommand } from './commands/media' +import { searchCommand } from './commands/search' +import { infoCommand } from './commands/info' +import { installCommand } from './commands/install' +import { openCommand } from './commands/open' +import { renderCommand } from './commands/render' +import { sheetCommand } from './commands/sheet' +import { slidesCommand } from './commands/slides' +import { CommandRegistry, commandHelp, type CommandContext } from './registry' +import { CliError, EXIT, formatHuman, toJsonError, toJsonOk, type ExitCode } from './result' + +declare const __GENOFFICE_VERSION__: string | undefined + +/** The @genoffice/cli package version: inlined by build.mjs, read from disk when running from source. */ +export const VERSION: string = + typeof __GENOFFICE_VERSION__ === 'string' ? __GENOFFICE_VERSION__ : devVersion() + +function devVersion(): string { + try { + const dir = typeof __dirname === 'string' ? __dirname : dirname(fileURLToPath(import.meta.url)) + return `${JSON.parse(readFileSync(join(dir, '..', 'package.json'), 'utf-8')).version}-dev` + } catch { + return '0.0.0-dev' + } +} + +export function defaultRegistry(): CommandRegistry { + return new CommandRegistry() + .register(infoCommand) + .register(convertCommand) + .register(createCommand) + .register(slidesCommand) + .register(sheetCommand) + .register(docsCommand) + .register(renderCommand) + .register(guideCommand) + .register(searchCommand) + .register(imageCommand) + .register(mediaCommand) + .register(openCommand) + .register(capabilitiesCommand) + .register(installCommand) +} + +export interface RunIo { + stdout: (text: string) => void + stderr: (text: string) => void +} + +export interface RunOptions { + cwd?: string + env?: NodeJS.ProcessEnv + registry?: CommandRegistry + io?: RunIo +} + +/** Runs one invocation; returns the exit code instead of exiting so tests and hosts can embed it. */ +export async function runCli(argv: readonly string[], opts: RunOptions = {}): Promise { + const registry = opts.registry ?? defaultRegistry() + const io = opts.io ?? { + stdout: (t) => process.stdout.write(t + '\n'), + stderr: (t) => process.stderr.write(t + '\n'), + } + const args = parseArgs(argv, booleanFlags(registry)) + const json = flagBool(args, 'json') + const name = args.positionals.shift() ?? null + + const fail = (err: CliError): ExitCode => { + if (json) io.stdout(JSON.stringify(toJsonError(name, err))) + else + io.stderr( + `genoffice: ${err.message}` + (err.detail ? `\n ${JSON.stringify(err.detail)}` : ''), + ) + return err.code + } + + if (flagBool(args, 'version')) { + io.stdout(json ? JSON.stringify({ status: 'ok', version: VERSION }) : `genoffice ${VERSION}`) + return EXIT.ok + } + if (name === null || (name === 'help' && args.positionals.length === 0)) { + io.stdout(globalHelp(registry)) + return name === null && !flagBool(args, 'help') ? EXIT.usage : EXIT.ok + } + const def = registry.get(name === 'help' ? args.positionals[0] : name) + if (!def) + return fail( + new CliError(EXIT.usage, `unknown command: ${name}`, { + commands: registry.list().map((d) => d.name), + }), + ) + if (name === 'help' || flagBool(args, 'help')) { + io.stdout(commandHelp(def)) + return EXIT.ok + } + const known = new Set(['json', 'help', 'version', ...(def.options ?? []).map((o) => o.name)]) + const unknown = Object.keys(args.flags).filter((f) => !known.has(f)) + if (unknown.length) { + return fail( + new CliError( + EXIT.usage, + `unknown option${unknown.length > 1 ? 's' : ''} for ${def.name}: ${unknown.map((f) => `--${f}`).join(', ')}`, + { + options: [...known].map((f) => `--${f}`), + }, + ), + ) + } + + const ctx: CommandContext = { + cwd: opts.cwd ?? process.cwd(), + env: opts.env ?? process.env, + log: (m) => io.stderr(m), + } + const started = Date.now() + const audit = (status: 'ok' | 'error', code: ExitCode, outputPath?: string) => + appendAudit(ctx.env, { + command: def.name, + argv: redactArgv(argv), + status, + code, + ...(outputPath ? { output_path: outputPath } : {}), + ms: Date.now() - started, + cwd: ctx.cwd, + }) + try { + const result = await def.run(args, ctx) + audit('ok', EXIT.ok, result.outputPath) + io.stdout(json ? JSON.stringify(toJsonOk(def.name, result)) : formatHuman(result)) + return EXIT.ok + } catch (err) { + const error = + err instanceof CliError + ? err + : new CliError(EXIT.conversion, err instanceof Error ? err.message : String(err)) + audit('error', error.code) + return fail(error) + } +} + +const SECRET_FLAG = /^--(password|api[-_]?key|token|secret)$/i + +/** Secrets never reach the audit log; the flag stays so the call is still recognizable. */ +export function redactArgv(argv: readonly string[]): string[] { + const out: string[] = [] + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]! + const eq = arg.indexOf('=') + if (eq !== -1 && SECRET_FLAG.test(arg.slice(0, eq))) { + out.push(`${arg.slice(0, eq)}=***`) + continue + } + out.push(arg) + if (SECRET_FLAG.test(arg) && i + 1 < argv.length) { + out.push('***') + i++ + } + } + return out +} + +function booleanFlags(registry: CommandRegistry): Set { + const names = new Set(['json', 'help', 'version']) + for (const def of registry.list()) { + for (const o of def.options ?? []) if (!o.value) names.add(o.name) + } + return names +} + +function globalHelp(registry: CommandRegistry): string { + const defs = registry.list() + const width = Math.max(...defs.map((d) => d.name.length)) + return [ + `genoffice ${VERSION} — GenOffice command line`, + '', + 'Usage: genoffice [options]', + '', + 'Commands:', + ...defs.map((d) => ` ${d.name.padEnd(width)} ${d.summary}`), + '', + 'Global options:', + ' --json machine-readable output (one JSON object on stdout)', + ' --help show help for a command', + ' --version print the version', + '', + 'Exit codes: 0 ok, 1 usage, 2 file, 3 conversion failed, 4 app not available', + ].join('\n') +} + +const isMain = + typeof require !== 'undefined' && typeof module !== 'undefined' && require.main === module +if (isMain) { + // stdout is async on a pipe: exiting right after write() drops everything past the + // 64 KiB pipe buffer, so a `--json` consumer would see a cut JSON object + const exit = (code: number) => process.stdout.write('', () => process.exit(code)) + runCli(process.argv.slice(2)).then(exit, (err) => { + process.stderr.write( + `genoffice: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`, + ) + exit(EXIT.conversion) + }) +} diff --git a/packages/cli/src/cloud.ts b/packages/cli/src/cloud.ts new file mode 100644 index 0000000..197c157 --- /dev/null +++ b/packages/cli/src/cloud.ts @@ -0,0 +1,49 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { setGskProxyUrl } from '@genoffice/ai-search' +import { genofficeUserDataDir } from './gui' +import { packagedResourcesDir } from './resources' + +/** + * The cloud commands (search / image / media) reuse the editors' provider + * routing: Genspark when signed in (~/.genoffice/auth.json) and cloud tools + * are on, otherwise the BYOK provider chosen in the app's AI settings. That + * settings file lives in the shell's Electron userData directory, which genoffice + * has to locate without Electron. + */ +export function aiSettingsPath(env: NodeJS.ProcessEnv): string { + return env.GENOFFICE_AI_SETTINGS || join(genofficeUserDataDir(env), 'ai-settings.json') +} + +/** First http(s) proxy in the usual environment variables, as the app's main process reads them. */ +export function proxyUrlFromEnv(env: NodeJS.ProcessEnv): string | null { + return ( + [ + env.HTTPS_PROXY, + env.https_proxy, + env.HTTP_PROXY, + env.http_proxy, + env.ALL_PROXY, + env.all_proxy, + ].find((v) => v && /^https?:\/\//.test(v)) ?? null + ) +} + +let prepared = false + +/** Once per process: proxy for fetch and the gsk children, and the packaged gsk CLI location. */ +export async function prepareCloud(env: NodeJS.ProcessEnv): Promise { + if (prepared) return + prepared = true + const proxy = proxyUrlFromEnv(env) + if (proxy) { + setGskProxyUrl(proxy) + const { ProxyAgent, setGlobalDispatcher } = await import('undici') + setGlobalDispatcher(new ProxyAgent(proxy)) + } + const packaged = packagedResourcesDir() + if (packaged && !env.GSK_CLI_PATH) { + const entry = join(packaged, 'gsk', 'node_modules', '@genspark', 'cli', 'dist', 'index.js') + if (existsSync(entry)) process.env.GSK_CLI_PATH = entry + } +} diff --git a/packages/cli/src/commands/capabilities.ts b/packages/cli/src/commands/capabilities.ts new file mode 100644 index 0000000..6a4fb60 --- /dev/null +++ b/packages/cli/src/commands/capabilities.ts @@ -0,0 +1,63 @@ +import { + activeMediaProvider, + activeSearchProvider, + cloudToolsEnabled, + imageGenerationAvailable, + mediaAnalysisAvailable, +} from '@genoffice/ai-provider' +import { hasGskAuth, readAiSettingsFile } from '@genoffice/ai-search' +import { aiSettingsPath, prepareCloud } from '../cloud' +import type { CommandDef } from '../registry' +import { appLaunch } from '../resources' + +/** + * What the cloud commands can do on this machine, decided from GenOffice's + * own settings without a network call: a Genspark login with cloud tools on, + * or a BYOK key the user entered in Settings. Unkeyed fallbacks (DuckDuckGo) + * do not count as configured. Agents check this once before planning work + * that needs photos or web facts. + */ +export const capabilitiesCommand: CommandDef = { + name: 'capabilities', + summary: + 'Report which cloud features (search, image search, image generation, media analysis) are configured in GenOffice, and whether the app is installed.', + usage: 'capabilities', + async run(_args, ctx) { + await prepareCloud(ctx.env) + const settings = readAiSettingsFile(aiSettingsPath(ctx.env)) + const gsk = hasGskAuth() && cloudToolsEnabled(settings) + const searchProvider = activeSearchProvider(settings) + const keyedSearch = searchProvider !== 'genspark' + const search = gsk || keyedSearch + const imageSearch = gsk || searchProvider === 'serper' + const imageGeneration = imageGenerationAvailable(settings, hasGskAuth()) + const mediaAnalysis = mediaAnalysisAvailable(settings, hasGskAuth()) + const via = (byok: string | null | undefined) => (byok ? byok : gsk ? 'genspark' : null) + const detail = { + search: { available: search, via: keyedSearch ? searchProvider : gsk ? 'genspark' : null }, + image_search: { + available: imageSearch, + via: searchProvider === 'serper' ? 'serper' : gsk ? 'genspark' : null, + }, + image_generation: { + available: imageGeneration, + via: imageGeneration ? via(activeMediaProvider(settings, 'image')) : null, + }, + media_analysis: { + available: mediaAnalysis, + via: mediaAnalysis ? via(activeMediaProvider(settings, 'analysis')) : null, + }, + app: { available: appLaunch(ctx.env) !== null }, + settings_path: aiSettingsPath(ctx.env), + } + const on = Object.entries(detail) + .filter(([k, v]) => k !== 'settings_path' && (v as { available: boolean }).available) + .map(([k]) => k) + return { + summary: on.length + ? `configured: ${on.join(', ')}` + : 'no cloud feature configured; the app is not installed', + detail, + } + }, +} diff --git a/packages/cli/src/commands/convert.ts b/packages/cli/src/commands/convert.ts new file mode 100644 index 0000000..56e4bc2 --- /dev/null +++ b/packages/cli/src/commands/convert.ts @@ -0,0 +1,177 @@ +import { writeFileSync } from 'node:fs' +import { basename, dirname, extname, join } from 'node:path' +import { PdfLoadError } from '@genoffice/pdf2docx' +import { flagBool, flagString, type ParsedArgs } from '../args' +import { csvToXlsx } from '../formats/csv' +import { convertPdf, type PdfTarget } from '../formats/pdf' +import { convertLegacyWorkbook, sheetToCsv } from '../formats/xlsx' +import { exportViaApp, type AppExportTarget } from '../formats/app-export' +import { htmlToMarkdown, markdownToDocx, markdownToHtml } from '../formats/markdown' +import { closeDocument, documentHtml, openDocument } from '../formats/docx' +import { extension, readInput, resolveInput, resolveOutput } from '../fs' +import type { CommandContext, CommandDef } from '../registry' +import { CliError, EXIT } from '../result' + +/** Conversions that run in this process. */ +const NODE_ROUTES: Record = { + pdf: ['docx', 'pptx', 'xlsx'], + csv: ['xlsx'], + xls: ['xlsx'], + xlsb: ['xlsx'], + ods: ['xlsx'], + md: ['docx', 'html'], + markdown: ['docx', 'html'], + docx: ['md'], + xlsx: ['csv'], + xlsm: ['csv'], +} + +/** + * Conversions the GenOffice binary runs for us in its hidden headless-export + * mode: anything that needs an app renderer (page layout for pdf, the Word + * editor's HTML export, html2docx). Mirrors HEADLESS_TARGETS in the shell. + */ +const APP_ROUTES: Record = { + csv: ['pdf'], + xls: ['pdf'], + md: ['pdf'], + markdown: ['pdf'], + docx: ['pdf', 'html'], + xlsx: ['pdf'], + xlsm: ['pdf'], + pptx: ['pdf'], + html: ['pdf', 'docx'], + htm: ['pdf', 'docx'], +} + +const ROUTES: Record = Object.fromEntries( + [...new Set([...Object.keys(NODE_ROUTES), ...Object.keys(APP_ROUTES)])].map((from) => [ + from, + [...(NODE_ROUTES[from] ?? []), ...(APP_ROUTES[from] ?? [])], + ]), +) + +function appTarget(from: string, to: string): AppExportTarget | null { + const target = APP_ROUTES[from]?.find((t) => t === to) + return target ?? null +} + +export const convertCommand: CommandDef = { + name: 'convert', + summary: 'Convert a document to another format using the GenOffice engines.', + usage: 'convert --to [--out ] [--force] [--password ] [--sheet ]', + options: [ + { name: 'to', value: 'format', description: 'target format: ' + describeRoutes() }, + { name: 'out', value: 'path', description: 'output file (default: same name, new extension)' }, + { name: 'force', description: 'overwrite an existing output file' }, + { name: 'password', value: 'pw', description: 'password for an encrypted PDF' }, + { + name: 'sheet', + value: 'name', + description: 'xlsx→csv: worksheet to export (default: the active one)', + }, + ], + async run(args, ctx) { + const input = resolveInput(args.positionals[0], ctx) + const from = extension(input) + const to = flagString(args, 'to')?.toLowerCase() + if (!to) throw new CliError(EXIT.usage, 'missing --to ') + const targets = ROUTES[from] + if (!targets?.includes(to)) { + throw new CliError(EXIT.usage, `cannot convert .${from} to .${to}`, { + supported: describeRoutes(), + }) + } + // before run(): the sidecar and app routes write the output themselves + const output = resolveOutput(flagString(args, 'out'), ctx, { + fallback: join(dirname(input), `${basename(input, extname(input))}.${to}`), + force: flagBool(args, 'force'), + fresh: true, + }) + const result = await run(input, from, to, output, args, ctx) + if (result.bytes) writeFileSync(output, result.bytes) + return { + summary: `converted ${basename(input)} → ${basename(output)}`, + outputPath: output, + detail: result.detail, + } + }, +} + +interface Produced { + bytes?: Uint8Array + detail: Record +} + +async function run( + input: string, + from: string, + to: string, + output: string, + args: ParsedArgs, + ctx: CommandContext, +): Promise { + const password = flagString(args, 'password') + const viaApp = appTarget(from, to) + if (viaApp) { + const r = await exportViaApp(input, viaApp, output, { env: ctx.env, log: ctx.log }) + return { detail: { via: 'genoffice --headless-export', summary: r.summary } } + } + if (from === 'pdf') { + try { + const r = await convertPdf(readInput(input), to as PdfTarget, { + password, + onProgress: (page, total) => ctx.log(`page ${page}/${total}`), + }) + return { bytes: r.bytes, detail: { pages: r.pages, warnings: r.warnings } } + } catch (err) { + if (err instanceof PdfLoadError) { + const code = err.code === 'password-required' ? EXIT.file : EXIT.conversion + throw new CliError(code, err.message, { reason: err.code }) + } + throw err + } + } + if (from === 'md' || from === 'markdown') { + const text = Buffer.from(readInput(input)).toString('utf-8') + const title = basename(input, extname(input)) + if (to === 'html') { + return { bytes: Buffer.from(await markdownToHtml(text, title), 'utf-8'), detail: { title } } + } + return { bytes: await markdownToDocx(text, { file: input, ctx }), detail: { title } } + } + if (from === 'csv') { + const sheet = basename(input, extname(input)).slice(0, 31) || 'Sheet1' + return { bytes: await csvToXlsx(readInput(input), sheet), detail: { sheet } } + } + if (to === 'csv') { + const { csv, ...detail } = await sheetToCsv(input, { sheet: flagString(args, 'sheet') }) + // UTF-8 BOM, as the app writes it, so Excel opens the file without a wizard + return { bytes: Buffer.from('\ufeff' + csv, 'utf-8'), detail } + } + if (to === 'md') { + const doc = await openDocument(readInput(input)) + try { + const exported = documentHtml(doc) + const markdown = await htmlToMarkdown(exported.html) + return { + bytes: Buffer.from(markdown.replace(/\n{3,}/g, '\n\n').trimEnd() + '\n', 'utf-8'), + detail: { + blocks: doc.editor.state.doc.childCount, + skipped: exported.skipped, + formulas_as_text: exported.formulasAsText, + }, + } + } finally { + closeDocument(doc) + } + } + const r = await convertLegacyWorkbook(input, output) + return { detail: { sheets: r.sheets, cells: r.cells } } +} + +function describeRoutes(): string { + return Object.entries(ROUTES) + .map(([from, tos]) => `${from}→${tos.join('/')}`) + .join(', ') +} diff --git a/packages/cli/src/commands/create.ts b/packages/cli/src/commands/create.ts new file mode 100644 index 0000000..9961f80 --- /dev/null +++ b/packages/cli/src/commands/create.ts @@ -0,0 +1,264 @@ +import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { basename, dirname, extname, isAbsolute, resolve } from 'node:path' +import { flagBool, flagString } from '../args' +import { assertAllowed, resolveInput, resolveOutput } from '../fs' +import { applyOps, blankDeck, inlineLocalFiles, parseOps, saveDeck } from '../formats/pptx' +import { buildDeckFromDir, buildDeckFromSpec, stageContext } from '../formats/slide-spec' +import { + additionPlan, + blankWorkbook, + cellEditsFromTable, + csvTable, + writeWorkbook, + type TableInput, +} from '../formats/xlsx' +import { exportViaApp } from '../formats/app-export' +import { blankDocument, closeDocument, fillFromHtml, saveDocument } from '../formats/docx' +import { markdownToDocx } from '../formats/markdown' +import { readOpsInput } from '../ops-input' +import type { CommandContext, CommandDef } from '../registry' +import type { TxnResult } from '@genoffice/pptx-ops' +import { CliError, EXIT, type CommandResult } from '../result' +import { txnFailure, txnDetail } from './txn' + +/** Document types that can be built here. */ +const TYPES = ['pptx', 'xlsx', 'docx', 'pdf'] as const + +export const createCommand: CommandDef = { + name: 'create', + summary: 'Create a new document from structured content.', + usage: + 'create --type (--ops | --spec [--outline ] | --from ) --out [--force]', + options: [ + { name: 'type', value: 'type', description: `document type: ${TYPES.join(', ')}` }, + { + name: 'ops', + value: 'file', + description: + 'pptx: JSON array of ops (or {"ops":[...]}) applied one by one to a blank one-slide deck (later ops can target slides added earlier); "-" reads stdin. See `genoffice guide slides`.', + }, + { + name: 'spec', + value: 'file', + description: + 'pptx: a deck spec (pages of px-positioned text, shapes and images on a 1280x720 canvas) built into one slide per page, or a directory of one-page spec files taken in name order; "-" reads stdin. See `genoffice guide slides spec` and `genoffice guide slides design`.', + }, + { + name: 'outline', + value: 'file', + description: + 'pptx --spec : the deck outline the pages were written from (default: outline.json in or beside the directory); every page file is checked against its entry and the build refuses to run until every outline page has its file', + }, + { + name: 'from', + value: 'file', + description: + 'xlsx: a .csv, or a .json holding a 2-D array of cell values or { "sheets": [{ "name", "rows" }] }; strings starting with "=" are formulas. docx: a .md file, or a .html file holding a restricted-HTML fragment (see `genoffice guide docs`). pdf: any .md/.html/.docx/.xlsx/.pptx file, printed by the GenOffice renderer', + }, + { name: 'out', value: 'path', description: 'output file (required)' }, + { name: 'force', description: 'overwrite an existing output file' }, + ], + async run(args, ctx) { + const type = flagString(args, 'type')?.toLowerCase() + if (!type) throw new CliError(EXIT.usage, 'missing --type ') + if (!(TYPES as readonly string[]).includes(type)) { + throw new CliError(EXIT.usage, `cannot create .${type} yet`, { supported: [...TYPES] }) + } + const output = resolveOutput(flagString(args, 'out'), ctx, { + force: flagBool(args, 'force'), + fresh: true, + }) + if (type === 'pdf') { + const from = flagString(args, 'from') + if (!from) throw new CliError(EXIT.usage, 'pdf needs --from ') + const source = resolveInput(from, ctx) + const r = await exportViaApp(source, 'pdf', output, { env: ctx.env, log: ctx.log }) + return { + summary: `created ${basename(output)}`, + outputPath: output, + detail: { via: 'genoffice --headless-export', summary: r.summary }, + } + } + if (type === 'docx') { + const r = await createDocx(args, ctx) + writeFileSync(output, r.bytes) + return { summary: `created ${basename(output)}`, outputPath: output, detail: r.detail } + } + if (type === 'xlsx') { + const r = await createXlsx(args, ctx, output) + return { + summary: `created ${basename(output)} (${r.sheets} sheets)`, + outputPath: output, + detail: r, + } + } + const result = + flagString(args, 'spec') !== undefined + ? await createPptxFromSpec(args, ctx) + : await createPptx(args, ctx) + writeFileSync(output, result.bytes) + return { + summary: `created ${basename(output)} (${result.slides} slides)`, + outputPath: output, + detail: result.detail, + } + }, +} + +async function createPptx( + args: Parameters[0], + ctx: CommandContext, +): Promise<{ bytes: Uint8Array; slides: number; detail: CommandResult['detail'] }> { + const { text, source } = readOpsInput(args, ctx) + const ops = inlineLocalFiles(parseOps(text, source), ctx) + const opened = await blankDeck() + // One transaction per op: the executor validates a batch against the + // pre-transaction deck, so slides added earlier in the list would not yet + // exist for later ops. Nothing is written unless every op applies. + const records: NonNullable = [] + for (const [index, op] of ops.entries()) { + const r = applyOps(opened, [op], { isolation: 'atomic' }) + if (!r.applied) throw txnFailure(r, index) + records.push(...(r.records ?? [])) + } + return { + bytes: await saveDeck(opened), + slides: opened.deck.slides.length, + detail: txnDetail({ applied: true, records }), + } +} + +async function createPptxFromSpec( + args: Parameters[0], + ctx: CommandContext, +): Promise<{ bytes: Uint8Array; slides: number; detail: CommandResult['detail'] }> { + const spec = flagString(args, 'spec')! + const next = + 'genoffice slides audit for the geometry audit; genoffice slides render --out for PNGs; genoffice slides replace --slide n --spec to rebuild one page' + const outlinePath = flagString(args, 'outline') + const dir = spec === '-' ? null : specDirectory(spec, ctx) + if (dir) { + const stage = stageContext(dir, ctx, outlinePath ? resolveInput(outlinePath, ctx) : undefined) + const built = await buildDeckFromDir(dir, ctx, stage) + return { + bytes: built.bytes, + slides: built.pages, + detail: { + via: 'deck spec directory', + files: built.files.map((f) => basename(f)), + issues: built.issues, + imageFailures: built.imageFailures, + outline: stage.outline + ? { file: stage.outline.file, findings: built.outlineFindings } + : null, + style: stage.style ? { file: stage.style.file, offPalette: built.offPalette } : null, + notes: stage.notes, + next, + }, + } + } + if (outlinePath) throw new CliError(EXIT.usage, '--outline goes with --spec ') + const source = spec === '-' ? 'stdin' : resolveInput(spec, ctx) + const text = spec === '-' ? readFileSync(0, 'utf-8') : readFileSync(source, 'utf-8') + const built = await buildDeckFromSpec( + text, + source, + ctx, + spec === '-' ? undefined : dirname(source), + ) + return { + bytes: built.bytes, + slides: built.pages, + detail: { via: 'deck spec', issues: built.issues, imageFailures: built.imageFailures, next }, + } +} + +function specDirectory(spec: string, ctx: CommandContext): string | null { + const abs = isAbsolute(spec) ? spec : resolve(ctx.cwd, spec) + if (!existsSync(abs) || !statSync(abs).isDirectory()) return null + return assertAllowed(abs, ctx.env, 'read') +} + +async function createXlsx( + args: Parameters[0], + ctx: CommandContext, + output: string, +): Promise> { + const from = flagString(args, 'from') + if (!from) throw new CliError(EXIT.usage, 'xlsx needs --from ') + const source = resolveInput(from, ctx) + const tables = readTables(source, basename(source, extname(source))) + const [first, ...rest] = tables + if (!first) throw new CliError(EXIT.usage, `${from}: no sheets`) + const edits = tables.flatMap((t) => cellEditsFromTable(t.name, t.rows)) + const r = await writeWorkbook(await blankWorkbook(first.name), edits, output, { + plan: additionPlan( + first.name, + rest.map((t) => t.name), + ), + }) + + return { + sheets: tables.length, + cells: r.cells, + formulas: r.formulas, + cached_values: r.cachedValues, + ...(r.warning ? { warning: r.warning } : {}), + } +} + +function readTables(source: string, fallbackName: string): TableInput[] { + const sheetName = fallbackName.slice(0, 31) || 'Sheet1' + if (extname(source).toLowerCase() === '.csv') return [csvTable(readFileSync(source), sheetName)] + let parsed: unknown + try { + parsed = JSON.parse(readFileSync(source, 'utf-8')) + } catch (err) { + throw new CliError(EXIT.usage, `${source}: not valid JSON (${(err as Error).message})`) + } + if (Array.isArray(parsed)) return [{ name: sheetName, rows: parsed as TableInput['rows'] }] + const sheets = (parsed as { sheets?: unknown })?.sheets + if (!Array.isArray(sheets) || sheets.length === 0) { + throw new CliError( + EXIT.usage, + `${source}: expected a 2-D array or { "sheets": [{ "name", "rows" }] }`, + ) + } + return sheets.map((s, i) => { + const t = s as Partial + if (typeof t.name !== 'string' || !Array.isArray(t.rows)) { + throw new CliError(EXIT.usage, `${source}: sheets[${i}] needs "name" and "rows"`) + } + return { name: t.name, rows: t.rows } + }) +} + +async function createDocx( + args: Parameters[0], + ctx: CommandContext, +): Promise<{ bytes: Uint8Array; detail: Record }> { + const from = flagString(args, 'from') + if (!from) throw new CliError(EXIT.usage, 'docx needs --from ') + const source = resolveInput(from, ctx) + const text = readFileSync(source, 'utf-8') + const ext = extname(source).toLowerCase() + if (ext === '.md' || ext === '.markdown') { + return { + bytes: await markdownToDocx(text, { file: source, ctx }), + detail: { source: 'markdown' }, + } + } + if (ext === '.html' || ext === '.htm') { + const doc = await blankDocument() + try { + const blocks = fillFromHtml(doc, text) + return { bytes: await saveDocument(doc), detail: { source: 'html', blocks } } + } finally { + closeDocument(doc) + } + } + throw new CliError( + EXIT.usage, + `docx --from needs a .md or .html file, got ${ext || 'no extension'}`, + ) +} diff --git a/packages/cli/src/commands/docs.ts b/packages/cli/src/commands/docs.ts new file mode 100644 index 0000000..1987b46 --- /dev/null +++ b/packages/cli/src/commands/docs.ts @@ -0,0 +1,159 @@ +import { writeFileSync } from 'node:fs' +import { basename, dirname } from 'node:path' +import { flagBool, flagString } from '../args' +import { + applyDocOps, + blockRangeHtml, + closeDocument, + describeDocument, + headerFooterState, + listComments, + listRevisions, + openDocument, + saveDocument, +} from '../formats/docx' +import { readInput, resolveInput, resolveOutput } from '../fs' +import { readOpsInput } from '../ops-input' +import type { CommandContext, CommandDef } from '../registry' +import { CliError, EXIT, type CommandResult } from '../result' + +export const docsCommand: CommandDef = { + name: 'docs', + summary: 'Read or edit a .docx with the same ops the in-app AI uses.', + usage: 'docs [options]', + options: [ + { name: 'range', value: 'a-b', description: 'read: block index range (default: all)' }, + { name: 'html', description: 'read: also return the range as restricted HTML' }, + { name: 'full', description: 'read: whole block text instead of a 200-character preview' }, + { + name: 'comments', + description: + 'read: list every comment thread (ids for reply_comment / resolve_comment, anchored block, resolved state)', + }, + { name: 'revisions', description: 'read: list pending tracked changes with their block index' }, + { + name: 'header-footer', + description: 'read: the header and footer text per variant ({PAGE} / {NUMPAGES} tokens)', + }, + { + name: 'ops', + value: 'file', + description: + 'apply: JSON array of ops (apply_ops entries, plus insert_content / replace_blocks with an html field, insert_image, insert_chart / edit_chart, set_header_footer, reply_comment / resolve_comment); "-" reads stdin. See `genoffice guide docs`.', + }, + { + name: 'dry-run', + description: 'apply: run the batch in memory and report each step without writing', + }, + { name: 'out', value: 'path', description: 'apply: write here instead of in place' }, + { + name: 'force', + description: + 'apply: overwrite an existing --out file, or write while GenOffice has the file open', + }, + ], + async run(args, ctx) { + const [verb, file] = args.positionals + switch (verb) { + case 'read': + return read(file, args, ctx) + case 'apply': + return apply(file, args, ctx) + default: + throw new CliError(EXIT.usage, 'expected "docs read " or "docs apply "') + } + }, +} + +type Args = Parameters[0] + +function parseRange(spec: string | undefined, count: number): [number, number] | undefined { + if (spec === undefined) return undefined + const m = /^(\d+)(?:-(\d+))?$/.exec(spec) + if (!m) throw new CliError(EXIT.usage, '--range must look like 3 or 3-10 (block indexes)') + const start = Number(m[1]) + const end = m[2] === undefined ? start : Number(m[2]) + if (start > end || end >= count) { + throw new CliError(EXIT.usage, `--range out of bounds (0-${count - 1})`) + } + return [start, end] +} + +async function read( + file: string | undefined, + args: Args, + ctx: CommandContext, +): Promise { + const path = resolveInput(file, ctx) + const doc = await openDocument(readInput(path)) + try { + const count = doc.editor.state.doc.childCount + const range = parseRange(flagString(args, 'range'), count) + const blocks = describeDocument(doc, range, flagBool(args, 'full')) + const detail: Record = { + blocks: count, + range: range ? `${range[0]}-${range[1]}` : `0-${count - 1}`, + items: blocks, + units: 'block indexes are 0-based positions in the body; ops target them', + } + if (flagBool(args, 'html')) { + const [s, e] = range ?? [0, count - 1] + detail.html = blockRangeHtml(doc, s, e) + } + if (flagBool(args, 'comments')) detail.comments = listComments(doc) + if (flagBool(args, 'revisions')) detail.revisions = listRevisions(doc) + if (flagBool(args, 'header-footer')) detail.headerFooter = headerFooterState(doc) + return { summary: `${basename(path)}: ${count} blocks`, detail } + } finally { + closeDocument(doc) + } +} + +async function apply( + file: string | undefined, + args: Args, + ctx: CommandContext, +): Promise { + const path = resolveInput(file, ctx) + const { text, source } = readOpsInput(args, ctx) + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch (err) { + throw new CliError(EXIT.usage, `${source}: not valid JSON (${(err as Error).message})`) + } + const ops = Array.isArray(parsed) + ? parsed + : parsed && typeof parsed === 'object' && Array.isArray((parsed as { ops?: unknown }).ops) + ? (parsed as { ops: unknown[] }).ops + : null + if (!ops?.length) throw new CliError(EXIT.usage, `${source}: expected a non-empty array of ops`) + const dryRun = flagBool(args, 'dry-run') + const doc = await openDocument(readInput(path)) + try { + const results = await applyDocOps(doc, ops as Record[], { + ctx, + baseDir: source === 'stdin' ? undefined : dirname(source), + }) + if (dryRun) { + return { + summary: `dry run: ${ops.length} ops validated, nothing written`, + detail: { plan: results.map((r, i) => `${i}: ${r.op}: ${r.output.split('\n')[0]}`) }, + } + } + const output = resolveOutput(flagString(args, 'out'), ctx, { + fallback: path, + force: flagBool(args, 'force'), + // in-place edits overwrite by design; --out onto another existing file needs --force + fresh: flagString(args, 'out') !== undefined, + }) + writeFileSync(output, await saveDocument(doc)) + return { + summary: `applied ${ops.length} ops to ${basename(output)}`, + outputPath: output, + detail: { results, blocks: doc.editor.state.doc.childCount }, + } + } finally { + closeDocument(doc) + } +} diff --git a/packages/cli/src/commands/guide.ts b/packages/cli/src/commands/guide.ts new file mode 100644 index 0000000..6186539 --- /dev/null +++ b/packages/cli/src/commands/guide.ts @@ -0,0 +1,131 @@ +import { flagBool } from '../args' +import type { CommandDef } from '../registry' +import { docsGuide } from '../formats/docx' +import { CliError, EXIT, type CommandResult } from '../result' + +/** Same markdown the in-app AI loads on demand (load_guide); shipped inside the CLI so it never drifts from the ops. */ +export const guideCommand: CommandDef = { + name: 'guide', + summary: 'Print the op reference and design guides an agent needs before writing ops or specs.', + usage: 'guide [group|design|spec] [--index]', + options: [ + { name: 'index', description: 'one-line signature of every op instead of a group guide' }, + ], + async run(args) { + const [domain, group] = args.positionals + if (domain === 'docs') return docsGuideResult() + if (domain === 'sheets') return { summary: SHEETS_GUIDE } + if (domain !== 'slides') { + throw new CliError(EXIT.usage, 'guides available for: slides, docs, sheets', { + usage: 'genoffice guide slides | genoffice guide docs | genoffice guide sheets', + }) + } + if (group === 'design' || group === 'spec') { + const { SLIDES_GUIDES } = await import('@genoffice/pipelines/slides') + return { summary: SLIDES_GUIDES[group].content } + } + const docs = await import('@genoffice/pptx-ops/op-docs') + if (flagBool(args, 'index')) { + return { summary: docs.opSignatureIndex() } + } + if (!group) { + return { + summary: [ + 'Op groups (genoffice guide slides prints one):', + docs.opGuideCatalog(), + '', + 'Building a new deck: `genoffice guide slides design` (the staged workflow: style sheet, outline, one page file at a time, build, QC) and `genoffice guide slides spec` (the outline and page spec JSON for `genoffice slides check` and `genoffice create --type pptx --spec`).', + '', + 'Every op: { "op": "", "target": { "slide": , "el"?: "e_*" }, ...fields }.', + 'Units are EMU (914400 per inch); font sizes are pt. `genoffice slides read ` lists ids and geometry.', + 'Vocabulary:', + docs.opVocabulary(), + ].join('\n'), + } + } + const content = docs.opGuide(group) + if (!content) { + throw new CliError(EXIT.usage, `unknown group: ${group}`, { groups: [...docs.OP_GROUPS] }) + } + return { summary: content } + }, +} + +async function docsGuideResult(): Promise { + const g = await docsGuide() + return { + summary: [ + 'Word ops (genoffice docs apply --ops): a JSON array; every entry has "op".', + 'Targets: { "blockIndexes": [..] } or { "nodeType": "docHeading"|"docParagraph"|"docListItem", "headingLevel"? }; get indexes from `genoffice docs read`.', + '', + ...g.signatures, + '', + 'insert_content {html, afterBlockIndex?} — new blocks after an index (-1 = start of document; omitted = end of document)', + 'replace_blocks {html, startBlockIndex, endBlockIndex} — rewrite a block range', + 'insert_image {url, maxWidthPx?: 480, afterBlockIndex?} — url is a local path (absolute, or relative to the current directory then to the ops file), a data: URL or an http(s) URL; png/jpg/gif; scaled down to maxWidthPx; appended when afterBlockIndex is omitted', + 'insert_chart {kind: "bar"|"line"|"pie", title?, categories: string[], series: [{name?, values: (number|null)[]}], afterBlockIndex?} — native Word chart; values per series match the categories', + 'edit_chart {blockIndex, title?, categories?: (string|null)[], series?: [{index, name?, values?: (number|null)[]}]} — change the data of a chart block (`genoffice docs read` lists blocks with kind "chart"); counts must match the original, null keeps a position', + 'set_header_footer {kind: "header"|"footer", text, view?: "default"|"first"|"even"} — plain text, \\n between lines, {PAGE} / {NUMPAGES} become page-number fields, "" clears; view first/even switches the different-first-page / odd-even setting on; `genoffice docs read --header-footer` shows the current text', + 'reply_comment {parentId, text} / resolve_comment {id} — ids from `genoffice docs read --comments`; replies attach to the thread root', + '', + g.htmlRules, + ].join('\n'), + } +} + +/** The headless sheets workbook DSL (the in-app propose_operations vocabulary, minus the editor-only ops). */ +const SHEETS_GUIDE = [ + 'Excel ops (genoffice sheet apply --ops): a JSON array; every entry has "op". Address a worksheet with', + '"sheet": "" (omitted = the active sheet; `genoffice sheet read` lists names). Ranges are A1:D9,', + 'rows are 1-based, columns are letters. Strings starting with "=" are formulas.', + '', + 'Content:', + ' set_cell {sheet?, address, value} set_formula {sheet?, address, formula}', + ' set_range {sheet?, range, values: [[..],..]} clear_cell {sheet?, address} clear_range {sheet?, range}', + ' fill_range {sheet?, source, target} copy_range {sheet?, source, target}', + ' find_replace {sheet?, range?, find, replace} sort_range {sheet?, range, byColumn: "B", order: "asc"|"desc", hasHeader?}', + 'Format:', + ' format_range {sheet?, range, format: {bold?, italic?, underline?, strikethrough?, fontFamily?, fontSize?,', + ' fontColor?, fillColor?, numberFormat?, horizontalAlign?: left|center|right, verticalAlign?: top|center|bottom,', + ' wrapText?, textRotation?: -90..90|"vertical", indent?, border?: {type: all|top|bottom|left|right|none, color?}}}', + ' (null clears a property; colors are #RRGGBB)', + ' add_conditional_format {sheet?, range, rule} rule = {kind: "number", operator: greaterThan|greaterThanOrEqual|lessThan|', + ' lessThanOrEqual|equal|notEqual|between|notBetween, value, value2?, format} | {kind: "text", operator: contains|notContains|', + ' beginsWith|endsWith, text, format} | {kind: "blank", blank: bool, format} | {kind: "duplicate", unique?, format} |', + ' {kind: "top10", rank, percent?, bottom?, format} | {kind: "formula", formula: "=…", format} |', + ' {kind: "colorScale", minColor, midColor?, maxColor} | {kind: "dataBar", color?}; format = {fillColor?, fontColor?, bold?, italic?}', + ' clear_conditional_formats {sheet?} (a sheet that already has rules must be cleared before new ones are added)', + ' set_data_validation {sheet?, range, validation | null} validation = {kind: "list", values: [..]} | {kind: "listRef", range} |', + ' {kind: "numberBetween", min, max} | {kind: "dateBetween", start: "YYYY-MM-DD", end} | {kind: "checkbox"} | {kind: "formula", formula: "=…"}', + 'Layout:', + ' merge_cells {sheet?, range} unmerge_cells {sheet?, range}', + ' set_row_height {sheet?, row, count?, heightPoints} set_col_width {sheet?, column, count?, widthPx}', + ' set_rows_hidden {sheet?, row, count?, hidden} set_cols_hidden {sheet?, column, count?, hidden}', + ' set_freeze {sheet?, rows, columns} (0/0 unfreezes)', + ' set_filter {sheet?, range} set_filter_criteria {sheet?, column, values: [..] | null} clear_filter {sheet?}', + ' set_page_setup {sheet?, orientation?: portrait|landscape, paperSize?: 9 (A4) | 1 (Letter) …, scale? | fitToWidth?/fitToHeight?,', + ' margins?: normal|wide|narrow, printGridlines?, printHeadings?, printArea?: "A1:F40" | null}', + ' protect_sheet {sheet?, protected}', + 'Data:', + ' set_hyperlink {sheet?, address, target: "https://…" | "Sheet1!A1" | null} set_note {sheet?, address, text | null}', + ' add_defined_name {name, ref: "Sheet1!$A$2:$A$9"} delete_defined_name {name} (not in a batch with sheet or row/column ops)', + ' add_table {sheet?, range, name?, style?: "TableStyleMedium2", bandedRows?} (first row = unique, non-empty column names)', + 'Visuals:', + ' add_chart {sheet?, chartType: column|bar|line|area|pie|doughnut|scatter|radar|combo, dataRange, title?, anchorCell?}', + ' (header row and a leading category column are detected; the chart lands two columns right of the data unless anchorCell)', + ' edit_chart {chartPath: "xl/charts/chart1.xml", title?, chartType?, legend?: none|right|bottom|top|left,', + ' dataLabels?: none|value|percent|category-percent, grouping?: clustered|stacked|percentStacked, seriesColors?: {"0": "#RRGGBB"},', + ' axisTitles?: {category?, value?}} (`genoffice sheet read` lists chart ids under features.charts)', + ' add_image {sheet?, path: "/abs/or/relative.png" | "https://…", anchorCell} add_shape {sheet?, shapeType | "textbox", anchorCell, fillColor?, text?}', + 'Structure (cannot share a batch with content ops):', + ' insert_rows {sheet?, row, count} delete_rows {sheet?, row, count}', + ' insert_cols {sheet?, column, count} delete_cols {sheet?, column, count}', + ' add_sheet {name} delete_sheet {sheet} rename_sheet {sheet, name} duplicate_sheet {sheet, name?}', + ' move_sheet {sheet, position} set_sheet_hidden {sheet, hidden}', + '', + 'Not available headless (use the GenOffice app): pivots (add_pivot, refresh_pivot), sparklines, edits to tables or', + 'shapes created in an editor session (add/delete_table_row/column, delete_table, edit_shape, delete_visual), convert_to_values.', + 'Adding a conditional format or data validation to a sheet that already has rules is refused (the CLI cannot carry the', + 'existing rules over): clear_conditional_formats first, or use the app. set_filter_criteria needs a filter without criteria.', + 'Formulas written by a batch are evaluated by the workbook engine and stored with their results.', +].join('\n') diff --git a/packages/cli/src/commands/image.ts b/packages/cli/src/commands/image.ts new file mode 100644 index 0000000..508b4eb --- /dev/null +++ b/packages/cli/src/commands/image.ts @@ -0,0 +1,142 @@ +import { randomBytes } from 'node:crypto' +import { writeFileSync } from 'node:fs' +import { extname } from 'node:path' +import { fileURLToPath } from 'node:url' +import { generateImageTool } from '@genoffice/ai-search' +import { fetchRemoteImage } from '@genoffice/electron-utils/remote-image' +import { flagBool, flagString } from '../args' +import { aiSettingsPath, prepareCloud } from '../cloud' +import { resolveInput, resolveOutput } from '../fs' +import type { CommandDef } from '../registry' +import { CliError, EXIT } from '../result' + +const ASPECTS = ['1:1', '4:3', '16:9', '9:16', '3:4', '2:3', '3:2', 'auto'] +const SIZES = ['auto', '0.5k', '1k', '2k', '3k', '4k'] + +const EXTS_BY_MIME: Record = { + 'image/png': ['png'], + 'image/jpeg': ['jpg', 'jpeg'], + 'image/webp': ['webp'], + 'image/gif': ['gif'], +} + +export const imageCommand: CommandDef = { + name: 'image', + summary: + 'Generate an image from a prompt with the configured image provider and save it as a file.', + usage: 'image [--out ] [--aspect 16:9] [--size 1k] [--ref ]... [--force]', + options: [ + { + name: 'out', + value: 'file', + description: 'where to save (default: generated-image-