openpencil/tests/engine/app/document/io/changes.test.ts

106 lines
3.6 KiB
TypeScript
Raw Normal View History

fix: protect unsaved documents and defer credential access (#713) * fix(app): protect unsaved documents when closing Mark tabs with unsaved content updates and ask whether to save before closing them. The prompt now covers tab closes, the desktop window close button, and the application Quit action, which previously discarded work when autosave had no writable target. Track a content revision separately from scene and recovery versions so a save only clears the indicator when it wrote the revision it captured. Cancelled pickers, failed writes, and edits made during a save keep the document open. Desktop uses the platform alert; the browser keeps the styled dialog. The desktop menu replaces the predefined Quit item so the accelerator and Dock-independent quit path request confirmation instead of exiting. * fix(ai): resolve credentials only when used Opening a document, creating a chat, or browsing chat history connected the provider and read saved secrets, which triggered system credential prompts without user intent. Startup now reads credential status only, migration runs inside the first explicit resolution, and the chat panel initializes local history without creating a transport. Stock-photo keys resolve per search instead of at settings refresh, and credentials still marked legacy count as configured so upgrading does not appear to lose them. * refactor(ai): export diagnostics from Settings only Chat kept its own debug log, copied mixed app-wide usage into a conversation export, and reported a missing cache rate as zero. Remove that surface and record AI requests, model steps, and tool activity as correlated diagnostic events instead. Settings remains the single export location, usage summaries can now distinguish unreported telemetry from zero, and transcript or tool payloads are no longer part of the export. * fix(ai): clear legacy credentials for real Clearing a Pexels, Unsplash, or provider key only removed the current store entry. A value that still lived in legacy storage kept the key configured, so a later search migrated and used the credential the user had just removed. Migrate before mutating so clearing also removes the legacy value, and share one in-flight migration so the media and provider paths cannot migrate the same plaintext twice. * fix(ai): scope credential migration per source Sharing one migration promise process-wide let a second storage return the first migration's result, leaving its own legacy keys unmigrated while reporting success. Track in-flight migrations per storage and serialize them, because every migration writes to the same store and concurrent runs could overwrite each other. * fix(app): destroy the window after a confirmed close Tauri's onCloseRequested helper destroys the window itself when a handler returns without preventing the event. Approving a close therefore invoked plugin:window|destroy, which the capability set did not grant, so the window stayed open with a permission error after saving. Always intercept the request and destroy the window explicitly once the choice is confirmed, and grant core:window:allow-destroy in place of the now-unused close permission. * fix(app): show a filled dot for unsaved tabs The unsaved indicator used a stroked Lucide circle whose fill attribute kept it an empty outline, reading as a disabled control. Draw the indicator as a filled accent dot matching the status dots used elsewhere in the app. * refactor(app): focus the unsaved prompt with VueUse Replace the manual watcher, nextTick, and component $el focus with useFocus, which focuses the Save button when the dialog mounts. Assert the focus in the close-protection test so the Return-saves behavior stays covered. * refactor(app): route Quit through the shared menu channel The Quit item emitted a bespoke app:request-exit event and the close module listened for it, while every other native item travels as a menu-event id dispatched by the shell and editor menu composables. Emit menu-event "quit" for both the Quit item and the platform exit request, handle it in useShellMenu beside check-updates, and share one confirmAppExit so window closes and app exits agree on a single approval. * refactor(app): generate the macOS app menu entries The application menu hardcoded its labels and the Quit accelerator in Rust while every other menu entry is generated from APP_MENU_SCHEMA. Move the custom app entries (About, Check for Updates, Quit) into APP_MENU_APP_ITEMS and emit desktop/generated/app-menu.json, keyed by id so the native builder cannot silently drop a label. Placement stays in Rust because the OS-predefined items sit between them, and the menu title now comes from the packaged product name. * build(tauri-menu): check generated menus against the schema The generated menu files are committed but nothing verified them, so a schema edit could silently leave desktop/generated stale until the next release build regenerated it. Split the renderers from the write step, register the tool as a workspace so its dependencies resolve, and compare the committed files with the schema in a test that runs with the other tool checks. * fix(app): serialize exit confirmations The window close handler and the Quit item both call confirmAppExit, and the per-handler closing flag does not cover the two paths. Both could run close preparation, so an unsaved document could be prompted twice. Share one in-flight confirmation and clear it when it settles, so a cancelled or failed attempt still prompts again on the next request.
2026-09-17 12:25:15 +00:00
import { expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core/editor'
perf: speed up opening large pages (#953) * perf(canvas): find guide owners from an index instead of walking the page Drawing and hit-testing guides visited every layer of the page on each frame to find the few that carry guides; on a large page that took about 1.2s of a load's rendering. The graph now keeps the set of layers with guides current from its node events, and both read it. * perf(layout): write only changed geometry and request one render per layout pass Layout wrote every laid-out layer's geometry whether or not it changed, so each pass over a large page notified every graph listener for every layer; a page load spent about 1s handling those updates. Layout now writes only the fields that changed, and the updates a layout pass makes ask for a single render, queued for before the next frame, instead of bumping the editor's reactive versions once per layer. * test(canvas): drop the graph double the guide tests no longer use * perf(fig): copy an opened file once on the main thread instead of three times Opening a .fig in the browser copied the file for a main-thread fallback the caller's buffer already served, then copied it twice more for the worker, which parses from one and keeps the other as the original archive. A 109MB file briefly took over 400MB on the main thread. The fallback now reuses the caller's buffer, and the worker receives one copy and makes its archive copy itself. * docs(changelog): note faster large-page loads * fix(app): run recovery and autosave after edits, not redraws Recovery and autosave watched sceneVersion, a render counter that every requestRender bumps: opening a file, layout passes, fonts, and each layer a page loads. Safari has no File System Access API, so its opened files have no writable source and always get recovery snapshots. Loading a page also invalidated the original archive, so a snapshot encoded the whole document again; on the Preline UI kit's CMS page that ran about 100 s on the main thread in WebKit before failing. Recovery, autosave, and saved versions now follow the content revision of createDocumentChanges. A page's layers loading from the opened file, which runs inside applyImportedStateDuring on both the worker and main-thread paths, no longer counts as an edit for that revision or for the original archive, and asks for one render rather than one per layer. In WebKit the CMS page switch drops from 105-133 s to 21 s, and its longest main-thread stall from 90-117 s to 1.4 s. * refactor(app): stop storing a version with recovery snapshots Adopting a snapshot now protects the document's current content revision, so nothing reads the version a snapshot was taken at. Snapshots saved by earlier versions carry a sceneVersion field instead; dropping the field keeps the metadata type true for both. Tests tell snapshots apart by the bytes they were built with.
2026-10-07 20:57:57 +00:00
import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
import { populateFigPage } from '@open-pencil/core/io/formats/fig'
import { initCodec } from '@open-pencil/core/kiwi'
import { computeAllLayouts } from '@open-pencil/core/layout'
perf: speed up opening large pages (#953) * perf(canvas): find guide owners from an index instead of walking the page Drawing and hit-testing guides visited every layer of the page on each frame to find the few that carry guides; on a large page that took about 1.2s of a load's rendering. The graph now keeps the set of layers with guides current from its node events, and both read it. * perf(layout): write only changed geometry and request one render per layout pass Layout wrote every laid-out layer's geometry whether or not it changed, so each pass over a large page notified every graph listener for every layer; a page load spent about 1s handling those updates. Layout now writes only the fields that changed, and the updates a layout pass makes ask for a single render, queued for before the next frame, instead of bumping the editor's reactive versions once per layer. * test(canvas): drop the graph double the guide tests no longer use * perf(fig): copy an opened file once on the main thread instead of three times Opening a .fig in the browser copied the file for a main-thread fallback the caller's buffer already served, then copied it twice more for the worker, which parses from one and keeps the other as the original archive. A 109MB file briefly took over 400MB on the main thread. The fallback now reuses the caller's buffer, and the worker receives one copy and makes its archive copy itself. * docs(changelog): note faster large-page loads * fix(app): run recovery and autosave after edits, not redraws Recovery and autosave watched sceneVersion, a render counter that every requestRender bumps: opening a file, layout passes, fonts, and each layer a page loads. Safari has no File System Access API, so its opened files have no writable source and always get recovery snapshots. Loading a page also invalidated the original archive, so a snapshot encoded the whole document again; on the Preline UI kit's CMS page that ran about 100 s on the main thread in WebKit before failing. Recovery, autosave, and saved versions now follow the content revision of createDocumentChanges. A page's layers loading from the opened file, which runs inside applyImportedStateDuring on both the worker and main-thread paths, no longer counts as an edit for that revision or for the original archive, and asks for one render rather than one per layer. In WebKit the CMS page switch drops from 105-133 s to 21 s, and its longest main-thread stall from 90-117 s to 1.4 s. * refactor(app): stop storing a version with recovery snapshots Adopting a snapshot now protects the document's current content revision, so nothing reads the version a snapshot was taken at. Snapshots saved by earlier versions carry a sceneVersion field instead; dropping the field keeps the metadata type true for both. Tests tell snapshots apart by the bytes they were built with.
2026-10-07 20:57:57 +00:00
import { SceneGraph } from '@open-pencil/scene-graph'
fix: protect unsaved documents and defer credential access (#713) * fix(app): protect unsaved documents when closing Mark tabs with unsaved content updates and ask whether to save before closing them. The prompt now covers tab closes, the desktop window close button, and the application Quit action, which previously discarded work when autosave had no writable target. Track a content revision separately from scene and recovery versions so a save only clears the indicator when it wrote the revision it captured. Cancelled pickers, failed writes, and edits made during a save keep the document open. Desktop uses the platform alert; the browser keeps the styled dialog. The desktop menu replaces the predefined Quit item so the accelerator and Dock-independent quit path request confirmation instead of exiting. * fix(ai): resolve credentials only when used Opening a document, creating a chat, or browsing chat history connected the provider and read saved secrets, which triggered system credential prompts without user intent. Startup now reads credential status only, migration runs inside the first explicit resolution, and the chat panel initializes local history without creating a transport. Stock-photo keys resolve per search instead of at settings refresh, and credentials still marked legacy count as configured so upgrading does not appear to lose them. * refactor(ai): export diagnostics from Settings only Chat kept its own debug log, copied mixed app-wide usage into a conversation export, and reported a missing cache rate as zero. Remove that surface and record AI requests, model steps, and tool activity as correlated diagnostic events instead. Settings remains the single export location, usage summaries can now distinguish unreported telemetry from zero, and transcript or tool payloads are no longer part of the export. * fix(ai): clear legacy credentials for real Clearing a Pexels, Unsplash, or provider key only removed the current store entry. A value that still lived in legacy storage kept the key configured, so a later search migrated and used the credential the user had just removed. Migrate before mutating so clearing also removes the legacy value, and share one in-flight migration so the media and provider paths cannot migrate the same plaintext twice. * fix(ai): scope credential migration per source Sharing one migration promise process-wide let a second storage return the first migration's result, leaving its own legacy keys unmigrated while reporting success. Track in-flight migrations per storage and serialize them, because every migration writes to the same store and concurrent runs could overwrite each other. * fix(app): destroy the window after a confirmed close Tauri's onCloseRequested helper destroys the window itself when a handler returns without preventing the event. Approving a close therefore invoked plugin:window|destroy, which the capability set did not grant, so the window stayed open with a permission error after saving. Always intercept the request and destroy the window explicitly once the choice is confirmed, and grant core:window:allow-destroy in place of the now-unused close permission. * fix(app): show a filled dot for unsaved tabs The unsaved indicator used a stroked Lucide circle whose fill attribute kept it an empty outline, reading as a disabled control. Draw the indicator as a filled accent dot matching the status dots used elsewhere in the app. * refactor(app): focus the unsaved prompt with VueUse Replace the manual watcher, nextTick, and component $el focus with useFocus, which focuses the Save button when the dialog mounts. Assert the focus in the close-protection test so the Return-saves behavior stays covered. * refactor(app): route Quit through the shared menu channel The Quit item emitted a bespoke app:request-exit event and the close module listened for it, while every other native item travels as a menu-event id dispatched by the shell and editor menu composables. Emit menu-event "quit" for both the Quit item and the platform exit request, handle it in useShellMenu beside check-updates, and share one confirmAppExit so window closes and app exits agree on a single approval. * refactor(app): generate the macOS app menu entries The application menu hardcoded its labels and the Quit accelerator in Rust while every other menu entry is generated from APP_MENU_SCHEMA. Move the custom app entries (About, Check for Updates, Quit) into APP_MENU_APP_ITEMS and emit desktop/generated/app-menu.json, keyed by id so the native builder cannot silently drop a label. Placement stays in Rust because the OS-predefined items sit between them, and the menu title now comes from the packaged product name. * build(tauri-menu): check generated menus against the schema The generated menu files are committed but nothing verified them, so a schema edit could silently leave desktop/generated stale until the next release build regenerated it. Split the renderers from the write step, register the tool as a workspace so its dependencies resolve, and compare the committed files with the schema in a test that runs with the other tool checks. * fix(app): serialize exit confirmations The window close handler and the Quit item both call confirmAppExit, and the per-handler closing flag does not cover the two paths. Both could run close preparation, so an unsaved document could be prompted twice. Share one in-flight confirmation and clear it when it settles, so a cancelled or failed attempt still prompts again on the next request.
2026-09-17 12:25:15 +00:00
import { createDocumentChanges } from '@/app/document/io/changes'
test('repainting and selection do not dirty a document; content mutations do', () => {
const editor = createEditor()
const changes = createDocumentChanges(editor)
try {
editor.requestRender()
editor.requestRepaint()
editor.clearSelection()
expect(changes.hasUnsavedChanges()).toBe(false)
editor.createShape('RECTANGLE', 0, 0, 100, 100)
expect(changes.hasUnsavedChanges()).toBe(true)
changes.markSaved()
expect(changes.hasUnsavedChanges()).toBe(false)
editor.undo.record({
label: 'Variable edit',
forward: () => undefined,
inverse: () => undefined
})
expect(changes.hasUnsavedChanges()).toBe(true)
} finally {
changes.dispose()
editor.dispose()
}
})
test('saving an earlier revision cannot clear edits made while exporting or picking a file', () => {
const editor = createEditor()
const changes = createDocumentChanges(editor)
try {
editor.createShape('RECTANGLE', 0, 0, 100, 100)
const saving = changes.capture()
editor.createShape('ELLIPSE', 0, 0, 100, 100)
changes.markSaved(saving)
expect(changes.hasUnsavedChanges()).toBe(true)
changes.markSaved()
expect(changes.hasUnsavedChanges()).toBe(false)
changes.markChanged()
expect(changes.hasUnsavedChanges()).toBe(true)
} finally {
changes.dispose()
editor.dispose()
}
})
test('laying out a page does not dirty a document; an edit that relays it out does', () => {
const editor = createEditor()
const changes = createDocumentChanges(editor)
try {
const page = editor.state.currentPageId
const row = editor.graph.createNode('FRAME', page, {
layoutMode: 'HORIZONTAL',
primaryAxisSizing: 'HUG',
itemSpacing: 8,
width: 10,
height: 10
})
editor.graph.createNode('RECTANGLE', row.id, { width: 40, height: 20 })
editor.graph.createNode('RECTANGLE', row.id, { width: 40, height: 20 })
changes.markSaved()
computeAllLayouts(editor.graph, page)
expect(editor.graph.getNode(row.id)?.width).toBe(88)
expect(changes.hasUnsavedChanges()).toBe(false)
editor.graph.updateNode(row.id, { itemSpacing: 16 })
computeAllLayouts(editor.graph, page)
expect(changes.hasUnsavedChanges()).toBe(true)
} finally {
changes.dispose()
editor.dispose()
}
})
perf: speed up opening large pages (#953) * perf(canvas): find guide owners from an index instead of walking the page Drawing and hit-testing guides visited every layer of the page on each frame to find the few that carry guides; on a large page that took about 1.2s of a load's rendering. The graph now keeps the set of layers with guides current from its node events, and both read it. * perf(layout): write only changed geometry and request one render per layout pass Layout wrote every laid-out layer's geometry whether or not it changed, so each pass over a large page notified every graph listener for every layer; a page load spent about 1s handling those updates. Layout now writes only the fields that changed, and the updates a layout pass makes ask for a single render, queued for before the next frame, instead of bumping the editor's reactive versions once per layer. * test(canvas): drop the graph double the guide tests no longer use * perf(fig): copy an opened file once on the main thread instead of three times Opening a .fig in the browser copied the file for a main-thread fallback the caller's buffer already served, then copied it twice more for the worker, which parses from one and keeps the other as the original archive. A 109MB file briefly took over 400MB on the main thread. The fallback now reuses the caller's buffer, and the worker receives one copy and makes its archive copy itself. * docs(changelog): note faster large-page loads * fix(app): run recovery and autosave after edits, not redraws Recovery and autosave watched sceneVersion, a render counter that every requestRender bumps: opening a file, layout passes, fonts, and each layer a page loads. Safari has no File System Access API, so its opened files have no writable source and always get recovery snapshots. Loading a page also invalidated the original archive, so a snapshot encoded the whole document again; on the Preline UI kit's CMS page that ran about 100 s on the main thread in WebKit before failing. Recovery, autosave, and saved versions now follow the content revision of createDocumentChanges. A page's layers loading from the opened file, which runs inside applyImportedStateDuring on both the worker and main-thread paths, no longer counts as an edit for that revision or for the original archive, and asks for one render rather than one per layer. In WebKit the CMS page switch drops from 105-133 s to 21 s, and its longest main-thread stall from 90-117 s to 1.4 s. * refactor(app): stop storing a version with recovery snapshots Adopting a snapshot now protects the document's current content revision, so nothing reads the version a snapshot was taken at. Snapshots saved by earlier versions carry a sceneVersion field instead; dropping the field keeps the metadata type true for both. Tests tell snapshots apart by the bytes they were built with.
2026-10-07 20:57:57 +00:00
test("loading a page's layers from the opened file does not dirty a document", async () => {
await initCodec()
const source = new SceneGraph()
source.createNode('RECTANGLE', source.addPage('Second').id, { name: 'Loaded later' })
const bytes = await exportFigFile(source)
const graph = await parseFigFile(bytes.slice().buffer, { populate: 'first-page' })
const editor = createEditor({ graph })
const changes = createDocumentChanges(editor)
try {
const page = graph.getPages()[1]
expect(populateFigPage(graph, page.id)).toBe(true)
computeAllLayouts(graph, page.id)
expect(graph.getChildren(page.id)).toHaveLength(1)
expect(changes.hasUnsavedChanges()).toBe(false)
editor.graph.createNode('RECTANGLE', page.id, { width: 10, height: 10 })
expect(changes.hasUnsavedChanges()).toBe(true)
} finally {
changes.dispose()
editor.dispose()
}
})