diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b88619..a32bb73 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,3 +90,76 @@ jobs: - name: Test run: npm test + + # Preservation gate: a no-op-adjacent edit through the OOXML gateway must + # leave every untouched package entry byte-identical (fails closed otherwise). + - name: Sheets compatibility gate + run: | + npm run fixtures -w @genoffice/sheets + npm run compat -w @genoffice/sheets + + e2e: + # 22.04, not -latest: 24.04's AppArmor hardening blocks Electron renderer + # spawn under xvfb even with --no-sandbox and the userns sysctl lifted + runs-on: ubuntu-22.04 + timeout-minutes: 45 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 20 + cache: npm + cache-dependency-path: package-lock.json + + - name: Setup Rust + uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable branch, 2026-07 + with: + toolchain: stable + + - name: Cache cargo (xlsx-sidecar) + uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 + with: + workspaces: apps/sheets/native/xlsx-engine + + - name: Install dependencies + run: npm ci + + - name: Build apps + run: npm run build:all + + - name: Generate sheets fixtures + run: npm run fixtures -w @genoffice/sheets + + # Newer Ubuntu kernels ship an AppArmor policy that blocks unprivileged + # user namespaces, which kills the Chromium zygote even with --no-sandbox + # (window opens, renderer never loads). The knob only exists on kernels + # that enforce the restriction, so skip it where it is absent instead of + # failing the job (22.04 runner images vary by kernel). + - name: Allow unprivileged user namespaces (Electron) + run: | + if sysctl kernel.apparmor_restrict_unprivileged_userns >/dev/null 2>&1; then + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + else + echo "kernel.apparmor_restrict_unprivileged_userns not present — skipping" + fi + + # Electron needs a display server on Linux runners. DEBUG=pw:browser + # forwards the Electron process stdout/stderr into the CI log so launch + # failures are diagnosable. + - name: E2E (Electron shell) + env: + DEBUG: 'pw:browser' + run: xvfb-run --auto-servernum -- npm run test:e2e + + - name: Upload E2E artifacts on failure + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: e2e-artifacts + path: | + e2e/artifacts + e2e/test-results + retention-days: 7 diff --git a/README.md b/README.md index 2af0954..4d12562 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,19 @@ An AI-native office suite for macOS and Windows: word processor, spreadsheet, presentations, and PDF — five Electron apps sharing one engine layer, built around AI editing as a first-class workflow rather than a bolted-on chat box. +[![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) + +[Watch the demo video on YouTube](https://www.youtube.com/watch?v=B2pLdMX95v4) + ## Download Signed installers built from `main`: +- **macOS** (Apple Silicon): [GenOffice-0.5.1-arm64.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.5.1/GenOffice-0.5.1-arm64.dmg) +- **Windows** (x64): [GenOfficeSetup-v0.5.1.exe](https://github.com/genspark-ai/genoffice/releases/download/v0.5.1/GenOfficeSetup-v0.5.1.exe) + +Previous version: + - **macOS** (Apple Silicon): [GenOffice-0.4.110-arm64.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.4.110/GenOffice-0.4.110-arm64.dmg) - **Windows** (x64): [GenOfficeSetup-v0.4.110.exe](https://github.com/genspark-ai/genoffice/releases/download/v0.4.110/GenOfficeSetup-v0.4.110.exe) diff --git a/apps/docs/build/icon-mac.png b/apps/docs/build/icon-mac.png new file mode 100644 index 0000000..997f243 Binary files /dev/null and b/apps/docs/build/icon-mac.png differ diff --git a/apps/docs/build/icon.icns b/apps/docs/build/icon.icns index 7b20c76..8a53f78 100644 Binary files a/apps/docs/build/icon.icns and b/apps/docs/build/icon.icns differ diff --git a/apps/docs/src/main/atomic-write.ts b/apps/docs/src/main/atomic-write.ts new file mode 100644 index 0000000..b3c6281 --- /dev/null +++ b/apps/docs/src/main/atomic-write.ts @@ -0,0 +1,52 @@ +import { randomBytes } from 'node:crypto' +import { rename, unlink, writeFile } from 'node:fs/promises' +import { basename, dirname, join } from 'node:path' + +/** Transient Windows codes: antivirus/indexer briefly locks the rename target. */ +const RETRYABLE_RENAME_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']) +const RENAME_RETRIES = 4 + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) + +/** + * Same-dir temp file + rename, so a crash mid-write can't truncate the target. + * Rename-over-existing fails transiently on Windows under Defender/indexer + * locks: retry with backoff, then fall back to an in-place write — losing + * atomicity for that one save beats failing a save the previous plain + * writeFileSync would have completed. + */ +export async function atomicWriteFile(filePath: string, data: Buffer): Promise { + const tmp = join( + dirname(filePath), + `.${basename(filePath)}.${randomBytes(6).toString('hex')}.tmp`, + ) + try { + await writeFile(tmp, data) + for (let attempt = 0; ; attempt++) { + try { + await rename(tmp, filePath) + return + } catch (err) { + const code = (err as NodeJS.ErrnoException).code ?? '' + if (!RETRYABLE_RENAME_CODES.has(code) || attempt >= RENAME_RETRIES) throw err + await sleep(50 * 2 ** attempt) + } + } + } catch (err) { + try { + await unlink(tmp) + } catch { + /* tmp never created */ + } + if (RETRYABLE_RENAME_CODES.has((err as NodeJS.ErrnoException).code ?? '')) { + await writeFile(filePath, data) + return + } + throw err + } +} + +/** 'PK\x03\x04' local-file-header check — cheap docx/zip sanity test. */ +export function looksLikeZip(bytes: Buffer): boolean { + return bytes.length >= 4 && bytes.readUInt32LE(0) === 0x04034b50 +} diff --git a/apps/docs/src/main/docs-main.ts b/apps/docs/src/main/docs-main.ts index 8aa6f08..79dcce4 100644 --- a/apps/docs/src/main/docs-main.ts +++ b/apps/docs/src/main/docs-main.ts @@ -1,6 +1,5 @@ import { createHash } from 'node:crypto' import { - copyFileSync, existsSync, mkdirSync, readdirSync, @@ -9,12 +8,17 @@ import { unlinkSync, writeFileSync, } from 'node:fs' +import { copyFile, mkdir, readFile, readdir, stat, unlink } from 'node:fs/promises' import { basename, join } from 'node:path' import { BrowserWindow, Menu, WebContentsView, app, dialog, ipcMain, shell } from 'electron' import { + appMenuLabels, + contextMenuLabels, fetchWithSsrfGuard, + installContextMenu, installNavigationGuard, safeExternalUrl, + windowMenuTemplate, } from '@genoffice/electron-utils' import { createI18n, getUiLang, normalizeLang, setUiLang } from '@genoffice/i18n' import { ProjectStore } from '@genoffice/project-store' @@ -27,6 +31,8 @@ import type { } from 'electron' import { parseFileToText } from '@genoffice/file-parse' import { + AiCreditsError, + AiTimeoutError, chatForProvider, defaultAiSettings, resolveAiSettings, @@ -57,6 +63,8 @@ import type { } from '../shared/ipc' import { ATTACHMENT_IMAGE_EXTS } from '../shared/ipc' import { findDocxPath } from '../shared/open-file' +import { atomicWriteFile, looksLikeZip } from './atomic-write' +import { isExternallyModified, type DiskFileState } from './external-change' import { initDocsAutoUpdater } from './updater' /** @@ -84,6 +92,9 @@ const tMain = createI18n({ autosaveDiscard: '放弃', btnDontSave: '不保存', btnCancel: '取消', + extModifiedMsg: '文件已被其他程序修改。', + extModifiedDetail: '仍要保存并覆盖磁盘上的更改吗?', + btnOverwrite: '覆盖', dlgInsertImage: '插入图片', filterImages: '图片', dlgAddAttachment: '添加附件', @@ -174,6 +185,9 @@ const tMain = createI18n({ autosaveDiscard: 'Discard', btnDontSave: "Don't Save", btnCancel: 'Cancel', + extModifiedMsg: 'The file has been modified by another program.', + extModifiedDetail: 'Save anyway and overwrite the changes on disk?', + btnOverwrite: 'Overwrite', dlgInsertImage: 'Insert Image', filterImages: 'Images', dlgAddAttachment: 'Add Attachments', @@ -264,6 +278,9 @@ const tMain = createI18n({ autosaveDiscard: '破棄', btnDontSave: '保存しない', btnCancel: 'キャンセル', + extModifiedMsg: 'このファイルは別のプログラムによって変更されています。', + extModifiedDetail: 'このまま保存してディスク上の変更を上書きしますか?', + btnOverwrite: '上書き', dlgInsertImage: '画像の挿入', filterImages: '画像', dlgAddAttachment: '添付ファイルの追加', @@ -356,6 +373,9 @@ const tMain = createI18n({ autosaveDiscard: '취소', btnDontSave: '저장 안 함', btnCancel: '취소', + extModifiedMsg: '이 파일이 다른 프로그램에서 수정되었습니다.', + extModifiedDetail: '그래도 저장하여 디스크의 변경 사항을 덮어쓸까요?', + btnOverwrite: '덮어쓰기', dlgInsertImage: '그림 삽입', filterImages: '그림', dlgAddAttachment: '첨부 파일 추가', @@ -449,6 +469,9 @@ const tMain = createI18n({ autosaveDiscard: 'Ignorer', btnDontSave: 'Ne pas enregistrer', btnCancel: 'Annuler', + extModifiedMsg: 'Le fichier a été modifié par un autre programme.', + extModifiedDetail: 'Enregistrer quand même et écraser les modifications sur le disque ?', + btnOverwrite: 'Écraser', dlgInsertImage: 'Insérer une image', filterImages: 'Images', dlgAddAttachment: 'Ajouter des pièces jointes', @@ -542,6 +565,9 @@ const tMain = createI18n({ autosaveDiscard: 'Verwerfen', btnDontSave: 'Nicht speichern', btnCancel: 'Abbrechen', + extModifiedMsg: 'Die Datei wurde von einem anderen Programm geändert.', + extModifiedDetail: 'Trotzdem speichern und die Änderungen auf dem Datenträger überschreiben?', + btnOverwrite: 'Überschreiben', dlgInsertImage: 'Bild einfügen', filterImages: 'Bilder', dlgAddAttachment: 'Anlagen hinzufügen', @@ -634,6 +660,9 @@ const tMain = createI18n({ autosaveDiscard: 'Descartar', btnDontSave: 'No guardar', btnCancel: 'Cancelar', + extModifiedMsg: 'El archivo ha sido modificado por otro programa.', + extModifiedDetail: '¿Guardar de todos modos y sobrescribir los cambios en el disco?', + btnOverwrite: 'Sobrescribir', dlgInsertImage: 'Insertar imagen', filterImages: 'Imágenes', dlgAddAttachment: 'Agregar datos adjuntos', @@ -725,6 +754,9 @@ const tMain = createI18n({ autosaveDiscard: 'ละทิ้ง', btnDontSave: 'ไม่บันทึก', btnCancel: 'ยกเลิก', + extModifiedMsg: 'ไฟล์ถูกแก้ไขโดยโปรแกรมอื่น', + extModifiedDetail: 'บันทึกต่อไปและเขียนทับการเปลี่ยนแปลงบนดิสก์หรือไม่?', + btnOverwrite: 'เขียนทับ', dlgInsertImage: 'แทรกรูปภาพ', filterImages: 'รูปภาพ', dlgAddAttachment: 'เพิ่มสิ่งที่แนบ', @@ -817,6 +849,9 @@ const tMain = createI18n({ autosaveDiscard: 'Buang', btnDontSave: 'Jangan Simpan', btnCancel: 'Batal', + extModifiedMsg: 'File telah diubah oleh program lain.', + extModifiedDetail: 'Tetap simpan dan timpa perubahan di disk?', + btnOverwrite: 'Timpa', dlgInsertImage: 'Sisipkan Gambar', filterImages: 'Gambar', dlgAddAttachment: 'Tambahkan Lampiran', @@ -908,6 +943,9 @@ const tMain = createI18n({ autosaveDiscard: 'Отклонить', btnDontSave: 'Не сохранять', btnCancel: 'Отмена', + extModifiedMsg: 'Файл был изменён другой программой.', + extModifiedDetail: 'Всё равно сохранить и перезаписать изменения на диске?', + btnOverwrite: 'Перезаписать', dlgInsertImage: 'Вставить рисунок', filterImages: 'Изображения', dlgAddAttachment: 'Добавить вложения', @@ -1000,6 +1038,9 @@ const tMain = createI18n({ autosaveDiscard: 'تجاهل', btnDontSave: 'عدم الحفظ', btnCancel: 'إلغاء', + extModifiedMsg: 'تم تعديل الملف بواسطة برنامج آخر.', + extModifiedDetail: 'هل تريد الحفظ على أي حال والكتابة فوق التغييرات على القرص؟', + btnOverwrite: 'استبدال', dlgInsertImage: 'إدراج صورة', filterImages: 'الصور', dlgAddAttachment: 'إضافة مرفقات', @@ -1092,6 +1133,9 @@ const tMain = createI18n({ autosaveDiscard: 'Descartar', btnDontSave: 'Não Salvar', btnCancel: 'Cancelar', + extModifiedMsg: 'O arquivo foi modificado por outro programa.', + extModifiedDetail: 'Salvar mesmo assim e sobrescrever as alterações no disco?', + btnOverwrite: 'Sobrescrever', dlgInsertImage: 'Inserir Imagem', filterImages: 'Imagens', dlgAddAttachment: 'Adicionar Anexos', @@ -1184,6 +1228,9 @@ const tMain = createI18n({ autosaveDiscard: 'Ignora', btnDontSave: 'Non salvare', btnCancel: 'Annulla', + extModifiedMsg: 'Il file è stato modificato da un altro programma.', + extModifiedDetail: 'Salvare comunque e sovrascrivere le modifiche sul disco?', + btnOverwrite: 'Sovrascrivi', dlgInsertImage: 'Inserisci immagine', filterImages: 'Immagini', dlgAddAttachment: 'Aggiungi allegati', @@ -1276,6 +1323,9 @@ const tMain = createI18n({ autosaveDiscard: 'Odrzuć', btnDontSave: 'Nie zapisuj', btnCancel: 'Anuluj', + extModifiedMsg: 'Plik został zmodyfikowany przez inny program.', + extModifiedDetail: 'Zapisać mimo to i nadpisać zmiany na dysku?', + btnOverwrite: 'Nadpisz', dlgInsertImage: 'Wstaw obraz', filterImages: 'Obrazy', dlgAddAttachment: 'Dodaj załączniki', @@ -1368,6 +1418,9 @@ const tMain = createI18n({ autosaveDiscard: 'Negeren', btnDontSave: 'Niet opslaan', btnCancel: 'Annuleren', + extModifiedMsg: 'Het bestand is door een ander programma gewijzigd.', + extModifiedDetail: 'Toch opslaan en de wijzigingen op schijf overschrijven?', + btnOverwrite: 'Overschrijven', dlgInsertImage: 'Afbeelding invoegen', filterImages: 'Afbeeldingen', dlgAddAttachment: 'Bijlagen toevoegen', @@ -1460,6 +1513,9 @@ const tMain = createI18n({ autosaveDiscard: 'Buang', btnDontSave: 'Jangan Simpan', btnCancel: 'Batal', + extModifiedMsg: 'Fail telah diubah oleh program lain.', + extModifiedDetail: 'Simpan juga dan tulis ganti perubahan pada cakera?', + btnOverwrite: 'Tulis Ganti', dlgInsertImage: 'Sisipkan Imej', filterImages: 'Imej', dlgAddAttachment: 'Tambah Lampiran', @@ -1551,6 +1607,9 @@ const tMain = createI18n({ autosaveDiscard: 'התעלם', btnDontSave: 'אל תשמור', btnCancel: 'ביטול', + extModifiedMsg: 'הקובץ שונה על ידי תוכנית אחרת.', + extModifiedDetail: 'לשמור בכל זאת ולדרוס את השינויים בדיסק?', + btnOverwrite: 'דרוס', dlgInsertImage: 'הוספת תמונה', filterImages: 'תמונות', dlgAddAttachment: 'הוספת קבצים מצורפים', @@ -1642,6 +1701,9 @@ const tMain = createI18n({ autosaveDiscard: 'छोड़ें', btnDontSave: 'न सहेजें', btnCancel: 'रद्द करें', + extModifiedMsg: 'फ़ाइल को किसी अन्य प्रोग्राम ने बदल दिया है।', + extModifiedDetail: 'फिर भी सहेजें और डिस्क पर मौजूद बदलावों को अधिलेखित करें?', + btnOverwrite: 'अधिलेखित करें', dlgInsertImage: 'छवि सम्मिलित करें', filterImages: 'छवियाँ', dlgAddAttachment: 'अनुलग्नक जोड़ें', @@ -1733,6 +1795,9 @@ const tMain = createI18n({ autosaveDiscard: '放棄', btnDontSave: '不儲存', btnCancel: '取消', + extModifiedMsg: '檔案已被其他程式修改。', + extModifiedDetail: '仍要儲存並覆寫磁碟上的變更嗎?', + btnOverwrite: '覆寫', dlgInsertImage: '插入圖片', filterImages: '圖片', dlgAddAttachment: '新增附件', @@ -1830,6 +1895,10 @@ let runtime: DocsRuntimeConfig = { export function configureDocsRuntime(config: DocsRuntimeConfig): void { runtime = config + // shell mode: the shell queues argv files itself (per-tab pendingWindowOpens); + // the module-scope fallback would leak the double-clicked file into the next + // blank tab's consume-pending-open + pendingOpenPath = null } let mainWindow: BrowserWindow | null = null @@ -1902,13 +1971,15 @@ export function openExternalDocx(filePath: string | null): void { pendingOpenPath = filePath return } - void loadDocx(filePath).then((result) => { - if (!result || win.isDestroyed()) return - if (win.isMinimized()) win.restore() - win.show() - win.focus() - win.webContents.send('docs:opened', result) - }) + void loadDocx(filePath, win.webContents.id) + .then((result) => { + if (!result || win.isDestroyed()) return + if (win.isMinimized()) win.restore() + win.show() + win.focus() + win.webContents.send('docs:opened', result) + }) + .catch((err) => dialog.showErrorBox(tm('dlgOpenDoc'), String(err))) } function userDataPath(...parts: string[]): string { @@ -1970,8 +2041,14 @@ export function removeRecentFiles(filePaths: string[]): void { * title bar (docs keeps path state on the renderer side). */ export function docsFileRenamed(wc: WebContents, oldPath: string, newPath: string): void { // keep the save allowlist in sync so docs:save accepts the renamed path - docWritablePaths.delete(oldPath) - docWritablePaths.add(newPath) + docWritablePaths.get(wc.id)?.delete(oldPath) + allowDocWrite(wc.id, newPath) + const states = docDiskStates.get(wc.id) + const recorded = states?.get(oldPath) + if (states && recorded) { + states.delete(oldPath) + states.set(newPath, recorded) + } wc.send('docs:renamed', { oldPath, newPath }) } @@ -2010,17 +2087,137 @@ export function toggleStarredFile(filePath: string): void { // ---- original archive (pass-through base: original file archived by content hash) ---- -function archiveOriginal(filePath: string, bytes: Buffer): string { - const hash = createHash('sha256').update(bytes).digest('hex') +async function archiveOriginal(filePath: string, bytes: Buffer): Promise { + const hash = sha256Hex(bytes) const dir = userDataPath('originals') - mkdirSync(dir, { recursive: true }) + await mkdir(dir, { recursive: true }) const target = join(dir, `${hash}.docx`) - if (!existsSync(target)) copyFileSync(filePath, target) + if (!existsSync(target)) await copyFile(filePath, target) + void pruneOriginals(dir) return hash } -/** paths the renderer may overwrite via docs:save — populated by open/save-as flows */ -const docWritablePaths = new Set() +const ORIGINALS_MAX_BYTES = 500 * 1024 * 1024 +let originalsPruneRunning = false + +/** cap the archive's total size; oldest by mtime go first (never blocks the open path) */ +async function pruneOriginals(dir: string): Promise { + if (originalsPruneRunning) return + originalsPruneRunning = true + try { + const files: Array<{ path: string; size: number; mtimeMs: number }> = [] + for (const name of await readdir(dir)) { + try { + const s = await stat(join(dir, name)) + if (s.isFile()) files.push({ path: join(dir, name), size: s.size, mtimeMs: s.mtimeMs }) + } catch { + /* removed concurrently */ + } + } + let total = files.reduce((sum, f) => sum + f.size, 0) + files.sort((a, b) => a.mtimeMs - b.mtimeMs) + for (const f of files) { + if (total <= ORIGINALS_MAX_BYTES) break + try { + await unlink(f.path) + total -= f.size + } catch { + /* already gone */ + } + } + } catch { + /* directory unreadable: retry on the next archive */ + } finally { + originalsPruneRunning = false + } +} + +/** per-renderer paths writable via docs:save — populated by open/save-as flows */ +const docWritablePaths = new Map>() +/** per-renderer PDF export targets authorized via the export save dialog */ +const pdfWritablePaths = new Map>() +const tornDownWcIds = new Set() + +function allowDocWrite(wcId: number, filePath: string): void { + const set = docWritablePaths.get(wcId) ?? new Set() + set.add(filePath) + docWritablePaths.set(wcId, set) +} + +function canDocWrite(wcId: number, filePath: string): boolean { + return docWritablePaths.get(wcId)?.has(filePath) === true +} + +function allowPdfWrite(wcId: number, filePath: string): void { + const set = pdfWritablePaths.get(wcId) ?? new Set() + set.add(filePath) + pdfWritablePaths.set(wcId, set) +} + +function canPdfWrite(wcId: number, filePath: string): boolean { + return pdfWritablePaths.get(wcId)?.has(filePath) === true +} + +function dropDocWriter(wcId: number): void { + docWritablePaths.delete(wcId) + pdfWritablePaths.delete(wcId) + docDiskStates.delete(wcId) + // Destroyed renderers count as torn down too: window-close paths never run + // teardownDocsRenderer, but an in-flight save handler resuming after the + // destruction must still fail its re-check (wcIds are never reused, so the + // set only accumulates a few integers per session). + tornDownWcIds.add(wcId) +} + +// ── External-modification detection: remember the disk state at every read/write +// so docs:save can refuse to clobber edits made by Word/another window ── +const docDiskStates = new Map>() + +const sha256Hex = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex') + +async function rememberDiskState(wcId: number, filePath: string, bytes: Buffer): Promise { + try { + const s = await stat(filePath) + const states = docDiskStates.get(wcId) ?? new Map() + states.set(filePath, { mtimeMs: s.mtimeMs, size: s.size, hash: sha256Hex(bytes) }) + docDiskStates.set(wcId, states) + } catch { + /* unstatable target: skip tracking; the next save simply won't flag a conflict */ + } +} + +async function diskChangedExternally(wcId: number, filePath: string): Promise { + let current: { mtimeMs: number; size: number } | null + try { + current = await stat(filePath) + } catch { + current = null + } + return isExternallyModified(docDiskStates.get(wcId)?.get(filePath), current, async () => { + try { + return sha256Hex(await readFile(filePath)) + } catch { + return null + } + }) +} + +/** A closed docs tab detaches without destroying its webContents (shell freeze + * workaround), so the orphan must lose write access and stop its timers — otherwise + * its 30s recovery loop resurrects content the user already discarded. */ +export function teardownDocsRenderer(contents: WebContents): void { + tornDownWcIds.add(contents.id) + // Sweep recovery copies for this renderer's documents: every non-crash close + // either saved (docs:save already cleared it) or explicitly discarded, so a + // copy still on disk here is a leftover from an in-flight recovery write. + for (const p of docWritablePaths.get(contents.id) ?? []) clearRecoveryCopy(p) + // reclaim every per-wcId grant, not just doc saves — the orphaned renderer + // must also lose its dialog-authorized PDF targets and disk-state cache + docWritablePaths.delete(contents.id) + pdfWritablePaths.delete(contents.id) + docDiskStates.delete(contents.id) + if (!contents.isDestroyed()) contents.send('docs:teardown') +} // ── Crash recovery: dirty renderers push a copy every 30s // (docs:write-recovery); a normal save cleans it up; open offers Restore/Discard ── @@ -2028,7 +2225,12 @@ const recoveryDir = () => userDataPath('docs-autosave') const recoveryPathFor = (filePath: string) => join(recoveryDir(), `${createHash('sha1').update(filePath).digest('hex').slice(0, 16)}.docx`) +/** Bumped by every clear: an in-flight docs:write-recovery that started before + * the bump must not recreate the file it is about to land (stale-recovery race). */ +const recoveryClearEpochs = new Map() + function clearRecoveryCopy(filePath: string): void { + recoveryClearEpochs.set(filePath, (recoveryClearEpochs.get(filePath) ?? 0) + 1) try { unlinkSync(recoveryPathFor(filePath)) } catch { @@ -2043,8 +2245,11 @@ async function maybeRecoverDocBytes(filePath: string, original: Buffer): Promise try { if (!existsSync(asPath)) return original if (statSync(asPath).mtimeMs <= statSync(filePath).mtimeMs) { - unlinkSync(asPath) - return original + // a crashed partial write bumps mtime yet corrupts the file — keep the copy then + if (looksLikeZip(original)) { + unlinkSync(asPath) + return original + } } } catch { return original @@ -2064,7 +2269,7 @@ async function maybeRecoverDocBytes(filePath: string, original: Buffer): Promise : await dialog.showMessageBox(options) if (r.response === 0) { try { - return readFileSync(asPath) + return await readFile(asPath) } catch { return original } @@ -2073,14 +2278,16 @@ async function maybeRecoverDocBytes(filePath: string, original: Buffer): Promise return original } -async function loadDocx(filePath: string): Promise { +async function loadDocx(filePath: string, wcId: number): Promise { if (typeof filePath !== 'string' || !/\.docx$/i.test(filePath)) return null if (!existsSync(filePath)) return null - const original = readFileSync(filePath) - const hash = archiveOriginal(filePath, original) + const original = await readFile(filePath) + const hash = await archiveOriginal(filePath, original) const bytes = await maybeRecoverDocBytes(filePath, original) pushRecent(filePath) - docWritablePaths.add(filePath) + allowDocWrite(wcId, filePath) + // record the on-disk file, not the recovery copy: what matters is what save would overwrite + await rememberDiskState(wcId, filePath, original) return { path: filePath, name: basename(filePath), @@ -2321,18 +2528,40 @@ export function registerAiIpc(): void { } const controller = new AbortController() activeAiStreams.set(requestId, controller) + // wire-activity keepalive: lets the renderer's silence watchdog tell a slow turn from a dead one + let lastPing = 0 + const ping = () => { + const now = Date.now() + if (now - lastPing < 5_000) return + lastPing = now + send({ requestId, type: 'ping' }) + } try { + let stopReason: string | undefined await streamForProvider(provider, config, system, messages, tools, maxTokens, { signal: controller.signal, onDelta: (text) => send({ requestId, type: 'delta', text }), onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }), + onActivity: ping, + onStopReason: (reason) => { + stopReason = reason + }, }) - send({ requestId, type: 'done' }) + send({ requestId, type: 'done', stopReason }) } catch (err) { if (controller.signal.aborted) { send({ requestId, type: 'done' }) } else { - send({ requestId, type: 'error', error: err instanceof Error ? err.message : String(err) }) + send({ + requestId, + type: 'error', + error: err instanceof Error ? err.message : String(err), + ...(err instanceof AiTimeoutError + ? { errorCode: 'timeout' as const } + : err instanceof AiCreditsError + ? { errorCode: 'credits' as const } + : {}), + }) } } finally { activeAiStreams.delete(requestId) @@ -2609,10 +2838,10 @@ export function registerDocsIpc(): void { properties: ['openFile'], }) if (result.canceled || result.filePaths.length === 0) return null - return loadDocx(result.filePaths[0]) + return loadDocx(result.filePaths[0], event.sender.id) }) - ipcMain.handle('docs:open-path', (_event, filePath: string) => loadDocx(filePath)) + ipcMain.handle('docs:open-path', (event, filePath: string) => loadDocx(filePath, event.sender.id)) ipcMain.handle('docs:consume-pending-open', (event) => { rendererReady = true @@ -2620,11 +2849,11 @@ export function registerDocsIpc(): void { const queued = pendingWindowOpens.get(event.sender.id) if (queued) { pendingWindowOpens.delete(event.sender.id) - return loadDocx(queued) + return loadDocx(queued, event.sender.id) } const filePath = pendingOpenPath pendingOpenPath = null - return filePath ? loadDocx(filePath) : null + return filePath ? loadDocx(filePath, event.sender.id) : null }) /** returns true when this tab was opened via "New Document" and should start blank */ @@ -2637,27 +2866,75 @@ export function registerDocsIpc(): void { return false }) - ipcMain.handle('docs:save', (_event, filePath: string, data: ArrayBuffer) => { - try { - // only paths the user opened or chose via save-as may be overwritten - if (typeof filePath !== 'string' || !docWritablePaths.has(filePath)) { - return { ok: false, error: 'save target is not an opened document' } + ipcMain.handle( + 'docs:save', + async (event, filePath: string, data: ArrayBuffer, auto?: boolean) => { + try { + // only paths this renderer opened or chose via save-as may be overwritten + if (typeof filePath !== 'string' || !canDocWrite(event.sender.id, filePath)) { + return { ok: false, error: 'save target is not an opened document' } + } + if (await diskChangedExternally(event.sender.id, filePath)) { + // autosave must never clobber another program's edits silently; the + // renderer stays dirty and the next manual save raises the dialog + if (auto === true) return { ok: false, reason: 'external-modified' } + const options = { + type: 'warning' as const, + message: tm('extModifiedMsg'), + detail: tm('extModifiedDetail'), + buttons: [tm('btnOverwrite'), tm('btnCancel')], + defaultId: 0, + cancelId: 1, + noLink: true, + } + const parent = dialogParent(event) + const { response } = + parent && !parent.isDestroyed() + ? await dialog.showMessageBox(parent, options) + : await dialog.showMessageBox(options) + if (response !== 0) return { ok: false, reason: 'external-modified' } + } + // The tab may have been closed while the external-change check or the + // overwrite prompt was pending: a Don't Save close revoked this tab's + // grants, and landing the write now would persist discarded edits. + if (tornDownWcIds.has(event.sender.id) || !canDocWrite(event.sender.id, filePath)) { + return { ok: false, error: 'save target is not an opened document' } + } + const bytes = Buffer.from(data) + await atomicWriteFile(filePath, bytes) + await rememberDiskState(event.sender.id, filePath, bytes) + clearRecoveryCopy(filePath) + pushRecent(filePath) + return { ok: true } + } catch (err) { + return { ok: false, error: String(err) } } - writeFileSync(filePath, Buffer.from(data)) - clearRecoveryCopy(filePath) - pushRecent(filePath) - return { ok: true } - } catch (err) { - return { ok: false, error: String(err) } - } - }) + }, + ) // crash-recovery copy from a dirty renderer; best-effort, never surfaces - ipcMain.handle('docs:write-recovery', (_event, filePath: string, data: ArrayBuffer) => { + ipcMain.handle('docs:write-recovery', async (event, filePath: string, data: ArrayBuffer) => { try { - if (typeof filePath !== 'string' || !docWritablePaths.has(filePath)) return { ok: false } - mkdirSync(recoveryDir(), { recursive: true }) - writeFileSync(recoveryPathFor(filePath), Buffer.from(data)) + if (tornDownWcIds.has(event.sender.id)) return { ok: false } + if (typeof filePath !== 'string' || !canDocWrite(event.sender.id, filePath)) + return { ok: false } + // snapshot before any await: a save or discard that clears the recovery + // copy while this write is in flight bumps the epoch and invalidates it + const epoch = recoveryClearEpochs.get(filePath) ?? 0 + await mkdir(recoveryDir(), { recursive: true }) + await atomicWriteFile(recoveryPathFor(filePath), Buffer.from(data)) + // The tab may have been closed ("Don't Save" clears the copy, teardown + // revokes access) or the document saved (docs:save clears the copy) while + // the write was in flight. A write that lost either race would offer + // discarded or already-saved content as recovery on the next open — undo it. + if ( + tornDownWcIds.has(event.sender.id) || + !canDocWrite(event.sender.id, filePath) || + (recoveryClearEpochs.get(filePath) ?? 0) !== epoch + ) { + clearRecoveryCopy(filePath) + return { ok: false } + } return { ok: true } } catch { return { ok: false } @@ -2665,15 +2942,22 @@ export function registerDocsIpc(): void { }) ipcMain.handle('docs:save-as', async (event, defaultName: string, data: ArrayBuffer) => { + // an orphaned (closed-tab) renderer must not open dialogs or land new files + if (tornDownWcIds.has(event.sender.id)) return { ok: false } const result = await saveDialog(event, { title: tm('dlgSaveAs'), defaultPath: defaultName, filters: [{ name: tm('filterWord'), extensions: ['docx'] }], }) if (result.canceled || !result.filePath) return { ok: false } + // the tab may have been closed while the dialog was open; checked before the + // write because Save As may overwrite an existing file (no safe rollback) + if (tornDownWcIds.has(event.sender.id)) return { ok: false } try { - writeFileSync(result.filePath, Buffer.from(data)) - docWritablePaths.add(result.filePath) + const bytes = Buffer.from(data) + await atomicWriteFile(result.filePath, bytes) + allowDocWrite(event.sender.id, result.filePath) + await rememberDiskState(event.sender.id, result.filePath, bytes) pushRecent(result.filePath) notifyFileSaved(event.sender, result.filePath) return { ok: true, path: result.filePath } @@ -2682,11 +2966,22 @@ export function registerDocsIpc(): void { } }) - ipcMain.handle('docs:save-new', (event, defaultName: string, data: ArrayBuffer) => { + ipcMain.handle('docs:save-new', async (event, defaultName: string, data: ArrayBuffer) => { try { + // a discarded draft in an orphaned renderer must not silently persist + // itself to the default folder after the user chose Don't Save + if (tornDownWcIds.has(event.sender.id)) return { ok: false } const filePath = uniquePathIn(defaultSaveDir(), defaultName) - writeFileSync(filePath, Buffer.from(data)) - docWritablePaths.add(filePath) + const bytes = Buffer.from(data) + await atomicWriteFile(filePath, bytes) + // teardown may have happened while the write was in flight — the path is + // freshly created, so rolling it back is safe (mirrors docs:write-recovery) + if (tornDownWcIds.has(event.sender.id)) { + await unlink(filePath).catch(() => {}) + return { ok: false } + } + allowDocWrite(event.sender.id, filePath) + await rememberDiskState(event.sender.id, filePath, bytes) pushRecent(filePath) notifyFileSaved(event.sender, filePath) return { ok: true, path: filePath } @@ -2805,7 +3100,11 @@ export function registerDocsIpc(): void { pageHeightTwips: number, outPath?: string, ) => { + // renderer-supplied outPath is only honored when a save dialog authorized it before 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('dlgExportPdf'), @@ -2814,6 +3113,7 @@ export function registerDocsIpc(): void { }) if (result.canceled || !result.filePath) return { ok: false } filePath = result.filePath + allowPdfWrite(event.sender.id, filePath) } try { const data = await event.sender.printToPDF({ @@ -2858,6 +3158,9 @@ export function registerDocsIpc(): void { 'docs:save-merged-pdf', async (event, defaultName: string, base64Parts: string[], outPath?: string) => { 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('dlgExportPdf'), @@ -2866,6 +3169,7 @@ export function registerDocsIpc(): void { }) if (result.canceled || !result.filePath) return { ok: false } filePath = result.filePath + allowPdfWrite(event.sender.id, filePath) } try { const { PDFDocument } = await import('pdf-lib') @@ -3141,7 +3445,7 @@ export function buildDocsMenu(): void { { label: tm('menuMacros'), enabled: false }, ], }, - { label: tm('menuWindow'), role: 'windowMenu' }, + windowMenuTemplate(process.platform, appMenuLabels(getUiLang())), { label: tm('menuHelp'), role: 'help', @@ -3214,6 +3518,7 @@ export function createDocsWindow(openPath?: string): BrowserWindow { }) win.on('closed', () => { pendingWindowOpens.delete(webContentsId) + dropDocWriter(webContentsId) // release any close-guard waiter still keyed on the gone webContents closeCheckWaiters.get(webContentsId)?.({ dirty: false, autoSave: false }) closeCheckWaiters.delete(webContentsId) @@ -3266,10 +3571,15 @@ ipcMain.on('docs:close-save-result', (event, ok: unknown) => { /** Ask the renderer for pre-close state (dirty flag + autosave switch); no reply within 2s * fails CLOSED — a busy or wedged renderer may well hold unsaved changes, so the caller - * prompts instead of closing silently. */ + * prompts instead of closing silently. Concurrent callers share one query: a second + * request must not overwrite the pending waiter (that stranded the first until timeout). */ +const closeStateQueries = new Map>() + function queryCloseState(contents: WebContents): Promise { if (contents.isDestroyed()) return Promise.resolve({ dirty: false, autoSave: false }) - return new Promise((resolve) => { + const pending = closeStateQueries.get(contents.id) + if (pending) return pending + const query = new Promise((resolve) => { const timer = setTimeout(() => { closeCheckWaiters.delete(contents.id) resolve({ dirty: true, autoSave: false, unresponsive: true }) @@ -3279,7 +3589,9 @@ function queryCloseState(contents: WebContents): Promise { resolve(state) }) contents.send('docs:close-check') - }) + }).finally(() => closeStateQueries.delete(contents.id)) + closeStateQueries.set(contents.id, query) + return query } export async function docsQueryDirty(contents: WebContents): Promise { @@ -3307,7 +3619,24 @@ function requestRendererSave(contents: WebContents): Promise { * to run the full save flow (new documents open Save As) and await the result; * failure/cancel/timeout keeps the document open. */ -export async function requestDocsClose( +export function requestDocsClose( + contents: WebContents, + parent?: BrowserWindow | null, +): Promise { + // re-entry (close clicked again while the prompt is up) joins the same flow + // instead of stacking dialogs / stranding the first waiter + const pending = docsCloseRequests.get(contents.id) + if (pending) return pending + const request = performDocsClose(contents, parent).finally(() => + docsCloseRequests.delete(contents.id), + ) + docsCloseRequests.set(contents.id, request) + return request +} + +const docsCloseRequests = new Map>() + +async function performDocsClose( contents: WebContents, parent?: BrowserWindow | null, ): Promise { @@ -3387,6 +3716,7 @@ export function createDocsView(openPath?: string): WebContentsView { const wcId = view.webContents.id view.webContents.once('destroyed', () => { pendingWindowOpens.delete(wcId) + dropDocWriter(wcId) closeCheckWaiters.get(wcId)?.({ dirty: false, autoSave: false }) closeCheckWaiters.delete(wcId) closeSaveWaiters.get(wcId)?.(false) @@ -3404,6 +3734,7 @@ export function hasDocsWindow(): boolean { export function startDocsStandalone(): void { installNavigationGuard(app) + installContextMenu(app, () => contextMenuLabels(getUiLang())) // dev runs must not share the packaged app's userData (recent files, AI settings) // or its single-instance lock — otherwise `npm run dev` silently quits whenever // the installed GenOffice Docs is open and forwards its argv there instead. diff --git a/apps/docs/src/main/external-change.ts b/apps/docs/src/main/external-change.ts new file mode 100644 index 0000000..f2e1674 --- /dev/null +++ b/apps/docs/src/main/external-change.ts @@ -0,0 +1,24 @@ +/** Disk snapshot recorded at the last read/write of a document path. */ +export interface DiskFileState { + mtimeMs: number + size: number + hash: string +} + +/** + * True when the file on disk no longer matches the recorded state, i.e. another + * program wrote it since we last read/saved it. No record (path never tracked) + * or a missing file (deleted externally) is not a conflict — the save proceeds + * and recreates the file. The hash read only runs when mtime+size already + * disagree, so the common no-conflict save never rereads the file. + */ +export async function isExternallyModified( + recorded: DiskFileState | undefined, + current: { mtimeMs: number; size: number } | null, + readHash: () => string | null | Promise, +): Promise { + if (!recorded || !current) return false + if (current.mtimeMs === recorded.mtimeMs && current.size === recorded.size) return false + const hash = await readHash() + return hash !== null && hash !== recorded.hash +} diff --git a/apps/docs/src/preload/index.ts b/apps/docs/src/preload/index.ts index 6aa396e..da3d608 100644 --- a/apps/docs/src/preload/index.ts +++ b/apps/docs/src/preload/index.ts @@ -36,9 +36,15 @@ const api: DesktopApi = { ipcRenderer.on('docs:renamed', listener) return () => ipcRenderer.removeListener('docs:renamed', listener) }, - saveDocx: (path: string, data: ArrayBuffer) => ipcRenderer.invoke('docs:save', path, data), + saveDocx: (path: string, data: ArrayBuffer, auto?: boolean) => + ipcRenderer.invoke('docs:save', path, data, auto === true), writeRecoveryCopy: (path: string, data: ArrayBuffer) => ipcRenderer.invoke('docs:write-recovery', path, data), + onTeardown: (handler) => { + const listener = () => handler() + ipcRenderer.on('docs:teardown', listener) + return () => ipcRenderer.removeListener('docs:teardown', listener) + }, saveDocxAs: (defaultName: string, data: ArrayBuffer) => ipcRenderer.invoke('docs:save-as', defaultName, data), saveDocxNew: (defaultName: string, data: ArrayBuffer) => diff --git a/apps/docs/src/renderer/App.tsx b/apps/docs/src/renderer/App.tsx index 8486c87..f86c642 100644 --- a/apps/docs/src/renderer/App.tsx +++ b/apps/docs/src/renderer/App.tsx @@ -65,8 +65,11 @@ import { textHasCjk, } from './line-metrics' import { saveUntilPersisted } from './save-until-persisted' +import { cachedByDoc } from './doc-cache' +import { useShallowStable, useStableCallbacks } from './use-stable' import { FindPanel } from './components/FindPanel' import { Ribbon } from './components/Ribbon' +import { computeFormatState } from './components/ribbon-format-state' import { IconRedo, IconSave, IconUndo } from './components/icons' import { LinkInsertModal, @@ -74,7 +77,6 @@ import { insertImageViaDialog, insertPageBreakAt, insertTableAt, - setParaAttrs, type InkPenSettings, type RevisionDisplayMode, type ViewMode, @@ -88,8 +90,14 @@ import { } from './components/ContextMenu' import { PromptModal } from './components/PromptModal' import { t, useI18n } from './i18n/locale' -import { setActiveSubEditor, subscribeSubEditorState } from './editor/active-editor' +import { + getActiveSubEditor, + setActiveSubEditor, + subscribeSubEditorState, +} from './editor/active-editor' import type { CompareEntry } from './editor/compare' +import { collectHeadings } from './editor/headings' +import { setSelectionAlign } from './editor/direction' import { editorExtensions, @@ -102,6 +110,7 @@ import { collectRevisions, gotoRevision, type TrackChangesStorage } from './edit import { NavPane } from './components/NavPane' import { Ruler } from './components/Ruler' import { docLineFactor, docStyleCss, docThemeCss } from './doc-style-css' +import { isDocDirty } from './doc-dirty' import { EMPTY_HF_VARIANTS, hfFromPart, @@ -151,6 +160,13 @@ const _IS_MAC = navigator.platform.toLowerCase().includes('mac') const twipsToPx = (twips: number) => (twips / 1440) * 96 +const EMPTY_BLOCKS: Block[] = [] + +// O(doc) derivations cached by PM doc reference: caret moves and unrelated +// state updates reuse the last result instead of re-walking the whole document +const wordCountOfDoc = cachedByDoc((d) => countWords(d.textContent)) +const revisionCountOfDoc = cachedByDoc((d) => collectRevisions(d).length) + /** * Document position of a measured line-start DOM anchor. posAtDOM works from the DOM * tree, unlike posAtCoords whose viewport hit-testing returns degenerate positions for @@ -246,7 +262,7 @@ const DEFAULT_SETTINGS: AiSettings = { export function App() { // subscribe to language switches for re-render; strings all go through module-level t, so memoized callbacks never capture stale closures - useI18n() + const { lang } = useI18n() const [doc, setDoc] = useState(null) /** true until the pending-open / new-blank boot checks settle; the start screen stays hidden meanwhile */ const bootPendingRef = useRef | null>(null) @@ -457,6 +473,8 @@ export function App() { entries: CompareEntry[] } | null>(null) const [autoSave, setAutoSave] = useState(() => localStorage.getItem('aidocs.autoSave') === '1') + // tab closed but this renderer kept alive (shell freeze workaround): go inert + const [tornDown, setTornDown] = useState(false) const [aiPreset, setAiPreset] = useState<{ text: string nonce: number @@ -616,15 +634,18 @@ export function App() { document.title = doc ? doc.fileName : 'GenOffice Docs' }, [doc]) + useEffect(() => window.desktop.onTeardown?.(() => setTornDown(true)), []) + // Crash-recovery copy: while the document is dirty, push a serialized // copy to the main process every 30s; a normal save (or discarding on close) removes // it, and reopening the file offers Restore/Discard when a newer copy exists. useEffect(() => { + if (tornDown) return const timer = window.setInterval(() => { void writeRecoveryCopyImpl(fileCtxRef.current) }, 30_000) return () => window.clearInterval(timer) - }, []) + }, [tornDown]) // Recompute the document-level line-height factor while editing: // docStyleCss decides it once at parse time, so typing CJK into a blank document @@ -1314,7 +1335,7 @@ export function App() { const submitProtectModal = useCallback(() => submitProtectModalImpl(reviewCtxRef.current), []) const compareWithFile = useCallback(() => compareWithFileImpl(reviewCtxRef.current), []) - const revisionCount = editor && doc ? collectRevisions(editor.state.doc).length : 0 + const revisionCount = editor && doc ? revisionCountOfDoc(editor.state.doc) : 0 /** Word's page-width / whole-page zoom: compute the actual zoom ratio from the current window size */ const zoomFit = useCallback( @@ -1540,13 +1561,12 @@ export function App() { const nums = secs.length > 1 ? pageNumbers(slices, secs) : slices.map((_, i) => i + 1) const byEl = new Map(mBlocks.filter((b) => b.el).map((b) => [b.el as HTMLElement, b.top])) const pages: number[] = [] - editor.state.doc.forEach((node, offset) => { - if (node.type.name !== 'docHeading' || !node.textContent.trim()) return - const dom = editor.view.nodeDOM(offset) as HTMLElement | null + for (const h of collectHeadings(editor.state.doc)) { + const dom = editor.view.nodeDOM(h.pos) as HTMLElement | null const top = dom ? byEl.get(dom) : undefined const idx = top === undefined ? 1 : pageAt(slices, top + 1) pages.push(nums[Math.min(Math.max(idx, 1), nums.length) - 1] ?? idx) - }) + } return pages }, [ editor, @@ -1880,30 +1900,7 @@ export function App() { // "has unsaved changes" check shared by the close guard and autosave; refreshed on every // render (all edit paths forceRender), so the guard's query reads the latest value const anyDirtyRef = useRef(false) - const hasUnsavedChanges = - dirtyRef.current || - sectionDirty || - sectionsDirty.length > 0 || - trailingStartType !== null || - pageColorDirty || - headerDirty || - footerDirty || - hfVariantsDirty.length > 0 || - Object.keys(sectionHfEdits).length > 0 || - pgNumEdit !== null || - pgNumDirtySections.length > 0 || - numberingDirty || - Object.keys(styleUpserts).length > 0 || - titlePgDirty || - evenOddHfDirty || - watermarkDirty || - inksDirty || - notesDirty || - sourcesDirty || - themeFontsDirty || - themeColorsDirty || - commentsDirty || - protectionDirty + const hasUnsavedChanges = isDocDirty(fileCtxRef.current) anyDirtyRef.current = hasUnsavedChanges // close guard: the main process queries dirty state before closing a tab/window; choosing "Save" runs a full save and reports back @@ -1918,10 +1915,13 @@ export function App() { const offSave = window.desktop.onCloseSaveRequest?.(() => { // Closing must not report success while edits are still unpersisted, so a // save that raced with typing is retried until the file catches up. + // save(false) never prompts — a pathless first save lands silently in the + // default folder — so retrying is always safe; reporting "persisted" just + // because the snapshot had no path yet would close over mid-save edits. void saveUntilPersisted({ save: () => save(false), wasIncomplete: () => saveIncompleteRef.current, - hasPath: () => !!doc?.filePath, + hasPath: () => true, }).then( (ok) => window.desktop.reportCloseSaveResult(ok === true), () => window.desktop.reportCloseSaveResult(false), @@ -1935,31 +1935,9 @@ export function App() { // autosave: every 30s and on window blur, silently persist pending changes useEffect(() => { - if (!autoSave || !doc || !doc.filePath) return + if (tornDown || !autoSave || !doc || !doc.filePath) return const tick = () => { - const anyDirty = - dirtyRef.current || - sectionDirty || - sectionsDirty.length > 0 || - trailingStartType !== null || - pageColorDirty || - headerDirty || - footerDirty || - hfVariantsDirty.length > 0 || - Object.keys(sectionHfEdits).length > 0 || - pgNumEdit !== null || - pgNumDirtySections.length > 0 || - numberingDirty || - Object.keys(styleUpserts).length > 0 || - titlePgDirty || - evenOddHfDirty || - watermarkDirty || - inksDirty || - notesDirty || - sourcesDirty || - themeFontsDirty || - themeColorsDirty - if (!anyDirty) return + if (!isDocDirty(fileCtxRef.current)) return if (editor?.view.composing) return // don't interrupt IME input const active = document.activeElement as HTMLElement | null if (active?.closest('td[contenteditable], .doc-textbox')) return // mid in-place edit @@ -1971,30 +1949,7 @@ export function App() { window.clearInterval(id) window.removeEventListener('blur', tick) } - }, [ - autoSave, - doc, - editor, - save, - sectionDirty, - pageColorDirty, - headerDirty, - footerDirty, - hfVariantsDirty, - sectionHfEdits, - pgNumEdit, - pgNumDirtySections, - numberingDirty, - styleUpserts, - titlePgDirty, - evenOddHfDirty, - watermarkDirty, - inksDirty, - notesDirty, - sourcesDirty, - themeFontsDirty, - themeColorsDirty, - ]) + }, [tornDown, autoSave, doc, editor, save]) // After an AI run finishes on a never-saved document, silently save it once: the // first save derives the file name from the first heading (see deriveAutoFileName @@ -2012,7 +1967,16 @@ export function App() { }, [editor, save]) useEffect(() => { + // editing shortcuts only fire when focus is in an editor surface (main + // ProseMirror, textbox sub-editor, in-place table cell) or nowhere at all — + // never while typing in the find box, AI input or other form fields + const focusInEditor = () => { + const el = document.activeElement + if (!el || el === document.body) return true + return !!(el as HTMLElement).closest('.ProseMirror, td[contenteditable]') + } const handler = (e: KeyboardEvent) => { + const canEdit = !!editor?.isEditable && focusInEditor() if ((e.metaKey || e.ctrlKey) && e.key === 's') { e.preventDefault() void save(e.shiftKey) @@ -2026,39 +1990,41 @@ export function App() { if (doc) setShowFind(true) } // Word dialog shortcuts: Font ⌘D / Paragraph ⌥⌘M / Hyperlink ⌘K - if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key === 'd' && doc) { + if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key === 'd' && doc && canEdit) { e.preventDefault() setShowFontDialog(true) } - if ((e.metaKey || e.ctrlKey) && e.altKey && e.code === 'KeyM' && doc) { + if ((e.metaKey || e.ctrlKey) && e.altKey && e.code === 'KeyM' && doc && canEdit) { e.preventDefault() setShowParaDialog(true) } - if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key === 'k' && doc) { + if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key === 'k' && doc && canEdit) { e.preventDefault() setShowLinkModal(true) } - if (e.key === 'F9' && doc) { + if (e.key === 'F9' && doc && editor?.isEditable) { e.preventDefault() updateFields() } // Word alignment shortcuts - const ALIGN_KEYS: Record = { - l: null, + const ALIGN_KEYS: Record = { + l: 'left', e: 'center', r: 'right', j: 'justify', } - if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key in ALIGN_KEYS && editor) { + if ( + (e.metaKey || e.ctrlKey) && + !e.shiftKey && + !e.altKey && + e.key in ALIGN_KEYS && + editor && + canEdit + ) { e.preventDefault() - const align = ALIGN_KEYS[e.key] - editor - .chain() - .focus() - .updateAttributes('docParagraph', { align }) - .updateAttributes('docHeading', { align }) - .updateAttributes('docListItem', { align }) - .run() + // route into a focused textbox sub-editor, like the ribbon does + const target = getActiveSubEditor() ?? editor + setSelectionAlign(target, ALIGN_KEYS[e.key]) } } window.addEventListener('keydown', handler) @@ -2079,7 +2045,8 @@ export function App() { // native application menu → renderer commands useEffect(() => { return window.desktop.onMenuCommand((command, payload) => { - const align = (value: string | null) => editor && setParaAttrs(editor, { align: value }) + const align = (value: 'left' | 'center' | 'right' | 'justify') => + editor && setSelectionAlign(editor, value) switch (command) { case 'new': void newFile() @@ -2164,7 +2131,7 @@ export function App() { editor?.chain().focus().toggleMark('underline').run() break case 'align-left': - align(null) + align('left') break case 'align-center': align('center') @@ -2268,9 +2235,173 @@ export function App() { } }, [editor, openRecent, save, status, exportPdf]) + // 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 + const formatState = useShallowStable( + computeFormatState(editor, doc?.parsed.styles, doc?.parsed.docDefaults), + ) + + // registerStyleUpsert mutates doc.parsed.styles in place; clone per upsert so the + // memoized Ribbon sees a new reference and refreshes its style gallery + const ribbonStyles = useMemo( + () => (doc ? new Map(doc.parsed.styles) : undefined), + // eslint-disable-next-line react-hooks/exhaustive-deps -- styleUpserts: in-place styles mutations must produce a new Map identity + [doc, styleUpserts], + ) + + /** every function prop of the memoized Ribbon, with stable identities (dispatches into the latest render's closures) */ + const ribbonActions = useStableCallbacks({ + allocateNumId: (kind: 'bullet' | 'ordered') => allocateListNumId(kind), + createListDef: (levels: CustomNumberingLevel[]) => createCustomListDef(levels), + onStylesPanel: () => setShowStylesPanel((v) => !v), + onParagraphDialog: () => setShowParaDialog(true), + onOpen: () => void openFile(), + onSave: () => void save(false), + onSaveAs: () => void save(true), + onToggleAi: () => setShowAi((v) => !v), + onSection: (next: SectionSettings) => { + // layout applies to the cursor's section; the final section's sectPr goes through SaveOptions.section (also drives canvas geometry) + setSections((prev) => + prev.map((s, i) => (i === activeSection ? { ...s, settings: next } : s)), + ) + if (sections.length <= 1 || activeSection === sections.length - 1) { + setSection(next) + setSectionDirty(true) + } else { + setSectionsDirty((d) => (d.includes(activeSection) ? d : [...d, activeSection])) + setStatus(t('appSectionSettingsApplied', { n: activeSection + 1 })) + } + }, + onInsertSectionBreak: (type: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage') => + insertSectionBreak(type), + onPageColor: (next: string | null) => { + setPageColor(next) + setPageColorDirty(true) + }, + onWatermark: (next: string | null) => { + setWatermark(next) + setWatermarkDirty(true) + setStatus(next ? t('appWatermarkSet', { text: next }) : t('appWatermarkRemoved')) + }, + onThemeFonts: (fonts: ThemeFonts) => { + setThemeFonts(fonts) + setThemeFontsDirty(true) + setStatus(t('appThemeFontsChanged')) + }, + onThemeColors: (colors: ThemeColors) => { + setThemeColors(colors) + setThemeColorsDirty(true) + setStatus(t('appThemeColorsApplied', { name: colors.name ?? '' })) + }, + onInkTool: setInkTool, + onInkPen: setInkPen, + onInkHighlighter: setInkHighlighter, + onInkClearAll: clearInks, + onInsertNote: insertNote, + onAddSource: (source: SourceInfo) => { + setSources((prev) => [...prev, source]) + setSourcesDirty(true) + setStatus(t('appSourceAdded', { title: source.title })) + }, + headingPages, + onZoom: setZoom, + onZoomFit: zoomFit, + onDarkCanvas: setDarkCanvas, + onAiPreset: (text: string) => { + // Word's Editor / Translate start working as soon as they're clicked + setShowAi(true) + setAiPreset({ text, nonce: Date.now(), autoRun: true }) + }, + onHeader: (next: HeaderFooter) => { + setHeader(next) + setHeaderDirty(true) + }, + onPageNumFormat: openPgNumModal, + onInsertField: insertField, + onFooter: (next: HeaderFooter) => { + setFooter(next) + setFooterDirty(true) + }, + onTitlePg: toggleTitlePg, + onEvenOddHf: (on: boolean) => { + setEvenOddHf(on) + setEvenOddHfDirty(true) + setHfView(on ? 'even' : 'default') + setStatus(on ? t('appEvenOddOn') : t('appEvenOddOff')) + }, + onShowMarks: setShowMarks, + onShowRuler: setShowRuler, + onShowNav: setShowNav, + onShowComments: () => setShowComments(true), + onNewComment: startNewComment, + onTrackChanges: setTrackChanges, + onRevisionDisplay: setRevisionDisplay, + onAcceptRevision: (all: boolean) => handleRevision('accept', all), + onRejectRevision: (all: boolean) => handleRevision('reject', all), + onGotoRevision: (dir: 1 | -1) => { + if (editor) gotoRevision(editor, dir) + }, + onToggleProtection: toggleProtection, + onCompare: () => void compareWithFile(), + onViewMode: setViewMode, + onReadMode: setReadMode, + onShowGrid: setShowGrid, + onSplitView: setSplitView, + onPagePreview: () => setShowPagePreview(true), + }) + + const closeCommentsPanel = useCallback(() => { + setShowComments(false) + cancelNewComment() + }, [cancelNewComment]) + + const hasDoc = !!doc + const quickActions = useMemo( + () => ( + <> + + + + +