From d24c964a3e693a52d9fece4fef03a4de34d0d853 Mon Sep 17 00:00:00 2001 From: merrick-2002 Date: Wed, 9 Sep 2026 18:19:13 +0800 Subject: [PATCH] Sync snapshot (2026-09-09) (#271) - **New app: GenOffice HTML.** Open, edit and generate .html pages: a source pane with a sandboxed live preview, click-to-select elements with a floating toolbar and style panel, device-size preview, image tools and a present mode. AI generates whole pages from a brief with style directions and offers page-wide Restyle, Theme and Summarize. Export to Word runs locally through the built-in html2docx converter (native, editable OOXML; no print-to-PDF detour). - **AI:** separate BYOK providers for web search, image generation and image/video analysis; new Codex App Server provider; Ask AI quotes the selected text and keeps it highlighted while it runs; custom AI panel text size; blocked requests retry through the Chromium network stack. - **App:** global AutoSave setting shared by every editor; AI panel text size and chat spellcheck toggles (genoffice#249); Czech (cs) UI locale (genoffice#259); Save As defaults to the document's folder; PDF export no longer aborts on CJK file paths on Windows. - **Docs:** Export as HTML; comments and replies edit in place from the comments pane; the caret can leave a trailing table (genoffice#266); spellcheck re-marks text as soon as it is re-enabled; AI edits are character-precise on partial selections; zoom keeps the scroll position; pasting a cell from Sheets takes the destination font. - **Sheets:** Find no longer freezes on wide or streamed grids; Replace searches as you type; cached values of external-workbook formulas are kept instead of #ERROR! (genoffice#235); "number stored as text" is a warning, not an error (genoffice#236); paste repeats into the target range like Excel; filter criteria survive save/reopen; saves retry when Windows locks the file; many Excel-fidelity fixes for column widths, row heights, charts, slicers, number formats and CJK fonts. - **Slides:** PDF export works for large presentations (genoffice#264); EMF/WMF picture fonts and East Asian theme fonts resolve correctly; decks with missing layouts or embedded styles still open; outline-only pie slices render. - **PDF:** highlight and underline geometry aligns with the text; Shift+arrows extend the selection instead of paging. - **Markdown:** Find and replace (Ctrl+F / Ctrl+H) (genoffice#253); mermaid code blocks render as diagrams (genoffice#263); better print quality. - Thanks to community contributors @GoodScholar, @aniruddhaadak80 and @Sun8854, and to @hanyscz, @qgzln, @zyp997, @bisslot, @krakotay and @Ben03151 for the reports. Co-authored-by: GenOffice --- .github/workflows/ci.yml | 16 + .prettierignore | 6 + README.md | 63 +- apps/docs/package.json | 2 +- apps/docs/src/main/docs-main.ts | 270 +- apps/docs/src/main/updater.ts | 8 + apps/docs/src/preload/index.ts | 17 + apps/docs/src/renderer/App.tsx | 234 +- apps/docs/src/renderer/ai/AiPanel.tsx | 89 +- apps/docs/src/renderer/ai/commands.ts | 1163 ------ apps/docs/src/renderer/ai/doc-utils.ts | 56 + apps/docs/src/renderer/ai/docs-skill.ts | 18 +- apps/docs/src/renderer/ai/ops.ts | 1421 +++++++ apps/docs/src/renderer/ai/protocol.ts | 397 +- apps/docs/src/renderer/ai/tools.ts | 169 +- .../src/renderer/components/AiAskPopover.tsx | 6 +- .../src/renderer/components/CommentsPanel.tsx | 202 +- .../src/renderer/components/ContextMenu.tsx | 4 +- apps/docs/src/renderer/components/Ribbon.tsx | 99 +- apps/docs/src/renderer/components/icons.tsx | 18 + .../renderer/components/ribbon-insert-tab.tsx | 20 +- .../src/renderer/components/ribbon-tabs.tsx | 76 +- apps/docs/src/renderer/editor/comments.ts | 46 + apps/docs/src/renderer/editor/extensions.ts | 22 +- apps/docs/src/renderer/editor/indent.ts | 70 +- apps/docs/src/renderer/editor/paste-text.ts | 45 +- apps/docs/src/renderer/file-actions.ts | 30 + apps/docs/src/renderer/html-export.ts | 449 +++ apps/docs/src/renderer/i18n/ai/ar.ts | 1 + apps/docs/src/renderer/i18n/ai/cs.ts | 158 + apps/docs/src/renderer/i18n/ai/de.ts | 1 + apps/docs/src/renderer/i18n/ai/en.ts | 1 + apps/docs/src/renderer/i18n/ai/es.ts | 1 + apps/docs/src/renderer/i18n/ai/fr.ts | 1 + apps/docs/src/renderer/i18n/ai/he.ts | 1 + apps/docs/src/renderer/i18n/ai/hi.ts | 1 + apps/docs/src/renderer/i18n/ai/id.ts | 1 + apps/docs/src/renderer/i18n/ai/it.ts | 1 + apps/docs/src/renderer/i18n/ai/ja.ts | 1 + apps/docs/src/renderer/i18n/ai/ko.ts | 1 + apps/docs/src/renderer/i18n/ai/ms.ts | 1 + apps/docs/src/renderer/i18n/ai/nl.ts | 1 + apps/docs/src/renderer/i18n/ai/pl.ts | 1 + apps/docs/src/renderer/i18n/ai/pt.ts | 1 + apps/docs/src/renderer/i18n/ai/ru.ts | 1 + apps/docs/src/renderer/i18n/ai/th.ts | 1 + apps/docs/src/renderer/i18n/ai/zh-TW.ts | 1 + apps/docs/src/renderer/i18n/ai/zh.ts | 1 + apps/docs/src/renderer/i18n/app/ar.ts | 6 + apps/docs/src/renderer/i18n/app/cs.ts | 358 ++ apps/docs/src/renderer/i18n/app/de.ts | 6 + apps/docs/src/renderer/i18n/app/en.ts | 6 + apps/docs/src/renderer/i18n/app/es.ts | 6 + apps/docs/src/renderer/i18n/app/fr.ts | 6 + apps/docs/src/renderer/i18n/app/he.ts | 6 + apps/docs/src/renderer/i18n/app/hi.ts | 6 + apps/docs/src/renderer/i18n/app/id.ts | 6 + apps/docs/src/renderer/i18n/app/it.ts | 6 + apps/docs/src/renderer/i18n/app/ja.ts | 6 + apps/docs/src/renderer/i18n/app/ko.ts | 6 + apps/docs/src/renderer/i18n/app/ms.ts | 6 + apps/docs/src/renderer/i18n/app/nl.ts | 6 + apps/docs/src/renderer/i18n/app/pl.ts | 6 + apps/docs/src/renderer/i18n/app/pt.ts | 6 + apps/docs/src/renderer/i18n/app/ru.ts | 6 + apps/docs/src/renderer/i18n/app/th.ts | 6 + apps/docs/src/renderer/i18n/app/zh-TW.ts | 6 + apps/docs/src/renderer/i18n/app/zh.ts | 6 + apps/docs/src/renderer/i18n/locale.tsx | 2 + apps/docs/src/renderer/i18n/ribbon/cs.ts | 709 ++++ apps/docs/src/renderer/i18n/strings-ai.ts | 2 + apps/docs/src/renderer/i18n/strings-app.ts | 2 + apps/docs/src/renderer/i18n/strings-editor.ts | 57 + apps/docs/src/renderer/i18n/strings-ribbon.ts | 2 + apps/docs/src/renderer/i18n/strings-table.ts | 1 + apps/docs/src/renderer/i18n/strings.ts | 7 + apps/docs/src/renderer/main.tsx | 9 +- apps/docs/src/renderer/pagination-slices.ts | 7 + apps/docs/src/renderer/review-actions.ts | 24 +- apps/docs/src/renderer/styles.css | 27 +- apps/docs/src/shared/ipc.ts | 28 +- apps/docs/tests/agent-docs.test.ts | 311 +- .../tests/ai-deleted-revision-context.test.ts | 16 +- apps/docs/tests/ai-rich-generation.test.ts | 8 +- apps/docs/tests/ai-track-revisions.test.ts | 28 +- apps/docs/tests/char-indent-save.test.ts | 24 +- apps/docs/tests/col-block-width-css.test.ts | 21 +- apps/docs/tests/commands.test.ts | 1001 ----- apps/docs/tests/comment-edit.test.ts | 215 + apps/docs/tests/comment-word-anchor.test.ts | 100 + apps/docs/tests/context-menu.test.ts | 63 +- apps/docs/tests/html-export.test.ts | 77 + apps/docs/tests/inline-rule.test.ts | 18 +- apps/docs/tests/insert-tab-comment.test.ts | 85 + apps/docs/tests/invisible-chars-save.test.ts | 6 +- apps/docs/tests/move-mode.test.ts | 9 +- apps/docs/tests/ops.test.ts | 1112 ++++++ apps/docs/tests/pagination.test.ts | 34 + apps/docs/tests/paste-single-cell.test.ts | 107 + apps/docs/tests/raw-ppr.test.ts | 12 +- apps/docs/tests/render-isolation.test.ts | 1 + apps/docs/tests/revisions.test.ts | 4 +- .../tests/table-trailing-paragraph.test.ts | 105 + apps/html/electron.vite.config.ts | 19 + apps/html/package.json | 47 + apps/html/src/main/asset-lifecycle.ts | 1300 ++++++ apps/html/src/main/asset-mime.ts | 129 + apps/html/src/main/atomic-write.ts | 46 + apps/html/src/main/html-main.ts | 1647 ++++++++ apps/html/src/main/html2docx-driver.ts | 178 + apps/html/src/main/index.ts | 3 + apps/html/src/main/preview-document.ts | 39 + apps/html/src/main/preview-protocol.ts | 45 + apps/html/src/preload/index.ts | 116 + apps/html/src/renderer/App.tsx | 1491 +++++++ apps/html/src/renderer/PresentView.tsx | 33 + apps/html/src/renderer/ai/AiPanel.tsx | 1673 ++++++++ apps/html/src/renderer/ai/EditQueueCard.tsx | 206 + apps/html/src/renderer/ai/doc-nav.ts | 11 + apps/html/src/renderer/ai/edit-queue.ts | 114 + apps/html/src/renderer/ai/files-skill.ts | 94 + apps/html/src/renderer/ai/html-skill.ts | 55 + apps/html/src/renderer/ai/intent.ts | 26 + apps/html/src/renderer/ai/page-writer.ts | 165 + apps/html/src/renderer/ai/search-skill.ts | 57 + apps/html/src/renderer/ai/tools.ts | 799 ++++ apps/html/src/renderer/ai/transport.ts | 18 + apps/html/src/renderer/assets/attach-icon.png | Bin 0 -> 1415 bytes .../src/renderer/assets/file-document.png | Bin 0 -> 618 bytes apps/html/src/renderer/assets/file-excel.png | Bin 0 -> 706 bytes .../html/src/renderer/assets/file-general.png | Bin 0 -> 539 bytes apps/html/src/renderer/assets/file-image.png | Bin 0 -> 753 bytes apps/html/src/renderer/assets/file-pdf.png | Bin 0 -> 778 bytes apps/html/src/renderer/assets/file-ppt.png | Bin 0 -> 717 bytes apps/html/src/renderer/assets/file-video.png | Bin 0 -> 715 bytes apps/html/src/renderer/assets/file-voice.png | Bin 0 -> 726 bytes apps/html/src/renderer/assets/file-word.png | Bin 0 -> 798 bytes .../src/renderer/assets/send-enter-off.png | Bin 0 -> 4247 bytes .../src/renderer/assets/send-enter-on.png | Bin 0 -> 3742 bytes apps/html/src/renderer/assets/send-stop.png | Bin 0 -> 2875 bytes .../src/renderer/components/AiAskPopover.tsx | 274 ++ .../src/renderer/components/Breadcrumb.tsx | 59 + .../src/renderer/components/BriefCard.tsx | 428 ++ .../src/renderer/components/ClarifyCard.tsx | 216 + .../src/renderer/components/ColorField.tsx | 135 + .../src/renderer/components/FloatToolbar.tsx | 389 ++ apps/html/src/renderer/components/Ribbon.tsx | 340 ++ .../src/renderer/components/StylePanel.tsx | 340 ++ apps/html/src/renderer/components/icons.tsx | 166 + apps/html/src/renderer/document/auto-name.ts | 57 + .../src/renderer/document/background-style.ts | 16 + apps/html/src/renderer/document/blank.ts | 16 + apps/html/src/renderer/document/brief.ts | 133 + apps/html/src/renderer/document/envelope.ts | 33 + .../src/renderer/document/float-position.ts | 45 + .../html/src/renderer/document/image-style.ts | 74 + apps/html/src/renderer/document/match.ts | 273 ++ apps/html/src/renderer/document/ops.ts | 502 +++ apps/html/src/renderer/document/parse-map.ts | 209 + apps/html/src/renderer/document/patch.ts | 70 + apps/html/src/renderer/env.d.ts | 13 + apps/html/src/renderer/i18n/ai/ar.ts | 173 + apps/html/src/renderer/i18n/ai/cs.ts | 175 + apps/html/src/renderer/i18n/ai/de.ts | 178 + apps/html/src/renderer/i18n/ai/en.ts | 174 + apps/html/src/renderer/i18n/ai/es.ts | 178 + apps/html/src/renderer/i18n/ai/fr.ts | 176 + apps/html/src/renderer/i18n/ai/he.ts | 170 + apps/html/src/renderer/i18n/ai/hi.ts | 175 + apps/html/src/renderer/i18n/ai/id.ts | 175 + apps/html/src/renderer/i18n/ai/it.ts | 177 + apps/html/src/renderer/i18n/ai/ja.ts | 176 + apps/html/src/renderer/i18n/ai/ko.ts | 173 + apps/html/src/renderer/i18n/ai/ms.ts | 177 + apps/html/src/renderer/i18n/ai/nl.ts | 177 + apps/html/src/renderer/i18n/ai/pl.ts | 176 + apps/html/src/renderer/i18n/ai/pt.ts | 179 + apps/html/src/renderer/i18n/ai/ru.ts | 175 + apps/html/src/renderer/i18n/ai/th.ts | 173 + apps/html/src/renderer/i18n/ai/zh-TW.ts | 166 + apps/html/src/renderer/i18n/ai/zh.ts | 165 + apps/html/src/renderer/i18n/app/ar.ts | 120 + apps/html/src/renderer/i18n/app/cs.ts | 120 + apps/html/src/renderer/i18n/app/de.ts | 122 + apps/html/src/renderer/i18n/app/en.ts | 121 + apps/html/src/renderer/i18n/app/es.ts | 123 + apps/html/src/renderer/i18n/app/fr.ts | 123 + apps/html/src/renderer/i18n/app/he.ts | 119 + apps/html/src/renderer/i18n/app/hi.ts | 122 + apps/html/src/renderer/i18n/app/id.ts | 121 + apps/html/src/renderer/i18n/app/it.ts | 123 + apps/html/src/renderer/i18n/app/ja.ts | 121 + apps/html/src/renderer/i18n/app/ko.ts | 120 + apps/html/src/renderer/i18n/app/ms.ts | 120 + apps/html/src/renderer/i18n/app/nl.ts | 123 + apps/html/src/renderer/i18n/app/pl.ts | 120 + apps/html/src/renderer/i18n/app/pt.ts | 122 + apps/html/src/renderer/i18n/app/ru.ts | 120 + apps/html/src/renderer/i18n/app/th.ts | 119 + apps/html/src/renderer/i18n/app/zh-TW.ts | 118 + apps/html/src/renderer/i18n/app/zh.ts | 117 + apps/html/src/renderer/i18n/locale.tsx | 65 + apps/html/src/renderer/i18n/strings-ai.ts | 45 + apps/html/src/renderer/i18n/strings-app.ts | 45 + apps/html/src/renderer/i18n/strings.ts | 25 + apps/html/src/renderer/index.html | 16 + apps/html/src/renderer/main.tsx | 47 + .../src/renderer/preview/DraftPreview.tsx | 38 + .../src/renderer/preview/PreviewFrame.tsx | 66 + .../renderer/preview/inspector-protocol.ts | 120 + apps/html/src/renderer/preview/inspector.js | 544 +++ apps/html/src/renderer/preview/instrument.ts | 25 + .../html/src/renderer/source/SourceEditor.tsx | 156 + apps/html/src/renderer/source/cm-find.ts | 50 + apps/html/src/renderer/source/cm-highlight.ts | 33 + apps/html/src/renderer/source/cm-setup.ts | 114 + apps/html/src/renderer/source/find-target.ts | 58 + apps/html/src/renderer/styles.css | 3514 +++++++++++++++++ apps/html/src/shared/ipc.ts | 265 ++ apps/html/tests/asset-lifecycle.test.ts | 490 +++ apps/html/tests/asset-mime.test.ts | 96 + apps/html/tests/auto-name.test.ts | 75 + apps/html/tests/background-style.test.ts | 36 + apps/html/tests/blank.test.ts | 34 + apps/html/tests/brief.test.ts | 89 + apps/html/tests/cm-find.test.ts | 84 + apps/html/tests/document.test.ts | 170 + apps/html/tests/edit-queue.test.ts | 85 + apps/html/tests/float-position.test.ts | 46 + apps/html/tests/image-style.test.ts | 51 + apps/html/tests/ops.test.ts | 277 ++ apps/html/tests/page-writer.test.ts | 186 + apps/html/tests/tools.test.ts | 439 ++ apps/html/tsconfig.json | 14 + apps/html/vite.renderer.config.ts | 12 + apps/html/vitest.config.ts | 9 + apps/markdown/package.json | 5 +- apps/markdown/src/main/markdown-main.ts | 54 +- apps/markdown/src/preload/index.ts | 16 +- apps/markdown/src/renderer/App.tsx | 59 +- apps/markdown/src/renderer/ai/AiPanel.tsx | 121 +- apps/markdown/src/renderer/ai/edit-queue.ts | 2 +- .../src/renderer/ai/markdown-skill.ts | 36 +- apps/markdown/src/renderer/ai/tools.ts | 450 +-- .../src/renderer/components/AiAskPopover.tsx | 6 +- .../src/renderer/components/Ribbon.tsx | 73 +- .../src/renderer/components/TableMenu.tsx | 21 +- .../src/renderer/components/icons.tsx | 1 + .../src/renderer/editor/CodeBlockView.tsx | 88 +- .../src/renderer/editor/aiHighlight.ts | 58 +- .../src/renderer/editor/blockDragHandle.ts | 16 +- .../src/renderer/editor/blockKeymap.ts | 115 +- .../src/renderer/editor/extensions.ts | 4 + .../src/renderer/editor/findTarget.ts | 84 + .../src/renderer/editor/inactiveSelection.ts | 51 + apps/markdown/src/renderer/editor/mermaid.ts | 93 + apps/markdown/src/renderer/editor/ops.ts | 1037 +++++ .../src/renderer/editor/searchHighlight.ts | 49 + .../src/renderer/editor/slashCommand.ts | 62 +- .../src/renderer/export/docxExport.ts | 30 +- .../markdown/src/renderer/export/printHtml.ts | 6 +- apps/markdown/src/renderer/i18n/locale.tsx | 1 + apps/markdown/src/renderer/i18n/strings.ts | 640 ++- apps/markdown/src/renderer/main.tsx | 10 +- apps/markdown/src/renderer/styles.css | 56 + apps/markdown/src/shared/ipc.ts | 26 +- apps/markdown/tests/ai-tools.test.ts | 168 +- apps/markdown/tests/docx-export.test.ts | 28 + apps/markdown/tests/find-panel.test.ts | 234 ++ apps/markdown/tests/markdown-nodes.test.ts | 8 + apps/markdown/tests/ops.test.ts | 370 ++ apps/markdown/tests/slash-and-image.test.ts | 11 +- apps/pdf/package.json | 2 +- apps/pdf/src/main/pdf-main.ts | 66 +- apps/pdf/src/preload/index.ts | 7 + apps/pdf/src/renderer/App.tsx | 1011 ++--- apps/pdf/src/renderer/ai/AiPanel.tsx | 51 +- apps/pdf/src/renderer/ai/pdf-skill.ts | 25 +- apps/pdf/src/renderer/ai/tools.ts | 524 ++- apps/pdf/src/renderer/annotations.ts | 3 +- apps/pdf/src/renderer/edit-ops/index.ts | 17 + apps/pdf/src/renderer/edit-ops/ops.ts | 655 +++ apps/pdf/src/renderer/edit-ops/registry.ts | 159 + apps/pdf/src/renderer/i18n/locale.tsx | 1 + apps/pdf/src/renderer/i18n/strings.ts | 397 ++ apps/pdf/src/renderer/main.tsx | 9 +- apps/pdf/src/shared/ipc.ts | 8 +- apps/pdf/src/shared/op-docs.ts | 202 + apps/pdf/tests/ai-tools.test.ts | 462 ++- apps/pdf/tests/annotations.test.ts | 13 + apps/pdf/tests/edit-ops.test.ts | 511 +++ apps/pdf/tests/op-docs.test.ts | 60 + apps/sheets/native/xlsx-engine/src/lib.rs | 7 + apps/sheets/native/xlsx-engine/src/recalc.rs | 151 +- apps/sheets/native/xlsx-engine/src/tests.rs | 247 ++ apps/sheets/native/xlsx-engine/src/types.rs | 37 + apps/sheets/native/xlsx-engine/src/visuals.rs | 65 + .../native/xlsx-engine/src/visuals/charts.rs | 46 + .../native/xlsx-engine/src/visuals/drawing.rs | 88 +- .../native/xlsx-engine/src/visuals/tests.rs | 131 +- .../sheets/native/xlsx-engine/src/workbook.rs | 33 +- .../native/xlsx-engine/src/worksheet.rs | 155 +- .../sheets/native/xlsx-engine/src/xml_util.rs | 52 + apps/sheets/package.json | 2 +- apps/sheets/src/gateway/csv-import.ts | 4 +- apps/sheets/src/gateway/xlsx-escapes.ts | 20 + apps/sheets/src/gateway/xlsx-gateway.ts | 34 +- apps/sheets/src/gateway/xlsx-package-io.ts | 102 +- apps/sheets/src/gateway/xlsx-page-setup.ts | 31 +- apps/sheets/src/gateway/xlsx-structure.ts | 32 +- apps/sheets/src/main/sheets-main.ts | 123 +- apps/sheets/src/preload/index.ts | 126 +- apps/sheets/src/renderer/App.tsx | 1577 +------- apps/sheets/src/renderer/ColorDropdown.tsx | 40 +- apps/sheets/src/renderer/ExcelShell.tsx | 33 +- apps/sheets/src/renderer/WorkbookVisuals.tsx | 372 +- apps/sheets/src/renderer/ai/AiChatPanel.tsx | 8 +- .../sheets/src/renderer/ai/create-document.ts | 9 +- apps/sheets/src/renderer/ai/image-skill.ts | 16 +- apps/sheets/src/renderer/ai/tools.ts | 14 +- .../src/renderer/ai/workbook-readers.ts | 4 +- apps/sheets/src/renderer/app-constants.ts | 2 +- .../sheets/src/renderer/arrow-collapse-fix.ts | 110 + .../sheets/src/renderer/autofit-line-pitch.ts | 115 + .../src/renderer/autofit-wrap-budget.ts | 45 + .../sheets/src/renderer/cell-font-fallback.ts | 22 +- .../src/renderer/chart-category-vector.ts | 39 + .../sheets/src/renderer/chart-sync-pending.ts | 108 + .../src/renderer/clipboard-anchor-tile.ts | 137 + apps/sheets/src/renderer/edit-journal.ts | 32 +- apps/sheets/src/renderer/excel-jump-nav.ts | 57 +- .../src/renderer/filter-range-outline.ts | 31 + apps/sheets/src/renderer/formula-closure.ts | 11 +- apps/sheets/src/renderer/formula-lexer-fix.ts | 129 +- .../src/renderer/formula-newline-display.ts | 54 + .../src/renderer/formula-stream-hold.ts | 31 +- apps/sheets/src/renderer/i18n/ai/cs.ts | 110 + apps/sheets/src/renderer/i18n/app/ar.ts | 3 + apps/sheets/src/renderer/i18n/app/cs.ts | 1335 +++++++ apps/sheets/src/renderer/i18n/app/de.ts | 4 + apps/sheets/src/renderer/i18n/app/en.ts | 4 + apps/sheets/src/renderer/i18n/app/es.ts | 4 + apps/sheets/src/renderer/i18n/app/fr.ts | 4 + apps/sheets/src/renderer/i18n/app/he.ts | 3 + apps/sheets/src/renderer/i18n/app/hi.ts | 4 + apps/sheets/src/renderer/i18n/app/id.ts | 4 + apps/sheets/src/renderer/i18n/app/it.ts | 4 + apps/sheets/src/renderer/i18n/app/ja.ts | 4 + apps/sheets/src/renderer/i18n/app/ko.ts | 3 + apps/sheets/src/renderer/i18n/app/ms.ts | 4 + apps/sheets/src/renderer/i18n/app/nl.ts | 4 + apps/sheets/src/renderer/i18n/app/pl.ts | 4 + apps/sheets/src/renderer/i18n/app/pt.ts | 4 + apps/sheets/src/renderer/i18n/app/ru.ts | 4 + apps/sheets/src/renderer/i18n/app/th.ts | 3 + apps/sheets/src/renderer/i18n/app/zh-TW.ts | 3 + apps/sheets/src/renderer/i18n/app/zh.ts | 3 + apps/sheets/src/renderer/i18n/dialogs/cs.ts | 404 ++ apps/sheets/src/renderer/i18n/locale.tsx | 2 + apps/sheets/src/renderer/i18n/strings-ai.ts | 2 + apps/sheets/src/renderer/i18n/strings-app.ts | 2 + .../src/renderer/i18n/strings-dialogs.ts | 2 + apps/sheets/src/renderer/i18n/strings.ts | 1 + apps/sheets/src/renderer/lazy-find.ts | 16 +- apps/sheets/src/renderer/main.tsx | 9 +- apps/sheets/src/renderer/menu-input-enter.ts | 63 + .../src/renderer/number-as-text-alert.ts | 27 + apps/sheets/src/renderer/numfmt-fix.ts | 34 +- apps/sheets/src/renderer/op-executor.ts | 1513 +++++++ .../src/renderer/page-layout-actions.ts | 46 +- apps/sheets/src/renderer/plan-operations.ts | 120 +- .../sheets/src/renderer/replace-autosearch.ts | 105 + apps/sheets/src/renderer/ribbon-actions.ts | 188 +- apps/sheets/src/renderer/ribbon-icons.tsx | 123 + apps/sheets/src/renderer/save-actions.ts | 4 +- apps/sheets/src/renderer/shape-text-scale.ts | 29 + .../src/renderer/shared-formula-journal.ts | 66 + apps/sheets/src/renderer/sparse-find.ts | 174 + apps/sheets/src/renderer/styles.css | 115 +- apps/sheets/src/renderer/univer-locales.ts | 67 +- apps/sheets/src/renderer/univer-state.ts | 4 + apps/sheets/src/renderer/univer-sync.ts | 334 +- apps/sheets/src/renderer/visual-edit-sync.ts | 102 +- apps/sheets/src/shared/desktop-api.ts | 160 +- apps/sheets/tests/array-formulas.test.ts | 23 +- apps/sheets/tests/arrow-collapse-fix.test.ts | 68 + apps/sheets/tests/autofit-line-pitch.test.ts | 129 + apps/sheets/tests/autofit-wrap-budget.test.ts | 110 + apps/sheets/tests/cell-font-fallback.test.ts | 47 +- .../tests/chart-category-vector.test.ts | 69 + apps/sheets/tests/chart-hidden-axis.test.ts | 92 + apps/sheets/tests/chart-point-labels.test.ts | 140 + apps/sheets/tests/chart-sync-pending.test.ts | 190 + .../tests/clipboard-anchor-tile.test.ts | 70 + apps/sheets/tests/column-width-mdw.test.ts | 65 +- apps/sheets/tests/column-width-narrow.test.ts | 62 + apps/sheets/tests/csv-import.test.ts | 1 + apps/sheets/tests/edit-journal.test.ts | 21 + apps/sheets/tests/excel-jump-nav.test.ts | 39 + apps/sheets/tests/formula-closure.test.ts | 7 + apps/sheets/tests/formula-lexer-fix.test.ts | 91 +- .../tests/formula-newline-display.test.ts | 127 + .../formula-stream-hold-full-recalc.test.ts | 111 + apps/sheets/tests/lazy-gate.test.ts | 97 +- .../sheets/tests/number-as-text-alert.test.ts | 51 + apps/sheets/tests/numfmt-fix.test.ts | 31 + apps/sheets/tests/op-executor-ui.test.ts | 43 + .../tests/promote-file-atomically.test.ts | 158 + apps/sheets/tests/replace-autosearch.test.ts | 117 + apps/sheets/tests/row-height-import.test.ts | 1 + apps/sheets/tests/save-recovery-mode.test.ts | 21 + apps/sheets/tests/shape-text-scale.test.ts | 52 + .../tests/shared-formula-journal.test.ts | 118 + apps/sheets/tests/shrink-to-fit.test.ts | 31 +- apps/sheets/tests/sparse-find.test.ts | 168 + apps/sheets/tests/univer-locales.test.ts | 80 +- .../sheets/tests/univer-range-loading.test.ts | 4 +- .../tests/unsupported-function-cache.test.ts | 22 + apps/sheets/tests/view-transform.test.ts | 1 + apps/sheets/tests/xlsx-defined-names.test.ts | 16 + apps/sheets/tests/xlsx-escapes.test.ts | 103 + apps/sheets/tests/xlsx-page-setup.test.ts | 29 + apps/sheets/tests/xlsx-recalc.test.ts | 118 + apps/sheets/tests/xlsx-save-edits.test.ts | 12 + apps/sheets/tests/xlsx-structure.test.ts | 22 + apps/shell/build/html.icns | Bin 0 -> 94690 bytes apps/shell/build/html.ico | Bin 0 -> 11528 bytes apps/shell/electron-builder.cjs | 19 + apps/shell/package.json | 2 +- apps/shell/src/main/assets/menu-html.png | Bin 0 -> 434 bytes apps/shell/src/main/assets/menu-html@2x.png | Bin 0 -> 898 bytes apps/shell/src/main/index.ts | 410 +- apps/shell/src/main/pdf2docx-local.ts | 8 +- apps/shell/src/main/recent-files.ts | 5 +- apps/shell/src/main/tab-manager.ts | 84 +- apps/shell/src/main/updater.ts | 15 + apps/shell/src/preload/index.ts | 54 +- apps/shell/src/renderer/src/Home.tsx | 11 +- apps/shell/src/renderer/src/SettingsModal.tsx | 532 ++- apps/shell/src/renderer/src/TabBar.tsx | 16 + .../src/renderer/src/assets/file-html.svg | 4 + apps/shell/src/renderer/src/locale.tsx | 1 + apps/shell/src/renderer/src/settings.css | 22 + apps/shell/src/renderer/src/strings.ts | 839 +++- apps/shell/src/shared/home-api.ts | 42 + apps/shell/src/shared/tabs-api.ts | 2 +- apps/shell/tests/ai-panel-prefs.test.ts | 49 + apps/shell/tests/pdf2docx-local-argv.test.ts | 23 + apps/shell/tests/settings-ai-panel.test.ts | 169 + apps/shell/tests/settings-analytics.test.ts | 59 +- apps/shell/tsconfig.json | 3 +- apps/slides/package.json | 2 +- apps/slides/src/main/ai-ipc.ts | 60 +- apps/slides/src/main/fonts.ts | 32 +- apps/slides/src/main/i18n-main.ts | 132 + apps/slides/src/main/metafile-fonts.ts | 156 + apps/slides/src/main/ops/table-ops.ts | 103 +- apps/slides/src/main/slides-main.ts | 94 +- apps/slides/src/preload/index.ts | 15 + apps/slides/src/renderer/App.tsx | 31 +- apps/slides/src/renderer/ChartBody.tsx | 9 +- apps/slides/src/renderer/ai/AiPanel.tsx | 51 +- .../src/renderer/ai/prompts/qc-geometry.md | 15 + .../src/renderer/ai/prompts/qc-visual.md | 21 + apps/slides/src/renderer/ai/prompts/system.md | 74 + apps/slides/src/renderer/ai/slide-qc.ts | 42 +- apps/slides/src/renderer/ai/slides-skill.ts | 219 +- .../slides/src/renderer/components/Ribbon.tsx | 81 +- .../src/renderer/components/RibbonHomeTab.tsx | 15 - .../src/renderer/components/context-tabs.ts | 10 + apps/slides/src/renderer/components/icons.tsx | 39 +- .../src/renderer/components/ribbon-shared.tsx | 7 +- apps/slides/src/renderer/i18n/ai/ar.ts | 7 +- apps/slides/src/renderer/i18n/ai/cs.ts | 226 ++ apps/slides/src/renderer/i18n/ai/de.ts | 7 +- apps/slides/src/renderer/i18n/ai/en.ts | 7 +- apps/slides/src/renderer/i18n/ai/es.ts | 7 +- apps/slides/src/renderer/i18n/ai/fr.ts | 7 +- apps/slides/src/renderer/i18n/ai/he.ts | 7 +- apps/slides/src/renderer/i18n/ai/hi.ts | 7 +- apps/slides/src/renderer/i18n/ai/id.ts | 7 +- apps/slides/src/renderer/i18n/ai/it.ts | 7 +- apps/slides/src/renderer/i18n/ai/ja.ts | 7 +- apps/slides/src/renderer/i18n/ai/ko.ts | 7 +- apps/slides/src/renderer/i18n/ai/ms.ts | 7 +- apps/slides/src/renderer/i18n/ai/nl.ts | 7 +- apps/slides/src/renderer/i18n/ai/pl.ts | 7 +- apps/slides/src/renderer/i18n/ai/pt.ts | 7 +- apps/slides/src/renderer/i18n/ai/ru.ts | 7 +- apps/slides/src/renderer/i18n/ai/th.ts | 7 +- apps/slides/src/renderer/i18n/ai/zh-TW.ts | 7 +- apps/slides/src/renderer/i18n/ai/zh.ts | 7 +- apps/slides/src/renderer/i18n/app/cs.ts | 235 ++ apps/slides/src/renderer/i18n/locale.tsx | 2 + apps/slides/src/renderer/i18n/panes/cs.ts | 279 ++ apps/slides/src/renderer/i18n/ribbon/ar.ts | 3 + apps/slides/src/renderer/i18n/ribbon/cs.ts | 735 ++++ apps/slides/src/renderer/i18n/ribbon/de.ts | 3 + apps/slides/src/renderer/i18n/ribbon/en.ts | 3 + apps/slides/src/renderer/i18n/ribbon/es.ts | 3 + apps/slides/src/renderer/i18n/ribbon/fr.ts | 3 + apps/slides/src/renderer/i18n/ribbon/he.ts | 3 + apps/slides/src/renderer/i18n/ribbon/hi.ts | 3 + apps/slides/src/renderer/i18n/ribbon/id.ts | 3 + apps/slides/src/renderer/i18n/ribbon/it.ts | 3 + apps/slides/src/renderer/i18n/ribbon/ja.ts | 3 + apps/slides/src/renderer/i18n/ribbon/ko.ts | 3 + apps/slides/src/renderer/i18n/ribbon/ms.ts | 3 + apps/slides/src/renderer/i18n/ribbon/nl.ts | 3 + apps/slides/src/renderer/i18n/ribbon/pl.ts | 3 + apps/slides/src/renderer/i18n/ribbon/pt.ts | 3 + apps/slides/src/renderer/i18n/ribbon/ru.ts | 3 + apps/slides/src/renderer/i18n/ribbon/th.ts | 3 + apps/slides/src/renderer/i18n/ribbon/zh-TW.ts | 3 + apps/slides/src/renderer/i18n/ribbon/zh.ts | 3 + apps/slides/src/renderer/i18n/strings-ai.ts | 2 + apps/slides/src/renderer/i18n/strings-app.ts | 2 + .../slides/src/renderer/i18n/strings-panes.ts | 2 + .../src/renderer/i18n/strings-ribbon.ts | 2 + apps/slides/src/renderer/i18n/strings.ts | 1 + apps/slides/src/renderer/main.tsx | 9 +- .../src/renderer/picture-edit-actions.ts | 24 + apps/slides/src/shared/ipc.ts | 15 + apps/slides/src/shared/prompts/ops/slide.md | 2 + apps/slides/src/shared/prompts/ops/table.md | 47 +- apps/slides/tests/ai-picture-tools.test.ts | 13 +- apps/slides/tests/context-tabs.test.ts | 11 + apps/slides/tests/edit-ops.test.ts | 65 + apps/slides/tests/embedded-fonts.test.ts | 57 + apps/slides/tests/metafile-fonts.test.ts | 114 + e2e/docs-spellcheck-reenable.spec.ts | 75 + e2e/home.spec.ts | 7 +- e2e/html-tab.spec.ts | 554 +++ e2e/markdown-tab.spec.ts | 60 +- e2e/pdf-shift-arrow-selection.spec.ts | 86 + e2e/sheets-arrow-collapse.spec.ts | 154 + e2e/sheets-filter-outline.spec.ts | 188 + e2e/sheets-filter-reopen.spec.ts | 181 + e2e/sheets-jump-scroll.spec.ts | 115 + e2e/sheets-menu-input-enter.spec.ts | 110 + e2e/sheets-paste-anchor-tile.spec.ts | 112 + e2e/sheets-paste-shared-formula-save.spec.ts | 116 + e2e/theme-visual.spec.ts | 32 + eslint.config.mjs | 11 + package-lock.json | 1573 +++++++- package.json | 10 +- packages/agent-core/package.json | 2 +- packages/ai-provider/package.json | 2 +- packages/ai-provider/src/browser.ts | 2 + packages/ai-provider/src/codex-app-server.ts | 233 +- packages/ai-provider/src/fetch.ts | 31 +- packages/ai-provider/src/http-error.ts | 15 +- packages/ai-provider/src/index.ts | 43 + packages/ai-provider/src/media-protocols.ts | 712 ++++ packages/ai-provider/src/media.ts | 320 ++ .../ai-provider/src/protocols/anthropic.ts | 8 + .../src/protocols/openai-compatible.ts | 16 +- packages/ai-provider/src/providers.ts | 12 +- packages/ai-provider/src/search-settings.ts | 42 + packages/ai-provider/src/types.ts | 75 + packages/ai-provider/tests/chat.test.ts | 4 +- .../tests/codex-app-server.test.ts | 101 + packages/ai-provider/tests/fetch.test.ts | 37 + packages/ai-provider/tests/http-error.test.ts | 24 + packages/ai-provider/tests/media.test.ts | 487 +++ .../ai-provider/tests/search-settings.test.ts | 55 + packages/ai-provider/tests/stream.test.ts | 69 +- packages/ai-search/package.json | 4 +- packages/ai-search/src/index.ts | 213 +- packages/ai-search/src/media-tools.ts | 197 + packages/ai-search/src/search-tools.ts | 55 + packages/ai-search/tests/search.test.ts | 86 + packages/docx-engine/package.json | 2 +- packages/electron-utils/package.json | 2 +- packages/electron-utils/src/app-menu.ts | 19 +- packages/electron-utils/src/context-menu.ts | 3 +- packages/electron-utils/src/dialog-memory.ts | 14 + packages/electron-utils/src/drop-open.ts | 2 +- .../electron-utils/src/generated-images.ts | 85 + packages/electron-utils/src/index.ts | 7 +- packages/electron-utils/src/remote-image.ts | 10 + .../electron-utils/tests/app-menu.test.ts | 3 +- .../tests/dialog-memory.test.ts | 32 +- .../tests/generated-images.test.ts | 41 + packages/file-parse/package.json | 2 +- packages/font-metrics/package.json | 2 +- packages/html2docx/ARCHITECTURE.md | 719 ++++ packages/html2docx/README.md | 46 + packages/html2docx/package.json | 27 + .../html2docx/src/browser/core/classifier.js | 1149 ++++++ .../html2docx/src/browser/core/decorators.js | 245 ++ .../src/browser/core/layouts-controls.js | 1079 +++++ .../src/browser/core/paragraphs-document.js | 294 ++ .../src/browser/core/runs-screenshots.js | 745 ++++ packages/html2docx/src/browser/core/styles.js | 460 +++ .../src/browser/core/tables-lists.js | 516 +++ packages/html2docx/src/browser/forms-media.js | 176 + packages/html2docx/src/browser/pages.js | 779 ++++ packages/html2docx/src/browser/table.js | 295 ++ .../html2docx/src/browser/visual-effects.js | 51 + packages/html2docx/src/convert.ts | 499 +++ packages/html2docx/src/driver.ts | 46 + packages/html2docx/src/drivers/playwright.ts | 119 + packages/html2docx/src/extract.ts | 41 + packages/html2docx/src/generate.ts | 32 + packages/html2docx/src/generate/bookmarks.ts | 25 + .../src/generate/content-controls.ts | 60 + .../html2docx/src/generate/document-meta.ts | 69 + packages/html2docx/src/generate/fonts.ts | 60 + packages/html2docx/src/generate/numbering.ts | 77 + .../html2docx/src/generate/page-settings.ts | 280 ++ .../html2docx/src/generate/render-context.ts | 54 + packages/html2docx/src/generate/renderer.ts | 706 ++++ .../html2docx/src/generate/table-renderers.ts | 1177 ++++++ packages/html2docx/src/generate/word-utils.ts | 359 ++ packages/html2docx/src/index.ts | 6 + packages/html2docx/src/raw.d.ts | 4 + packages/html2docx/tests/features.test.ts | 1617 ++++++++ packages/html2docx/tools/cli.ts | 81 + packages/html2docx/tsconfig.json | 12 + packages/html2docx/vitest.config.ts | 10 + packages/i18n/package.json | 2 +- packages/i18n/src/index.ts | 3 + packages/i18n/tests/i18n.test.ts | 4 + packages/pdf2docx/package.json | 2 +- packages/pdf2docx/src/analyze/floats.ts | 7 + packages/pdf2docx/src/analyze/index.ts | 9 +- packages/pdf2docx/src/analyze/shapes.ts | 56 +- packages/pdf2docx/src/analyze/stream.ts | 16 +- packages/pdf2docx/src/extract/index.ts | 296 +- packages/pdf2docx/src/geometry.ts | 63 + packages/pdf2docx/src/ir.ts | 2 + packages/pdf2docx/src/pipeline.ts | 13 +- .../tests/bank-statement-repro.test.ts | 70 + packages/pdf2docx/tests/helpers/fixtures.ts | 94 + .../pdf2docx/tests/print-content-box.test.ts | 206 + packages/pdf2docx/tests/stitch.test.ts | 32 + packages/pptx-engine/package.json | 2 +- packages/pptx-engine/src/chart.ts | 22 +- packages/pptx-engine/src/parse.ts | 39 +- packages/pptx-engine/src/placeholder.ts | 13 +- packages/pptx-engine/src/theme.ts | 53 +- packages/pptx-engine/src/zip.ts | 47 +- packages/pptx-engine/tests/chart.test.ts | 16 + .../tests/slide-chain-fallback.test.ts | 72 + .../tests/theme-script-fonts.test.ts | 46 + packages/pptx-render/package.json | 2 +- packages/pptx-render/src/build-chart.ts | 38 +- packages/pptx-render/src/render-tree.ts | 7 +- .../pptx-render/tests/build-chart.test.ts | 46 +- packages/project-store/package.json | 2 +- packages/project-store/src/index.ts | 1 + packages/project-store/src/ipc.ts | 21 +- packages/project-store/src/store.ts | 10 + packages/project-store/src/types.ts | 8 + packages/project-store/tests/store.test.ts | 13 + packages/ui/package.json | 11 +- packages/ui/src/AiComposer.tsx | 3 + packages/ui/src/AiScopeQuote.tsx | 20 + packages/ui/src/ai-panel-prefs-store.ts | 45 + packages/ui/src/ai-panel-prefs.css | 7 + packages/ui/src/ai-panel-prefs.ts | 71 + packages/ui/src/ai-scope-quote.css | 38 + packages/ui/src/auto-save-pref.ts | 101 + packages/ui/src/cutout.ts | 179 + packages/ui/src/find-panel.css | 120 + packages/ui/src/find-panel.tsx | 284 ++ packages/ui/src/find-text.ts | 36 + packages/ui/src/image-dialogs.css | 154 + packages/ui/src/image-dialogs.tsx | 533 +++ packages/ui/src/index.ts | 46 + packages/ui/src/tokens.css | 9 + packages/ui/tests/auto-save-pref.test.ts | 39 + packages/ui/vitest.config.ts | 8 + tools/build-stale-preloads.mjs | 2 +- tools/check-licenses.mjs | 2 + tools/gen-file-association-icons.mjs | 1 + tools/gen-third-party-notices.mjs | 1 + 678 files changed, 75586 insertions(+), 7492 deletions(-) delete mode 100644 apps/docs/src/renderer/ai/commands.ts create mode 100644 apps/docs/src/renderer/ai/doc-utils.ts create mode 100644 apps/docs/src/renderer/ai/ops.ts create mode 100644 apps/docs/src/renderer/html-export.ts create mode 100644 apps/docs/src/renderer/i18n/ai/cs.ts create mode 100644 apps/docs/src/renderer/i18n/app/cs.ts create mode 100644 apps/docs/src/renderer/i18n/ribbon/cs.ts delete mode 100644 apps/docs/tests/commands.test.ts create mode 100644 apps/docs/tests/comment-edit.test.ts create mode 100644 apps/docs/tests/comment-word-anchor.test.ts create mode 100644 apps/docs/tests/html-export.test.ts create mode 100644 apps/docs/tests/insert-tab-comment.test.ts create mode 100644 apps/docs/tests/ops.test.ts create mode 100644 apps/docs/tests/paste-single-cell.test.ts create mode 100644 apps/docs/tests/table-trailing-paragraph.test.ts create mode 100644 apps/html/electron.vite.config.ts create mode 100644 apps/html/package.json create mode 100644 apps/html/src/main/asset-lifecycle.ts create mode 100644 apps/html/src/main/asset-mime.ts create mode 100644 apps/html/src/main/atomic-write.ts create mode 100644 apps/html/src/main/html-main.ts create mode 100644 apps/html/src/main/html2docx-driver.ts create mode 100644 apps/html/src/main/index.ts create mode 100644 apps/html/src/main/preview-document.ts create mode 100644 apps/html/src/main/preview-protocol.ts create mode 100644 apps/html/src/preload/index.ts create mode 100644 apps/html/src/renderer/App.tsx create mode 100644 apps/html/src/renderer/PresentView.tsx create mode 100644 apps/html/src/renderer/ai/AiPanel.tsx create mode 100644 apps/html/src/renderer/ai/EditQueueCard.tsx create mode 100644 apps/html/src/renderer/ai/doc-nav.ts create mode 100644 apps/html/src/renderer/ai/edit-queue.ts create mode 100644 apps/html/src/renderer/ai/files-skill.ts create mode 100644 apps/html/src/renderer/ai/html-skill.ts create mode 100644 apps/html/src/renderer/ai/intent.ts create mode 100644 apps/html/src/renderer/ai/page-writer.ts create mode 100644 apps/html/src/renderer/ai/search-skill.ts create mode 100644 apps/html/src/renderer/ai/tools.ts create mode 100644 apps/html/src/renderer/ai/transport.ts create mode 100644 apps/html/src/renderer/assets/attach-icon.png create mode 100644 apps/html/src/renderer/assets/file-document.png create mode 100644 apps/html/src/renderer/assets/file-excel.png create mode 100644 apps/html/src/renderer/assets/file-general.png create mode 100644 apps/html/src/renderer/assets/file-image.png create mode 100644 apps/html/src/renderer/assets/file-pdf.png create mode 100644 apps/html/src/renderer/assets/file-ppt.png create mode 100644 apps/html/src/renderer/assets/file-video.png create mode 100644 apps/html/src/renderer/assets/file-voice.png create mode 100644 apps/html/src/renderer/assets/file-word.png create mode 100644 apps/html/src/renderer/assets/send-enter-off.png create mode 100644 apps/html/src/renderer/assets/send-enter-on.png create mode 100644 apps/html/src/renderer/assets/send-stop.png create mode 100644 apps/html/src/renderer/components/AiAskPopover.tsx create mode 100644 apps/html/src/renderer/components/Breadcrumb.tsx create mode 100644 apps/html/src/renderer/components/BriefCard.tsx create mode 100644 apps/html/src/renderer/components/ClarifyCard.tsx create mode 100644 apps/html/src/renderer/components/ColorField.tsx create mode 100644 apps/html/src/renderer/components/FloatToolbar.tsx create mode 100644 apps/html/src/renderer/components/Ribbon.tsx create mode 100644 apps/html/src/renderer/components/StylePanel.tsx create mode 100644 apps/html/src/renderer/components/icons.tsx create mode 100644 apps/html/src/renderer/document/auto-name.ts create mode 100644 apps/html/src/renderer/document/background-style.ts create mode 100644 apps/html/src/renderer/document/blank.ts create mode 100644 apps/html/src/renderer/document/brief.ts create mode 100644 apps/html/src/renderer/document/envelope.ts create mode 100644 apps/html/src/renderer/document/float-position.ts create mode 100644 apps/html/src/renderer/document/image-style.ts create mode 100644 apps/html/src/renderer/document/match.ts create mode 100644 apps/html/src/renderer/document/ops.ts create mode 100644 apps/html/src/renderer/document/parse-map.ts create mode 100644 apps/html/src/renderer/document/patch.ts create mode 100644 apps/html/src/renderer/env.d.ts create mode 100644 apps/html/src/renderer/i18n/ai/ar.ts create mode 100644 apps/html/src/renderer/i18n/ai/cs.ts create mode 100644 apps/html/src/renderer/i18n/ai/de.ts create mode 100644 apps/html/src/renderer/i18n/ai/en.ts create mode 100644 apps/html/src/renderer/i18n/ai/es.ts create mode 100644 apps/html/src/renderer/i18n/ai/fr.ts create mode 100644 apps/html/src/renderer/i18n/ai/he.ts create mode 100644 apps/html/src/renderer/i18n/ai/hi.ts create mode 100644 apps/html/src/renderer/i18n/ai/id.ts create mode 100644 apps/html/src/renderer/i18n/ai/it.ts create mode 100644 apps/html/src/renderer/i18n/ai/ja.ts create mode 100644 apps/html/src/renderer/i18n/ai/ko.ts create mode 100644 apps/html/src/renderer/i18n/ai/ms.ts create mode 100644 apps/html/src/renderer/i18n/ai/nl.ts create mode 100644 apps/html/src/renderer/i18n/ai/pl.ts create mode 100644 apps/html/src/renderer/i18n/ai/pt.ts create mode 100644 apps/html/src/renderer/i18n/ai/ru.ts create mode 100644 apps/html/src/renderer/i18n/ai/th.ts create mode 100644 apps/html/src/renderer/i18n/ai/zh-TW.ts create mode 100644 apps/html/src/renderer/i18n/ai/zh.ts create mode 100644 apps/html/src/renderer/i18n/app/ar.ts create mode 100644 apps/html/src/renderer/i18n/app/cs.ts create mode 100644 apps/html/src/renderer/i18n/app/de.ts create mode 100644 apps/html/src/renderer/i18n/app/en.ts create mode 100644 apps/html/src/renderer/i18n/app/es.ts create mode 100644 apps/html/src/renderer/i18n/app/fr.ts create mode 100644 apps/html/src/renderer/i18n/app/he.ts create mode 100644 apps/html/src/renderer/i18n/app/hi.ts create mode 100644 apps/html/src/renderer/i18n/app/id.ts create mode 100644 apps/html/src/renderer/i18n/app/it.ts create mode 100644 apps/html/src/renderer/i18n/app/ja.ts create mode 100644 apps/html/src/renderer/i18n/app/ko.ts create mode 100644 apps/html/src/renderer/i18n/app/ms.ts create mode 100644 apps/html/src/renderer/i18n/app/nl.ts create mode 100644 apps/html/src/renderer/i18n/app/pl.ts create mode 100644 apps/html/src/renderer/i18n/app/pt.ts create mode 100644 apps/html/src/renderer/i18n/app/ru.ts create mode 100644 apps/html/src/renderer/i18n/app/th.ts create mode 100644 apps/html/src/renderer/i18n/app/zh-TW.ts create mode 100644 apps/html/src/renderer/i18n/app/zh.ts create mode 100644 apps/html/src/renderer/i18n/locale.tsx create mode 100644 apps/html/src/renderer/i18n/strings-ai.ts create mode 100644 apps/html/src/renderer/i18n/strings-app.ts create mode 100644 apps/html/src/renderer/i18n/strings.ts create mode 100644 apps/html/src/renderer/index.html create mode 100644 apps/html/src/renderer/main.tsx create mode 100644 apps/html/src/renderer/preview/DraftPreview.tsx create mode 100644 apps/html/src/renderer/preview/PreviewFrame.tsx create mode 100644 apps/html/src/renderer/preview/inspector-protocol.ts create mode 100644 apps/html/src/renderer/preview/inspector.js create mode 100644 apps/html/src/renderer/preview/instrument.ts create mode 100644 apps/html/src/renderer/source/SourceEditor.tsx create mode 100644 apps/html/src/renderer/source/cm-find.ts create mode 100644 apps/html/src/renderer/source/cm-highlight.ts create mode 100644 apps/html/src/renderer/source/cm-setup.ts create mode 100644 apps/html/src/renderer/source/find-target.ts create mode 100644 apps/html/src/renderer/styles.css create mode 100644 apps/html/src/shared/ipc.ts create mode 100644 apps/html/tests/asset-lifecycle.test.ts create mode 100644 apps/html/tests/asset-mime.test.ts create mode 100644 apps/html/tests/auto-name.test.ts create mode 100644 apps/html/tests/background-style.test.ts create mode 100644 apps/html/tests/blank.test.ts create mode 100644 apps/html/tests/brief.test.ts create mode 100644 apps/html/tests/cm-find.test.ts create mode 100644 apps/html/tests/document.test.ts create mode 100644 apps/html/tests/edit-queue.test.ts create mode 100644 apps/html/tests/float-position.test.ts create mode 100644 apps/html/tests/image-style.test.ts create mode 100644 apps/html/tests/ops.test.ts create mode 100644 apps/html/tests/page-writer.test.ts create mode 100644 apps/html/tests/tools.test.ts create mode 100644 apps/html/tsconfig.json create mode 100644 apps/html/vite.renderer.config.ts create mode 100644 apps/html/vitest.config.ts create mode 100644 apps/markdown/src/renderer/editor/findTarget.ts create mode 100644 apps/markdown/src/renderer/editor/inactiveSelection.ts create mode 100644 apps/markdown/src/renderer/editor/mermaid.ts create mode 100644 apps/markdown/src/renderer/editor/ops.ts create mode 100644 apps/markdown/src/renderer/editor/searchHighlight.ts create mode 100644 apps/markdown/tests/find-panel.test.ts create mode 100644 apps/markdown/tests/ops.test.ts create mode 100644 apps/pdf/src/renderer/edit-ops/index.ts create mode 100644 apps/pdf/src/renderer/edit-ops/ops.ts create mode 100644 apps/pdf/src/renderer/edit-ops/registry.ts create mode 100644 apps/pdf/src/shared/op-docs.ts create mode 100644 apps/pdf/tests/edit-ops.test.ts create mode 100644 apps/pdf/tests/op-docs.test.ts create mode 100644 apps/sheets/src/gateway/xlsx-escapes.ts create mode 100644 apps/sheets/src/renderer/arrow-collapse-fix.ts create mode 100644 apps/sheets/src/renderer/autofit-line-pitch.ts create mode 100644 apps/sheets/src/renderer/autofit-wrap-budget.ts create mode 100644 apps/sheets/src/renderer/chart-category-vector.ts create mode 100644 apps/sheets/src/renderer/chart-sync-pending.ts create mode 100644 apps/sheets/src/renderer/clipboard-anchor-tile.ts create mode 100644 apps/sheets/src/renderer/filter-range-outline.ts create mode 100644 apps/sheets/src/renderer/formula-newline-display.ts create mode 100644 apps/sheets/src/renderer/i18n/ai/cs.ts create mode 100644 apps/sheets/src/renderer/i18n/app/cs.ts create mode 100644 apps/sheets/src/renderer/i18n/dialogs/cs.ts create mode 100644 apps/sheets/src/renderer/menu-input-enter.ts create mode 100644 apps/sheets/src/renderer/number-as-text-alert.ts create mode 100644 apps/sheets/src/renderer/op-executor.ts create mode 100644 apps/sheets/src/renderer/replace-autosearch.ts create mode 100644 apps/sheets/src/renderer/shape-text-scale.ts create mode 100644 apps/sheets/src/renderer/shared-formula-journal.ts create mode 100644 apps/sheets/src/renderer/sparse-find.ts create mode 100644 apps/sheets/tests/arrow-collapse-fix.test.ts create mode 100644 apps/sheets/tests/autofit-line-pitch.test.ts create mode 100644 apps/sheets/tests/autofit-wrap-budget.test.ts create mode 100644 apps/sheets/tests/chart-category-vector.test.ts create mode 100644 apps/sheets/tests/chart-hidden-axis.test.ts create mode 100644 apps/sheets/tests/chart-point-labels.test.ts create mode 100644 apps/sheets/tests/chart-sync-pending.test.ts create mode 100644 apps/sheets/tests/clipboard-anchor-tile.test.ts create mode 100644 apps/sheets/tests/column-width-narrow.test.ts create mode 100644 apps/sheets/tests/formula-newline-display.test.ts create mode 100644 apps/sheets/tests/formula-stream-hold-full-recalc.test.ts create mode 100644 apps/sheets/tests/number-as-text-alert.test.ts create mode 100644 apps/sheets/tests/op-executor-ui.test.ts create mode 100644 apps/sheets/tests/promote-file-atomically.test.ts create mode 100644 apps/sheets/tests/replace-autosearch.test.ts create mode 100644 apps/sheets/tests/shape-text-scale.test.ts create mode 100644 apps/sheets/tests/shared-formula-journal.test.ts create mode 100644 apps/sheets/tests/sparse-find.test.ts create mode 100644 apps/sheets/tests/xlsx-escapes.test.ts create mode 100644 apps/shell/build/html.icns create mode 100644 apps/shell/build/html.ico create mode 100644 apps/shell/src/main/assets/menu-html.png create mode 100644 apps/shell/src/main/assets/menu-html@2x.png create mode 100644 apps/shell/src/renderer/src/assets/file-html.svg create mode 100644 apps/shell/tests/ai-panel-prefs.test.ts create mode 100644 apps/shell/tests/pdf2docx-local-argv.test.ts create mode 100644 apps/shell/tests/settings-ai-panel.test.ts create mode 100644 apps/slides/src/main/metafile-fonts.ts create mode 100644 apps/slides/src/renderer/ai/prompts/qc-geometry.md create mode 100644 apps/slides/src/renderer/ai/prompts/qc-visual.md create mode 100644 apps/slides/src/renderer/ai/prompts/system.md create mode 100644 apps/slides/src/renderer/i18n/ai/cs.ts create mode 100644 apps/slides/src/renderer/i18n/app/cs.ts create mode 100644 apps/slides/src/renderer/i18n/panes/cs.ts create mode 100644 apps/slides/src/renderer/i18n/ribbon/cs.ts create mode 100644 apps/slides/tests/embedded-fonts.test.ts create mode 100644 apps/slides/tests/metafile-fonts.test.ts create mode 100644 e2e/docs-spellcheck-reenable.spec.ts create mode 100644 e2e/html-tab.spec.ts create mode 100644 e2e/pdf-shift-arrow-selection.spec.ts create mode 100644 e2e/sheets-arrow-collapse.spec.ts create mode 100644 e2e/sheets-filter-outline.spec.ts create mode 100644 e2e/sheets-filter-reopen.spec.ts create mode 100644 e2e/sheets-jump-scroll.spec.ts create mode 100644 e2e/sheets-menu-input-enter.spec.ts create mode 100644 e2e/sheets-paste-anchor-tile.spec.ts create mode 100644 e2e/sheets-paste-shared-formula-save.spec.ts create mode 100644 packages/ai-provider/src/media-protocols.ts create mode 100644 packages/ai-provider/src/media.ts create mode 100644 packages/ai-provider/src/search-settings.ts create mode 100644 packages/ai-provider/tests/http-error.test.ts create mode 100644 packages/ai-provider/tests/media.test.ts create mode 100644 packages/ai-provider/tests/search-settings.test.ts create mode 100644 packages/ai-search/src/media-tools.ts create mode 100644 packages/ai-search/src/search-tools.ts create mode 100644 packages/electron-utils/src/generated-images.ts create mode 100644 packages/electron-utils/tests/generated-images.test.ts create mode 100644 packages/html2docx/ARCHITECTURE.md create mode 100644 packages/html2docx/README.md create mode 100644 packages/html2docx/package.json create mode 100644 packages/html2docx/src/browser/core/classifier.js create mode 100644 packages/html2docx/src/browser/core/decorators.js create mode 100644 packages/html2docx/src/browser/core/layouts-controls.js create mode 100644 packages/html2docx/src/browser/core/paragraphs-document.js create mode 100644 packages/html2docx/src/browser/core/runs-screenshots.js create mode 100644 packages/html2docx/src/browser/core/styles.js create mode 100644 packages/html2docx/src/browser/core/tables-lists.js create mode 100644 packages/html2docx/src/browser/forms-media.js create mode 100644 packages/html2docx/src/browser/pages.js create mode 100644 packages/html2docx/src/browser/table.js create mode 100644 packages/html2docx/src/browser/visual-effects.js create mode 100644 packages/html2docx/src/convert.ts create mode 100644 packages/html2docx/src/driver.ts create mode 100644 packages/html2docx/src/drivers/playwright.ts create mode 100644 packages/html2docx/src/extract.ts create mode 100644 packages/html2docx/src/generate.ts create mode 100644 packages/html2docx/src/generate/bookmarks.ts create mode 100644 packages/html2docx/src/generate/content-controls.ts create mode 100644 packages/html2docx/src/generate/document-meta.ts create mode 100644 packages/html2docx/src/generate/fonts.ts create mode 100644 packages/html2docx/src/generate/numbering.ts create mode 100644 packages/html2docx/src/generate/page-settings.ts create mode 100644 packages/html2docx/src/generate/render-context.ts create mode 100644 packages/html2docx/src/generate/renderer.ts create mode 100644 packages/html2docx/src/generate/table-renderers.ts create mode 100644 packages/html2docx/src/generate/word-utils.ts create mode 100644 packages/html2docx/src/index.ts create mode 100644 packages/html2docx/src/raw.d.ts create mode 100644 packages/html2docx/tests/features.test.ts create mode 100644 packages/html2docx/tools/cli.ts create mode 100644 packages/html2docx/tsconfig.json create mode 100644 packages/html2docx/vitest.config.ts create mode 100644 packages/pdf2docx/tests/bank-statement-repro.test.ts create mode 100644 packages/pdf2docx/tests/print-content-box.test.ts create mode 100644 packages/pptx-engine/tests/slide-chain-fallback.test.ts create mode 100644 packages/pptx-engine/tests/theme-script-fonts.test.ts create mode 100644 packages/ui/src/AiScopeQuote.tsx create mode 100644 packages/ui/src/ai-panel-prefs-store.ts create mode 100644 packages/ui/src/ai-panel-prefs.css create mode 100644 packages/ui/src/ai-panel-prefs.ts create mode 100644 packages/ui/src/ai-scope-quote.css create mode 100644 packages/ui/src/auto-save-pref.ts create mode 100644 packages/ui/src/cutout.ts create mode 100644 packages/ui/src/find-panel.css create mode 100644 packages/ui/src/find-panel.tsx create mode 100644 packages/ui/src/find-text.ts create mode 100644 packages/ui/src/image-dialogs.css create mode 100644 packages/ui/src/image-dialogs.tsx create mode 100644 packages/ui/tests/auto-save-pref.test.ts create mode 100644 packages/ui/vitest.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb8fdc2..3b5c43c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,6 +82,22 @@ jobs: fi npm run check:theme-colors + # 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). + - name: Check public-repo hygiene + 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 + if [ -f tools/check-public-hygiene.mjs ]; then + node tools/check-public-hygiene.mjs + else + echo "public-hygiene gate not present in this checkout; skipped" + fi + # Keep tracked code comments and contributor-facing documentation # English-only; functional CJK strings and AI prompt examples are allowed. - name: Check comments/docs are English-only diff --git a/.prettierignore b/.prettierignore index a5333dc..07fcd29 100644 --- a/.prettierignore +++ b/.prettierignore @@ -16,3 +16,9 @@ scripts/drivers/driver.*.mjs # Vendored third-party sources stay byte-identical to upstream. packages/*/src/vendor/ + +# LLM prompt text: prettier rewrites *_* markers and list indentation, changing what the model reads. +apps/slides/src/renderer/ai/prompts/*.md + +# In-page extractor fragments: concatenated into one function body, kept verbatim. +packages/html2docx/src/browser/ diff --git a/README.md b/README.md index 7f3ad48..a545455 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,9 @@ GenOffice is a free, open-source alternative to Microsoft Office for macOS, Windows, and Linux, built around AI editing as a first-class workflow rather than a bolted-on chat box. It opens and saves the real Microsoft Office formats — Word (`.docx`), Excel (`.xlsx`), PowerPoint (`.pptx`) — and edits -PDF and Markdown too: a word processor, spreadsheet, presentation editor, -PDF editor, and Markdown editor as six Electron apps sharing one engine -layer. +PDF, Markdown, and HTML too: a word processor, spreadsheet, presentation +editor, PDF editor, Markdown editor, and a design-first AI HTML page builder +as seven Electron apps sharing one engine layer. [![Meet GenOffice — the world's first full-featured open-source AI Office (video)](https://img.youtube.com/vi/B2pLdMX95v4/maxresdefault.jpg)](https://www.youtube.com/watch?v=B2pLdMX95v4) @@ -30,8 +30,11 @@ layer. - **Excel-compatible spreadsheets** — in-house engine with a Rust `.xlsx` sidecar, own charts, pivot tables, slicers. - **PowerPoint-compatible presentations** — in-house `.pptx` engine with masters, layouts, smart guides, non-destructive crop. - **Markdown to Word, fully local** — the same OOXML engine, no Pandoc, no cloud. +- **HTML to Word, fully local** — Export as Word renders the page in the built-in Chromium, reduces it to a document intent tree (headings, paragraphs, lists, tables, cards, KPI rows, form fields, page backgrounds) and writes native, editable OOXML; only visuals with no Word counterpart (charts, icons, decorated boxes) become pictures. No print-to-PDF detour, no cloud. +- **AI-designed HTML pages** — generate landing pages, reports, and posters as single self-contained HTML files, design-first; a _Write content_ mode for plain articles. - **AI that edits documents** — block-level edits with snapshots and diffs, document-aware agents. - **Bring your own key (BYOK)** — run the AI on your own API key: Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, OpenCode Zen/Go, or any OpenAI-compatible endpoint — or sign in with Genspark and skip keys entirely. +- **BYOK for search and media too** — web search on your own Serper or Tavily key; image generation, image analysis, and video analysis each on the provider you choose (OpenAI, Gemini, Doubao/Seedream, GLM, Grok, Qwen, MiniMax, or any OpenAI-compatible images endpoint), configured per capability in _AI Media & Search_. - **Agent tools built in** — web/image search, image generation, media analysis. - **Light / dark / system themes.** - **macOS, Windows, Linux.** @@ -43,7 +46,7 @@ layer. | ------------------------------------ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------- | | **macOS** — Apple Silicon (arm64) | macOS 11+ | [Latest `.dmg` (arm64)](https://github.com/genspark-ai/genoffice/releases/latest) | | **macOS** — Intel (x64) | macOS 11+ | [Latest `.dmg` (x64)](https://github.com/genspark-ai/genoffice/releases/latest) | -| **Windows** (x64) | Windows 10+ | [Latest `.exe` installer](https://github.com/genspark-ai/genoffice/releases/latest) | +| **Windows** (x64, most PCs) | Windows 10+, Intel/AMD | [Latest `-x64.exe` installer](https://github.com/genspark-ai/genoffice/releases/latest) | | **Windows** on Arm (ARM64) | Windows 11 on Arm (Snapdragon X and similar) | [Latest `-arm64.exe` installer](https://github.com/genspark-ai/genoffice/releases/latest) | | **Linux** — Debian / Ubuntu | x86_64, glibc 2.34+ (Ubuntu 22.04 or newer) | [Latest `.deb`](https://github.com/genspark-ai/genoffice/releases/latest) | | **Linux** — Fedora / RHEL / openSUSE | x86_64, glibc 2.34+ (Fedora 35+, RHEL 9+, Leap 15.6+) | [Latest `.rpm`](https://github.com/genspark-ai/genoffice/releases/latest) | @@ -79,14 +82,15 @@ chmod +x GenOffice-.AppImage ## Apps -| App | Product | What it is | -| --------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `apps/docs` | **GenOffice Docs** | `.docx` word processor. Byte-preserving round trip: only dirty paragraphs are regenerated (paragraph patch), everything else in the original file is kept byte-for-byte, so opening and saving never breaks layout in Word. Paginated view whose line metrics reproduce the original document's layout, tracked changes, comments, styles, equations, ink. | -| `apps/sheets` | **GenOffice Sheets** | `.xlsx` spreadsheet. UI built on the open-source [Univer](https://github.com/dream-num/univer) core (Apache-2.0) with a large layer of in-house extensions; `.xlsx` import/export runs through an in-house Rust sidecar (calamine + IronCalc), charts are rendered in-house (Konva), plus pivot tables, slicers, conditional formatting, and formula tracing. | -| `apps/slides` | **GenOffice Slides** | `.pptx` presentations. In-house `.pptx` parse/render/edit engine with masters, charts, cropping, ink, and text shaping (HarfBuzz metrics). | -| `apps/pdf` | **GenOffice PDF** | `.pdf` viewer/editor on [pdf.js](https://github.com/mozilla/pdf.js) (Apache-2.0) + [pdf-lib](https://github.com/Hopding/pdf-lib) (MIT): annotations, forms, outlines, stamps, signatures, page operations, and printing support. True text editing — paragraph selection with in-block reflow, alignment restoration, original-font preservation — and content-stream image insert/edit, all rewriting page content streams through [PDFium](https://pdfium.googlesource.com/pdfium/) wasm (BSD-3-Clause) with subset-embedded fonts — no cover-up annotations. Converts PDFs into editable Word, PowerPoint, and Excel files fully locally (`packages/pdf2docx`), with OCR support for scanned pages (system OCR on macOS and Windows). | -| `apps/markdown` | **GenOffice Markdown** | `.md` / `.markdown` editor: Tiptap block editor over plain Markdown files — headings, lists, tables, images, code blocks — saved back as plain Markdown, hosted in shell tabs. | -| `apps/shell` | **GenOffice** | The suite shell: home screen, tabbed hosting of the five editors, light/dark/system theme, auto-update. | +| App | Product | What it is | +| --------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `apps/docs` | **GenOffice Docs** | `.docx` word processor. Byte-preserving round trip: only dirty paragraphs are regenerated (paragraph patch), everything else in the original file is kept byte-for-byte, so opening and saving never breaks layout in Word. Paginated view whose line metrics reproduce the original document's layout, tracked changes, comments, styles, equations, ink. | +| `apps/sheets` | **GenOffice Sheets** | `.xlsx` spreadsheet. UI built on the open-source [Univer](https://github.com/dream-num/univer) core (Apache-2.0) with a large layer of in-house extensions; `.xlsx` import/export runs through an in-house Rust sidecar (calamine + IronCalc), charts are rendered in-house (Konva), plus pivot tables, slicers, conditional formatting, and formula tracing. | +| `apps/slides` | **GenOffice Slides** | `.pptx` presentations. In-house `.pptx` parse/render/edit engine with masters, charts, cropping, ink, and text shaping (HarfBuzz metrics). | +| `apps/pdf` | **GenOffice PDF** | `.pdf` viewer/editor on [pdf.js](https://github.com/mozilla/pdf.js) (Apache-2.0) + [pdf-lib](https://github.com/Hopding/pdf-lib) (MIT): annotations, forms, outlines, stamps, signatures, page operations, and printing support. True text editing — paragraph selection with in-block reflow, alignment restoration, original-font preservation — and content-stream image insert/edit, all rewriting page content streams through [PDFium](https://pdfium.googlesource.com/pdfium/) wasm (BSD-3-Clause) with subset-embedded fonts — no cover-up annotations. Converts PDFs into editable Word, PowerPoint, and Excel files fully locally (`packages/pdf2docx`), with OCR support for scanned pages (system OCR on macOS and Windows). | +| `apps/html` | **GenOffice HTML** | Single-file `.html` page builder, design-first. A blank page starts from two intents: _Design a page_ (the AI proposes a design brief — hook, palette, typography, section layouts — with alternative style directions to pick from, then writes the page against `--brief-*` design tokens) or _Write content_ (an article, announcement, or guide written straight into a clean page). Live sandboxed preview with an inspector: click to select an element, double-click to edit text, a floating toolbar and style panel for typography, box, color, and image edits, and element-scoped Ask AI; CodeMirror source view kept in sync; desktop / tablet / phone widths; Present in the tab, fullscreen, or a new tab; export to PDF, and to Word as a native editable `.docx` built on-device by `packages/html2docx`. | +| `apps/markdown` | **GenOffice Markdown** | `.md` / `.markdown` editor: Tiptap block editor over plain Markdown files — headings, lists, tables, images, code blocks — saved back as plain Markdown, hosted in shell tabs. | +| `apps/shell` | **GenOffice** | The suite shell: home screen, tabbed hosting of the six editors, light/dark/system theme, auto-update. | Every app embeds the same AI panel: block-granular AI editing with version snapshots and diffs in docs, a tool-calling agent over workbook/slide/PDF @@ -107,7 +111,11 @@ GPT, and Gemini families). Or bring your own key (BYOK) in the AI settings: Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, and OpenCode Zen/Go are built in, plus a custom provider slot for any OpenAI-compatible endpoint (base URL + key), local servers -included. A +included. Image generation and image/video analysis have their own provider +catalog (AI Media & Search settings): OpenAI, Gemini, Doubao/Seedream, GLM +CogView, Grok Imagine, Qwen-Image, MiniMax or any OpenAI-compatible images +endpoint, each with its own key and assignable per capability; web search can +likewise run on your own Serper or Tavily key. A Genspark account also unlocks the Genspark ("gsk") tool endpoints the agents build on — web and image search, image generation and editing, image/audio/video analysis, and audio transcription — all reachable through @@ -124,6 +132,10 @@ All pure TypeScript, no Electron dependency, unit-tested (except the UI kit): - `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 @@ -142,7 +154,7 @@ npm install npm run fixtures # generate test .docx fixtures npm test # engine + app unit tests (docs/sheets/slides need no display) npm run typecheck # tsc --noEmit across every workspace -npm run dev # all five editors + shell against Vite dev servers +npm run dev # all six editors + shell against Vite dev servers npm run dev:docs # a single app (same pattern works per workspace) npm run dist:mac # package macOS dmg (regenerates third-party notices) npm run dist:win # package Windows nsis installer @@ -203,6 +215,28 @@ key (BYOK) for Claude, OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen, Doubao, MiniMax, Grok, Mistral, OpenRouter, and OpenCode Zen/Go, plus any OpenAI-compatible endpoint — including local model servers. +**Can I bring my own keys for search, image generation, and media analysis?** +Yes. Settings → AI Media & Search takes separate keys per capability: web +search on Serper or Tavily, and image generation, image analysis, and video +analysis each on OpenAI, Gemini, Doubao/Seedream, GLM, Grok, Qwen, MiniMax, or +any OpenAI-compatible images endpoint. Anything left on Genspark keeps using +your Genspark sign-in. + +**Can GenOffice design web pages?** +Yes. GenOffice HTML is a design-first page builder: describe a landing page, +report, or poster, pick a style direction from the proposed design brief, and +the AI lays out a single self-contained `.html` file you then refine visually +— select an element to restyle it or ask AI about it. Pages present +fullscreen and export to PDF and Word. + +**Can GenOffice convert HTML to Word?** +Yes — Export as Word in the HTML app produces a native, editable `.docx` +entirely on-device. The page is rendered in the built-in Chromium and reduced +to real Word structures: headings, paragraphs, lists, tables, cards, KPI rows, +form fields, and page backgrounds; only visuals with no Word counterpart +(charts, icons, decorated boxes) are embedded as pictures. Nothing is printed +to PDF first and nothing is uploaded. + **Does GenOffice collect any data?** Official packaged builds send limited usage analytics by default, and you can disable reporting at any time under Settings → General. Analytics never sends @@ -230,6 +264,7 @@ GenOffice would not be possible without these open-source projects: document assembly. - [Tiptap](https://tiptap.dev/) / [ProseMirror](https://prosemirror.net/) — the block editors in Docs and Markdown. +- [CodeMirror](https://codemirror.net/) (MIT) — the source editor in HTML. - [Konva](https://konvajs.org/) — canvas rendering for Slides and Sheets charts. - [HarfBuzz](https://github.com/harfbuzz/harfbuzz) (wasm) — text-shaping diff --git a/apps/docs/package.json b/apps/docs/package.json index 6c247be..2407cee 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -45,7 +45,7 @@ "react-dom": "^19.2.4", "typescript": "^5.9.3", "vite": "^7.3.1", - "vitest": "^4.1.0" + "vitest": "^4.1.11" }, "author": "GenOffice", "build": { diff --git a/apps/docs/src/main/docs-main.ts b/apps/docs/src/main/docs-main.ts index 4a975e4..f2e77ed 100644 --- a/apps/docs/src/main/docs-main.ts +++ b/apps/docs/src/main/docs-main.ts @@ -32,6 +32,7 @@ import { installNavigationGuard, printHtmlToPdf, safeExternalUrl, + saveAsSuggestion, showOpenDialogWithMemory, showSaveDialogWithMemory, toggleDevToolsItem, @@ -56,7 +57,10 @@ import { chatForProvider, defaultAiSettings, activeProvider, - cloudToolsEnabled, + testMediaProvider, + type AiMediaProviderConfig, + type AiMediaProviderId, + type AiSearchProviderId, resolveAiSettings, maxOutputTokensOf, setAiUserAgent, @@ -73,11 +77,12 @@ import { listCodexModels, shutdownCodexAppServers } from '@genoffice/ai-provider import { ensureGenofficeLogin, gskApiKey, - gskGenerateImage, + generateImageTool, + testSearchProvider, gskLoginInfo, hasGskAuth, - webSearch, - imageSearch, + webSearchTool, + imageSearchTool, } from '@genoffice/ai-search' import type { AiDocContent, @@ -150,6 +155,7 @@ const tMain = createI18n({ filterSupported: '支持的文件', filterAll: '所有文件', dlgExportPdf: '导出为 PDF', + dlgExportHtml: '导出为 HTML', errUnsupportedExt: '暂不支持 .{ext} 类型', errNotFile: '不是文件', errTooLarge: '超过 {mb}MB 上限', @@ -174,6 +180,7 @@ const tMain = createI18n({ menuSaveAs: '另存为…', menuPageSetup: '页面设置…', menuExportPdf: '导出为 PDF…', + menuExportHtml: '导出为 HTML…', menuPrint: '打印…', menuEdit: '编辑', menuUndo: '撤销', @@ -244,6 +251,7 @@ const tMain = createI18n({ filterSupported: 'Supported Files', filterAll: 'All Files', dlgExportPdf: 'Export as PDF', + dlgExportHtml: 'Export as HTML', errUnsupportedExt: '.{ext} files are not supported', errNotFile: 'not a file', errTooLarge: 'exceeds the {mb}MB limit', @@ -269,6 +277,7 @@ const tMain = createI18n({ menuSaveAs: 'Save As…', menuPageSetup: 'Page Setup…', menuExportPdf: 'Export as PDF…', + menuExportHtml: 'Export as HTML…', menuPrint: 'Print…', menuEdit: 'Edit', menuUndo: 'Undo', @@ -338,6 +347,7 @@ const tMain = createI18n({ filterSupported: 'サポートされているファイル', filterAll: 'すべてのファイル', dlgExportPdf: 'PDF としてエクスポート', + dlgExportHtml: 'HTML としてエクスポート', errUnsupportedExt: '.{ext} 形式には対応していません', errNotFile: 'ファイルではありません', errTooLarge: '{mb}MB の上限を超えています', @@ -364,6 +374,7 @@ const tMain = createI18n({ menuSaveAs: '名前を付けて保存…', menuPageSetup: 'ページ設定…', menuExportPdf: 'PDF としてエクスポート…', + menuExportHtml: 'HTML としてエクスポート…', menuPrint: '印刷…', menuEdit: '編集', menuUndo: '元に戻す', @@ -434,6 +445,7 @@ const tMain = createI18n({ filterSupported: '지원되는 파일', filterAll: '모든 파일', dlgExportPdf: 'PDF로 내보내기', + dlgExportHtml: 'HTML로 내보내기', errUnsupportedExt: '.{ext} 형식은 지원되지 않습니다', errNotFile: '파일이 아닙니다', errTooLarge: '{mb}MB 제한을 초과했습니다', @@ -460,6 +472,7 @@ const tMain = createI18n({ menuSaveAs: '다른 이름으로 저장…', menuPageSetup: '페이지 설정…', menuExportPdf: 'PDF로 내보내기…', + menuExportHtml: 'HTML로 내보내기…', menuPrint: '인쇄…', menuEdit: '편집', menuUndo: '실행 취소', @@ -531,6 +544,7 @@ const tMain = createI18n({ filterSupported: 'Fichiers pris en charge', filterAll: 'Tous les fichiers', dlgExportPdf: 'Exporter au format PDF', + dlgExportHtml: 'Exporter au format HTML', errUnsupportedExt: 'les fichiers .{ext} ne sont pas pris en charge', errNotFile: "n'est pas un fichier", errTooLarge: 'dépasse la limite de {mb} Mo', @@ -557,6 +571,7 @@ const tMain = createI18n({ menuSaveAs: 'Enregistrer sous…', menuPageSetup: 'Mise en page…', menuExportPdf: 'Exporter au format PDF…', + menuExportHtml: 'Exporter au format HTML…', menuPrint: 'Imprimer…', menuEdit: 'Édition', menuUndo: 'Annuler', @@ -628,6 +643,7 @@ const tMain = createI18n({ filterSupported: 'Unterstützte Dateien', filterAll: 'Alle Dateien', dlgExportPdf: 'Als PDF exportieren', + dlgExportHtml: 'Als HTML exportieren', errUnsupportedExt: '.{ext}-Dateien werden nicht unterstützt', errNotFile: 'keine Datei', errTooLarge: 'überschreitet das Limit von {mb} MB', @@ -654,6 +670,7 @@ const tMain = createI18n({ menuSaveAs: 'Speichern unter…', menuPageSetup: 'Seite einrichten…', menuExportPdf: 'Als PDF exportieren…', + menuExportHtml: 'Als HTML exportieren…', menuPrint: 'Drucken…', menuEdit: 'Bearbeiten', menuUndo: 'Rückgängig', @@ -724,6 +741,7 @@ const tMain = createI18n({ filterSupported: 'Archivos compatibles', filterAll: 'Todos los archivos', dlgExportPdf: 'Exportar como PDF', + dlgExportHtml: 'Exportar como HTML', errUnsupportedExt: 'los archivos .{ext} no son compatibles', errNotFile: 'no es un archivo', errTooLarge: 'supera el límite de {mb} MB', @@ -751,6 +769,7 @@ const tMain = createI18n({ menuSaveAs: 'Guardar como…', menuPageSetup: 'Configurar página…', menuExportPdf: 'Exportar como PDF…', + menuExportHtml: 'Exportar como HTML…', menuPrint: 'Imprimir…', menuEdit: 'Edición', menuUndo: 'Deshacer', @@ -820,6 +839,7 @@ const tMain = createI18n({ filterSupported: 'ไฟล์ที่รองรับ', filterAll: 'ไฟล์ทั้งหมด', dlgExportPdf: 'ส่งออกเป็น PDF', + dlgExportHtml: 'ส่งออกเป็น HTML', errUnsupportedExt: 'ไม่รองรับไฟล์ .{ext}', errNotFile: 'ไม่ใช่ไฟล์', errTooLarge: 'เกินขีดจำกัด {mb}MB', @@ -846,6 +866,7 @@ const tMain = createI18n({ menuSaveAs: 'บันทึกเป็น…', menuPageSetup: 'ตั้งค่าหน้ากระดาษ…', menuExportPdf: 'ส่งออกเป็น PDF…', + menuExportHtml: 'ส่งออกเป็น HTML…', menuPrint: 'พิมพ์…', menuEdit: 'แก้ไข', menuUndo: 'เลิกทำ', @@ -916,6 +937,7 @@ const tMain = createI18n({ filterSupported: 'File yang Didukung', filterAll: 'Semua File', dlgExportPdf: 'Ekspor sebagai PDF', + dlgExportHtml: 'Ekspor sebagai HTML', errUnsupportedExt: 'file .{ext} tidak didukung', errNotFile: 'bukan file', errTooLarge: 'melebihi batas {mb}MB', @@ -941,6 +963,7 @@ const tMain = createI18n({ menuSaveAs: 'Simpan Sebagai…', menuPageSetup: 'Penyetelan Halaman…', menuExportPdf: 'Ekspor sebagai PDF…', + menuExportHtml: 'Ekspor sebagai HTML…', menuPrint: 'Cetak…', menuEdit: 'Edit', menuUndo: 'Urungkan', @@ -1011,6 +1034,7 @@ const tMain = createI18n({ filterSupported: 'Поддерживаемые файлы', filterAll: 'Все файлы', dlgExportPdf: 'Экспорт в PDF', + dlgExportHtml: 'Экспорт в HTML', errUnsupportedExt: 'файлы .{ext} не поддерживаются', errNotFile: 'не является файлом', errTooLarge: 'превышает лимит {mb} МБ', @@ -1037,6 +1061,7 @@ const tMain = createI18n({ menuSaveAs: 'Сохранить как…', menuPageSetup: 'Параметры страницы…', menuExportPdf: 'Экспорт в PDF…', + menuExportHtml: 'Экспорт в HTML…', menuPrint: 'Печать…', menuEdit: 'Правка', menuUndo: 'Отменить', @@ -1107,6 +1132,7 @@ const tMain = createI18n({ filterSupported: 'الملفات المدعومة', filterAll: 'كل الملفات', dlgExportPdf: 'تصدير بتنسيق PDF', + dlgExportHtml: 'تصدير بتنسيق HTML', errUnsupportedExt: 'ملفات .{ext} غير مدعومة', errNotFile: 'ليس ملفًا', errTooLarge: 'يتجاوز الحد {mb}MB', @@ -1133,6 +1159,7 @@ const tMain = createI18n({ menuSaveAs: 'حفظ باسم…', menuPageSetup: 'إعداد الصفحة…', menuExportPdf: 'تصدير بتنسيق PDF…', + menuExportHtml: 'تصدير بتنسيق HTML…', menuPrint: 'طباعة…', menuEdit: 'تحرير', menuUndo: 'تراجع', @@ -1203,6 +1230,7 @@ const tMain = createI18n({ filterSupported: 'Arquivos Compatíveis', filterAll: 'Todos os Arquivos', dlgExportPdf: 'Exportar como PDF', + dlgExportHtml: 'Exportar como HTML', errUnsupportedExt: 'arquivos .{ext} não são suportados', errNotFile: 'não é um arquivo', errTooLarge: 'excede o limite de {mb}MB', @@ -1229,6 +1257,7 @@ const tMain = createI18n({ menuSaveAs: 'Salvar Como…', menuPageSetup: 'Configurar Página…', menuExportPdf: 'Exportar como PDF…', + menuExportHtml: 'Exportar como HTML…', menuPrint: 'Imprimir…', menuEdit: 'Editar', menuUndo: 'Desfazer', @@ -1299,6 +1328,7 @@ const tMain = createI18n({ filterSupported: 'File supportati', filterAll: 'Tutti i file', dlgExportPdf: 'Esporta come PDF', + dlgExportHtml: 'Esporta come HTML', errUnsupportedExt: 'i file .{ext} non sono supportati', errNotFile: 'non è un file', errTooLarge: 'supera il limite di {mb} MB', @@ -1325,6 +1355,7 @@ const tMain = createI18n({ menuSaveAs: 'Salva con nome…', menuPageSetup: 'Imposta pagina…', menuExportPdf: 'Esporta come PDF…', + menuExportHtml: 'Esporta come HTML…', menuPrint: 'Stampa…', menuEdit: 'Modifica', menuUndo: 'Annulla', @@ -1395,6 +1426,7 @@ const tMain = createI18n({ filterSupported: 'Obsługiwane pliki', filterAll: 'Wszystkie pliki', dlgExportPdf: 'Eksportuj jako PDF', + dlgExportHtml: 'Eksportuj jako HTML', errUnsupportedExt: 'pliki .{ext} nie są obsługiwane', errNotFile: 'to nie jest plik', errTooLarge: 'przekracza limit {mb} MB', @@ -1421,6 +1453,7 @@ const tMain = createI18n({ menuSaveAs: 'Zapisz jako…', menuPageSetup: 'Ustawienia strony…', menuExportPdf: 'Eksportuj jako PDF…', + menuExportHtml: 'Eksportuj jako HTML…', menuPrint: 'Drukuj…', menuEdit: 'Edycja', menuUndo: 'Cofnij', @@ -1466,6 +1499,104 @@ const tMain = createI18n({ menuShortcuts: 'Skróty klawiaturowe', menuDocsHelp: 'Pomoc GenOffice Docs', }, + cs: { + dlgOpenDoc: 'Otevřít dokument', + filterWord: 'Dokumenty Wordu', + dlgSaveAs: 'Uložit jako', + closeUnsavedMsg: 'Tento dokument obsahuje neuložené změny.', + closeUnsavedDetail: 'Chcete je před zavřením uložit?', + closeNoReplyMsg: 'Dokument neodpovídá a může obsahovat neuložené změny.', + closeNoReplyDetail: 'Přesto zavřít? Neuložené změny budou ztraceny.', + btnCloseAnyway: 'Přesto zavřít', + autosaveFoundTitle: 'Nalezena obnovená verze', + autosaveFoundBody: + 'Z poslední relace existují neuložené změny. Obnovit automaticky uloženou verzi?', + autosaveRestore: 'Obnovit', + autosaveDiscard: 'Zahodit', + btnDontSave: 'Neukládat', + btnCancel: 'Zrušit', + extModifiedMsg: 'Soubor byl změněn jiným programem.', + extModifiedDetail: 'Přesto uložit a přepsat změny na disku?', + btnOverwrite: 'Přepsat', + dlgInsertImage: 'Vložit obrázek', + filterImages: 'Obrázky', + dlgAddAttachment: 'Přidat přílohy', + filterSupported: 'Podporované soubory', + filterAll: 'Všechny soubory', + dlgExportPdf: 'Exportovat jako PDF', + dlgExportHtml: 'Exportovat jako HTML', + errUnsupportedExt: 'soubory .{ext} nejsou podporovány', + errNotFile: 'není soubor', + errTooLarge: 'překračuje limit {mb} MB', + errImageTooLarge: 'obrázek překračuje limit 5 MB', + errUnreadable: 'nelze přečíst', + errFileTooLarge: 'Soubor překračuje limit velikosti', + errParseFailed: 'Soubor se nepodařilo zpracovat', + errImageNoText: + 'Obrázkové přílohy neobsahují text; obrázek se odesílá spolu se zprávou uživatele', + errNotImage: 'nepodporovaný typ obrázku', + errGskNotLoggedIn: + 'Nejste přihlášeni do Genspark: klikněte níže na „Přihlásit se do Genspark“, přihlaste se a zkuste to znovu', + errNoApiKey: 'Pro {provider} není nakonfigurován žádný klíč API', + errAiBusy: 'Služba AI je právě zaneprázdněna — zkuste to prosím za chvíli znovu', + errNoModel: 'Není nakonfigurován název modelu', + menuFile: 'Soubor', + menuNewDoc: 'Nový dokument', + menuNewWindow: 'Nové okno', + menuOpen: 'Otevřít…', + menuOpenRecent: 'Otevřít poslední', + menuNoRecent: 'Žádné poslední dokumenty', + menuClose: 'Zavřít', + menuSave: 'Uložit', + menuSaveAs: 'Uložit jako…', + menuPageSetup: 'Vzhled stránky…', + menuExportPdf: 'Exportovat jako PDF…', + menuExportHtml: 'Exportovat jako HTML…', + menuPrint: 'Tisk…', + menuEdit: 'Úpravy', + menuUndo: 'Zpět', + menuRedo: 'Znovu', + menuCut: 'Vyjmout', + menuCopy: 'Kopírovat', + menuPaste: 'Vložit', + menuPasteMatch: 'Vložit a přizpůsobit styl', + menuFindReplace: 'Najít a nahradit…', + menuSelectAll: 'Vybrat vše', + menuView: 'Zobrazení', + menuZoomIn: 'Zvětšit', + menuZoomOut: 'Zmenšit', + menuZoom100: 'Skutečná velikost (100 %)', + menuPageWidth: 'Šířka stránky', + menuWholePage: 'Celá stránka', + menuAiSidebar: 'Boční panel AI', + menuDarkMode: 'Tmavý režim', + menuFullscreen: 'Přejít na celou obrazovku', + menuInsert: 'Vložení', + menuInsertTable: 'Tabulka (3×3)', + menuInsertImage: 'Obrázek…', + menuInsertPageBreak: 'Konec stránky', + menuInsertLink: 'Hypertextový odkaz…', + menuInsertEquation: 'Rovnice…', + menuComment: 'Komentář', + menuFormat: 'Formát', + menuBold: 'Tučné', + menuItalic: 'Kurzíva', + menuUnderline: 'Podtržení', + menuAlign: 'Zarovnat', + menuAlignLeft: 'Zarovnat vlevo', + menuAlignCenter: 'Zarovnat na střed', + menuAlignRight: 'Zarovnat vpravo', + menuAlignJustify: 'Zarovnat do bloku', + menuFont: 'Písmo…', + menuParagraph: 'Odstavec…', + menuTools: 'Nástroje', + menuWordCount: 'Počet slov…', + menuAiProofread: 'Korektura AI', + menuWindow: 'Okno', + menuHelp: 'Nápověda', + menuShortcuts: 'Klávesové zkratky', + menuDocsHelp: 'Nápověda GenOffice Docs', + }, nl: { dlgOpenDoc: 'Document openen', filterWord: 'Word-documenten', @@ -1491,6 +1622,7 @@ const tMain = createI18n({ filterSupported: 'Ondersteunde bestanden', filterAll: 'Alle bestanden', dlgExportPdf: 'Exporteren als PDF', + dlgExportHtml: 'Exporteren als HTML', errUnsupportedExt: '.{ext}-bestanden worden niet ondersteund', errNotFile: 'geen bestand', errTooLarge: 'overschrijdt de limiet van {mb} MB', @@ -1517,6 +1649,7 @@ const tMain = createI18n({ menuSaveAs: 'Opslaan als…', menuPageSetup: 'Pagina-instelling…', menuExportPdf: 'Exporteren als PDF…', + menuExportHtml: 'Exporteren als HTML…', menuPrint: 'Afdrukken…', menuEdit: 'Bewerken', menuUndo: 'Ongedaan maken', @@ -1587,6 +1720,7 @@ const tMain = createI18n({ filterSupported: 'Fail yang Disokong', filterAll: 'Semua Fail', dlgExportPdf: 'Eksport sebagai PDF', + dlgExportHtml: 'Eksport sebagai HTML', errUnsupportedExt: 'fail .{ext} tidak disokong', errNotFile: 'bukan fail', errTooLarge: 'melebihi had {mb}MB', @@ -1613,6 +1747,7 @@ const tMain = createI18n({ menuSaveAs: 'Simpan Sebagai…', menuPageSetup: 'Persediaan Halaman…', menuExportPdf: 'Eksport sebagai PDF…', + menuExportHtml: 'Eksport sebagai HTML…', menuPrint: 'Cetak…', menuEdit: 'Edit', menuUndo: 'Buat Asal', @@ -1682,6 +1817,7 @@ const tMain = createI18n({ filterSupported: 'קבצים נתמכים', filterAll: 'כל הקבצים', dlgExportPdf: 'ייצוא כ-PDF', + dlgExportHtml: 'ייצוא כ-HTML', errUnsupportedExt: 'קובצי .{ext} אינם נתמכים', errNotFile: 'אינו קובץ', errTooLarge: 'חורג מהמגבלה של {mb}MB', @@ -1707,6 +1843,7 @@ const tMain = createI18n({ menuSaveAs: 'שמירה בשם…', menuPageSetup: 'הגדרת עמוד…', menuExportPdf: 'ייצוא כ-PDF…', + menuExportHtml: 'ייצוא כ-HTML…', menuPrint: 'הדפסה…', menuEdit: 'עריכה', menuUndo: 'בטל', @@ -1777,6 +1914,7 @@ const tMain = createI18n({ filterSupported: 'समर्थित फ़ाइलें', filterAll: 'सभी फ़ाइलें', dlgExportPdf: 'PDF के रूप में निर्यात करें', + dlgExportHtml: 'HTML के रूप में निर्यात करें', errUnsupportedExt: '.{ext} फ़ाइलें समर्थित नहीं हैं', errNotFile: 'फ़ाइल नहीं है', errTooLarge: '{mb}MB की सीमा से अधिक है', @@ -1803,6 +1941,7 @@ const tMain = createI18n({ menuSaveAs: 'इस रूप में सहेजें…', menuPageSetup: 'पृष्ठ सेटअप…', menuExportPdf: 'PDF के रूप में निर्यात करें…', + menuExportHtml: 'HTML के रूप में निर्यात करें…', menuPrint: 'प्रिंट करें…', menuEdit: 'संपादन', menuUndo: 'पूर्ववत करें', @@ -1872,6 +2011,7 @@ const tMain = createI18n({ filterSupported: '支援的檔案', filterAll: '所有檔案', dlgExportPdf: '匯出為 PDF', + dlgExportHtml: '匯出為 HTML', errUnsupportedExt: '暫不支援 .{ext} 類型', errNotFile: '不是檔案', errTooLarge: '超過 {mb}MB 上限', @@ -1896,6 +2036,7 @@ const tMain = createI18n({ menuSaveAs: '另存新檔…', menuPageSetup: '版面設定…', menuExportPdf: '匯出為 PDF…', + menuExportHtml: '匯出為 HTML…', menuPrint: '列印…', menuEdit: '編輯', menuUndo: '復原', @@ -2612,11 +2753,6 @@ const TWIPS_PER_INCH = 1440 const SETTINGS_PATH = () => userDataPath('ai-settings.json') -/** live read: the shell settings pane writes the file; every tool call re-checks */ -function gskCloudToolsOn(): boolean { - return cloudToolsEnabled(readJson>(SETTINGS_PATH(), {})) -} - const activeAiStreams = new Map() /** @@ -2746,10 +2882,10 @@ export function registerAiIpc(): void { // shared search tools (content + images): Serper with DuckDuckGo fallback (same source as slides/sheets) ipcMain.handle('ai:web-search', async (_event, query: string, maxResults?: number) => { try { - return await webSearch( + return await webSearchTool( + SETTINGS_PATH(), String(query), typeof maxResults === 'number' ? maxResults : 6, - gskCloudToolsOn(), ) } catch (err) { return { results: [], method: 'error', error: String(err) } @@ -2757,10 +2893,10 @@ export function registerAiIpc(): void { }) ipcMain.handle('ai:image-search', async (_event, query: string, maxResults?: number) => { try { - return await imageSearch( + return await imageSearchTool( + SETTINGS_PATH(), String(query), typeof maxResults === 'number' ? maxResults : 8, - gskCloudToolsOn(), ) } catch (err) { return { images: [], method: 'error', error: String(err) } @@ -2796,30 +2932,34 @@ export function registerAiIpc(): void { // registered once a slides view exists, so docs needs its own channel ipcMain.handle( 'docs:ai-generate-image', - async (_event, op: { prompt?: unknown; aspectRatio?: unknown }) => { - if (!hasGskAuth()) - return { - error: 'Genspark account is not logged in on this machine; ask the user to log in first', - } - if (!gskCloudToolsOn()) - return { - error: - 'Genspark cloud tools are turned off in Settings (AI Model); enable them to use this tool', - } - const prompt = String(op?.prompt ?? '').trim() - if (!prompt) return { error: 'prompt must not be empty' } - try { - const r = await gskGenerateImage({ - prompt, - aspectRatio: op?.aspectRatio ? String(op.aspectRatio) : undefined, - }) - return { url: r.url } - } catch (err) { - return { error: err instanceof Error ? err.message : String(err) } - } - }, + (_event, op: { prompt?: unknown; aspectRatio?: unknown }) => + generateImageTool(SETTINGS_PATH(), { + prompt: String(op?.prompt ?? ''), + aspectRatio: op?.aspectRatio ? String(op.aspectRatio) : undefined, + }), ) + ipcMain.handle('ai:search-test', (_event, input: unknown) => { + const { provider, apiKey } = (input ?? {}) as { provider?: AiSearchProviderId; apiKey?: string } + if (!provider || provider === 'genspark') { + return hasGskAuth() ? { ok: true } : { ok: false, error: tm('errGskNotLoggedIn') } + } + return testSearchProvider(provider, String(apiKey ?? '')) + }) + + // settings-UI connection test for the media provider (genspark = the gsk login state) + ipcMain.handle('ai:media-test', (_event, input: unknown) => { + const { provider, config } = (input ?? {}) as { + provider?: AiMediaProviderId + config?: AiMediaProviderConfig + } + if (!provider || provider === 'genspark') { + return hasGskAuth() ? { ok: true } : { ok: false, error: tm('errGskNotLoggedIn') } + } + if (!config) return { ok: false, error: 'No media provider configuration' } + return testMediaProvider(provider, config) + }) + ipcMain.handle('ai:chat', async (_event, request: AiChatRequest) => { const { settings, system, user } = request const provider = settings.provider @@ -2954,6 +3094,7 @@ export function registerProjectIpc(): void { output?: string }> attachments?: Array<{ name: string; path?: string; ext?: string; sizeBytes?: number }> + scope?: { label: string; text?: string } }, ) => { const store = getProjectStore() @@ -2963,6 +3104,8 @@ export function registerProjectIpc(): void { } if (args.tools) msg.tools = args.tools if (args.attachments) msg.attachments = args.attachments + if (args.scope) msg.scope = args.scope + store.appendChatMessage(args.projectId, args.chatId, msg) }, ) @@ -3267,6 +3410,25 @@ export function registerDocsIpc(): void { } }) + // Blink only respells an editable as a consequence of real (trusted) typing + // of a word-committing character inside it: attribute flips, focus cycles, + // script selection moves, execCommand edits, fresh DOM nodes, synthetic + // clicks/arrow keys — and even a typed zero-width space — all leave existing + // typos unmarked (each verified pixel-by-pixel). + // Type one trusted space; the RENDERER removes it again by script (a + // trusted Backspace would work too, but its deletion re-suppresses the + // caret paragraph and that line stays unmarked) with ProseMirror's DOM + // observer paused, so the round trip never becomes a transaction. + ipcMain.handle('docs:respell-kick', async (event) => { + const wc = event.sender + if (tornDownWcIds.has(wc.id) || wc.isDestroyed()) return + wc.focus() + wc.sendInputEvent({ type: 'char', keyCode: ' ' }) + // resolve only after the input pipeline has delivered the keystroke, so + // the caller can scrub the space it produced + await new Promise((r) => setTimeout(r, 120)) + }) + ipcMain.handle( 'docs:save-as', async (event, defaultName: string, data: ArrayBuffer, sourcePath?: string | null) => { @@ -3274,7 +3436,10 @@ export function registerDocsIpc(): void { if (tornDownWcIds.has(event.sender.id)) return { ok: false } const result = await saveDialog(event, { title: tm('dlgSaveAs'), - defaultPath: defaultName, + defaultPath: saveAsSuggestion( + typeof sourcePath === 'string' ? sourcePath : null, + defaultName, + ), filters: [{ name: tm('filterWord'), extensions: ['docx'] }], }) if (result.canceled || !result.filePath) return { ok: false } @@ -3548,6 +3713,34 @@ export function registerDocsIpc(): void { }, ) + ipcMain.handle( + 'docs:export-html', + async (event, defaultName: string, html: string, outPath?: string) => { + if (typeof html !== 'string' || !html) return { ok: false, error: 'empty document' } + let filePath = outPath ?? null + if (filePath && !canPdfWrite(event.sender.id, filePath)) { + return { ok: false, error: 'export target is not an authorized path' } + } + if (!filePath) { + const result = await saveDialog(event, { + title: tm('dlgExportHtml'), + defaultPath: defaultName.replace(/\.docx$/i, '') + '.html', + filters: [{ name: 'HTML', extensions: ['html'] }], + }) + if (result.canceled || !result.filePath) return { ok: false } + filePath = result.filePath + allowPdfWrite(event.sender.id, filePath) + } + try { + writeFileSync(filePath, html, 'utf8') + openGeneratedFile(filePath) + return { ok: true, path: filePath } + } catch (err) { + return { ok: false, error: String(err), path: filePath } + } + }, + ) + // mixed paper-size export: the renderer prints group by group per size (other pages hidden via CSS); this produces one group's bytes ipcMain.handle( 'docs:print-pdf-buffer', @@ -3714,8 +3907,8 @@ export async function createAiDocument( openGeneratedFile(filePath) return { ok: true, path: filePath } } - if (type === 'md') { - const filePath = uniquePathIn(defaultSaveDir(), `${title}.md`) + if (type === 'md' || type === 'html') { + const filePath = uniquePathIn(defaultSaveDir(), `${title}.${type}`) await writeFile(filePath, content, 'utf8') openGeneratedFile(filePath) return { ok: true, path: filePath } @@ -3840,6 +4033,7 @@ export function buildDocsMenu(): void { { type: 'separator' }, { label: tm('menuPageSetup'), click: () => sendCommand('page-setup') }, { label: tm('menuExportPdf'), click: () => sendCommand('export-pdf') }, + { label: tm('menuExportHtml'), click: () => sendCommand('export-html') }, { label: tm('menuPrint'), accelerator: 'CmdOrCtrl+P', diff --git a/apps/docs/src/main/updater.ts b/apps/docs/src/main/updater.ts index 568af71..1f53dd0 100644 --- a/apps/docs/src/main/updater.ts +++ b/apps/docs/src/main/updater.ts @@ -130,6 +130,14 @@ const tUpd = createI18n({ updInstall: 'Uruchom ponownie i zainstaluj', updLater: 'Przypomnij później', }, + cs: { + updTitle: 'Aktualizace softwaru', + updHeadline: 'Je k dispozici nová verze', + updDesc: + 'Tato aktualizace obsahuje vylepšení výkonu a opravy chyb. Doporučujeme aktualizovat nyní.', + updInstall: 'Restartovat a nainstalovat', + updLater: 'Připomenout později', + }, nl: { updTitle: 'Software-update', updHeadline: 'Er is een nieuwe versie beschikbaar', diff --git a/apps/docs/src/preload/index.ts b/apps/docs/src/preload/index.ts index 86bf9ce..c8bf74c 100644 --- a/apps/docs/src/preload/index.ts +++ b/apps/docs/src/preload/index.ts @@ -1,5 +1,6 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron' import type { IpcRendererEvent } from 'electron' +import type { AiPanelPrefs } from '@genoffice/ui' import type { AiChatRequest, AiSettings, @@ -7,6 +8,7 @@ import type { AiStreamRequest, DesktopApi, MenuCommand, + AutoSaveDefault, UiTheme, } from '../shared/ipc' import type { ProjectApi } from '@genoffice/project-store' @@ -28,6 +30,18 @@ const api: DesktopApi = { ipcRenderer.on('app:theme-changed', listener) return () => ipcRenderer.removeListener('app:theme-changed', listener) }, + getAutoSaveDefault: () => ipcRenderer.invoke('app:get-auto-save-default'), + onAutoSaveDefaultChanged: (handler) => { + const listener = (_event: IpcRendererEvent, value: AutoSaveDefault) => handler(value) + ipcRenderer.on('app:auto-save-default-changed', listener) + return () => ipcRenderer.removeListener('app:auto-save-default-changed', listener) + }, + getAiPanelPrefs: () => ipcRenderer.invoke('app:get-ai-panel-prefs'), + onAiPanelPrefsChanged: (handler) => { + const listener = (_event: IpcRendererEvent, prefs: AiPanelPrefs) => handler(prefs) + ipcRenderer.on('app:ai-panel-prefs-changed', listener) + return () => ipcRenderer.removeListener('app:ai-panel-prefs-changed', listener) + }, onChromePressed: (handler) => { const listener = () => handler() ipcRenderer.on('app:chrome-pressed', listener) @@ -72,6 +86,7 @@ const api: DesktopApi = { ipcRenderer.on('docs:teardown', listener) return () => ipcRenderer.removeListener('docs:teardown', listener) }, + respellKick: () => ipcRenderer.invoke('docs:respell-kick'), saveDocxAs: (defaultName: string, data: ArrayBuffer, sourcePath?: string | null) => ipcRenderer.invoke('docs:save-as', defaultName, data, sourcePath ?? null), saveDocxNew: (defaultName: string, data: ArrayBuffer) => @@ -95,6 +110,8 @@ const api: DesktopApi = { outPath, scale, ), + exportHtml: (defaultName: string, html: string, outPath?: string) => + ipcRenderer.invoke('docs:export-html', defaultName, html, outPath), printPdfBuffer: (pageWidthTwips: number, pageHeightTwips: number, scale?: number) => ipcRenderer.invoke('docs:print-pdf-buffer', pageWidthTwips, pageHeightTwips, scale), saveMergedPdf: (defaultName: string, base64Parts: string[], outPath?: string) => diff --git a/apps/docs/src/renderer/App.tsx b/apps/docs/src/renderer/App.tsx index f215f9d..4bbdb16 100644 --- a/apps/docs/src/renderer/App.tsx +++ b/apps/docs/src/renderer/App.tsx @@ -13,9 +13,10 @@ 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 { Dropdown } from '@genoffice/ui' +import { Dropdown, useAutoSavePref } from '@genoffice/ui' +import { wordRangeAtCaret } from './editor/comments' import { markdownPasteHtml } from './editor/markdown-paste' -import { pasteTextSlice } from './editor/paste-text' +import { pasteTextSlice, singleCellPasteText } from './editor/paste-text' import { BLANK_BULLET_NUM_ID, BLANK_ORDERED_NUM_ID, @@ -219,6 +220,7 @@ import { import { applyAiDocContent as applyAiDocContentImpl, exportPdf as exportPdfImpl, + exportHtml as exportHtmlImpl, loadFile as loadFileImpl, newFile as newFileImpl, printDoc as printDocImpl, @@ -241,6 +243,7 @@ import { compareWithFile as compareWithFileImpl, deleteComment as deleteCommentImpl, deleteNote as deleteNoteImpl, + editComment as editCommentImpl, handleRevision as handleRevisionImpl, removeInks as removeInksImpl, replyToComment as replyToCommentImpl, @@ -780,7 +783,7 @@ export function App() { otherName: string entries: CompareEntry[] } | null>(null) - const [autoSave, setAutoSave] = useState(() => localStorage.getItem('aidocs.autoSave') === '1') + const [autoSave, setAutoSave] = useAutoSavePref('aidocs.autoSave', window.desktop) // tab closed but this renderer kept alive (shell freeze workaround): go inert const [tornDown, setTornDown] = useState(false) const [aiPreset, setAiPreset] = useState<{ @@ -853,6 +856,18 @@ export function App() { const data = event.clipboardData if (!data) return false const html = data.getData('text/html') + // 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 + // land it in the theme font (r176: Sheets cell → Docs pasted as Aptos) + if (html) { + const cellText = singleCellPasteText(html) + if (cellText !== null) { + const slice = pasteTextSlice(cellText, view.state.selection.$from, view) + view.dispatch(view.state.tr.replaceSelection(slice).scrollIntoView()) + return true + } + } // web-copied images (r139): "Copy image" in a browser puts a bitmap + // an HTML fragment + often the URL as text/plain // on the clipboard. Detect image-only HTML so the bitmap wins over @@ -1009,10 +1024,8 @@ export function App() { localStorage.setItem('aidocs.showAi', showAi ? '1' : '0') }, [showAi]) - useEffect(() => { - localStorage.setItem('aidocs.autoSave', autoSave ? '1' : '0') - }, [autoSave]) - + const spellcheckWasOn = useRef(spellcheck) + const respellKickBusy = useRef(false) useEffect(() => { localStorage.setItem(SPELLCHECK_KEY, spellcheck ? '1' : '0') // setOptions (not a direct DOM write): ProseMirror re-applies editorProps @@ -1026,51 +1039,160 @@ 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 + // 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 — + // even a typed zero-width space — existing typos stay unmarked. So on the + // re-enable transition, have the main process type one trusted space at + // the caret and remove it again by script (a trusted Backspace would work + // too, but its deletion re-suppresses the caret paragraph's markers). + // ProseMirror must not see any of it: its DOM observer is paused (no + // transaction, no history entry, no dirty flag) and a capture-phase key + // shield keeps its keymap and other key handlers out of the round trip — + // the same shield also tells us when the keystroke has actually landed. + if (spellcheck && !spellcheckWasOn.current) { + requestAnimationFrame(() => { + const view = editor.view + const dom = view.dom + if (!dom.isConnected || view.composing || respellKickBusy.current) return + respellKickBusy.current = true + const sub = getActiveSubEditor() + const prev = document.activeElement as HTMLElement | null + 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; + // view.focus() below restores the real selection from PM state after + if (sel && !sel.isCollapsed) sel.collapseToEnd() + // the kick inserts exactly one space at the caret; snapshot the caret + // text node so the scrub can restore it byte-identically + const caretNode = sel?.anchorNode + const caretText = caretNode instanceof Text ? caretNode : null + const caretData = caretText?.data ?? null + let sawKick = false + const shield = (e: KeyboardEvent) => { + if (e.key === ' ') sawKick = true + e.stopPropagation() + } + document.addEventListener('keydown', shield, true) + document.addEventListener('keypress', shield, true) + const observer = ( + view as unknown as { domObserver: { stop: () => void; start: () => void } } + ).domObserver + observer.stop() + const scrub = () => { + // caret in a text node: remove exactly the one inserted character. + // deleteData keeps the node's other spell markers alive — a whole + // `data` reassignment would wipe the paragraph's fresh squiggles. + if (caretText && caretData !== null && caretText.data !== caretData) { + const now = caretText.data + if (now.length === caretData.length + 1) { + let i = 0 + while (i < caretData.length && now[i] === caretData[i]) i++ + caretText.deleteData(i, 1) + } + if (caretText.data !== caretData) caretText.data = caretData + return + } + // the space landed elsewhere: Blink canonicalizes the insertion point + // (end of a link, mark boundary, empty paragraph) into a sibling or + // fresh text node — the caret it left sits right after the space + if (!sawKick) return + const after = window.getSelection() + const node = after?.anchorNode + if (!(node instanceof Text) || !after || after.anchorOffset === 0) return + if (node === caretText) return + const ch = node.data[after.anchorOffset - 1] + if (ch === ' ' || ch === '\u00a0') node.deleteData(after.anchorOffset - 1, 1) + } + void window.desktop + .respellKick() + .catch(() => undefined) + .then(async () => { + // the IPC can resolve before the input pipeline delivers the + // keystroke — wait for the shield to see it (or give up quietly: + // a kick that never landed left nothing to scrub) + const deadline = Date.now() + 800 + while (!sawKick && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 30)) + } + scrub() + observer.start() + document.removeEventListener('keydown', shield, true) + document.removeEventListener('keypress', shield, true) + respellKickBusy.current = false + 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 }) + }) + }) + } + spellcheckWasOn.current = spellcheck }, [editor, spellcheck]) // Pinch-to-zoom: Chromium delivers trackpad pinch as a wheel event // with ctrlKey set. Also support ⌘+scroll. Must be non-passive to preventDefault. - // The cursor-anchored zoom center is stashed for the zoom effect below so a - // Ctrl+wheel zoom keeps the content under the cursor in place (issue #238). - const zoomCenterRef = useRef<{ x: number; y: number } | null>(null) + // The viewport point under the cursor is stashed for the zoom layout effect + // below so the content there stays put (public #238); set only when the zoom + // actually changes, else a clamped tick would leave a stale anchor behind. + const zoomAnchorRef = useRef<{ vx: number; vy: number } | null>(null) useEffect(() => { const onWheel = (e: WheelEvent) => { if (!e.ctrlKey && !e.metaKey) return if (!(e.target as HTMLElement | null)?.closest?.('.editor-scroll')) return e.preventDefault() - const container = scrollContainerRef.current - if (container) { - const rect = container.getBoundingClientRect() - zoomCenterRef.current = { - x: e.clientX - rect.left + container.scrollLeft, - y: e.clientY - rect.top + container.scrollTop, - } - } - setZoom((z) => Math.min(200, Math.max(50, z - e.deltaY * 0.6))) + const rect = scrollContainerRef.current?.getBoundingClientRect() + const anchor = rect ? { vx: e.clientX - rect.left, vy: e.clientY - rect.top } : null + setZoom((z) => { + const next = Math.min(200, Math.max(50, z - e.deltaY * 0.6)) + if (next !== z) zoomAnchorRef.current = anchor + return next + }) } window.addEventListener('wheel', onWheel, { passive: false }) return () => window.removeEventListener('wheel', onWheel) }, []) - // Preserve scroll position when zoom changes (issue #238): rescale the - // scroll offsets around the zoom anchor (cursor for wheel zoom, viewport - // center for slider/menu/ribbon zoom) so the visible page stays in view. + // Keep the document point under the anchor (cursor for wheel zoom, viewport + // center otherwise) fixed across a zoom change. Runs after the zoomed layout + // is committed, so the page box is read post-zoom and the pre-zoom box is + // derived from it: CSS zoom scales the box linearly, the top edge is a fixed + // scroller padding, and `.doc-zoom` is margin-auto centered until it overflows. + // The pre-zoom scroll offsets come from the last scroll event: a zoom-out can + // shrink the overflow and clamp them before this effect gets to read them. + const scrollPosRef = useRef({ left: 0, top: 0 }) const prevZoomRef = useRef(zoom) - useEffect(() => { - const container = scrollContainerRef.current - if (!container) return + useLayoutEffect(() => { const prevZoom = prevZoomRef.current - if (prevZoom === zoom) return prevZoomRef.current = zoom + const anchor = zoomAnchorRef.current + zoomAnchorRef.current = null + const container = scrollContainerRef.current + const page = container?.querySelector('.doc-zoom') + if (!container || !page || prevZoom === zoom) return const ratio = zoom / prevZoom - const anchor = zoomCenterRef.current - const centerX = anchor ? anchor.x : container.scrollLeft + container.clientWidth / 2 - const centerY = anchor ? anchor.y : container.scrollTop + container.clientHeight / 2 - zoomCenterRef.current = null + const vx = anchor ? anchor.vx : container.clientWidth / 2 + const vy = anchor ? anchor.vy : container.clientHeight / 2 + const cs = getComputedStyle(container) + const padLeft = parseFloat(cs.paddingLeft) || 0 + const innerWidth = container.clientWidth - padLeft - (parseFloat(cs.paddingRight) || 0) + const containerRect = container.getBoundingClientRect() + const pageRect = page.getBoundingClientRect() + const pageLeft = pageRect.left - containerRect.left + container.scrollLeft + const pageTop = pageRect.top - containerRect.top + container.scrollTop + const prevPageLeft = padLeft + Math.max(0, (innerWidth - pageRect.width / ratio) / 2) + const prev = scrollPosRef.current - container.scrollLeft = centerX * ratio - container.clientWidth / 2 - container.scrollTop = centerY * ratio - container.clientHeight / 2 + const docX = Math.max(0, prev.left + vx - prevPageLeft) + const docY = Math.max(0, prev.top + vy - pageTop) + container.scrollLeft = pageLeft + docX * ratio - vx + container.scrollTop = pageTop + docY * ratio - vy + scrollPosRef.current = { left: container.scrollLeft, top: container.scrollTop } }, [zoom]) // ---- protection enforcement (Review > Protect Document) ---- @@ -1726,6 +1848,10 @@ export function App() { (outPath?: string) => exportPdfImpl(fileCtxRef.current, outPath), [], ) + const exportHtml = useCallback( + (outPath?: string) => exportHtmlImpl(fileCtxRef.current, outPath), + [], + ) const printDoc = useCallback(() => printDocImpl(fileCtxRef.current), []) // for real-device verification: trigger export directly via CDP (same as __pageDebug) @@ -1852,6 +1978,10 @@ export function App() { (parentId: string, text: string) => replyToCommentImpl(reviewCtxRef.current, parentId, text), [], ) + const editComment = useCallback( + (id: string, text: string) => editCommentImpl(reviewCtxRef.current, id, text), + [], + ) const resolveComment = useCallback( (id: string, done: boolean) => resolveCommentImpl(reviewCtxRef.current, id, done), [], @@ -3690,10 +3820,7 @@ export function App() { ) { e.preventDefault() const attrs = { lineSpacing: SPACING_KEYS[e.code], lineRule: null, lineRawTwips: null } - const sub = getActiveSubEditor() - // textbox schema has only docParagraph — setParaAttrs' heading/list updates would throw - if (sub) sub.chain().focus().updateAttributes('docParagraph', attrs).run() - else setParaAttrs(editor, attrs) + setParaAttrs(getActiveSubEditor() ?? editor, attrs) } // Paragraph styles ⌥⌘0 Normal / ⌥⌘1..3 headings (Ctrl+Shift+N is taken by New Window) const STYLE_KEYS: Record = { @@ -3976,6 +4103,9 @@ export function App() { case 'export-pdf': void exportPdf() break + case 'export-html': + void exportHtml() + break case 'print': if (doc) void printDoc() break @@ -3989,6 +4119,7 @@ export function App() { openRecent, save, exportPdf, + exportHtml, printDoc, zoomFit, openStats, @@ -4100,8 +4231,9 @@ export function App() { save: () => save(false), getStatus: () => status, exportPdfTo: (path: string) => exportPdf(path), + exportHtmlTo: (path: string) => exportHtml(path), } - }, [editor, openRecent, save, status, exportPdf]) + }, [editor, openRecent, save, status, exportPdf, exportHtml]) // shallow-stable snapshot of every editor read the ribbon displays: caret moves // that change none of it keep the reference, so the memoized Ribbon skips @@ -4543,7 +4675,7 @@ export function App() { showNav={showNav} commentCount={comments.length} openCommentCount={comments.filter((c) => !c.parentId && c.done !== true).length} - canComment={!editor.state.selection.empty} + canComment={!editor.state.selection.empty || wordRangeAtCaret(editor) !== null} trackChanges={trackChanges} spellcheck={spellcheck} revisionDisplay={revisionDisplay} @@ -4618,7 +4750,16 @@ export function App() { /> )}
-
+
{ + scrollPosRef.current = { + left: e.currentTarget.scrollLeft, + top: e.currentTarget.scrollTop, + } + }} + > {doc ? (
{ if (!editor) return - editor - .chain() - .focus() - .updateAttributes('docParagraph', { - tabStops: stops ? JSON.stringify(stops) : null, - }) - .updateAttributes('docHeading', { - tabStops: stops ? JSON.stringify(stops) : null, - }) - .updateAttributes('docListItem', { - tabStops: stops ? JSON.stringify(stops) : null, - }) - .run() + setParaAttrs(editor, { tabStops: stops ? JSON.stringify(stops) : null }) }} /> )} @@ -4816,6 +4945,7 @@ export function App() { composing={commentComposing} onSubmitNew={submitNewComment} onReply={replyToComment} + onEdit={editComment} onResolve={resolveComment} onCancelNew={cancelNewComment} onDelete={deleteComment} diff --git a/apps/docs/src/renderer/ai/AiPanel.tsx b/apps/docs/src/renderer/ai/AiPanel.tsx index 7e18422..75482b1 100644 --- a/apps/docs/src/renderer/ai/AiPanel.tsx +++ b/apps/docs/src/renderer/ai/AiPanel.tsx @@ -2,9 +2,11 @@ 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 { imageGenerationAvailable } from '@genoffice/ai-provider/browser' import type { AiSettings, AttachmentAddResult, AttachmentMeta } from '../../shared/ipc' import { ATTACHMENT_IMAGE_EXTS } from '../../shared/ipc' import type { PmNode } from '../editor/convert' +import { TABLE_TRAILING_SKIP } from '../editor/extensions' import { countWords, findNumId, type NumIds } from './protocol' import { DOC_NAV_SCHEME, navigateToBlock, parseDocNavHref } from './doc-nav' import { markDocSeen, type AiCommentsAccess, type AiHeaderFooterAccess } from './tools' @@ -17,6 +19,7 @@ import { resolveQueue, type DocsEditQueueItem, } from './edit-queue' +import { setInactiveSelectionShown } from '../editor/inactive-selection' import { applyRevisionsBy } from '../editor/revisions' import { DOCS_CONTINUE_INSTRUCTION } from './continuation' import { waitForFullContent } from '../phased-content' @@ -25,7 +28,7 @@ import { createFilesSkill } from './files-skill' import { createElectronTransport } from './transport' import { useI18n, t as tModule, aiLangDirective, type StringKey } from '../i18n/locale' import { Markdown } from '@genoffice/ui' -import { AiComposer, AiTypingIndicator } from '@genoffice/ui' +import { AiComposer, AiScopeQuote, AiTypingIndicator, type AiScopeQuoteData } from '@genoffice/ui' import { GensparkMark } from '../components/icons' import sendEnterOn from '../assets/send-enter-on.png' import sendEnterOff from '../assets/send-enter-off.png' @@ -82,8 +85,13 @@ interface ChatEntry { snapshot?: PmNode /** attachments consumed from the composer by this user message (read-only echo chips) */ attachments?: AttachmentMeta[] + /** the selection this user message targeted, frozen at send */ + scope?: AiScopeQuoteData } +/** longest selection excerpt echoed on a user bubble */ +const SCOPE_TEXT_MAX = 200 + /** clickable starter prompts for the empty state (fill the input, do not send) — * blank documents get generation starters, documents with content get edit starters */ const DRAFT_STARTER_PROMPTS: StringKey[] = [ @@ -423,6 +431,26 @@ export function AiPanel({ editorRef.current = editor const settingsRef = useRef(settings) settingsRef.current = settings + /** gsk login state for the generate_image gate (refreshed on mount and window focus) */ + const gskLoggedInRef = useRef(false) + useEffect(() => { + let alive = true + const refresh = () => { + // tests render the panel without a preload bridge + void window.desktop + ?.aiGskStatus?.() + .then((s) => { + if (alive) gskLoggedInRef.current = !!s?.loggedIn + }) + .catch(() => {}) + } + refresh() + window.addEventListener('focus', refresh) + return () => { + alive = false + window.removeEventListener('focus', refresh) + } + }, []) const blocksRef = useRef(blocks) blocksRef.current = blocks const numIdFallbackRef = useRef(numIdFallback) @@ -431,6 +459,8 @@ export function AiPanel({ attachmentsRef.current = attachments /** attachments consumed by the most recent send — retry resends the same set */ const lastAttachmentsRef = useRef([]) + /** the scope quote of the last send, so a retry reuses it instead of re-reading the live selection */ + const lastScopeRef = useRef(undefined) /** composer attachments plus everything already sent this session (deduped by path) */ const availableAttachments = (): AttachmentMeta[] => { const seen = new Set() @@ -508,6 +538,7 @@ export function AiPanel({ ext: a.ext ?? '', sizeBytes: a.sizeBytes ?? 0, })), + ...(m.scope ? { scope: m.scope } : {}), })), ) // restore model context: follow-ups after reopening a file continue the previous conversation (only when the loop is idle with no history) @@ -545,6 +576,7 @@ export function AiPanel({ output?: string }>, attachments?: AttachmentMeta[], + scope?: AiScopeQuoteData, ) => { const ids = chatRefIds.current const api = (window as Window & { projectApi?: typeof window.projectApi }).projectApi @@ -566,6 +598,7 @@ export function AiPanel({ })), } : {}), + ...(scope ? { scope } : {}), }) .catch(() => { /* silent */ @@ -600,6 +633,7 @@ export function AiPanel({ () => (trackChangesRef.current ? { author: AI_REVISION_AUTHOR } : undefined), () => commentsAccessRef.current, () => hfAccessRef.current, + () => imageGenerationAvailable(settingsRef.current, gskLoggedInRef.current), ), createFilesSkill(availableAttachments), ]), @@ -754,6 +788,29 @@ export function AiPanel({ editor.commands.setTextSelection(editor.state.selection.to) } + const selectionScopeQuote = (): AiScopeQuoteData | undefined => { + const { from, to, empty } = editor.state.selection + if (empty) return undefined + const text = editor.state.doc.textBetween(from, to, ' ', ' ').replace(/\s+/g, ' ').trim() + if (!text) return undefined + return { + label: t('aiScopeSelection', { words: countWords(text) }), + text: text.length > SCOPE_TEXT_MAX ? `${text.slice(0, SCOPE_TEXT_MAX)}…` : text, + } + } + + // the frozen-range highlight ends with the run, or as soon as the editor is focused again + useEffect(() => { + if (!busy) setInactiveSelectionShown(editor, false) + }, [busy, editor]) + useEffect(() => { + const off = () => setInactiveSelectionShown(editor, false) + editor.on('focus', off) + return () => { + editor.off('focus', off) + } + }, [editor]) + /** [label](docnav://block/N) links in replies select and scroll to that block */ const docNav = { scheme: DOC_NAV_SCHEME, @@ -807,6 +864,8 @@ export function AiPanel({ instruction: string, displayInstruction = instruction, attachmentsOverride?: AttachmentMeta[], + /** null = a retry that had no scope; undefined = capture the live selection */ + retryScope?: AiScopeQuoteData | null, ) => { const loop = loopRef.current if (!instruction || !loop || loop.busy || pendingSendRef.current) return @@ -823,6 +882,16 @@ export function AiPanel({ setAttachments([]) } lastAttachmentsRef.current = sentAtts + // the queue batch and the continue action carry their own display text: no selection quote + const scope = + retryScope !== undefined + ? (retryScope ?? undefined) + : displayInstruction === instruction + ? selectionScopeQuote() + : undefined + lastScopeRef.current = scope + // the popover input / composer own the DOM selection now: keep the targeted range visible until the run ends + if (scope) setInactiveSelectionShown(editor, true) instructionRef.current = instruction lastInstructionRef.current = instruction runToolsRef.current = [] @@ -834,6 +903,7 @@ export function AiPanel({ role: 'user', text: displayInstruction, ...(sentAtts.length > 0 ? { attachments: sentAtts } : {}), + ...(scope ? { scope } : {}), }, { role: 'assistant', text: '', streaming: true }, ]) @@ -843,7 +913,7 @@ export function AiPanel({ const generation = currentDocGeneration() const pending = { aborted: false } pendingSendRef.current = pending - persistMessage('user', instruction, undefined, sentAtts) + persistMessage('user', instruction, undefined, sentAtts, scope) // a rejected image read must not strand the run (busy would stay true forever): degrade to a no-image send void collectImageAttachments(sentAtts) .catch((): AgentImage[] => { @@ -895,7 +965,12 @@ export function AiPanel({ } const retry = () => - runWith(lastInstructionRef.current, lastInstructionRef.current, lastAttachmentsRef.current) + runWith( + lastInstructionRef.current, + lastInstructionRef.current, + lastAttachmentsRef.current, + lastScopeRef.current ?? null, + ) const continueRun = () => runWith(DOCS_CONTINUE_INSTRUCTION, t('aiContinue')) @@ -983,7 +1058,11 @@ export function AiPanel({ } const rollback = (entryIdx: number, snapshot: PmNode) => { - editor.commands.setContent(snapshot as never) + editor + .chain() + .setMeta(TABLE_TRAILING_SKIP, true) + .setContent(snapshot as never) + .run() // The document rewound to before this turn, so this and every later // rollback point now describe discarded futures setChat((prev) => @@ -1103,6 +1182,7 @@ export function AiPanel({ <> {historicChat.map((entry, i) => (
+ {entry.role === 'user' && entry.scope && } {entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && ( )} @@ -1169,6 +1249,7 @@ export function AiPanel({ key={i} className={`ai-msg ai-msg-${entry.role}${entry.role === 'assistant' && entry.streaming ? ' ai-msg-streaming' : ''}`} > + {entry.role === 'user' && entry.scope && } {entry.role === 'user' && entry.attachments && entry.attachments.length > 0 && ( )} diff --git a/apps/docs/src/renderer/ai/commands.ts b/apps/docs/src/renderer/ai/commands.ts deleted file mode 100644 index 71a6e01..0000000 --- a/apps/docs/src/renderer/ai/commands.ts +++ /dev/null @@ -1,1163 +0,0 @@ -import type { Editor } from '@tiptap/core' -import type { Node as PmDocNode, Schema } from '@tiptap/pm/model' -import type { Transaction } from '@tiptap/pm/state' -import { generateTocFieldXml, type TocEntry } from '@genoffice/docx-engine' -import { isEastAsianFontName } from '../font-list' -import { t } from '../i18n/locale' -import { blockRangePositions, isTrackedDeleted, liveText } from './protocol' - -/** - * Structured edit commands: the model emits a - * batchUpdate-style JSON envelope and code applies it deterministically on the - * PM doc — one transaction per envelope, so one undo reverts the whole round. - * The docx round trip is untouched: changed nodes become dirty via the normal - * signature comparison and regenerate on save; docxIndex anchors are never - * modified here. - */ - -// ---- command types (§4) ---- - -/** All given conditions filter with AND; at least one condition is required */ -export interface Target { - /** 'image' matches protected image blocks (docProtected + blockType image) */ - nodeType?: 'docHeading' | 'docParagraph' | 'docListItem' | 'image' - /** Restrict heading level (only with nodeType: 'docHeading') */ - headingLevel?: number - /** The block's plain text contains this substring (case-sensitive unless matchCase: false) */ - containsText?: string - matchCase?: boolean - /** By block index (the index output by buildDocumentContext, 0-based, current PM doc top-level order) */ - blockIndexes?: number[] - /** 'selection' = only blocks covered by the current selection; default = whole document */ - scope?: 'selection' | 'document' -} - -/** Run-level style; only keys listed in fields take effect, and null clears the property */ -export interface UpdateTextStyle { - target: Target - style: { - color?: string | null - highlight?: string | null - sizeHalfPoints?: number | null - font?: string | null - bold?: boolean - italic?: boolean - underline?: boolean - strike?: boolean - /** Super/subscript (enum values aligned with Google TextStyle.baselineOffset) */ - baselineOffset?: 'SUPERSCRIPT' | 'SUBSCRIPT' | 'NONE' | null - /** Hyperlink (aligned with Google TextStyle.link); null removes the link */ - link?: { url: string } | null - } - fields: Array -} - -/** Paragraph-level format; likewise constrained by the fields mask */ -export interface UpdateParagraphStyle { - target: Target - style: { - align?: 'left' | 'center' | 'right' | 'justify' | null - lineSpacing?: number | null - indentLeft?: number | null - indentRight?: number | null - /** First-line indent in twips; positive = first-line indent, negative = hanging indent (aligned with Google indentFirstLine) */ - indentFirstLine?: number | null - spaceBefore?: number | null - spaceAfter?: number | null - pageBreakBefore?: boolean - shadingFill?: string | null - /** Paragraph borders, a subset of "tblr" (simplified Google borderTop/Bottom/Left/Right) */ - borders?: string | null - } - fields: Array -} - -/** Paragraph promote/demote; level 0 = demote to body paragraph, 1-6 = the corresponding heading level */ -export interface SetHeadingLevel { - target: Target - level: 0 | 1 | 2 | 3 | 4 | 5 | 6 -} - -/** Find & replace (plain text, no cross-block matching); target narrows the scanned blocks */ -export interface ReplaceAllText { - containsText: string - replaceText: string - matchCase?: boolean - /** omitted = whole document */ - target?: Target -} - -/** - * Character-level styling: applies the run style only to the matched text - * itself (updateTextStyle always styles whole blocks). target narrows which - * blocks are scanned; omitted = whole document. - */ -export interface UpdateMatchedTextStyle { - containsText: string - matchCase?: boolean - target?: Target - style: UpdateTextStyle['style'] - fields: Array -} - -export interface DeleteBlocks { - target: Target -} - -/** Move the blocks in blockIndexes (relative order kept) after afterBlockIndex; -1 = document start */ -export interface MoveBlocks { - blockIndexes: number[] - afterBlockIndex: number -} - -/** - * Paragraphs to list (name and semantics aligned with Google's createParagraphBullets). - * BULLET*-prefixed presets = unordered, NUMBERED* = ordered; heading blocks aren't converted (counted in matched but unchanged). - */ -export interface CreateParagraphBullets { - target: Target - bulletPreset?: string -} - -/** List items back to body paragraphs (aligned with Google's deleteParagraphBullets) */ -export interface DeleteParagraphBullets { - target: Target -} - -/** Image block properties; giving only one of widthPx/heightPx scales the other side by the original ratio */ -export interface UpdateImageProperties { - target: Target - properties: { - widthPx?: number | null - heightPx?: number | null - align?: 'left' | 'center' | 'right' | null - } - fields: Array -} - -/** - * Insert a TOC field after the given block (a real TOC field; Word recomputes page numbers on open). - * Entries come from the current document's heading blocks; the command fails when there are no headings. - */ -export interface InsertToc { - /** Insert after this block index; -1 = document start */ - afterBlockIndex: number -} - -export type Command = - | { updateTextStyle: UpdateTextStyle } - | { updateMatchedTextStyle: UpdateMatchedTextStyle } - | { updateParagraphStyle: UpdateParagraphStyle } - | { setHeadingLevel: SetHeadingLevel } - | { replaceAllText: ReplaceAllText } - | { deleteBlocks: DeleteBlocks } - | { moveBlocks: MoveBlocks } - | { createParagraphBullets: CreateParagraphBullets } - | { deleteParagraphBullets: DeleteParagraphBullets } - | { updateImageProperties: UpdateImageProperties } - | { insertToc: InsertToc } - -/** numbering context so converted list items join real docx numbering on save */ -export interface CommandContext { - numIds?: { bullet: string | null; ordered: string | null } | null - /** record the envelope's changes as tracked revisions under this author */ - track?: { author: string } | null - /** - * Selection frozen (in block-index space) when the model last saw the doc. - * scope:'selection' resolves against this instead of the live selection, so - * the user clicking elsewhere mid-run cannot retarget the command. - */ - selection?: { startIndex: number; endIndex: number } | null -} - -export interface CommandEnvelope { - commands: Command[] -} - -export interface CommandResult { - command: string - matched: number - changed: number - skippedProtected: number - /** targets skipped because the text is a pending tracked deletion */ - skippedDeleted?: number - detail?: string -} - -export interface ExecuteOutcome { - ok: boolean - results: CommandResult[] - summary: string - error?: string -} - -// ---- envelope extraction ---- - -/** pull a command envelope out of a model response; null = not command mode */ -export function parseCommandEnvelope(raw: string): CommandEnvelope | null { - const text = raw.trim() - const fence = /```json\s*([\s\S]*?)```/.exec(text) - const candidate = fence ? fence[1].trim() : text.startsWith('{') ? text : null - if (!candidate) return null - try { - const parsed: unknown = JSON.parse(candidate) - if ( - parsed && - typeof parsed === 'object' && - Array.isArray((parsed as CommandEnvelope).commands) - ) { - return parsed as CommandEnvelope - } - } catch { - // not JSON: content mode - } - return null -} - -// ---- validation (whole-envelope: any invalid command rejects everything) ---- - -const NODE_TYPES = ['docHeading', 'docParagraph', 'docListItem', 'image'] as const -const TEXT_STYLE_KEYS = [ - 'color', - 'highlight', - 'sizeHalfPoints', - 'font', - 'bold', - 'italic', - 'underline', - 'strike', - 'baselineOffset', - 'link', -] as const -const PARA_STYLE_KEYS = [ - 'align', - 'lineSpacing', - 'indentLeft', - 'indentRight', - 'indentFirstLine', - 'spaceBefore', - 'spaceAfter', - 'pageBreakBefore', - 'shadingFill', - 'borders', -] as const -const BASELINE_OFFSETS = ['SUPERSCRIPT', 'SUBSCRIPT', 'NONE'] as const -const COMMAND_NAMES = [ - 'updateTextStyle', - 'updateMatchedTextStyle', - 'updateParagraphStyle', - 'setHeadingLevel', - 'replaceAllText', - 'deleteBlocks', - 'moveBlocks', - 'createParagraphBullets', - 'deleteParagraphBullets', - 'updateImageProperties', - 'insertToc', -] as const -const IMAGE_PROP_KEYS = ['widthPx', 'heightPx', 'align'] as const - -type CommandName = (typeof COMMAND_NAMES)[number] - -function validateTarget(target: unknown, where: string): string | null { - if (!target || typeof target !== 'object') return `${where}: missing target` - const t = target as Target - if (t.nodeType !== undefined && !NODE_TYPES.includes(t.nodeType)) { - return `${where}: unknown nodeType "${String(t.nodeType)}"` - } - if ( - t.headingLevel !== undefined && - (!Number.isInteger(t.headingLevel) || t.headingLevel < 1 || t.headingLevel > 6) - ) { - return `${where}: headingLevel must be an integer between 1 and 6` - } - if ( - t.blockIndexes !== undefined && - (!Array.isArray(t.blockIndexes) || t.blockIndexes.some((i) => !Number.isInteger(i) || i < 0)) - ) { - return `${where}: blockIndexes must be an array of non-negative integers` - } - const hasCondition = - t.nodeType !== undefined || - t.headingLevel !== undefined || - typeof t.containsText === 'string' || - (Array.isArray(t.blockIndexes) && t.blockIndexes.length > 0) || - t.scope === 'selection' - if (!hasCondition) return `${where}: target requires at least one condition` - return null -} - -function validateStyleCommand( - payload: { target?: unknown; style?: unknown; fields?: unknown }, - allowedKeys: readonly string[], - where: string, -): string | null { - const targetError = validateTarget(payload.target, where) - if (targetError) return targetError - if (!payload.style || typeof payload.style !== 'object') return `${where}: missing style` - if (!Array.isArray(payload.fields) || payload.fields.length === 0) { - return `${where}: fields must not be empty` - } - const bad = payload.fields.filter((f) => !allowedKeys.includes(String(f))) - if (bad.length > 0) return `${where}: unknown fields ${bad.map(String).join(', ')}` - return null -} - -/** value checks shared by every command speaking the updateTextStyle style vocabulary */ -function validateTextStyleValues(style: UpdateTextStyle['style'], where: string): string | null { - if ( - style.baselineOffset != null && - !(BASELINE_OFFSETS as readonly string[]).includes(style.baselineOffset) - ) { - return `${where}: baselineOffset must be SUPERSCRIPT/SUBSCRIPT/NONE` - } - if (style.link != null && typeof style.link.url !== 'string') { - return `${where}: link must be { url } or null` - } - return null -} - -export function validateEnvelope(envelope: unknown): string | null { - if (!envelope || typeof envelope !== 'object') return 'the envelope must be an object' - const commands = (envelope as CommandEnvelope).commands - if (!Array.isArray(commands) || commands.length === 0) return 'commands must be a non-empty array' - for (let i = 0; i < commands.length; i++) { - const command = commands[i] as Record - if (!command || typeof command !== 'object') return `command #${i}: must be an object` - const keys = Object.keys(command) - if (keys.length !== 1) return `command #${i}: must be a single-key object` - const name = keys[0] - const where = `command #${i} ${name}` - if (!COMMAND_NAMES.includes(name as CommandName)) return `${where}: unknown command` - const payload = command[name] as Record - if (!payload || typeof payload !== 'object') return `${where}: parameters must be an object` - let error: string | null = null - switch (name as CommandName) { - case 'updateTextStyle': { - error = validateStyleCommand(payload, TEXT_STYLE_KEYS, where) - if (!error) - error = validateTextStyleValues(payload.style as UpdateTextStyle['style'], where) - break - } - case 'updateParagraphStyle': - error = validateStyleCommand(payload, PARA_STYLE_KEYS, where) - break - case 'setHeadingLevel': { - error = validateTarget(payload.target, where) - const level = payload.level - if (!error && (!Number.isInteger(level) || Number(level) < 0 || Number(level) > 6)) { - error = `${where}: level must be an integer between 0 and 6` - } - break - } - case 'replaceAllText': - if (typeof payload.containsText !== 'string' || payload.containsText === '') { - error = `${where}: containsText must not be empty` - } else if (typeof payload.replaceText !== 'string') { - error = `${where}: replaceText must be a string` - } else if (payload.target !== undefined) { - error = validateTarget(payload.target, where) - } - break - case 'updateMatchedTextStyle': { - if (typeof payload.containsText !== 'string' || payload.containsText === '') { - error = `${where}: containsText must not be empty` - break - } - if (payload.target !== undefined) { - error = validateTarget(payload.target, where) - if (error) break - } - if (!payload.style || typeof payload.style !== 'object') { - error = `${where}: missing style` - } else if (!Array.isArray(payload.fields) || payload.fields.length === 0) { - error = `${where}: fields must not be empty` - } else { - const bad = payload.fields.filter( - (f) => !(TEXT_STYLE_KEYS as readonly string[]).includes(String(f)), - ) - if (bad.length > 0) error = `${where}: unknown fields ${bad.map(String).join(', ')}` - else error = validateTextStyleValues(payload.style as UpdateTextStyle['style'], where) - } - break - } - case 'deleteBlocks': - error = validateTarget(payload.target, where) - break - case 'moveBlocks': - if ( - !Array.isArray(payload.blockIndexes) || - payload.blockIndexes.length === 0 || - payload.blockIndexes.some((i) => !Number.isInteger(i) || Number(i) < 0) - ) { - error = `${where}: blockIndexes must be a non-empty array of non-negative integers` - } else if ( - !Number.isInteger(payload.afterBlockIndex) || - Number(payload.afterBlockIndex) < -1 - ) { - error = `${where}: afterBlockIndex must be an integer ≥ -1` - } - break - case 'createParagraphBullets': { - error = validateTarget(payload.target, where) - const preset = payload.bulletPreset - if ( - !error && - preset !== undefined && - (typeof preset !== 'string' || !/^(BULLET|NUMBERED)/.test(preset)) - ) { - error = `${where}: bulletPreset must start with BULLET or NUMBERED` - } - break - } - case 'deleteParagraphBullets': - error = validateTarget(payload.target, where) - break - case 'updateImageProperties': { - error = validateTarget(payload.target, where) - if (!error) { - if (!payload.properties || typeof payload.properties !== 'object') { - error = `${where}: missing properties` - } else if (!Array.isArray(payload.fields) || payload.fields.length === 0) { - error = `${where}: fields must not be empty` - } else { - const bad = payload.fields.filter( - (f) => !(IMAGE_PROP_KEYS as readonly string[]).includes(String(f)), - ) - if (bad.length > 0) error = `${where}: unknown fields ${bad.map(String).join(', ')}` - } - } - break - } - case 'insertToc': - if (!Number.isInteger(payload.afterBlockIndex) || Number(payload.afterBlockIndex) < -1) { - error = `${where}: afterBlockIndex must be an integer ≥ -1` - } - break - } - if (error) return error - } - return null -} - -// ---- target matching ---- - -interface TopBlock { - index: number - pos: number - node: PmDocNode -} - -interface SelRange { - from: number - to: number -} - -function topLevelBlocks(doc: PmDocNode): TopBlock[] { - const out: TopBlock[] = [] - let index = 0 - doc.forEach((node, offset) => { - out.push({ index, pos: offset, node }) - index++ - }) - return out -} - -function blockText(node: PmDocNode): string { - if (node.type.name === 'docProtected') { - return [node.attrs.label, node.attrs.previewText].filter(Boolean).join(' ') - } - // match against current content only, or targets would hit already-deleted revision text - return liveText(node) -} - -function matchTarget(doc: PmDocNode, target: Target, sel: SelRange): TopBlock[] { - return topLevelBlocks(doc).filter((b) => { - if (target.blockIndexes && !target.blockIndexes.includes(b.index)) return false - if (target.nodeType === 'image') { - if (b.node.type.name !== 'docProtected' || b.node.attrs.blockType !== 'image') return false - } else if (target.nodeType && b.node.type.name !== target.nodeType) { - return false - } - if (target.headingLevel !== undefined) { - if (b.node.type.name !== 'docHeading') return false - if (Number(b.node.attrs.level) !== target.headingLevel) return false - } - if (target.containsText) { - const text = blockText(b.node) - const hit = - target.matchCase === false - ? text.toLowerCase().includes(target.containsText.toLowerCase()) - : text.includes(target.containsText) - if (!hit) return false - } - if (target.scope === 'selection') { - const from = b.pos - const to = b.pos + b.node.nodeSize - const overlaps = to > sel.from && from < sel.to - const caretInside = sel.from === sel.to && sel.from >= from && sel.from <= to - if (!overlaps && !caretInside) return false - } - return true - }) -} - -// ---- executors (each reads tr.doc fresh, so sequential commands compose) ---- - -const BOOL_MARK_TYPES: Record = { - bold: 'bold', - italic: 'italic', - underline: 'underline', - strike: 'strike', -} -const TEXT_ATTR_KEYS = ['color', 'highlight', 'sizeHalfPoints', 'font'] as const - -function markChanged(tr: Transaction, pos: number): boolean { - const node = tr.doc.nodeAt(pos) - if (!node) return false - tr.setNodeMarkup(pos, undefined, { ...node.attrs, aiChanged: true }) - return true -} - -/** patch applied onto each text node's existing docTextStyle attrs (fonts route to their rFonts slot) */ -function buildTextMarkPatch(cmd: { - style: UpdateTextStyle['style'] - fields: UpdateTextStyle['fields'] -}): Record { - const markPatch: Record = {} - for (const f of cmd.fields) { - if (f === 'font') { - // route to the matching rFonts slot; clearing clears both - const v = cmd.style.font - if (!v) Object.assign(markPatch, { font: null, fontAscii: null }) - else if (isEastAsianFontName(v)) markPatch.font = v - else markPatch.fontAscii = v - } else if ((TEXT_ATTR_KEYS as readonly string[]).includes(f)) { - markPatch[f] = cmd.style[f as (typeof TEXT_ATTR_KEYS)[number]] ?? null - } else if (f === 'baselineOffset') { - const value = cmd.style.baselineOffset - markPatch.vertAlign = - value === 'SUPERSCRIPT' ? 'superscript' : value === 'SUBSCRIPT' ? 'subscript' : null - } - } - return markPatch -} - -function runUpdateTextStyle( - tr: Transaction, - schema: Schema, - cmd: UpdateTextStyle, - sel: SelRange, -): CommandResult { - const matched = matchTarget(tr.doc, cmd.target, sel) - const boolFields = cmd.fields.filter((f) => f in BOOL_MARK_TYPES) - const markPatch = buildTextMarkPatch(cmd) - const hasLink = cmd.fields.includes('link') - let changed = 0 - let skippedProtected = 0 - - for (const b of matched) { - if (b.node.type.name === 'docProtected') { - skippedProtected++ - continue - } - const before = b.node - const from = b.pos + 1 - const to = from + b.node.content.size - if (from < to) { - for (const f of boolFields) { - const markType = schema.marks[BOOL_MARK_TYPES[f]] - if (cmd.style[f]) tr.addMark(from, to, markType.create()) - else tr.removeMark(from, to, markType) - } - if (hasLink) { - if (cmd.style.link?.url) { - tr.addMark(from, to, schema.marks.link.create({ href: cmd.style.link.url, rId: null })) - } else { - tr.removeMark(from, to, schema.marks.link) - } - } - if (Object.keys(markPatch).length > 0) { - // merge per text node: only fields-listed attrs change, the rest survive - b.node.forEach((child, offset) => { - if (!child.isText) return - const childFrom = from + offset - const childTo = childFrom + child.nodeSize - const existing = child.marks.find((m) => m.type.name === 'docTextStyle')?.attrs ?? {} - // spread keeps every non-listed attr (fontAscii/styleId/rawRPr…) alive - const merged: Record = { ...existing, ...markPatch } - const empty = Object.values(merged).every((v) => v === null) - if (empty) tr.removeMark(childFrom, childTo, schema.marks.docTextStyle) - else tr.addMark(childFrom, childTo, schema.marks.docTextStyle.create(merged)) - }) - } - } - const after = tr.doc.nodeAt(b.pos) - if (after && !after.eq(before)) { - changed++ - markChanged(tr, b.pos) - } - } - return { command: 'updateTextStyle', matched: matched.length, changed, skippedProtected } -} - -function runUpdateParagraphStyle( - tr: Transaction, - cmd: UpdateParagraphStyle, - sel: SelRange, -): CommandResult { - const matched = matchTarget(tr.doc, cmd.target, sel) - let changed = 0 - let skippedProtected = 0 - for (const b of matched) { - if (b.node.type.name === 'docProtected') { - skippedProtected++ - continue - } - const attrs: Record = { ...b.node.attrs } - for (const f of cmd.fields) { - attrs[f] = cmd.style[f] ?? (f === 'pageBreakBefore' ? false : null) - // an explicit spacing value turns Word's "Auto" spacing off - if (f === 'spaceBefore') attrs.spaceBeforeAuto = false - if (f === 'spaceAfter') attrs.spaceAfterAuto = false - } - const dirty = Object.keys(attrs).some((f) => attrs[f] !== b.node.attrs[f]) - if (!dirty) continue - tr.setNodeMarkup(b.pos, undefined, { ...attrs, aiChanged: true }) - changed++ - } - return { command: 'updateParagraphStyle', matched: matched.length, changed, skippedProtected } -} - -function runSetHeadingLevel( - tr: Transaction, - schema: Schema, - cmd: SetHeadingLevel, - sel: SelRange, -): CommandResult { - const matched = matchTarget(tr.doc, cmd.target, sel) - let changed = 0 - let skippedProtected = 0 - for (const b of matched) { - if (b.node.type.name === 'docProtected') { - skippedProtected++ - continue - } - const isHeading = b.node.type.name === 'docHeading' - if (cmd.level === 0 && b.node.type.name === 'docParagraph') continue - if (cmd.level > 0 && isHeading && Number(b.node.attrs.level) === cmd.level) continue - const type = cmd.level === 0 ? schema.nodes.docParagraph : schema.nodes.docHeading - // styleId is tied to the old block role; generate.ts picks heading styles by level - const attrs: Record = { - ...b.node.attrs, - styleId: null, - aiChanged: true, - } - if (cmd.level > 0) attrs.level = cmd.level - tr.setNodeMarkup(b.pos, type, attrs) - changed++ - } - return { command: 'setHeadingLevel', matched: matched.length, changed, skippedProtected } -} - -function runReplaceAllText( - tr: Transaction, - schema: Schema, - cmd: ReplaceAllText, - sel: SelRange, -): CommandResult { - // an empty needle would match at every offset without ever advancing the scan below - if (!cmd.containsText) { - return { command: 'replaceAllText', matched: 0, changed: 0, skippedProtected: 0 } - } - const matchCase = cmd.matchCase !== false - const needle = matchCase ? cmd.containsText : cmd.containsText.toLowerCase() - const blocks = cmd.target ? matchTarget(tr.doc, cmd.target, sel) : topLevelBlocks(tr.doc) - const replacements: Array<{ from: number; to: number; marks: PmDocNode['marks'] }> = [] - const touchedIndexes = new Set() - let skippedProtected = 0 - let skippedDeleted = 0 - - for (const b of blocks) { - if (b.node.type.name === 'docProtected') { - if (blockText(b.node).includes(cmd.containsText)) skippedProtected++ - continue - } - const blockDeleted = isTrackedDeleted(b.node) - b.node.forEach((child, offset) => { - if (!child.isText || !child.text) return - const struck = blockDeleted || child.marks.some((m) => m.type.name === 'del') - const hay = matchCase ? child.text : child.text.toLowerCase() - let at = hay.indexOf(needle) - while (at !== -1) { - if (struck) { - skippedDeleted++ - } else { - const from = b.pos + 1 + offset + at - replacements.push({ from, to: from + needle.length, marks: child.marks }) - touchedIndexes.add(b.index) - } - at = hay.indexOf(needle, at + needle.length) - } - }) - } - - // apply back-to-front so earlier positions stay valid - for (const r of [...replacements].reverse()) { - if (cmd.replaceText) tr.replaceWith(r.from, r.to, schema.text(cmd.replaceText, r.marks)) - else tr.delete(r.from, r.to) - } - if (touchedIndexes.size > 0) { - for (const b of topLevelBlocks(tr.doc)) { - if (touchedIndexes.has(b.index)) markChanged(tr, b.pos) - } - } - return { - command: 'replaceAllText', - matched: touchedIndexes.size, - changed: touchedIndexes.size, - skippedProtected, - skippedDeleted, - detail: t('aiCmdReplacedCount', { count: replacements.length }), - } -} - -function runUpdateMatchedTextStyle( - tr: Transaction, - schema: Schema, - cmd: UpdateMatchedTextStyle, - sel: SelRange, -): CommandResult { - const matchCase = cmd.matchCase !== false - const needle = matchCase ? cmd.containsText : cmd.containsText.toLowerCase() - const blocks = cmd.target ? matchTarget(tr.doc, cmd.target, sel) : topLevelBlocks(tr.doc) - const boolFields = cmd.fields.filter((f) => f in BOOL_MARK_TYPES) - const markPatch = buildTextMarkPatch(cmd) - const hasLink = cmd.fields.includes('link') - const touched = new Set() - let styledCount = 0 - let skippedProtected = 0 - let skippedDeleted = 0 - - for (const b of blocks) { - if (b.node.type.name === 'docProtected') { - if (blockText(b.node).includes(cmd.containsText)) skippedProtected++ - continue - } - const blockDeleted = isTrackedDeleted(b.node) - b.node.forEach((child, offset) => { - if (!child.isText || !child.text) return - const struck = blockDeleted || child.marks.some((m) => m.type.name === 'del') - const hay = matchCase ? child.text : child.text.toLowerCase() - let at = hay.indexOf(needle) - while (at !== -1) { - if (struck) { - skippedDeleted++ - } else { - const from = b.pos + 1 + offset + at - const to = from + needle.length - for (const f of boolFields) { - const markType = schema.marks[BOOL_MARK_TYPES[f]] - if (cmd.style[f]) tr.addMark(from, to, markType.create()) - else tr.removeMark(from, to, markType) - } - if (hasLink) { - if (cmd.style.link?.url) { - tr.addMark( - from, - to, - schema.marks.link.create({ href: cmd.style.link.url, rId: null }), - ) - } else { - tr.removeMark(from, to, schema.marks.link) - } - } - if (Object.keys(markPatch).length > 0) { - const existing = child.marks.find((m) => m.type.name === 'docTextStyle')?.attrs ?? {} - // spread keeps every non-listed attr (fontAscii/styleId/rawRPr…) alive - const merged: Record = { ...existing, ...markPatch } - const empty = Object.values(merged).every((v) => v === null) - if (empty) tr.removeMark(from, to, schema.marks.docTextStyle) - else tr.addMark(from, to, schema.marks.docTextStyle.create(merged)) - } - styledCount++ - touched.add(b.index) - } - at = hay.indexOf(needle, at + needle.length) - } - }) - } - // mark steps never shift positions, so block offsets are still valid here - for (const b of topLevelBlocks(tr.doc)) { - if (touched.has(b.index)) markChanged(tr, b.pos) - } - return { - command: 'updateMatchedTextStyle', - matched: touched.size, - changed: touched.size, - skippedProtected, - skippedDeleted, - detail: String(styledCount), - } -} - -function runDeleteBlocks( - tr: Transaction, - schema: Schema, - cmd: DeleteBlocks, - sel: SelRange, -): CommandResult { - const blocks = topLevelBlocks(tr.doc) - const matchedAll = matchTarget(tr.doc, cmd.target, sel) - // deleting a pending deletion is a no-op (the tracker re-materializes it struck); - // skip and report so the model does not retry forever - const matched = matchedAll.filter((b) => !isTrackedDeleted(b.node)) - const skippedDeleted = matchedAll.length - matched.length - if (matched.length === blocks.length && matched.length > 0) { - // doc requires block+: deleting everything leaves one empty paragraph - tr.replaceWith(0, tr.doc.content.size, schema.nodes.docParagraph.create()) - return { - command: 'deleteBlocks', - matched: matchedAll.length, - changed: matched.length, - skippedProtected: 0, - skippedDeleted, - } - } - for (const b of [...matched].sort((a, z) => z.pos - a.pos)) { - tr.delete(b.pos, b.pos + b.node.nodeSize) - } - return { - command: 'deleteBlocks', - matched: matchedAll.length, - changed: matched.length, - skippedProtected: 0, - skippedDeleted, - } -} - -function runMoveBlocks(tr: Transaction, cmd: MoveBlocks): CommandResult { - const blocks = topLevelBlocks(tr.doc) - const movedSet = new Set(cmd.blockIndexes) - const outOfRange = cmd.blockIndexes.filter((i) => i >= blocks.length) - if (outOfRange.length > 0) - throw new Error(`moveBlocks: block indexes out of range ${outOfRange.join(', ')}`) - if (cmd.afterBlockIndex >= blocks.length) { - throw new Error(`moveBlocks: afterBlockIndex out of range ${cmd.afterBlockIndex}`) - } - if (movedSet.has(cmd.afterBlockIndex)) { - throw new Error('moveBlocks: afterBlockIndex must not be one of the moved blocks') - } - - // moved blocks keep document order; aiChanged marks the landing highlight - const moved = [...movedSet] - .sort((a, z) => a - z) - .map((i) => { - const node = blocks[i].node - if (node.type.name === 'docProtected') return node - return node.type.create({ ...node.attrs, aiChanged: true }, node.content, node.marks) - }) - const rest = blocks.filter((b) => !movedSet.has(b.index)) - let insertAt = 0 - if (cmd.afterBlockIndex >= 0) { - insertAt = rest.findIndex((b) => b.index === cmd.afterBlockIndex) + 1 - } - const children = [ - ...rest.slice(0, insertAt).map((b) => b.node), - ...moved, - ...rest.slice(insertAt).map((b) => b.node), - ] - tr.replaceWith(0, tr.doc.content.size, children) - return { - command: 'moveBlocks', - matched: moved.length, - changed: moved.length, - skippedProtected: 0, - } -} - -function runCreateParagraphBullets( - tr: Transaction, - schema: Schema, - cmd: CreateParagraphBullets, - sel: SelRange, - context: CommandContext, -): CommandResult { - const matched = matchTarget(tr.doc, cmd.target, sel) - const kind = cmd.bulletPreset?.startsWith('NUMBERED') ? 'ordered' : 'bullet' - const numId = context.numIds?.[kind] ?? null - let changed = 0 - let skippedProtected = 0 - for (const b of matched) { - if (b.node.type.name === 'docProtected') { - skippedProtected++ - continue - } - // headings keep their role; converting them to list items would drop the level - if (b.node.type.name === 'docHeading') continue - if (b.node.type.name === 'docListItem') { - if (b.node.attrs.kind === kind) continue - tr.setNodeMarkup(b.pos, undefined, { - ...b.node.attrs, - kind, - numId: numId ?? b.node.attrs.numId, - aiChanged: true, - }) - changed++ - continue - } - tr.setNodeMarkup(b.pos, schema.nodes.docListItem, { - ...b.node.attrs, - styleId: null, - kind, - numId, - ilvl: 0, - aiChanged: true, - }) - changed++ - } - return { command: 'createParagraphBullets', matched: matched.length, changed, skippedProtected } -} - -function runDeleteParagraphBullets( - tr: Transaction, - schema: Schema, - cmd: DeleteParagraphBullets, - sel: SelRange, -): CommandResult { - const matched = matchTarget(tr.doc, cmd.target, sel) - let changed = 0 - let skippedProtected = 0 - for (const b of matched) { - if (b.node.type.name === 'docProtected') { - skippedProtected++ - continue - } - if (b.node.type.name !== 'docListItem') continue - tr.setNodeMarkup(b.pos, schema.nodes.docParagraph, { - ...b.node.attrs, - styleId: null, - aiChanged: true, - }) - changed++ - } - return { command: 'deleteParagraphBullets', matched: matched.length, changed, skippedProtected } -} - -function runUpdateImageProperties( - tr: Transaction, - cmd: UpdateImageProperties, - sel: SelRange, -): CommandResult { - const matched = matchTarget(tr.doc, cmd.target, sel) - let changed = 0 - for (const b of matched) { - if (b.node.type.name !== 'docProtected' || b.node.attrs.blockType !== 'image') continue - const attrs: Record = { ...b.node.attrs } - if (cmd.fields.includes('align')) attrs.imageAlign = cmd.properties.align ?? null - const wantW = cmd.fields.includes('widthPx') ? (cmd.properties.widthPx ?? null) : null - const wantH = cmd.fields.includes('heightPx') ? (cmd.properties.heightPx ?? null) : null - const curW = Number(b.node.attrs.imageWidthPx) || null - const curH = Number(b.node.attrs.imageHeightPx) || null - if (wantW && wantH) { - attrs.imageWidthPx = Math.round(wantW) - attrs.imageHeightPx = Math.round(wantH) - } else if (wantW && curW && curH) { - attrs.imageWidthPx = Math.round(wantW) - attrs.imageHeightPx = Math.round((wantW * curH) / curW) - } else if (wantH && curW && curH) { - attrs.imageHeightPx = Math.round(wantH) - attrs.imageWidthPx = Math.round((wantH * curW) / curH) - } - // save-side patching needs both dimensions; a lone dimension with unknown - // original size cannot be scaled and is skipped - const dirty = Object.keys(attrs).some((k) => attrs[k] !== b.node.attrs[k]) - if (!dirty) continue - tr.setNodeMarkup(b.pos, undefined, attrs) - changed++ - } - return { command: 'updateImageProperties', matched: matched.length, changed, skippedProtected: 0 } -} - -function runInsertToc(tr: Transaction, schema: Schema, cmd: InsertToc): CommandResult { - const blocks = topLevelBlocks(tr.doc) - const entries: TocEntry[] = [] - for (const b of blocks) { - if (b.node.type.name === 'docHeading' && b.node.textContent.trim()) { - entries.push({ level: Number(b.node.attrs.level) || 1, text: b.node.textContent }) - } - } - if (entries.length === 0) { - throw new Error( - 'insertToc: the document has no headings (levels 1-6), cannot generate a table of contents', - ) - } - if (cmd.afterBlockIndex >= blocks.length) { - throw new Error(`insertToc: afterBlockIndex out of range ${cmd.afterBlockIndex}`) - } - // one protected block per TOC line (same shape as the ribbon's TOC button); - // the begin fldChar is dirty so Word recalculates page numbers on open - const nodes = generateTocFieldXml(entries).map((xml, i) => - schema.nodes.docProtected.create({ - docxIndex: null, - blockType: 'passthrough', - label: 'TOC field', - genXml: xml, - fieldDisplay: { kind: 'tocLine', left: entries[i].text, right: '', level: entries[i].level }, - }), - ) - const pos = - cmd.afterBlockIndex === -1 - ? 0 - : blocks[cmd.afterBlockIndex].pos + blocks[cmd.afterBlockIndex].node.nodeSize - tr.insert(pos, nodes) - return { - command: 'insertToc', - matched: entries.length, - changed: nodes.length, - skippedProtected: 0, - } -} - -// ---- entry point ---- - -/** frozen block-index scope -> current PM positions (indexes clamped: AI edits earlier in the run may have shrunk the doc) */ -function frozenSelectionRange( - editor: Editor, - frozen: CommandContext['selection'], -): SelRange | null { - if (!frozen) return null - const last = editor.state.doc.childCount - 1 - const start = Math.min(Math.max(frozen.startIndex, 0), last) - const end = Math.min(Math.max(frozen.endIndex, start), last) - return blockRangePositions(editor, start, end) -} - -function summarize(results: CommandResult[]): string { - const total = results.reduce((sum, r) => sum + r.changed, 0) - if (total === 0) { - const skipped = results.reduce((sum, r) => sum + r.skippedProtected, 0) - return skipped > 0 ? t('aiCmdNoneSkipped', { count: skipped }) : t('aiCmdNone') - } - const parts = results.map((r) => { - let part: string - switch (r.command) { - case 'updateTextStyle': - part = t('aiCmdTextStyle', { count: r.changed }) - break - case 'updateMatchedTextStyle': - part = t('aiCmdMatchedStyle', { count: r.detail ?? '0', blocks: r.changed }) - break - case 'updateParagraphStyle': - part = t('aiCmdParaStyle', { count: r.changed }) - break - case 'setHeadingLevel': - part = t('aiCmdHeading', { count: r.changed }) - break - case 'replaceAllText': - part = t('aiCmdReplaceAll', { - count: r.changed, - detail: r.detail ?? t('aiCmdReplaceFallback'), - }) - break - case 'deleteBlocks': - part = t('aiCmdDeleted', { count: r.changed }) - break - case 'moveBlocks': - part = t('aiCmdMoved', { count: r.changed }) - break - case 'createParagraphBullets': - part = t('aiCmdToList', { count: r.changed }) - break - case 'deleteParagraphBullets': - part = t('aiCmdToBody', { count: r.changed }) - break - case 'updateImageProperties': - part = t('aiCmdImages', { count: r.changed }) - break - case 'insertToc': - part = t('aiCmdToc', { count: r.matched }) - break - default: - part = `${r.command}: ${r.changed}` - } - if (r.skippedProtected > 0) part += t('aiCmdSkipped', { count: r.skippedProtected }) - return part - }) - return parts.join(';') -} - -export function executeCommands( - editor: Editor, - envelope: CommandEnvelope, - context: CommandContext = {}, -): ExecuteOutcome { - const validationError = validateEnvelope(envelope) - if (validationError) return { ok: false, results: [], summary: '', error: validationError } - - const tr = editor.state.tr - const schema = editor.schema - const selection = frozenSelectionRange(editor, context.selection) ?? editor.state.selection - const results: CommandResult[] = [] - try { - for (const command of envelope.commands) { - // selection positions mapped through the steps applied so far - const sel: SelRange = { - from: tr.mapping.map(selection.from), - to: tr.mapping.map(selection.to), - } - if ('updateTextStyle' in command) { - results.push(runUpdateTextStyle(tr, schema, command.updateTextStyle, sel)) - } else if ('updateMatchedTextStyle' in command) { - results.push(runUpdateMatchedTextStyle(tr, schema, command.updateMatchedTextStyle, sel)) - } else if ('updateParagraphStyle' in command) { - results.push(runUpdateParagraphStyle(tr, command.updateParagraphStyle, sel)) - } else if ('setHeadingLevel' in command) { - results.push(runSetHeadingLevel(tr, schema, command.setHeadingLevel, sel)) - } else if ('replaceAllText' in command) { - results.push(runReplaceAllText(tr, schema, command.replaceAllText, sel)) - } else if ('deleteBlocks' in command) { - results.push(runDeleteBlocks(tr, schema, command.deleteBlocks, sel)) - } else if ('createParagraphBullets' in command) { - results.push( - runCreateParagraphBullets(tr, schema, command.createParagraphBullets, sel, context), - ) - } else if ('deleteParagraphBullets' in command) { - results.push(runDeleteParagraphBullets(tr, schema, command.deleteParagraphBullets, sel)) - } else if ('updateImageProperties' in command) { - results.push(runUpdateImageProperties(tr, command.updateImageProperties, sel)) - } else if ('insertToc' in command) { - results.push(runInsertToc(tr, schema, command.insertToc)) - } else { - results.push(runMoveBlocks(tr, command.moveBlocks)) - } - } - } catch (e) { - return { - ok: false, - results: [], - summary: '', - error: e instanceof Error ? e.message : String(e), - } - } - - if (tr.steps.length > 0) { - // route through the TrackChanges recorder so AI format/text edits become - // reviewable revisions under the AI author (same pipeline as manual edits) - const storage = editor.storage.trackChanges as { enabled: boolean; author: string } | undefined - if (context.track && storage) { - const prev = { enabled: storage.enabled, author: storage.author } - storage.enabled = true - storage.author = context.track.author - try { - editor.view.dispatch(tr) - } finally { - storage.enabled = prev.enabled - storage.author = prev.author - } - } else { - editor.view.dispatch(tr) - } - } - return { ok: true, results, summary: summarize(results) } -} diff --git a/apps/docs/src/renderer/ai/doc-utils.ts b/apps/docs/src/renderer/ai/doc-utils.ts new file mode 100644 index 0000000..65adcbc --- /dev/null +++ b/apps/docs/src/renderer/ai/doc-utils.ts @@ -0,0 +1,56 @@ +import type { Editor } from '@tiptap/core' +import type { Node as ProseMirrorNode } from '@tiptap/pm/model' + +/** ProseMirror positions of a top-level child index range */ +export function blockRangePositions( + editor: Editor, + startIndex: number, + endIndex: number, +): { from: number; to: number } { + const doc = editor.state.doc + let from = 0 + let to = 0 + let index = 0 + doc.forEach((node, offset) => { + if (index === startIndex) from = offset + if (index === endIndex) to = offset + node.nodeSize + index++ + }) + return { from, to } +} + +// ---- tracked deletions (pending revisions are not current content) ---- + +const hasDelMark = (node: ProseMirrorNode) => node.marks.some((m) => m.type.name === 'del') + +/** block text as it reads once pending tracked deletions are applied (textContent minus del runs) */ +export function liveText(node: ProseMirrorNode): string { + if ((node.attrs?.blockRevision as { kind?: string } | null)?.kind === 'del') return '' + let out = '' + const walk = (child: ProseMirrorNode): void => { + if (hasDelMark(child)) return + if (child.isText) out += child.text ?? '' + else if (child.isLeaf) out += child.type.spec.leafText?.(child) ?? '' + else child.forEach(walk) + } + node.forEach(walk) + return out +} + +/** + * The whole block is a pending deletion revision (struck through in the editor). + * Checked structurally, not by text length: atom leaves (inline formulas, ruby) + * carry no textContent, so a live formula must still count as live content. + */ +export function isTrackedDeleted(node: ProseMirrorNode): boolean { + if ((node.attrs?.blockRevision as { kind?: string } | null)?.kind === 'del') return true + let hasContent = false + let hasLive = false + node.descendants((child) => { + if (child.isText || (child.isInline && child.isLeaf)) { + hasContent = true + if (!hasDelMark(child)) hasLive = true + } + }) + return hasContent && !hasLive +} diff --git a/apps/docs/src/renderer/ai/docs-skill.ts b/apps/docs/src/renderer/ai/docs-skill.ts index ee6d392..3df0877 100644 --- a/apps/docs/src/renderer/ai/docs-skill.ts +++ b/apps/docs/src/renderer/ai/docs-skill.ts @@ -16,6 +16,9 @@ import { type FrozenSelection, } from './tools' +const IMAGE_GEN_OFF_NOTE = + '\n\nNote: generate_image is currently unavailable (no image provider: signed out of Genspark or cloud tools off, and no media API key in Settings). Do not call or promise it; use image_search for imagery.' + /** * The docx capability as an AgentSkill: document skeleton context, the five * document tools, and the local executor. Future apps register their own @@ -27,6 +30,8 @@ export function createDocsSkill( getTrack?: () => AiTrack | undefined, getComments?: () => AiCommentsAccess | undefined, getHf?: () => AiHeaderFooterAccess | undefined, + /** live predicate (gsk login && cloud-tools toggle, or a BYOK media key); false hides generate_image */ + imageGenAvailable?: () => boolean, ): 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 @@ -34,8 +39,17 @@ export function createDocsSkill( let frozen: FrozenSelection | null = null return { id: 'docx', - systemPrompt: AGENT_SYSTEM_PROMPT, - tools: AGENT_TOOLS, + // live: the predicate is re-read before every model request + get systemPrompt() { + return imageGenAvailable?.() === false + ? AGENT_SYSTEM_PROMPT + IMAGE_GEN_OFF_NOTE + : AGENT_SYSTEM_PROMPT + }, + get tools() { + return imageGenAvailable?.() === false + ? AGENT_TOOLS.filter((t) => t.name !== 'generate_image') + : AGENT_TOOLS + }, buildContext: () => { const editor = getEditor() markDocSeen(editor) // the context the model receives is the freshness baseline for index-addressed writes diff --git a/apps/docs/src/renderer/ai/ops.ts b/apps/docs/src/renderer/ai/ops.ts new file mode 100644 index 0000000..096acda --- /dev/null +++ b/apps/docs/src/renderer/ai/ops.ts @@ -0,0 +1,1421 @@ +import type { Editor } from '@tiptap/core' +import type { Node as PmDocNode, Schema } from '@tiptap/pm/model' +import type { Transaction } from '@tiptap/pm/state' +import { generateTocFieldXml, type TocEntry } from '@genoffice/docx-engine' +import { isEastAsianFontName } from '../font-list' +import { t } from '../i18n/locale' +import { blockRangePositions, isTrackedDeleted, liveText } from './doc-utils' + +/** + * Canonical edit ops for the document. The model (apply_ops) and, later, the + * ribbon issue the same flat `{ op, target, ...fields }` records: a registry + * validates the whole batch up front and applies it as one ProseMirror + * transaction, so one undo reverts the batch. Fields are patches: a present + * key sets the property, null clears it, an absent key leaves it untouched. + * The docx round trip is untouched — changed nodes become dirty via the normal + * signature comparison and regenerate on save; docxIndex anchors are never + * modified here. + */ + +// ---- target ---- + +/** All given conditions filter with AND; at least one condition is required */ +export interface Target { + /** 'image' matches protected image blocks (docProtected + blockType image) */ + nodeType?: 'docHeading' | 'docParagraph' | 'docListItem' | 'image' + /** Restrict heading level (only with nodeType: 'docHeading') */ + headingLevel?: number + /** The block's plain text contains this substring (case-sensitive unless matchCase: false) */ + containsText?: string + matchCase?: boolean + /** By block index (the index output by buildDocumentContext, 0-based, current PM doc top-level order) */ + blockIndexes?: number[] + /** 'selection' = only blocks covered by the current selection (run-level ops narrow to the selected characters); default = whole document */ + scope?: 'selection' | 'document' + /** explicit ProseMirror range standing in for the selection (UI callers that captured a range earlier) */ + range?: { from: number; to: number } +} + +export interface FontFields { + bold?: boolean + italic?: boolean + underline?: boolean + strike?: boolean + color?: string | null + highlight?: string | null + /** points */ + fontSize?: number | null + fontFamily?: string | null + baseline?: 'superscript' | 'subscript' | 'none' | null + link?: { url: string } | null +} + +export interface ParagraphFields { + align?: 'left' | 'center' | 'right' | 'justify' | null + lineSpacing?: number | null + indentLeft?: number | null + indentRight?: number | null + /** twips; positive = first-line indent, negative = hanging indent */ + indentFirstLine?: number | null + spaceBefore?: number | null + spaceAfter?: number | null + pageBreakBefore?: boolean + shadingFill?: string | null + /** Paragraph borders, a subset of "tblr" */ + borders?: string | null +} + +export interface Op { + op: string + target?: Target + [key: string]: unknown +} + +export interface OpContext { + /** numbering context so converted list items join real docx numbering on save */ + numIds?: { bullet: string | null; ordered: string | null } | null + /** record the batch's changes as tracked revisions under this author */ + track?: { author: string } | null + /** + * Selection frozen when the model last saw the doc. scope:'selection' + * resolves against this instead of the live selection, so the user clicking + * elsewhere mid-run cannot retarget the op. from/to (PM positions) keep a + * partial selection character-precise; without them the block range is used. + */ + selection?: { startIndex: number; endIndex: number; from?: number; to?: number } | null + /** who issues the batch: the model (default) or the app's own UI (ribbon, shortcuts, dialogs) */ + source?: 'ai' | 'ui' + /** flag changed blocks with the yellow AI highlight (default: only for source 'ai') */ + markAi?: boolean + /** validate and plan only; nothing is dispatched */ + dryRun?: boolean +} + +/** the changed-block highlight belongs to AI edits only */ +const wantsAiMark = (ctx: OpContext): boolean => ctx.markAi ?? ctx.source !== 'ui' + +export interface OpResult { + op: string + matched: number + changed: number + skippedProtected: number + /** targets skipped because the text is a pending tracked deletion */ + skippedDeleted?: number + detail?: string +} + +export interface ExecuteOutcome { + ok: boolean + results: OpResult[] + summary: string + error?: string + /** one line per op, in order (always on success, alone on dryRun) */ + plan?: string[] +} + +// ---- registry ---- + +interface SelRange { + from: number + to: number +} + +interface RunEnv { + tr: Transaction + schema: Schema + sel: SelRange + ctx: OpContext +} + +interface OpDef { + name: string + /** one-line usage: listed in the tool description, appended to validation errors */ + signature: string + /** keys allowed besides op / target */ + keys: readonly string[] + /** target is required (default), optional, or not accepted */ + target: 'required' | 'optional' | 'none' + /** UI-only: never listed for the model, rejected as unknown when the source is the model */ + hidden?: boolean + validate(op: Op, where: string): string | null + apply(op: Op, env: RunEnv): OpResult +} + +const REGISTRY = new Map() + +function register(def: OpDef): void { + REGISTRY.set(def.name, def) +} + +const callable = () => [...REGISTRY.values()].filter((d) => !d.hidden) + +/** ops the model may call */ +export function opNames(): string[] { + return callable().map((d) => d.name) +} + +export function opSignatures(): string[] { + return callable().map((d) => d.signature) +} + +// ---- validation ---- + +const NODE_TYPES = ['docHeading', 'docParagraph', 'docListItem', 'image'] as const +const BASELINES = ['superscript', 'subscript', 'none'] as const +const ALIGNS = ['left', 'center', 'right', 'justify'] as const +const FONT_KEYS = [ + 'bold', + 'italic', + 'underline', + 'strike', + 'color', + 'highlight', + 'fontSize', + 'fontFamily', + 'baseline', + 'link', +] as const +const PARA_KEYS = [ + 'align', + 'lineSpacing', + 'indentLeft', + 'indentRight', + 'indentFirstLine', + 'spaceBefore', + 'spaceAfter', + 'pageBreakBefore', + 'shadingFill', + 'borders', +] as const +const IMAGE_KEYS = ['widthPx', 'heightPx', 'align'] as const + +function validateTarget(target: unknown, where: string): string | null { + if (!target || typeof target !== 'object') return `${where}: missing target` + const tg = target as Target + if (tg.nodeType !== undefined && !NODE_TYPES.includes(tg.nodeType)) { + return `${where}: unknown nodeType "${String(tg.nodeType)}"` + } + if ( + tg.headingLevel !== undefined && + (!Number.isInteger(tg.headingLevel) || tg.headingLevel < 1 || tg.headingLevel > 6) + ) { + return `${where}: headingLevel must be an integer between 1 and 6` + } + if ( + tg.blockIndexes !== undefined && + (!Array.isArray(tg.blockIndexes) || tg.blockIndexes.some((i) => !Number.isInteger(i) || i < 0)) + ) { + return `${where}: blockIndexes must be an array of non-negative integers` + } + if (tg.range !== undefined) { + const r = tg.range as { from?: unknown; to?: unknown } | null + if (!r || typeof r.from !== 'number' || typeof r.to !== 'number' || r.from > r.to) { + return `${where}: range must be { from, to } positions with from ≤ to` + } + } + const hasCondition = + tg.nodeType !== undefined || + tg.headingLevel !== undefined || + typeof tg.containsText === 'string' || + (Array.isArray(tg.blockIndexes) && tg.blockIndexes.length > 0) || + tg.scope === 'selection' || + tg.range !== undefined + if (!hasCondition) return `${where}: target requires at least one condition` + return null +} + +function validateShape(op: Op, def: OpDef, where: string): string | null { + if (def.target === 'none' && op.target !== undefined) { + return `${where}: does not take a target` + } + if (def.target === 'required' || op.target !== undefined) { + const error = validateTarget(op.target, where) + if (error) return error + } + const unknown = Object.keys(op).filter( + (k) => k !== 'op' && k !== 'target' && !def.keys.includes(k), + ) + if (unknown.length > 0) { + return `${where}: unknown field(s) ${unknown.join(', ')}; allowed: ${def.keys.join(', ')}` + } + return null +} + +const present = (op: Op, keys: readonly string[]): string[] => + keys.filter((k) => op[k] !== undefined) + +const HEX = /^#?([0-9a-f]{6})$/i + +/** "#RRGGBB" or "RRGGBB" -> "RRGGBB"; null passes through */ +function normalizeHex(value: unknown, where: string, field: string): string | null { + if (value === null) return null + const m = typeof value === 'string' ? HEX.exec(value.trim()) : null + if (!m) + throw new Error( + `${where}: ${field} must be a 6-digit hex color like "#1A73E8" (or null to clear)`, + ) + return m[1].toUpperCase() +} + +function checkHex(value: unknown, where: string, field: string): string | null { + try { + normalizeHex(value, where, field) + return null + } catch (e) { + return e instanceof Error ? e.message : String(e) + } +} + +const isNumberOrNull = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v)) +/** a present number must be positive; null (= clear) passes */ +const isPositiveOrNull = (v: unknown) => + v === null || (typeof v === 'number' && Number.isFinite(v) && v > 0) +const isStringOrNull = (v: unknown) => v === null || typeof v === 'string' + +function validateFontFields(op: Op, where: string): string | null { + for (const k of ['bold', 'italic', 'underline', 'strike'] as const) { + if (op[k] !== undefined && typeof op[k] !== 'boolean') return `${where}: ${k} must be a boolean` + } + if (op.color !== undefined) { + const error = checkHex(op.color, where, 'color') + if (error) return error + } + if (op.highlight !== undefined && !isStringOrNull(op.highlight)) { + return `${where}: highlight must be a color name / hex string or null` + } + if (op.fontSize !== undefined && !isPositiveOrNull(op.fontSize)) { + return `${where}: fontSize must be a positive number of points (or null to clear)` + } + if (op.fontFamily !== undefined && !isStringOrNull(op.fontFamily)) { + return `${where}: fontFamily must be a string or null` + } + if ( + op.baseline !== undefined && + op.baseline !== null && + !(BASELINES as readonly string[]).includes(String(op.baseline)) + ) { + return `${where}: baseline must be superscript / subscript / none (or null)` + } + if (op.link !== undefined && op.link !== null) { + const link = op.link as { url?: unknown } + if (!link || typeof link !== 'object' || typeof link.url !== 'string') { + return `${where}: link must be { url } or null` + } + } + if (present(op, FONT_KEYS).length === 0) { + return `${where}: give at least one font field (${FONT_KEYS.join(', ')})` + } + return null +} + +function validateParagraphFields(op: Op, where: string): string | null { + if ( + op.align !== undefined && + op.align !== null && + !(ALIGNS as readonly string[]).includes(String(op.align)) + ) { + return `${where}: align must be left / center / right / justify (or null)` + } + for (const k of [ + 'lineSpacing', + 'indentLeft', + 'indentRight', + 'indentFirstLine', + 'spaceBefore', + 'spaceAfter', + ] as const) { + if (op[k] !== undefined && !isNumberOrNull(op[k])) + return `${where}: ${k} must be a number or null` + } + if (op.pageBreakBefore !== undefined && typeof op.pageBreakBefore !== 'boolean') { + return `${where}: pageBreakBefore must be a boolean` + } + if (op.shadingFill !== undefined) { + const error = checkHex(op.shadingFill, where, 'shadingFill') + if (error) return error + } + if (op.borders !== undefined && op.borders !== null) { + if (typeof op.borders !== 'string' || !/^[tblr]*$/.test(op.borders)) { + return `${where}: borders must be a subset of "tblr" (or null)` + } + } + if (present(op, PARA_KEYS).length === 0) { + return `${where}: give at least one paragraph field (${PARA_KEYS.join(', ')})` + } + return null +} + +function validateAfterBlockIndex(op: Op, where: string): string | null { + if (!Number.isInteger(op.afterBlockIndex) || Number(op.afterBlockIndex) < -1) { + return `${where}: afterBlockIndex must be an integer ≥ -1 (-1 = start of document)` + } + return null +} + +// ---- target matching ---- + +interface TopBlock { + index: number + pos: number + node: PmDocNode + /** absolute range of the selected characters inside this block (partial selection); run-level ops stay inside it */ + clip?: SelRange +} + +function topLevelBlocks(doc: PmDocNode): TopBlock[] { + const out: TopBlock[] = [] + let index = 0 + doc.forEach((node, offset) => { + out.push({ index, pos: offset, node }) + index++ + }) + return out +} + +function blockText(node: PmDocNode): string { + if (node.type.name === 'docProtected') { + return [node.attrs.label, node.attrs.previewText].filter(Boolean).join(' ') + } + // match against current content only, or targets would hit already-deleted revision text + return liveText(node) +} + +function matchTarget(doc: PmDocNode, target: Target, sel: SelRange): TopBlock[] { + return topLevelBlocks(doc).filter((b) => { + if (target.blockIndexes && !target.blockIndexes.includes(b.index)) return false + if (target.nodeType === 'image') { + if (b.node.type.name !== 'docProtected' || b.node.attrs.blockType !== 'image') return false + } else if (target.nodeType && b.node.type.name !== target.nodeType) { + return false + } + if (target.headingLevel !== undefined) { + if (b.node.type.name !== 'docHeading') return false + if (Number(b.node.attrs.level) !== target.headingLevel) return false + } + if (target.containsText) { + const text = blockText(b.node) + const hit = + target.matchCase === false + ? text.toLowerCase().includes(target.containsText.toLowerCase()) + : text.includes(target.containsText) + if (!hit) return false + } + const scoped = scopedRange(target, sel) + if (scoped) { + const from = b.pos + const to = b.pos + b.node.nodeSize + const overlaps = to > scoped.from && from < scoped.to + const caretInside = scoped.from === scoped.to && scoped.from >= from && scoped.from <= to + if (!overlaps && !caretInside) return false + if (overlaps && scoped.from < scoped.to && b.node.isTextblock) { + const contentFrom = from + 1 + const contentTo = contentFrom + b.node.content.size + const clipFrom = Math.max(scoped.from, contentFrom) + const clipTo = Math.min(scoped.to, contentTo) + if (clipFrom > contentFrom || clipTo < contentTo) b.clip = { from: clipFrom, to: clipTo } + } + } + return true + }) +} + +/** the range a selection-style target resolves against: an explicit range, else the (frozen or live) selection */ +function scopedRange(target: Target, sel: SelRange): SelRange | null { + if (target.range) return target.range + return target.scope === 'selection' ? sel : null +} + +const PARAGRAPH_TYPES = new Set(['docParagraph', 'docHeading', 'docListItem']) + +interface ParagraphHit { + node: PmDocNode + pos: number +} + +/** + * Paragraph-like nodes an op formats inside a matched block: the block itself + * when it is a text block; for containers (tables) the nested paragraphs, kept + * to the scoped range when the target is selection-based — the ribbon's + * "align" inside a table cell must reach that cell's paragraph only. + */ +function paragraphsIn(b: TopBlock, scoped: SelRange | null): ParagraphHit[] { + if (b.node.type.name === 'docProtected') return [] + if (b.node.isTextblock) return [{ node: b.node, pos: b.pos }] + const hits: ParagraphHit[] = [] + b.node.descendants((node, offset) => { + if (!PARAGRAPH_TYPES.has(node.type.name)) return true + const pos = b.pos + 1 + offset + const end = pos + node.nodeSize + if (scoped) { + const overlaps = end > scoped.from && pos < scoped.to + const caretInside = scoped.from === scoped.to && scoped.from >= pos && scoped.from <= end + if (!overlaps && !caretInside) return false + } + hits.push({ node, pos }) + return false + }) + return hits +} + +/** true when [from, to) lies inside the block's selected span (no clip = whole block is fair game) */ +function insideClip(b: TopBlock, from: number, to: number): boolean { + return !b.clip || (from >= b.clip.from && to <= b.clip.to) +} + +const targetOf = (op: Op): Target => op.target as Target + +// ---- executors (each reads tr.doc fresh, so sequential ops compose) ---- + +const BOOL_MARK_TYPES: Record = { + bold: 'bold', + italic: 'italic', + underline: 'underline', + strike: 'strike', +} + +/** attrs for a block the op changed: the AI highlight rides along unless the caller opted out */ +function changedAttrs(ctx: OpContext, attrs: Record): Record { + return wantsAiMark(ctx) ? { ...attrs, aiChanged: true } : attrs +} + +function markChanged(tr: Transaction, pos: number, ctx: OpContext): void { + if (!wantsAiMark(ctx)) return + const node = tr.doc.nodeAt(pos) + if (node) tr.setNodeMarkup(pos, undefined, { ...node.attrs, aiChanged: true }) +} + +/** + * Patch paragraph attrs on every paragraph the matched blocks contain. The one + * implementation behind the model's setParagraphFormat and the ribbon's + * setParagraphAttrs; `imageAlign` (UI alignment) also lands on matched image + * blocks as their w:jc. An explicit spacing value turns Word's "Auto" spacing off. + */ +function applyParagraphPatch( + env: RunEnv, + op: Op, + patch: Record, + imageAlign?: unknown, +): OpResult { + const { tr, ctx, sel } = env + const target = targetOf(op) + const matched = matchTarget(tr.doc, target, sel) + const scoped = scopedRange(target, sel) + if ('spaceBefore' in patch && !('spaceBeforeAuto' in patch)) patch.spaceBeforeAuto = false + if ('spaceAfter' in patch && !('spaceAfterAuto' in patch)) patch.spaceAfterAuto = false + let changed = 0 + let skippedProtected = 0 + for (const b of matched) { + if (b.node.type.name === 'docProtected') { + if (imageAlign !== undefined && b.node.attrs.blockType === 'image') { + const align = imageAlign ?? null + if (b.node.attrs.imageAlign !== align) { + tr.setNodeMarkup(b.pos, undefined, { ...b.node.attrs, imageAlign: align }) + changed++ + } + } else { + skippedProtected++ + } + continue + } + for (const p of paragraphsIn(b, scoped)) { + const attrs = { ...p.node.attrs, ...patch } + const dirty = Object.keys(patch).some((k) => attrs[k] !== p.node.attrs[k]) + if (!dirty) continue + tr.setNodeMarkup(p.pos, undefined, changedAttrs(ctx, attrs)) + changed++ + } + } + return { op: op.op, matched: matched.length, changed, skippedProtected } +} + +/** patch applied onto each text node's existing docTextStyle attrs (fonts route to their rFonts slot) */ +function buildTextMarkPatch(op: Op): Record { + const patch: Record = {} + if (op.fontFamily !== undefined) { + // route to the matching rFonts slot; clearing clears both + const v = op.fontFamily as string | null + if (!v) Object.assign(patch, { font: null, fontAscii: null }) + else if (isEastAsianFontName(v)) patch.font = v + else patch.fontAscii = v + } + if (op.color !== undefined) patch.color = normalizeHex(op.color, op.op, 'color') + if (op.highlight !== undefined) patch.highlight = op.highlight ?? null + if (op.fontSize !== undefined) { + patch.sizeHalfPoints = op.fontSize === null ? null : Math.round((op.fontSize as number) * 2) + } + if (op.baseline !== undefined) { + const v = op.baseline + patch.vertAlign = v === 'superscript' || v === 'subscript' ? v : null + } + return patch +} + +/** apply the op's mark-level font fields to [from, to) of a block's text nodes */ +function applyFontRange( + env: RunEnv, + op: Op, + boolKeys: string[], + markPatch: Record, + from: number, + to: number, + node: PmDocNode, + contentFrom: number, +): void { + const { tr, schema } = env + for (const k of boolKeys) { + const markType = schema.marks[BOOL_MARK_TYPES[k]] + if (op[k]) tr.addMark(from, to, markType.create()) + else tr.removeMark(from, to, markType) + } + if (op.link !== undefined) { + const url = (op.link as { url?: string } | null)?.url + if (url) tr.addMark(from, to, schema.marks.link.create({ href: url, rId: null })) + else tr.removeMark(from, to, schema.marks.link) + } + if (Object.keys(markPatch).length === 0) return + // merge per text node: only the given attrs change, the rest survive + node.forEach((child, offset) => { + if (!child.isText) return + const childFrom = Math.max(contentFrom + offset, from) + const childTo = Math.min(contentFrom + offset + child.nodeSize, to) + if (childFrom >= childTo) return + const existing = child.marks.find((m) => m.type.name === 'docTextStyle')?.attrs ?? {} + // spread keeps every non-listed attr (fontAscii/styleId/rawRPr…) alive + const merged: Record = { ...existing, ...markPatch } + const empty = Object.values(merged).every((v) => v === null) + if (empty) tr.removeMark(childFrom, childTo, schema.marks.docTextStyle) + else tr.addMark(childFrom, childTo, schema.marks.docTextStyle.create(merged)) + }) +} + +function runSetFont(op: Op, env: RunEnv): OpResult { + const { tr, ctx, sel } = env + const matched = matchTarget(tr.doc, targetOf(op), sel) + const boolKeys = present(op, Object.keys(BOOL_MARK_TYPES)) + const markPatch = buildTextMarkPatch(op) + let changed = 0 + let skippedProtected = 0 + for (const b of matched) { + if (b.node.type.name === 'docProtected') { + skippedProtected++ + continue + } + const before = b.node + const contentFrom = b.pos + 1 + const from = b.clip?.from ?? contentFrom + const to = b.clip?.to ?? contentFrom + b.node.content.size + if (from < to) applyFontRange(env, op, boolKeys, markPatch, from, to, b.node, contentFrom) + const after = tr.doc.nodeAt(b.pos) + if (after && !after.eq(before)) { + changed++ + markChanged(tr, b.pos, ctx) + } + } + return { op: 'setFont', matched: matched.length, changed, skippedProtected } +} + +function runSetParagraphFormat(op: Op, env: RunEnv): OpResult { + const patch: Record = {} + for (const k of present(op, PARA_KEYS)) { + if (k === 'shadingFill') patch.shadingFill = normalizeHex(op.shadingFill, op.op, 'shadingFill') + else if (k === 'pageBreakBefore') patch.pageBreakBefore = op.pageBreakBefore === true + else patch[k] = op[k] ?? null + } + return applyParagraphPatch(env, op, patch) +} + +/** UI: raw paragraph attrs (any schema attr, e.g. lineRule / tabStops / dropCap); align also lands on images */ +function runSetParagraphAttrs(op: Op, env: RunEnv): OpResult { + const attrs = { ...(op.attrs as Record) } + return applyParagraphPatch(env, op, attrs, 'align' in attrs ? attrs.align : undefined) +} + +/** Word's ribbon indent step: half an inch, in twips */ +const INDENT_STEP = 720 + +/** UI: ribbon increase/decrease indent — list items change level, paragraphs and headings snap to the next half-inch stop */ +function runStepIndent(op: Op, env: RunEnv): OpResult { + const { tr, ctx, sel } = env + const delta = Number(op.delta) + const target = targetOf(op) + const matched = matchTarget(tr.doc, target, sel) + const scoped = scopedRange(target, sel) + let changed = 0 + for (const b of matched) { + for (const p of paragraphsIn(b, scoped)) { + if (p.node.type.name === 'docListItem') { + const ilvl = Number(p.node.attrs.ilvl) || 0 + const next = Math.min(Math.max(ilvl + delta, 0), 8) + if (next === ilvl) continue + tr.setNodeMarkup(p.pos, undefined, changedAttrs(ctx, { ...p.node.attrs, ilvl: next })) + changed++ + continue + } + const cur = Number(p.node.attrs.indentLeft) || 0 + const next = + delta > 0 + ? Math.floor(cur / INDENT_STEP) * INDENT_STEP + INDENT_STEP + : Math.max(Math.ceil(cur / INDENT_STEP) * INDENT_STEP - INDENT_STEP, 0) + if (next === cur) continue + tr.setNodeMarkup( + p.pos, + undefined, + changedAttrs(ctx, { ...p.node.attrs, indentLeft: next || null }), + ) + changed++ + } + } + return { op: 'stepIndent', matched: matched.length, changed, skippedProtected: 0 } +} + +/** + * UI: Word's Ctrl+T / Ctrl+Shift+T — a hanging indent moves the left indent one + * stop right while pulling the first line back by the same amount, so + * continuation lines sit under the body text; the reverse walks it back and + * only clears the negative first line once the left indent is home. + */ +function runStepHangingIndent(op: Op, env: RunEnv): OpResult { + const { tr, ctx, sel } = env + const delta = Number(op.delta) + const target = targetOf(op) + const matched = matchTarget(tr.doc, target, sel) + const scoped = scopedRange(target, sel) + let changed = 0 + for (const b of matched) { + for (const p of paragraphsIn(b, scoped)) { + const left = Number(p.node.attrs.indentLeft) || 0 + const nextLeft = Math.max( + delta > 0 + ? Math.floor(left / INDENT_STEP) * INDENT_STEP + INDENT_STEP + : Math.ceil(left / INDENT_STEP) * INDENT_STEP - INDENT_STEP, + 0, + ) + const nextHanging = nextLeft > 0 ? -Math.min(nextLeft, INDENT_STEP) : 0 + if (nextLeft === left && nextHanging === (Number(p.node.attrs.indentFirstLine) || 0)) continue + tr.setNodeMarkup( + p.pos, + undefined, + changedAttrs(ctx, { + ...p.node.attrs, + indentLeft: nextLeft || null, + indentFirstLine: nextHanging || null, + }), + ) + changed++ + } + } + return { op: 'stepHangingIndent', matched: matched.length, changed, skippedProtected: 0 } +} + +function runSetHeadingLevel(op: Op, env: RunEnv): OpResult { + const { tr, schema, ctx, sel } = env + const level = Number(op.level) + const matched = matchTarget(tr.doc, targetOf(op), sel) + let changed = 0 + let skippedProtected = 0 + for (const b of matched) { + if (b.node.type.name === 'docProtected') { + skippedProtected++ + continue + } + const isHeading = b.node.type.name === 'docHeading' + if (level === 0 && b.node.type.name === 'docParagraph') continue + if (level > 0 && isHeading && Number(b.node.attrs.level) === level) continue + const type = level === 0 ? schema.nodes.docParagraph : schema.nodes.docHeading + // styleId is tied to the old block role; generate.ts picks heading styles by level + const attrs: Record = { ...b.node.attrs, styleId: null } + if (level > 0) attrs.level = level + tr.setNodeMarkup(b.pos, type, changedAttrs(ctx, attrs)) + changed++ + } + return { op: 'setHeadingLevel', matched: matched.length, changed, skippedProtected } +} + +function runFindReplace(op: Op, env: RunEnv): OpResult { + const { tr, schema, ctx, sel } = env + const find = String(op.find) + const replace = String(op.replace ?? '') + const matchCase = op.matchCase !== false + const needle = matchCase ? find : find.toLowerCase() + const blocks = op.target ? matchTarget(tr.doc, targetOf(op), sel) : topLevelBlocks(tr.doc) + const replacements: Array<{ from: number; to: number; marks: PmDocNode['marks'] }> = [] + const touchedIndexes = new Set() + let skippedProtected = 0 + let skippedDeleted = 0 + + for (const b of blocks) { + if (b.node.type.name === 'docProtected') { + if (blockText(b.node).includes(find)) skippedProtected++ + continue + } + const blockDeleted = isTrackedDeleted(b.node) + b.node.forEach((child, offset) => { + if (!child.isText || !child.text) return + const struck = blockDeleted || child.marks.some((m) => m.type.name === 'del') + const hay = matchCase ? child.text : child.text.toLowerCase() + let at = hay.indexOf(needle) + while (at !== -1) { + const from = b.pos + 1 + offset + at + if (struck) { + skippedDeleted++ + } else if (insideClip(b, from, from + needle.length)) { + replacements.push({ from, to: from + needle.length, marks: child.marks }) + touchedIndexes.add(b.index) + } + at = hay.indexOf(needle, at + needle.length) + } + }) + } + + // apply back-to-front so earlier positions stay valid + for (const r of [...replacements].reverse()) { + if (replace) tr.replaceWith(r.from, r.to, schema.text(replace, r.marks)) + else tr.delete(r.from, r.to) + } + if (touchedIndexes.size > 0) { + for (const b of topLevelBlocks(tr.doc)) { + if (touchedIndexes.has(b.index)) markChanged(tr, b.pos, ctx) + } + } + return { + op: 'findReplace', + matched: touchedIndexes.size, + changed: touchedIndexes.size, + skippedProtected, + skippedDeleted, + detail: t('aiCmdReplacedCount', { count: replacements.length }), + } +} + +function runSetMatchedFont(op: Op, env: RunEnv): OpResult { + const { tr, ctx, sel } = env + const text = String(op.text) + const matchCase = op.matchCase !== false + const needle = matchCase ? text : text.toLowerCase() + const blocks = op.target ? matchTarget(tr.doc, targetOf(op), sel) : topLevelBlocks(tr.doc) + const boolKeys = present(op, Object.keys(BOOL_MARK_TYPES)) + const markPatch = buildTextMarkPatch(op) + const touched = new Set() + let styledCount = 0 + let skippedProtected = 0 + let skippedDeleted = 0 + + for (const b of blocks) { + if (b.node.type.name === 'docProtected') { + if (blockText(b.node).includes(text)) skippedProtected++ + continue + } + const blockDeleted = isTrackedDeleted(b.node) + const contentFrom = b.pos + 1 + b.node.forEach((child, offset) => { + if (!child.isText || !child.text) return + const struck = blockDeleted || child.marks.some((m) => m.type.name === 'del') + const hay = matchCase ? child.text : child.text.toLowerCase() + let at = hay.indexOf(needle) + while (at !== -1) { + const from = contentFrom + offset + at + const to = from + needle.length + if (struck) { + skippedDeleted++ + } else if (insideClip(b, from, to)) { + applyFontRange(env, op, boolKeys, markPatch, from, to, b.node, contentFrom) + styledCount++ + touched.add(b.index) + } + at = hay.indexOf(needle, at + needle.length) + } + }) + } + // mark steps never shift positions, so block offsets are still valid here + for (const b of topLevelBlocks(tr.doc)) { + if (touched.has(b.index)) markChanged(tr, b.pos, ctx) + } + return { + op: 'setMatchedFont', + matched: touched.size, + changed: touched.size, + skippedProtected, + skippedDeleted, + detail: String(styledCount), + } +} + +function runDeleteBlocks(op: Op, env: RunEnv): OpResult { + const { tr, schema, sel } = env + const blocks = topLevelBlocks(tr.doc) + const matchedAll = matchTarget(tr.doc, targetOf(op), sel) + // a block that is already a pending deletion cannot be deleted again; + // skip and report so the model does not retry forever + const matched = matchedAll.filter((b) => !isTrackedDeleted(b.node)) + const skippedDeleted = matchedAll.length - matched.length + if (matched.length === blocks.length && matched.length > 0) { + // doc requires block+: deleting everything leaves one empty paragraph + tr.replaceWith(0, tr.doc.content.size, schema.nodes.docParagraph.create()) + } else { + for (const b of [...matched].sort((a, z) => z.pos - a.pos)) { + tr.delete(b.pos, b.pos + b.node.nodeSize) + } + } + return { + op: 'deleteBlocks', + matched: matchedAll.length, + changed: matched.length, + skippedProtected: 0, + skippedDeleted, + } +} + +function runMoveBlocks(op: Op, env: RunEnv): OpResult { + const { tr, ctx } = env + const blockIndexes = op.blockIndexes as number[] + const afterBlockIndex = Number(op.afterBlockIndex) + const blocks = topLevelBlocks(tr.doc) + const movedSet = new Set(blockIndexes) + const outOfRange = blockIndexes.filter((i) => i >= blocks.length) + if (outOfRange.length > 0) { + throw new Error(`moveBlocks: block indexes out of range ${outOfRange.join(', ')}`) + } + if (afterBlockIndex >= blocks.length) { + throw new Error(`moveBlocks: afterBlockIndex out of range ${afterBlockIndex}`) + } + if (movedSet.has(afterBlockIndex)) { + throw new Error('moveBlocks: afterBlockIndex must not be one of the moved blocks') + } + + // moved blocks keep document order; aiChanged marks the landing highlight + const moved = [...movedSet] + .sort((a, z) => a - z) + .map((i) => { + const node = blocks[i].node + if (node.type.name === 'docProtected' || !wantsAiMark(ctx)) return node + return node.type.create({ ...node.attrs, aiChanged: true }, node.content, node.marks) + }) + const rest = blocks.filter((b) => !movedSet.has(b.index)) + let insertAt = 0 + if (afterBlockIndex >= 0) { + insertAt = rest.findIndex((b) => b.index === afterBlockIndex) + 1 + } + const children = [ + ...rest.slice(0, insertAt).map((b) => b.node), + ...moved, + ...rest.slice(insertAt).map((b) => b.node), + ] + tr.replaceWith(0, tr.doc.content.size, children) + return { op: 'moveBlocks', matched: moved.length, changed: moved.length, skippedProtected: 0 } +} + +function runSetList(op: Op, env: RunEnv): OpResult { + const { tr, schema, ctx, sel } = env + const matched = matchTarget(tr.doc, targetOf(op), sel) + const kind = op.kind === 'number' ? 'ordered' : 'bullet' + const numId = ctx.numIds?.[kind] ?? null + let changed = 0 + let skippedProtected = 0 + for (const b of matched) { + if (b.node.type.name === 'docProtected') { + skippedProtected++ + continue + } + // headings keep their role; converting them to list items would drop the level + if (b.node.type.name === 'docHeading') continue + if (b.node.type.name === 'docListItem') { + if (b.node.attrs.kind === kind) continue + tr.setNodeMarkup( + b.pos, + undefined, + changedAttrs(ctx, { ...b.node.attrs, kind, numId: numId ?? b.node.attrs.numId }), + ) + changed++ + continue + } + tr.setNodeMarkup( + b.pos, + schema.nodes.docListItem, + changedAttrs(ctx, { ...b.node.attrs, styleId: null, kind, numId, ilvl: 0 }), + ) + changed++ + } + return { op: 'setList', matched: matched.length, changed, skippedProtected } +} + +function runClearList(op: Op, env: RunEnv): OpResult { + const { tr, schema, ctx, sel } = env + const matched = matchTarget(tr.doc, targetOf(op), sel) + let changed = 0 + let skippedProtected = 0 + for (const b of matched) { + if (b.node.type.name === 'docProtected') { + skippedProtected++ + continue + } + if (b.node.type.name !== 'docListItem') continue + tr.setNodeMarkup( + b.pos, + schema.nodes.docParagraph, + changedAttrs(ctx, { ...b.node.attrs, styleId: null }), + ) + changed++ + } + return { op: 'clearList', matched: matched.length, changed, skippedProtected } +} + +function runSetImageProperties(op: Op, env: RunEnv): OpResult { + const { tr, sel } = env + const matched = matchTarget(tr.doc, targetOf(op), sel) + let changed = 0 + for (const b of matched) { + if (b.node.type.name !== 'docProtected' || b.node.attrs.blockType !== 'image') continue + const attrs: Record = { ...b.node.attrs } + if (op.align !== undefined) attrs.imageAlign = op.align ?? null + const wantW = (op.widthPx as number | null | undefined) ?? null + const wantH = (op.heightPx as number | null | undefined) ?? null + const curW = Number(b.node.attrs.imageWidthPx) || null + const curH = Number(b.node.attrs.imageHeightPx) || null + if (wantW && wantH) { + attrs.imageWidthPx = Math.round(wantW) + attrs.imageHeightPx = Math.round(wantH) + } else if (wantW && curW && curH) { + attrs.imageWidthPx = Math.round(wantW) + attrs.imageHeightPx = Math.round((wantW * curH) / curW) + } else if (wantH && curW && curH) { + attrs.imageHeightPx = Math.round(wantH) + attrs.imageWidthPx = Math.round((wantH * curW) / curH) + } + // save-side patching needs both dimensions; a lone dimension with unknown + // original size cannot be scaled and is skipped + const dirty = Object.keys(attrs).some((k) => attrs[k] !== b.node.attrs[k]) + if (!dirty) continue + tr.setNodeMarkup(b.pos, undefined, attrs) + changed++ + } + return { op: 'setImageProperties', matched: matched.length, changed, skippedProtected: 0 } +} + +function runInsertToc(op: Op, env: RunEnv): OpResult { + const { tr, schema } = env + const afterBlockIndex = Number(op.afterBlockIndex) + const blocks = topLevelBlocks(tr.doc) + const entries: TocEntry[] = [] + for (const b of blocks) { + if (b.node.type.name === 'docHeading' && b.node.textContent.trim()) { + entries.push({ level: Number(b.node.attrs.level) || 1, text: b.node.textContent }) + } + } + if (entries.length === 0) { + throw new Error( + 'insertToc: the document has no headings (levels 1-6), cannot generate a table of contents', + ) + } + if (afterBlockIndex >= blocks.length) { + throw new Error(`insertToc: afterBlockIndex out of range ${afterBlockIndex}`) + } + // one protected block per TOC line (same shape as the ribbon's TOC button); + // the begin fldChar is dirty so Word recalculates page numbers on open + const nodes = generateTocFieldXml(entries).map((xml, i) => + schema.nodes.docProtected.create({ + docxIndex: null, + blockType: 'passthrough', + label: 'TOC field', + genXml: xml, + fieldDisplay: { kind: 'tocLine', left: entries[i].text, right: '', level: entries[i].level }, + }), + ) + const pos = + afterBlockIndex === -1 ? 0 : blocks[afterBlockIndex].pos + blocks[afterBlockIndex].node.nodeSize + tr.insert(pos, nodes) + return { op: 'insertToc', matched: entries.length, changed: nodes.length, skippedProtected: 0 } +} + +// ---- op definitions ---- + +const FONT_SIGNATURE_FIELDS = + 'bold?, italic?, underline?, strike?, color?: "#RRGGBB"|null, highlight?, fontSize?: pt|null, fontFamily?: string|null, baseline?: "superscript"|"subscript"|"none"|null, link?: {url}|null' + +register({ + name: 'setFont', + signature: `{ op: "setFont", target, ${FONT_SIGNATURE_FIELDS} } // run-level style of the targeted blocks (only the selected characters when the target is a partial selection); a present field is set, null clears it, absent fields stay; fontFamily applies to its own script slot (an East Asian font keeps the run's Latin font and vice versa)`, + keys: FONT_KEYS, + target: 'required', + validate(op, where) { + return validateShape(op, this, where) ?? validateFontFields(op, where) + }, + apply: runSetFont, +}) + +register({ + name: 'setMatchedFont', + signature: `{ op: "setMatchedFont", text, matchCase?, target?, ${FONT_SIGNATURE_FIELDS} } // character-level: styles only the occurrences of text (not the whole block); target narrows the scanned blocks, omitted = whole document`, + keys: ['text', 'matchCase', ...FONT_KEYS], + target: 'optional', + validate(op, where) { + const shape = validateShape(op, this, where) + if (shape) return shape + if (typeof op.text !== 'string' || op.text === '') return `${where}: text must not be empty` + if (op.matchCase !== undefined && typeof op.matchCase !== 'boolean') { + return `${where}: matchCase must be a boolean` + } + return validateFontFields(op, where) + }, + apply: runSetMatchedFont, +}) + +register({ + name: 'setParagraphFormat', + signature: + '{ op: "setParagraphFormat", target, align?: "left"|"center"|"right"|"justify"|null, lineSpacing?, indentLeft?, indentRight?, indentFirstLine?, spaceBefore?, spaceAfter?, pageBreakBefore?: boolean, shadingFill?: "#RRGGBB"|null, borders?: subset of "tblr"|null } // paragraph format of the targeted blocks (whole blocks, even for a partial selection); lengths in twips, lineSpacing as a multiple; indentFirstLine positive = first-line indent, negative = hanging; a two-character CJK indent ≈ font size in pt × 40 twips', + keys: PARA_KEYS, + target: 'required', + validate(op, where) { + return validateShape(op, this, where) ?? validateParagraphFields(op, where) + }, + apply: runSetParagraphFormat, +}) + +register({ + name: 'setHeadingLevel', + signature: '{ op: "setHeadingLevel", target, level: 0-6 } // 0 = demote to body paragraph', + keys: ['level'], + target: 'required', + validate(op, where) { + const shape = validateShape(op, this, where) + if (shape) return shape + if (!Number.isInteger(op.level) || Number(op.level) < 0 || Number(op.level) > 6) { + return `${where}: level must be an integer between 0 and 6` + } + return null + }, + apply: runSetHeadingLevel, +}) + +register({ + name: 'findReplace', + signature: + '{ op: "findReplace", find, replace, matchCase?, target? } // plain-text find & replace inside runs (no cross-block matching); the replacement keeps the matched text\'s formatting — the right op for small in-place fixes; target narrows the scanned blocks (blockIndexes / scope:"selection" / nodeType), omitted = whole document', + keys: ['find', 'replace', 'matchCase'], + target: 'optional', + validate(op, where) { + const shape = validateShape(op, this, where) + if (shape) return shape + if (typeof op.find !== 'string' || op.find === '') return `${where}: find must not be empty` + if (typeof op.replace !== 'string') + return `${where}: replace must be a string (empty deletes the match)` + if (op.matchCase !== undefined && typeof op.matchCase !== 'boolean') { + return `${where}: matchCase must be a boolean` + } + return null + }, + apply: runFindReplace, +}) + +register({ + name: 'deleteBlocks', + signature: '{ op: "deleteBlocks", target }', + keys: [], + target: 'required', + validate(op, where) { + return validateShape(op, this, where) + }, + apply: runDeleteBlocks, +}) + +register({ + name: 'moveBlocks', + signature: + '{ op: "moveBlocks", blockIndexes: number[], afterBlockIndex } // move the blocks (relative order kept) after afterBlockIndex; -1 = start of document', + keys: ['blockIndexes', 'afterBlockIndex'], + target: 'none', + validate(op, where) { + const shape = validateShape(op, this, where) + if (shape) return shape + const indexes = op.blockIndexes + if ( + !Array.isArray(indexes) || + indexes.length === 0 || + indexes.some((i) => !Number.isInteger(i) || Number(i) < 0) + ) { + return `${where}: blockIndexes must be a non-empty array of non-negative integers` + } + return validateAfterBlockIndex(op, where) + }, + apply: runMoveBlocks, +}) + +register({ + name: 'setList', + signature: + '{ op: "setList", target, kind?: "bullet"|"number" } // paragraphs to list items (default bullet); heading blocks are not converted', + keys: ['kind'], + target: 'required', + validate(op, where) { + const shape = validateShape(op, this, where) + if (shape) return shape + if (op.kind !== undefined && op.kind !== 'bullet' && op.kind !== 'number') { + return `${where}: kind must be "bullet" or "number"` + } + return null + }, + apply: runSetList, +}) + +register({ + name: 'clearList', + signature: '{ op: "clearList", target } // list items back to body paragraphs', + keys: [], + target: 'required', + validate(op, where) { + return validateShape(op, this, where) + }, + apply: runClearList, +}) + +register({ + name: 'setImageProperties', + signature: + '{ op: "setImageProperties", target, widthPx?, heightPx?, align?: "left"|"center"|"right"|null } // image blocks only (target nodeType "image"); giving one dimension scales the other proportionally', + keys: IMAGE_KEYS, + target: 'required', + validate(op, where) { + const shape = validateShape(op, this, where) + if (shape) return shape + for (const k of ['widthPx', 'heightPx'] as const) { + if (op[k] !== undefined && !isPositiveOrNull(op[k])) { + return `${where}: ${k} must be a positive number (or null)` + } + } + if ( + op.align !== undefined && + op.align !== null && + !['left', 'center', 'right'].includes(String(op.align)) + ) { + return `${where}: align must be left / center / right (or null)` + } + if (present(op, IMAGE_KEYS).length === 0) { + return `${where}: give at least one of ${IMAGE_KEYS.join(', ')}` + } + return null + }, + apply: runSetImageProperties, +}) + +register({ + name: 'insertToc', + signature: + '{ op: "insertToc", afterBlockIndex } // insert a TOC field after that block (-1 = start of document); entries come from the current headings, Word computes page numbers on open; fails if the document has no headings', + keys: ['afterBlockIndex'], + target: 'none', + validate(op, where) { + return validateShape(op, this, where) ?? validateAfterBlockIndex(op, where) + }, + apply: runInsertToc, +}) + +// ---- UI-only ops (same executor, same target resolution, never offered to the model) ---- + +const validDelta = (op: Op, where: string): string | null => + op.delta === 1 || op.delta === -1 ? null : `${where}: delta must be 1 or -1` + +register({ + name: 'setParagraphAttrs', + signature: '{ op: "setParagraphAttrs", target, attrs: Record }', + keys: ['attrs'], + target: 'required', + hidden: true, + validate(op, where) { + const shape = validateShape(op, this, where) + if (shape) return shape + if (!op.attrs || typeof op.attrs !== 'object' || Object.keys(op.attrs).length === 0) { + return `${where}: attrs must be a non-empty object` + } + return null + }, + apply: runSetParagraphAttrs, +}) + +register({ + name: 'stepIndent', + signature: '{ op: "stepIndent", target, delta: 1|-1 }', + keys: ['delta'], + target: 'required', + hidden: true, + validate(op, where) { + return validateShape(op, this, where) ?? validDelta(op, where) + }, + apply: runStepIndent, +}) + +register({ + name: 'stepHangingIndent', + signature: '{ op: "stepHangingIndent", target, delta: 1|-1 }', + keys: ['delta'], + target: 'required', + hidden: true, + validate(op, where) { + return validateShape(op, this, where) ?? validDelta(op, where) + }, + apply: runStepHangingIndent, +}) + +// ---- entry point ---- + +/** frozen scope -> current PM positions: exact positions when captured, else the block range (indexes clamped: AI edits earlier in the run may have shrunk the doc) */ +function frozenSelectionRange(editor: Editor, frozen: OpContext['selection']): SelRange | null { + if (!frozen) return null + if (frozen.from !== undefined && frozen.to !== undefined) { + const size = editor.state.doc.content.size + const from = Math.min(Math.max(frozen.from, 0), size) + return { from, to: Math.min(Math.max(frozen.to, from), size) } + } + const last = editor.state.doc.childCount - 1 + const start = Math.min(Math.max(frozen.startIndex, 0), last) + const end = Math.min(Math.max(frozen.endIndex, start), last) + return blockRangePositions(editor, start, end) +} + +function summarize(results: OpResult[]): string { + const total = results.reduce((sum, r) => sum + r.changed, 0) + if (total === 0) { + const skipped = results.reduce((sum, r) => sum + r.skippedProtected, 0) + return skipped > 0 ? t('aiCmdNoneSkipped', { count: skipped }) : t('aiCmdNone') + } + const parts = results.map((r) => { + let part: string + switch (r.op) { + case 'setFont': + part = t('aiCmdTextStyle', { count: r.changed }) + break + case 'setMatchedFont': + part = t('aiCmdMatchedStyle', { count: r.detail ?? '0', blocks: r.changed }) + break + case 'setParagraphFormat': + part = t('aiCmdParaStyle', { count: r.changed }) + break + case 'setHeadingLevel': + part = t('aiCmdHeading', { count: r.changed }) + break + case 'findReplace': + part = t('aiCmdReplaceAll', { + count: r.changed, + detail: r.detail ?? t('aiCmdReplaceFallback'), + }) + break + case 'deleteBlocks': + part = t('aiCmdDeleted', { count: r.changed }) + break + case 'moveBlocks': + part = t('aiCmdMoved', { count: r.changed }) + break + case 'setList': + part = t('aiCmdToList', { count: r.changed }) + break + case 'clearList': + part = t('aiCmdToBody', { count: r.changed }) + break + case 'setImageProperties': + part = t('aiCmdImages', { count: r.changed }) + break + case 'insertToc': + part = t('aiCmdToc', { count: r.matched }) + break + default: + part = `${r.op}: ${r.changed}` + } + if (r.skippedProtected > 0) part += t('aiCmdSkipped', { count: r.skippedProtected }) + return part + }) + return parts.join(';') +} + +const failure = (error: string): ExecuteOutcome => ({ ok: false, results: [], summary: '', error }) + +/** + * Validate every op, then apply the batch as one transaction. Any invalid op + * rejects the whole batch (atomic) with every error listed, each followed by + * the op's usage line; dryRun stops after planning. + */ +export function executeOps(editor: Editor, ops: unknown, ctx: OpContext = {}): ExecuteOutcome { + if (!Array.isArray(ops) || ops.length === 0) return failure('ops must be a non-empty array') + const plan: string[] = [] + const errors: string[] = [] + const planned: Array<[Op, OpDef]> = [] + ops.forEach((raw, i) => { + const where = `op #${i}` + if (!raw || typeof raw !== 'object' || typeof (raw as Op).op !== 'string') { + errors.push(`${where}: must be an object with an "op" name field`) + return + } + const op = raw as Op + const def = REGISTRY.get(op.op) + if (!def || (def.hidden && ctx.source !== 'ui')) { + errors.push(`${where}: unknown op "${op.op}". Supported ops: [${opNames().join(', ')}]`) + return + } + const error = def.validate(op, `${where} ${op.op}`) + if (error) { + errors.push(`${error}\n usage: ${def.signature}`) + return + } + planned.push([op, def]) + plan.push(`#${i} ${op.op}${op.target ? ` ${JSON.stringify(op.target)}` : ''}`) + }) + if (errors.length > 0) { + return failure( + `${errors.join('\n')}\nNothing was applied (atomic): fix the op(s) and resend the whole batch.`, + ) + } + if (ctx.dryRun) return { ok: true, results: [], summary: '', plan } + + const tr = editor.state.tr + const schema = editor.schema + const selection = frozenSelectionRange(editor, ctx.selection) ?? editor.state.selection + const results: OpResult[] = [] + try { + for (const [op, def] of planned) { + // selection positions mapped through the steps applied so far + const sel: SelRange = { + from: tr.mapping.map(selection.from), + to: tr.mapping.map(selection.to), + } + results.push(def.apply(op, { tr, schema, sel, ctx })) + } + } catch (e) { + return failure(e instanceof Error ? e.message : String(e)) + } + + if (tr.steps.length > 0) { + // intent record for consumers downstream of the Step stream (journal, analytics) + tr.setMeta('docsOps', { source: ctx.source ?? 'ai', ops: planned.map(([op]) => op.op) }) + // route through the TrackChanges recorder so AI format/text edits become + // reviewable revisions under the AI author (same pipeline as manual edits) + const storage = editor.storage.trackChanges as { enabled: boolean; author: string } | undefined + if (ctx.track && storage) { + const prev = { enabled: storage.enabled, author: storage.author } + storage.enabled = true + storage.author = ctx.track.author + try { + editor.view.dispatch(tr) + } finally { + storage.enabled = prev.enabled + storage.author = prev.author + } + } else { + editor.view.dispatch(tr) + } + } + return { ok: true, results, summary: summarize(results), plan } +} + +/** + * The app's own UI (ribbon, shortcuts, dialogs) issues ops through here: no AI + * highlight, UI-only ops allowed, focus restored like a tiptap chain would. + * Returns true when something changed. A validation failure is a programming + * error in the caller, so it is logged rather than surfaced. + */ +export function runUiOps(editor: Editor, ops: Op[], opts: { focus?: boolean } = {}): boolean { + const outcome = executeOps(editor, ops, { source: 'ui' }) + if (!outcome.ok) { + console.error('runUiOps rejected', outcome.error) + return false + } + if (opts.focus !== false) editor.commands.focus() + return outcome.results.some((r) => r.changed > 0) +} diff --git a/apps/docs/src/renderer/ai/protocol.ts b/apps/docs/src/renderer/ai/protocol.ts index 29a25c5..fbae82a 100644 --- a/apps/docs/src/renderer/ai/protocol.ts +++ b/apps/docs/src/renderer/ai/protocol.ts @@ -1,5 +1,6 @@ import type { Editor } from '@tiptap/core' import type { Node as ProseMirrorNode } from '@tiptap/pm/model' +import { TextSelection } from '@tiptap/pm/state' import { TABLE_HEADER_FILL, type Block, @@ -12,6 +13,10 @@ import { equationBlockJson, inlineEquationNodeJson } from '../editor/equation' import { inheritFrom, inheritTableFormatting, sameBlockRole } from './inherit-formatting' import { collectRevisions, TRACK_IGNORE, type RevisionRange } from '../editor/revisions' import { countWords } from '../word-count' +import { blockRangePositions, isTrackedDeleted, liveText } from './doc-utils' +import { opSignatures } from './ops' + +export { blockRangePositions, isTrackedDeleted, liveText } /** * Agent protocol: the model runs a multi-turn tool-use loop — it reads the document skeleton @@ -29,59 +34,53 @@ const PREVIEW_MAX_CHARS = 60 const PREVIEW_TIGHT_CHARS = 20 /** - * Guide for the apply_commands tool: format, - * structure and batch operations travel as a batchUpdate-style JSON envelope - * executed deterministically by commands.ts. + * Guide for the apply_ops tool: format, structure and batch operations travel + * as a flat op list executed atomically by ops.ts. The signature lines come + * from the op registry, so the guide cannot drift from the implementation. */ -export const COMMANDS_GUIDE = [ - "The command format mimics documents.batchUpdate of the Google Docs API: each command is a single-key object; the fields array has the same semantics as Google's FieldMask — only the listed fields are updated, everything not listed is left untouched. Differences from Google: target uses semantic addressing (node type / text containment / block index), colors are 6-digit hex (no #), lengths are in twips, font sizes are in half-points.", +export const OPS_GUIDE = [ + 'apply_ops runs a list of ops as ONE atomic transaction: every op is validated first and any invalid op rejects the whole batch (the error quotes the op\'s usage line). Each op is a flat object { op, target?, ...fields }. Fields are patches: a present field is set, null clears it, an absent field is left untouched — never repeat properties the user did not ask to change. Colors are "#RRGGBB", font sizes are points, lengths are twips (1 pt = 20 twips). Pass dryRun: true to validate and see the plan without changing the document.', '', - 'The commands input is an array of commands executed in order. Command schema (TypeScript):', + 'Target (all conditions are ANDed; provide at least one):', '```', - 'interface Target { // all conditions are ANDed; provide at least one', + 'interface Target {', " nodeType?: 'docHeading' | 'docParagraph' | 'docListItem' | 'image' // image = image block", " headingLevel?: number // only together with nodeType: 'docHeading'", ' containsText?: string // block plain text contains this substring', ' matchCase?: boolean // defaults to true', ' blockIndexes?: number[] // indexes from the "document block list"', - " scope?: 'selection' | 'document' // selection = only blocks covered by the current selection", + " scope?: 'selection' | 'document' // selection = only blocks covered by the current selection; when part of a block is selected, setFont / setMatchedFont / findReplace act only on the selected characters (paragraph-level ops still apply to the whole block)", '}', - "{ updateTextStyle: { target, style: { color?, highlight?, sizeHalfPoints?, font?, bold?, italic?, underline?, strike?, baselineOffset?: 'SUPERSCRIPT'|'SUBSCRIPT'|'NONE', link?: {url}|null }, fields: string[] } } // value null = clear that property; font applies only to its own script's slot (an East Asian font keeps the run's Latin font and vice versa)", - "{ updateParagraphStyle: { target, style: { align?: 'left'|'center'|'right'|'justify', lineSpacing?, indentLeft?, indentRight?, indentFirstLine?, spaceBefore?, spaceAfter?, pageBreakBefore?, shadingFill?, borders?: subset of 'tblr'|null }, fields: string[] } } // indentFirstLine positive = first-line indent, negative = hanging; a two-character indent for CJK text ≈ font size in pt × 40 twips", - '{ setHeadingLevel: { target, level: 0-6 } } // 0 = demote to body paragraph', - "{ replaceAllText: { containsText, replaceText, matchCase?, target? } } // target narrows the scanned blocks (blockIndexes / scope:'selection' / nodeType); omitted = whole document. The replacement keeps the matched text's formatting — the right tool for small in-place fixes (a few words inside a sentence)", - '{ updateMatchedTextStyle: { containsText, matchCase?, target?, style, fields } } // character-level styling: applies the run style (same style/fields as updateTextStyle) only to the matched text itself, not the whole block', - '{ deleteBlocks: { target } }', - '{ moveBlocks: { blockIndexes: number[], afterBlockIndex: number } } // -1 = start of document', - '{ createParagraphBullets: { target, bulletPreset? } } // paragraphs to list; BULLET_* prefix = unordered, NUMBERED_* = ordered (default unordered); heading blocks are not converted', - '{ deleteParagraphBullets: { target } } // list items back to body paragraphs', - "{ updateImageProperties: { target, properties: { widthPx?, heightPx?, align?: 'left'|'center'|'right' }, fields } } // image blocks only; giving one dimension scales proportionally", - '{ insertToc: { afterBlockIndex } } // insert a TOC field after that block index (-1 = start of document); entries come from current headings, Word computes page numbers on open; fails if the document has no headings', + '```', + 'Ops:', + '```', + ...opSignatures(), '```', '', 'Common recipes:', - '- "Make all headings red" → commands: [{"updateTextStyle":{"target":{"nodeType":"docHeading"},"style":{"color":"FF0000"},"fields":["color"]}}]', - '- "1.5 line spacing for the whole document" → one updateParagraphStyle each for docParagraph / docHeading / docListItem, style {"lineSpacing":1.5}, fields ["lineSpacing"]', - '- "Demote the \'Risk Notice\' level-2 heading to level 3" → commands: [{"setHeadingLevel":{"target":{"nodeType":"docHeading","headingLevel":2,"containsText":"Risk Notice"},"level":3}}]', - '- "Delete blocks 3 to 5" → commands: [{"deleteBlocks":{"target":{"blockIndexes":[3,4,5]}}}]', - '- "Turn blocks 2 to 4 into a numbered list" → commands: [{"createParagraphBullets":{"target":{"blockIndexes":[2,3,4]},"bulletPreset":"NUMBERED_DECIMAL_ALPHA_ROMAN"}}]', - '- "Center all images" → commands: [{"updateImageProperties":{"target":{"nodeType":"image"},"properties":{"align":"center"},"fields":["align"]}}]', - '- "In block 5, change 8% to 9%" → commands: [{"replaceAllText":{"containsText":"8%","replaceText":"9%","target":{"blockIndexes":[5]}}}]', - '- "Bold every TODO:" → commands: [{"updateMatchedTextStyle":{"containsText":"TODO:","style":{"bold":true},"fields":["bold"]}}]', - '- "Two-character first-line indent for the whole document" (11 pt font) → one updateParagraphStyle for docParagraph, style {"indentFirstLine":440}, fields ["indentFirstLine"]', - '- "Insert a table of contents at the beginning" → commands: [{"insertToc":{"afterBlockIndex":-1}}]; if the user wants the TOC on its own page, also apply updateParagraphStyle to the first body block after the TOC with style {"pageBreakBefore":true}, fields ["pageBreakBefore"]', - '- Cover page recipe: use insert_content to insert one paragraph each for title/subtitle/date at the start of the document, then updateTextStyle to enlarge the title font (e.g. {"sizeHalfPoints":72}, fields ["sizeHalfPoints"]), updateParagraphStyle to center everything and give the title {"spaceBefore":4800}, and finally set {"pageBreakBefore":true} on the first body block after the cover', + '- "Make all headings red" → ops: [{"op":"setFont","target":{"nodeType":"docHeading"},"color":"#FF0000"}]', + '- "1.5 line spacing for the whole document" → one setParagraphFormat each for docParagraph / docHeading / docListItem with "lineSpacing":1.5', + '- "Demote the \'Risk Notice\' level-2 heading to level 3" → ops: [{"op":"setHeadingLevel","target":{"nodeType":"docHeading","headingLevel":2,"containsText":"Risk Notice"},"level":3}]', + '- "Delete blocks 3 to 5" → ops: [{"op":"deleteBlocks","target":{"blockIndexes":[3,4,5]}}]', + '- "Turn blocks 2 to 4 into a numbered list" → ops: [{"op":"setList","target":{"blockIndexes":[2,3,4]},"kind":"number"}]', + '- "Center all images" → ops: [{"op":"setImageProperties","target":{"nodeType":"image"},"align":"center"}]', + '- "In block 5, change 8% to 9%" → ops: [{"op":"findReplace","find":"8%","replace":"9%","target":{"blockIndexes":[5]}}]', + '- "Bold every TODO:" → ops: [{"op":"setMatchedFont","text":"TODO:","bold":true}]', + '- "Make the selected words 14 pt blue" (partial selection) → ops: [{"op":"setFont","target":{"scope":"selection"},"fontSize":14,"color":"#1A73E8"}]', + '- "Two-character first-line indent for the whole document" (11 pt font) → one setParagraphFormat for docParagraph with "indentFirstLine":440', + '- "Insert a table of contents at the beginning" → ops: [{"op":"insertToc","afterBlockIndex":-1}]; if the user wants the TOC on its own page, also setParagraphFormat the first body block after the TOC with "pageBreakBefore":true', + '- Cover page recipe: use insert_content to insert one paragraph each for title/subtitle/date at the start of the document, then setFont to enlarge the title (e.g. "fontSize":36), setParagraphFormat to center everything and give the title "spaceBefore":4800, and finally set "pageBreakBefore":true on the first body block after the cover', '', 'Discipline:', - '- Read the "document block list" before issuing commands; anything like "paragraph N / a certain section" must be addressed with block indexes from the list — never guess;', - '- Put only the properties the user explicitly asked for into fields;', - '- Protected blocks such as images cannot be modified with style commands (they are skipped); to change table content, use read_blocks to get the and rewrite it wholesale with replace_blocks (the table keeps its column widths, borders, shading and cell formatting; cells whose text you leave unchanged keep their content untouched).', + '- Read the "document block list" before issuing ops; anything like "paragraph N / a certain section" must be addressed with block indexes from the list — never guess;', + '- Only give the fields the user explicitly asked to change;', + '- Protected blocks such as images cannot be modified with style ops (they are skipped); to change table content, use read_blocks to get the
and rewrite it wholesale with replace_blocks (the table keeps its column widths, borders, shading and cell formatting; cells whose text you leave unchanged keep their content untouched).', '', 'Known error cases (must avoid):', - 'BC-1 Putting properties the user did not ask for into fields, wiping existing formatting by mistake;', + 'BC-1 Giving fields the user did not ask for, wiping existing formatting by mistake;', 'BC-2 A "whole document" formatting operation only changed docParagraph and missed docHeading/docListItem;', - 'BC-3 Addressing by word/character position (no such addressing exists); use block indexes or text containment instead;', - 'BC-4 Using replaceAllText sentence by sentence for rewrites such as translation/abbreviation; use the replace_blocks tool instead;', + 'BC-3 Addressing by word/character position (no such addressing exists); use block indexes, text containment or the selection instead;', + '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 = [ @@ -91,6 +90,7 @@ const HTML_RULES = [ '- Use
 for code samples (monospace font + shading, line breaks preserved); use 
for quotations (indent + left bar)', '- Use LaTeX for math (produces native Word equations): as a top-level block it becomes its own centered paragraph; placed inside

/

  • / text it is an inline formula flowing with the text, e.g.

    From E = mc^2 we know…

    ; supports the common subset of \\frac \\sqrt super/subscripts \\sum \\int \\lim matrix environments Greek letters etc., the align environment is not supported; invalid LaTeX fails the whole call — fix and retry', '- Do not include /, markdown code fences, or explanatory text', + "- … appears only in the context to mark the user's selection; it is not a tag you may write", '- Organize long content into sections with h2/h3 (unless the user only wants a single paragraph)', '- Keep the same language as the original document / user instruction, unless translation is requested', ].join('\n') @@ -112,9 +112,10 @@ 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;', - '- Formatting, structure, and batch operations (color/font size/line spacing/alignment/indent/heading level/find & replace/delete/move/list conversion) go through apply_commands — do not rewrite whole blocks with replace_blocks;', - '- Small in-place text fixes (changing a few words inside a sentence) go through apply_commands replaceAllText with a target — do not rewrite the whole block; styling every occurrence of a phrase (e.g. bold each "TODO") uses updateMatchedTextStyle;', + '- 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;', + '- When only part of a block is selected, the selected span is delimited by … and repeated as "Selected text": "this"/"the selected text" means exactly that span. Restyle it with apply_ops and target {"scope":"selection"} (run-level ops then touch only the selected characters); rewrite it with replace_selection. Never restyle or rewrite the whole block for a partial selection;', '- Web search: use web_search when you need up-to-date information/data/fact checking; search before writing about uncertain facts — do not fabricate;', '- Illustrations: when the user wants pictures, first image_search (English keywords work better) → pick a suitable result → insert_image with its imageUrl; when the user asks to generate/draw a picture, or search cannot match the needed illustration, use generate_image with a detailed English prompt;', '- Tracked deletions (struck-through revision text) are not part of the current content and are hidden from the block list/read_blocks/stats; when a [tracked deletion] tag or a skipped-deletion notice appears, that text is already deleted — never try to delete or rewrite it again (the user accepts/rejects revisions in the Review tab);', @@ -130,7 +131,7 @@ export const AGENT_SYSTEM_PROMPT = [ '', '# Template filling', '- When the user asks to fill in a template/form, first scan the document for placeholders: [bracketed labels], {{curly names}}, runs of underscores (____), and protected content-control blocks whose label reads as a field.', - "- List every placeholder found (with block indexes). Fill the ones the user's message answers via replaceAllText with a target so the surrounding formatting survives; for the rest, ask for the missing values in one consolidated question — never invent facts to fill a field.", + "- List every placeholder found (with block indexes). Fill the ones the user's message answers via findReplace with a target so the surrounding formatting survives; for the rest, ask for the missing values in one consolidated question — never invent facts to fill a field.", "- Dates follow the user's locale; never change text outside the placeholders.", '', '# Headers & footers', @@ -150,8 +151,8 @@ export const AGENT_SYSTEM_PROMPT = [ '# HTML fragment rules', HTML_RULES, '', - '# apply_commands command guide', - COMMANDS_GUIDE, + '# apply_ops guide', + OPS_GUIDE, ].join('\n') export { countWords } @@ -164,6 +165,9 @@ export interface SelectionScope { endIndex: number /** true when the user has an actual range selected (not just a caret) */ isRange: boolean + /** exact ProseMirror positions; run-level commands narrow to them when the range is partial */ + from?: number + to?: number } export function getSelectionScope(editor: Editor): SelectionScope { @@ -188,61 +192,31 @@ export function getSelectionScope(editor: Editor): SelectionScope { startIndex = doc.childCount - 1 endIndex = doc.childCount - 1 } - return { startIndex, endIndex, isRange: !empty } -} - -/** ProseMirror positions of a top-level child index range */ -export function blockRangePositions( - editor: Editor, - startIndex: number, - endIndex: number, -): { from: number; to: number } { - const doc = editor.state.doc - let from = 0 - let to = 0 - let index = 0 - doc.forEach((node, offset) => { - if (index === startIndex) from = offset - if (index === endIndex) to = offset + node.nodeSize - index++ - }) - return { from, to } -} - -// ---- tracked deletions (pending revisions are not current content) ---- - -const hasDelMark = (node: ProseMirrorNode) => node.marks.some((m) => m.type.name === 'del') - -/** block text as it reads once pending tracked deletions are applied (textContent minus del runs) */ -export function liveText(node: ProseMirrorNode): string { - if ((node.attrs?.blockRevision as { kind?: string } | null)?.kind === 'del') return '' - let out = '' - const walk = (child: ProseMirrorNode): void => { - if (hasDelMark(child)) return - if (child.isText) out += child.text ?? '' - else if (child.isLeaf) out += child.type.spec.leafText?.(child) ?? '' - else child.forEach(walk) - } - node.forEach(walk) - return out + return { startIndex, endIndex, isRange: !empty, from, to } } /** - * The whole block is a pending deletion revision (struck through in the editor). - * Checked structurally, not by text length: atom leaves (inline formulas, ruby) - * carry no textContent, so a live formula must still count as live content. + * The character-precise part of a range selection, clamped to its block range; + * null when the selection covers the blocks whole (or carries no positions). */ -export function isTrackedDeleted(node: ProseMirrorNode): boolean { - if ((node.attrs?.blockRevision as { kind?: string } | null)?.kind === 'del') return true - let hasContent = false - let hasLive = false - node.descendants((child) => { - if (child.isText || (child.isInline && child.isLeaf)) { - hasContent = true - if (!hasDelMark(child)) hasLive = true - } - }) - return hasContent && !hasLive +export function partialSelection( + editor: Editor, + scope: SelectionScope, +): { from: number; to: number } | null { + if (!scope.isRange || scope.from === undefined || scope.to === undefined) return null + const doc = editor.state.doc + if (scope.startIndex < 0 || scope.endIndex >= doc.childCount) return null + const { from, to } = blockRangePositions(editor, scope.startIndex, scope.endIndex) + const first = doc.child(scope.startIndex) + const last = doc.child(scope.endIndex) + // character precision exists only for top-level text blocks; a range that + // starts or ends inside a table / protected block keeps whole-block semantics + if (!first.isTextblock || !last.isTextblock) return null + if (scope.from <= from + 1 && scope.to >= to - 1) return null + return { + from: Math.min(Math.max(scope.from, from), to), + to: Math.min(Math.max(scope.to, from), to), + } } // ---- blocks -> restricted HTML ---- @@ -251,39 +225,82 @@ function escapeHtml(text: string): string { return text.replace(/&/g, '&').replace(//g, '>') } -function inlineToHtml(content: PmNode[] | undefined): string { +function wrapInlineText(raw: string, marks: PmMark[]): string { + let text = escapeHtml(raw) + const has = (type: string) => marks.some((m: PmMark) => m.type === type) + if (has('bold')) text = `${text}` + if (has('italic')) text = `${text}` + if (has('underline')) text = `${text}` + if (has('strike')) text = `${text}` + const link = marks.find((m: PmMark) => m.type === 'link') + if (link?.attrs?.href) text = `${text}` + return text +} + +function inlineAtomToHtml(node: PmNode): string { + if (node.type === 'hardBreak') return '
    ' + if (node.type === 'docInlineMath') { + // editor-created formulas round-trip as LaTeX; parsed-from-docx ones + // degrade to the flat token strip (structure lost if the model rewrites) + const source = String(node.attrs?.latex ?? '') || String(node.attrs?.text ?? '') + return source ? `${escapeHtml(source)}` : '' + } + if (node.type === 'docRuby') return escapeHtml(String(node.attrs?.base ?? '')) + return '' +} + +/** Character offsets (relative to the block's content start) of the user's selection inside this block */ +export interface InlineSelection { + from: number + to: number +} + +/** + * Inline content as restricted HTML. With `sel`, the selected span is + * delimited by … (text nodes split at the boundaries). Every inline + * node other than text is an atom, so it occupies exactly one position. + */ +function inlineToHtml(content: PmNode[] | undefined, sel?: InlineSelection): string { if (!content) return '' let html = '' - for (const node of content) { - // del-marked runs are pending deletions, not current content - if ((node.marks ?? []).some((m: PmMark) => m.type === 'del')) continue - if (node.type === 'hardBreak') { - html += '
    ' - continue + let pos = 0 + let open = false + let pending = sel && sel.from < sel.to ? sel : null + const boundary = (at: number) => { + if (!pending) return + if (!open && at >= pending.from && at < pending.to) { + html += '' + open = true } - if (node.type === 'docInlineMath') { - // editor-created formulas round-trip as LaTeX; parsed-from-docx ones - // degrade to the flat token strip (structure lost if the model rewrites) - const source = String(node.attrs?.latex ?? '') || String(node.attrs?.text ?? '') - if (source) html += `${escapeHtml(source)}` - continue + if (open && at >= pending.to) { + html += '' + open = false + pending = null } - if (node.type === 'docRuby') { - html += escapeHtml(String(node.attrs?.base ?? '')) - continue - } - if (node.type !== 'text' || !node.text) continue - let text = escapeHtml(node.text) - const marks = node.marks ?? [] - const has = (type: string) => marks.some((m: PmMark) => m.type === type) - if (has('bold')) text = `${text}` - if (has('italic')) text = `${text}` - if (has('underline')) text = `${text}` - if (has('strike')) text = `${text}` - const link = marks.find((m: PmMark) => m.type === 'link') - if (link?.attrs?.href) text = `${text}` - html += text } + for (const node of content) { + // del-marked runs are pending deletions, not current content (but they still occupy positions) + const deleted = (node.marks ?? []).some((m: PmMark) => m.type === 'del') + if (node.type === 'text') { + const text = node.text ?? '' + const marks = node.marks ?? [] + const end = pos + text.length + const cuts = [pos] + if (pending) for (const c of [pending.from, pending.to]) if (c > pos && c < end) cuts.push(c) + cuts.push(end) + for (let i = 0; i < cuts.length - 1; i++) { + boundary(cuts[i]) + if (!deleted) html += wrapInlineText(text.slice(cuts[i] - pos, cuts[i + 1] - pos), marks) + } + pos = end + continue + } + boundary(pos) + if (!deleted) html += inlineAtomToHtml(node) + pos += 1 + } + boundary(pos) + if (open) html += '' return html } @@ -296,6 +313,31 @@ function inlineToPlainText(content: PmNode[] | undefined): string { .join('') } +/**
     body: escaped plain text, the selected span delimited by … like the rich blocks */
    +function codeToHtml(content: PmNode[] | undefined, sel?: InlineSelection): string {
    +  if (!content) return ''
    +  const plain = inlineToPlainText(content)
    +  if (!sel || sel.from >= sel.to) return escapeHtml(plain)
    +  // deleted runs are dropped from the text but still occupy positions: map positions to text offsets
    +  let pos = 0
    +  let offset = 0
    +  let start = -1
    +  let end = -1
    +  for (const n of content) {
    +    const size = n.type === 'text' ? (n.text ?? '').length : 1
    +    const kept = !(n.marks ?? []).some((m: PmMark) => m.type === 'del')
    +    const width = kept ? (n.type === 'text' ? size : n.type === 'hardBreak' ? 1 : 0) : 0
    +    if (start < 0 && sel.from < pos + size)
    +      start = offset + (kept ? Math.max(sel.from - pos, 0) : 0)
    +    if (end < 0 && sel.to <= pos + size) end = offset + (kept ? Math.max(sel.to - pos, 0) : 0)
    +    pos += size
    +    offset += width
    +  }
    +  if (start < 0) start = plain.length
    +  if (end < 0) end = plain.length
    +  return `${escapeHtml(plain.slice(0, start))}${escapeHtml(plain.slice(start, end))}${escapeHtml(plain.slice(end))}`
    +}
    +
     /** paragraph carries the 
     preset (see CODE_BLOCK_PRESET) */
     function isCodeParagraph(node: PmNode): boolean {
       return (
    @@ -325,9 +367,15 @@ function tableToHtml(table: TableModel): string {
     
     /**
      * Serialize top-level nodes [startIndex, endIndex] into restricted HTML.
    - * Consecutive list items of the same kind are grouped into ul/ol.
    + * Consecutive list items of the same kind are grouped into ul/ol. With `sel`
    + * (absolute positions), the selected characters are delimited by ….
      */
    -export function serializeRangeToHtml(editor: Editor, startIndex: number, endIndex: number): string {
    +export function serializeRangeToHtml(
    +  editor: Editor,
    +  startIndex: number,
    +  endIndex: number,
    +  sel?: { from: number; to: number } | null,
    +): string {
       const json = editor.getJSON() as PmNode
       const children = (json.content ?? []).slice(startIndex, endIndex + 1)
       const parts: string[] = []
    @@ -339,6 +387,14 @@ export function serializeRangeToHtml(editor: Editor, startIndex: number, endInde
         parts.push(`<${tag}>${listBuffer.items.join('')}`)
         listBuffer = null
       }
    +  const inlineSel = (i: number): InlineSelection | undefined => {
    +    if (!sel) return undefined
    +    const pmNode = editor.state.doc.child(startIndex + i)
    +    const start = blockRangePositions(editor, startIndex + i, startIndex + i).from + 1
    +    const from = Math.max(sel.from, start) - start
    +    const to = Math.min(sel.to, start + pmNode.content.size) - start
    +    return from < to ? { from, to } : undefined
    +  }
     
       for (let i = 0; i < children.length; i++) {
         const node = children[i]
    @@ -350,22 +406,22 @@ export function serializeRangeToHtml(editor: Editor, startIndex: number, endInde
         if (node.type === 'docHeading') {
           flushList()
           const level = Math.min(Math.max(Number(node.attrs?.level) || 1, 1), 6)
    -      parts.push(`${inlineToHtml(node.content)}`)
    +      parts.push(`${inlineToHtml(node.content, inlineSel(i))}`)
         } else if (node.type === 'docListItem') {
           const kind = (node.attrs?.kind as string) ?? 'bullet'
           if (!listBuffer || listBuffer.kind !== kind) {
             flushList()
             listBuffer = { kind, items: [] }
           }
    -      listBuffer.items.push(`
  • ${inlineToHtml(node.content)}
  • `) + listBuffer.items.push(`
  • ${inlineToHtml(node.content, inlineSel(i))}
  • `) } else if (node.type === 'docParagraph') { flushList() if (isCodeParagraph(node)) { - parts.push(`
    ${escapeHtml(inlineToPlainText(node.content))}
    `) + parts.push(`
    ${codeToHtml(node.content, inlineSel(i))}
    `) } else if (isQuoteParagraph(node)) { - parts.push(`
    ${inlineToHtml(node.content)}
    `) + parts.push(`
    ${inlineToHtml(node.content, inlineSel(i))}
    `) } else { - parts.push(`

    ${inlineToHtml(node.content)}

    `) + parts.push(`

    ${inlineToHtml(node.content, inlineSel(i))}

    `) } } else if (node.type === 'docTable') { flushList() @@ -520,10 +576,13 @@ export function buildDocumentContext( } scope ??= getSelectionScope(editor) + const partialNote = partialSelection(editor, scope) + ? ' (part of the text only — see the markers in the selected content)' + : '' const selLine = scope.isRange ? scope.startIndex === scope.endIndex - ? `Current selection: block ${scope.startIndex}` - : `Current selection: blocks ${scope.startIndex}-${scope.endIndex}` + ? `Current selection: block ${scope.startIndex}${partialNote}` + : `Current selection: blocks ${scope.startIndex}-${scope.endIndex}${partialNote}` : `No selection; cursor is in block ${scope.startIndex}` // authoritative stats for answer mode (previews above may be clipped) @@ -701,18 +760,33 @@ export function buildDocContext( ): string { const isEmptyDoc = isBlankDocument(editor) scope ??= getSelectionScope(editor) + const partial = partialSelection(editor, scope) const selectionHtml = scope.isRange - ? clip(serializeRangeToHtml(editor, scope.startIndex, scope.endIndex), SELECTION_MAX_CHARS) + ? clip( + serializeRangeToHtml(editor, scope.startIndex, scope.endIndex, partial), + SELECTION_MAX_CHARS, + ) : '' + const selectedText = partial + ? editor.state.doc.textBetween(partial.from, partial.to, '\n', ' ') + : '' + const selectionLines = partial + ? [ + `Content selected by the user (blocks ${scope.startIndex}-${scope.endIndex}; ONLY the span inside … is selected, the rest of these blocks is shown for context):`, + selectionHtml, + `Selected text (${selectedText.length} characters): "${clip(selectedText, 1000)}"`, + ] + : [ + `Content selected by the user (blocks ${scope.startIndex}-${scope.endIndex}):`, + selectionHtml, + ] return [ isEmptyDoc ? 'The document is currently blank.' : `Document block list:\n${buildDocumentContext(editor, scope, hf)}`, // a blank body can still carry headers/footers (template setup): keep them visible isEmptyDoc && hf ? hfContextLines(hf).join('\n') : '', - selectionHtml - ? `Content selected by the user (blocks ${scope.startIndex}-${scope.endIndex}):\n${selectionHtml}` - : '', + selectionHtml ? selectionLines.join('\n') : '', comments && comments.length > 0 ? buildCommentsContext(editor, comments) : '', ] .filter(Boolean) @@ -1010,6 +1084,30 @@ export function parseHtmlFragment(raw: string, numIds: NumIds): PmNode[] { return out } +const BLOCK_TAG = /<\/?(h[1-6]|p|div|ul|ol|li|table|thead|tbody|tr|th|td|pre|blockquote)\b/gi + +/** + * Parse the replacement for a selected span: plain text or inline HTML, or a + * single

    …

    . Any other block structure is refused — the selection lives + * inside one text block, so a multi-block answer belongs to replace_blocks. + */ +export function parseInlineFragment(raw: string): PmNode[] { + let text = raw.trim() + const fence = /```(?:html)?\s*([\s\S]*?)```/.exec(text) + if (fence) text = fence[1].trim() + const single = /^]*)?>([\s\S]*)<\/p>$/i.exec(text) + if (single) text = single[1] + if (BLOCK_TAG.test(text)) { + BLOCK_TAG.lastIndex = 0 + throw new Error( + 'replace_selection takes inline content for the selected span only; block tags (p/h*/ul/table…) mean a rewrite of whole blocks — use replace_blocks', + ) + } + const parsed = new DOMParser().parseFromString(`

    ${text}

    `, 'text/html') + const p = parsed.body.firstElementChild + return p ? parseInline(p, []) : [] +} + // ---- applying parsed fragments ---- /** record the AI's content change as tracked revisions under this author */ @@ -1184,6 +1282,39 @@ export function replaceBlockRange( return true } +/** + * Replace an inline range inside one text block with the given inline nodes + * (the replace_selection tool). The new text becomes the selection so a + * follow-up scope:'selection' command targets it. With `track`, the old text + * stays struck through (del) and the new text follows with ins marks. + */ +export function replaceInlineRange( + editor: Editor, + from: number, + to: number, + nodes: ProseMirrorNode[], + track?: AiTrack, +): void { + const tr = editor.state.tr + const blockPos = tr.doc.resolve(from).before(1) + const inserted = nodes.reduce((size, n) => size + n.nodeSize, 0) + if (track) { + const date = revisionDate() + const { ins, del } = editor.schema.marks + tr.insert(to, nodes) + if (inserted > 0) tr.addMark(to, to + inserted, ins.create({ author: track.author, date })) + tr.addMark(from, to, del.create({ author: track.author, date })) + tr.setSelection(TextSelection.create(tr.doc, to, to + inserted)) + tr.setMeta(TRACK_IGNORE, true) + } else { + tr.replaceWith(from, to, nodes) + tr.setSelection(TextSelection.create(tr.doc, from, from + inserted)) + const block = tr.doc.nodeAt(blockPos) + if (block) tr.setNodeMarkup(blockPos, undefined, { ...block.attrs, aiChanged: true }) + } + editor.view.dispatch(tr) +} + /** insert the parsed nodes after the given top-level block index */ export function insertBlocksAfter( editor: Editor, diff --git a/apps/docs/src/renderer/ai/tools.ts b/apps/docs/src/renderer/ai/tools.ts index 82fff21..171b84a 100644 --- a/apps/docs/src/renderer/ai/tools.ts +++ b/apps/docs/src/renderer/ai/tools.ts @@ -1,9 +1,9 @@ import type { Editor } from '@tiptap/core' -import type { Node as ProseMirrorNode } from '@tiptap/pm/model' +import type { Mark, Node as ProseMirrorNode } from '@tiptap/pm/model' import type { ChartDisplay, CommentInfo, NewChart } from '@genoffice/docx-engine' import type { AgentToolCall, AgentToolDef, CreateDocumentType } from '../../shared/ipc' import { t } from '../i18n/locale' -import { executeCommands, type Command, type CommandEnvelope } from './commands' +import { executeOps, opNames } from './ops' import { blockRangePositions, buildCommentsContext, @@ -13,7 +13,9 @@ import { isBlankDocument, isTrackedDeleted, parseHtmlFragment, + parseInlineFragment, replaceBlockRange, + replaceInlineRange, serializeRangeToHtml, type AiHfState, type AiTrack, @@ -87,19 +89,41 @@ export const AGENT_TOOLS: AgentToolDef[] = [ }, }, { - name: 'apply_commands', + name: 'replace_selection', description: - 'Execute formatting/structure/batch commands (batchUpdate style, see the command guide in the system prompt): text style (whole-block or matched-text-only), paragraph format, heading level, find & replace, delete/move blocks, list conversion, image properties, TOC insertion.', + "Replace exactly the user's selected text (the … span in the context) with new inline content, leaving the rest of the block untouched. For rewording/translating/correcting a selected phrase or sentence inside a paragraph. The new text inherits the selection's formatting unless the fragment styles it. Requires a range selection inside one paragraph/heading/list item; for whole blocks or several blocks use replace_blocks.", inputSchema: { type: 'object', properties: { - commands: { - type: 'array', - description: 'array of commands executed in order; each command is a single-key object', - items: { type: 'object' }, + html: { + type: 'string', + description: + 'replacement inline content: plain text or restricted inline HTML (strong em u s a br formula)', }, }, - required: ['commands'], + required: ['html'], + }, + }, + { + name: 'apply_ops', + description: + `Run a list of formatting/structure ops as one atomic transaction (see the apply_ops guide in the system prompt): ${opNames().join(', ')}. ` + + 'Each op is a flat { op, target?, ...fields } object; fields are patches (present = set, null = clear, absent = untouched). Any invalid op rejects the whole batch with its usage line.', + inputSchema: { + type: 'object', + properties: { + ops: { + type: 'array', + description: + 'ops executed in order, e.g. [{"op":"setFont","target":{"nodeType":"docHeading"},"color":"#FF0000"}]', + items: { type: 'object' }, + }, + dryRun: { + type: 'boolean', + description: 'validate and return the plan without changing the document', + }, + }, + required: ['ops'], }, }, { @@ -181,7 +205,7 @@ export const AGENT_TOOLS: AgentToolDef[] = [ { name: 'generate_image', description: - 'Generate an illustration with AI from a text prompt and insert it into the document (at the cursor / end of document). For illustration/diagram-style art that image_search cannot find, or when the user asks to generate/draw a picture. Requires Genspark login with cloud tools enabled.', + 'Generate an illustration with AI from a text prompt and insert it into the document (at the cursor / end of document). For illustration/diagram-style art that image_search cannot find, or when the user asks to generate/draw a picture.', inputSchema: { type: 'object', properties: { @@ -298,19 +322,20 @@ export const AGENT_TOOLS: AgentToolDef[] = [ name: 'create_document', description: 'Create a NEW standalone file in the default save folder and open it in a new tab; the current document is not modified. Use when the user asks to put content into a new/separate document instead of this one. ' + - "type 'docx' (default) and 'pdf' take the same restricted HTML as insert_content in content; type 'md' takes Markdown source. Images and charts are not supported in the new file's initial content.", + "type 'docx' (default) and 'pdf' take the same restricted HTML as insert_content in content; type 'md' takes Markdown source; type 'html' takes a complete standalone HTML page (opens in the HTML editor). Images and charts are not supported in the new file's initial content.", inputSchema: { type: 'object', properties: { type: { type: 'string', - enum: ['docx', 'pdf', 'md'], + enum: ['docx', 'pdf', 'md', 'html'], description: "target file type (default 'docx')", }, title: { type: 'string', description: 'document title, used as the file name' }, content: { type: 'string', - description: 'full document content: restricted HTML for docx/pdf, Markdown for md', + description: + 'full document content: restricted HTML for docx/pdf, Markdown for md, a complete HTML page for html', }, }, required: ['title', 'content'], @@ -371,6 +396,9 @@ const fail = (summary: string, output: string): ToolExecution => ({ summary, }) +const clipText = (text: string, max: number): string => + text.length > max ? `${text.slice(0, max)}…` : text + /** * A model that saw gateway-flattened tool results can regurgitate them as the * html argument (raw {"index":…} block dumps, literal tags); @@ -399,6 +427,31 @@ function toolEchoError(html: string): string | null { } } +/** only marks the user's selection in the context; a model echoing it would write the marker into the document */ +function contextMarkerError(html: string): string | null { + return /<\/?sel\s*>/i.test(html) + ? 'html contains : that marker only delimits the selection in the context and is not document content; retry without it' + : null +} + +/** the range selection tools act on: the frozen scope when valid, else the live selection; null for a caret */ +function selectionRange( + editor: Editor, + scope?: SelectionScope | null, +): { from: number; to: number } | null { + if (scope) { + if (!scope.isRange) return null + if (scope.from !== undefined && scope.to !== undefined && scope.from < scope.to) + return { from: scope.from, to: scope.to } + } + const { from, to, empty } = editor.state.selection + return empty ? null : { from, to } +} + +/** formatting the fragment expresses itself (tags), so it must not also be inherited from the old text */ +const FRAGMENT_MARK_TYPES = new Set(['bold', 'italic', 'underline', 'strike', 'link']) +const REVISION_MARK_TYPES = new Set(['ins', 'del']) + /** Doc as last seen by the AI pipeline (context build / read / own write); a differing doc means the user edited in between. */ const docBaseline = new WeakMap() @@ -420,7 +473,8 @@ function editedExternally(editor: Editor): boolean { const INDEX_WRITE_SUMMARIES: Record string> = { insert_content: () => t('aiSumInsertContent'), replace_blocks: () => t('aiSumReplaceContent'), - apply_commands: () => t('aiSumApplyCommands'), + replace_selection: () => t('aiSumReplaceSelection'), + apply_ops: () => t('aiSumApplyCommands'), insert_chart: () => t('aiSumInsertChart'), edit_chart: () => t('aiSumEditChart'), } @@ -543,8 +597,8 @@ async function executeAsyncTool( } case 'create_document': { const typeRaw = call.input.type === undefined ? 'docx' : String(call.input.type) - if (typeRaw !== 'docx' && typeRaw !== 'pdf' && typeRaw !== 'md') - return fail(t('aiSumCreateDocument'), 'type must be one of docx/pdf/md') + if (typeRaw !== 'docx' && typeRaw !== 'pdf' && typeRaw !== 'md' && typeRaw !== 'html') + return fail(t('aiSumCreateDocument'), 'type must be one of docx/pdf/md/html') const type: CreateDocumentType = typeRaw const title = String(call.input.title ?? '').trim() if (!title) return fail(t('aiSumCreateDocument'), 'title must not be empty') @@ -553,6 +607,8 @@ async function executeAsyncTool( if (type !== 'md') { const echo = toolEchoError(content) if (echo) return fail(t('aiSumCreateDocument'), echo) + } + if (type === 'docx' || type === 'pdf') { // the new docx tab fills itself after this tool already returned, so // unparseable HTML must be rejected here, where the model can retry try { @@ -743,7 +799,7 @@ function executeSyncTool( case 'insert_content': { const html = String(call.input.html ?? '') - const echo = toolEchoError(html) + const echo = toolEchoError(html) ?? contextMarkerError(html) if (echo) return fail(t('aiSumInsertContent'), echo) let nodes: ReturnType try { @@ -781,7 +837,7 @@ function executeSyncTool( const range = validRange(editor, call.input.startBlockIndex, call.input.endBlockIndex) if (!range) return fail(t('aiSumReplaceContent'), rangeError(editor)) const html = String(call.input.html ?? '') - const echo = toolEchoError(html) + const echo = toolEchoError(html) ?? contextMarkerError(html) if (echo) return fail(t('aiSumReplaceContent'), echo) let nodes: ReturnType try { @@ -799,6 +855,60 @@ function executeSyncTool( } } + case 'replace_selection': { + const html = String(call.input.html ?? '') + const echo = toolEchoError(html) ?? contextMarkerError(html) + if (echo) return fail(t('aiSumReplaceSelection'), echo) + const range = selectionRange(editor, scope) + if (!range) { + return fail( + t('aiSumReplaceSelection'), + 'nothing is selected: replace_selection needs a range selection (the … span in the context); to rewrite whole blocks use replace_blocks', + ) + } + const doc = editor.state.doc + const $from = doc.resolve(range.from) + const $to = doc.resolve(range.to) + if ($from.depth !== 1 || !$from.sameParent($to) || !$from.parent.isTextblock) { + return fail( + t('aiSumReplaceSelection'), + 'the selection spans several blocks or sits in protected content (table, image, field); replace_selection only edits text inside one paragraph/heading/list item — use replace_blocks for that range', + ) + } + let inline: ReturnType + try { + inline = parseInlineFragment(html) + } catch (e) { + return fail(t('aiSumReplaceSelection'), e instanceof Error ? e.message : String(e)) + } + if (inline.length === 0) { + return fail(t('aiSumReplaceSelection'), 'html did not parse into any text') + } + const schema = editor.schema + const fragmentStyled = inline.some((n) => (n.marks ?? []).length > 0) + const anchor = $from.parent.childAfter($from.parentOffset).node + const inherited = (anchor?.marks ?? []).filter( + (m) => + !REVISION_MARK_TYPES.has(m.type.name) && + !(fragmentStyled && FRAGMENT_MARK_TYPES.has(m.type.name)), + ) + const nodes = inline.map((n) => { + if (n.type !== 'text') return schema.nodeFromJSON(n) + let marks: readonly Mark[] = inherited + for (const m of n.marks ?? []) marks = schema.markFromJSON(m).addToSet(marks) + return schema.text(n.text ?? '', marks) + }) + const blockIndex = $from.index(0) + const oldText = doc.textBetween(range.from, range.to, ' ', ' ') + replaceInlineRange(editor, range.from, range.to, nodes, track) + const newText = nodes.map((n) => n.textContent).join('') + return { + output: `Replaced the selected text in block ${blockIndex}: "${clipText(oldText, 200)}" → "${clipText(newText, 200)}". The rest of the block is unchanged; the new text is now selected.`, + mutated: true, + summary: t('aiSumReplaceSelection'), + } + } + case 'insert_chart': { const kind = String(call.input.kind ?? '') as NewChart['kind'] if (!['bar', 'line', 'pie'].includes(kind)) @@ -1040,15 +1150,22 @@ function executeSyncTool( } } - case 'apply_commands': { - const commands = call.input.commands - if (!Array.isArray(commands) || commands.length === 0) { - return fail(t('aiSumApplyCommands'), 'commands must be a non-empty array') + case 'apply_ops': { + const dryRun = call.input.dryRun === true + const outcome = executeOps(editor, call.input.ops, { + numIds, + track, + selection: scope, + dryRun, + }) + if (!outcome.ok) return fail(t('aiSumApplyCommands'), outcome.error ?? 'op execution failed') + if (dryRun) { + return { + output: `Dry run: ${outcome.plan?.length ?? 0} op(s) valid, nothing applied.\n${(outcome.plan ?? []).join('\n')}`, + mutated: false, + summary: t('aiSumApplyCommands'), + } } - const envelope: CommandEnvelope = { commands: commands as Command[] } - const outcome = executeCommands(editor, envelope, { numIds, track, selection: scope }) - if (!outcome.ok) - return fail(t('aiSumApplyCommands'), outcome.error ?? 'command execution failed') const changed = outcome.results.reduce((sum, r) => sum + r.changed, 0) const skippedDeleted = outcome.results.reduce((sum, r) => sum + (r.skippedDeleted ?? 0), 0) // explicit model-facing note so it stops retrying deletions of already-deleted text diff --git a/apps/docs/src/renderer/components/AiAskPopover.tsx b/apps/docs/src/renderer/components/AiAskPopover.tsx index c877e54..8b52c80 100644 --- a/apps/docs/src/renderer/components/AiAskPopover.tsx +++ b/apps/docs/src/renderer/components/AiAskPopover.tsx @@ -15,6 +15,7 @@ import { NodeSelection } from '@tiptap/pm/state' import { CellSelection } from '@tiptap/pm/tables' import { useI18n, type StringKey } from '../i18n/locale' import { AI_QUEUE_ANCHOR_CLICK, queueAnchorRange } from '../editor/ai-queue-anchors' +import { setInactiveSelectionShown } from '../editor/inactive-selection' import { EDIT_INSTRUCTION_MAX, EDIT_QUEUE_MAX, @@ -201,7 +202,8 @@ export function AiAskPopover({ const close = useCallback(() => { setOpen(null) setText('') - }, []) + setInactiveSelectionShown(editor, false) + }, [editor]) /** outside click keeps whatever was typed: a new note lands in the queue, an edit is saved */ const commitOrClose = useCallback(() => { @@ -224,11 +226,13 @@ export function AiAskPopover({ return () => document.removeEventListener('pointerdown', onPointerDown, true) }, [open, commitOrClose]) + // the input takes the DOM selection with it: keep the targeted range visible while the popover is open const openFromSelection = () => { setText('') setKind(selectionKind(editor)) setOpen({ mode: 'new' }) setTrigger(null) + setInactiveSelectionShown(editor, true) } const canSubmit = text.trim().length > 0 diff --git a/apps/docs/src/renderer/components/CommentsPanel.tsx b/apps/docs/src/renderer/components/CommentsPanel.tsx index 9280cb0..eaf6e89 100644 --- a/apps/docs/src/renderer/components/CommentsPanel.tsx +++ b/apps/docs/src/renderer/components/CommentsPanel.tsx @@ -2,7 +2,7 @@ import { memo, useEffect, useMemo, useRef, useState } from 'react' import type { Node as PmNode } from '@tiptap/pm/model' import type { CommentInfo } from '@genoffice/docx-engine' import { useI18n } from '../i18n/locale' -import { IconComment, IconTrash } from './icons' +import { IconComment, IconPencil, IconTrash } from './icons' function formatDate(iso?: string): string { if (!iso) return '' @@ -52,6 +52,7 @@ export const CommentsPanel = memo(function CommentsPanel({ composing, onSubmitNew, onReply, + onEdit, onResolve, onCancelNew, onDelete, @@ -65,6 +66,8 @@ export const CommentsPanel = memo(function CommentsPanel({ onSubmitNew: (text: string) => void /** Reply to a comment (anchor shares the parent comment's range) */ onReply: (parentId: string, text: string) => void + /** Replace a comment's or reply's text in place; author, date and anchor stay */ + onEdit: (id: string, text: string) => void /** Resolve/reopen the whole thread */ onResolve: (id: string, done: boolean) => void onCancelNew: () => void @@ -77,6 +80,8 @@ export const CommentsPanel = memo(function CommentsPanel({ const draftRef = useRef(null) const [replyTo, setReplyTo] = useState(null) const [replyDraft, setReplyDraft] = useState('') + const [editingId, setEditingId] = useState(null) + const [editDraft, setEditDraft] = useState('') // Word: resolved comments are collapsed/hidden by default const [showResolved, setShowResolved] = useState(false) @@ -94,6 +99,38 @@ export const CommentsPanel = memo(function CommentsPanel({ setReplyTo(null) } + const startEdit = (c: CommentInfo) => { + // the pencil toggles: a second click cancels instead of resetting the draft + if (editingId === c.id) { + setEditingId(null) + return + } + setEditingId(c.id) + setEditDraft(c.text) + setReplyTo(null) + } + + const submitEdit = () => { + const text = editDraft.trim() + if (!text || !editingId) return + onEdit(editingId, text) + setEditingId(null) + } + + /** an open edit belongs to this thread (parent or reply) — commit it before the thread collapses away */ + const flushEditIn = (threadId: string) => { + if (!editingId) return + if (editingId !== threadId && !repliesOf(threadId).some((r) => r.id === editingId)) return + const text = editDraft.trim() + if (text) onEdit(editingId, text) + setEditingId(null) + } + + /** the edited comment is going away — drop the draft with it */ + const cancelEditIn = (ids: string[]) => { + if (editingId && ids.includes(editingId)) setEditingId(null) + } + useEffect(() => { if (composing) draftRef.current?.focus() }, [composing]) @@ -108,51 +145,111 @@ export const CommentsPanel = memo(function CommentsPanel({ const renderThread = (c: CommentInfo) => { const anchor = anchorTexts.get(c.id) ?? '' const replies = repliesOf(c.id) - return ( -
    -