openpencil/tests/engine/app/document/close/controller.test.ts

97 lines
2.1 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'
test: typecheck the test suites and fix what that found (#896) * build: typecheck the test suites Tests were in no TypeScript program: no tsconfig included tests/** or packages/*/tests/**, and bun strips types without checking them, so a fixture could drop a required field and keep passing until something read it. @types/bun moves to the root because it was installed per package only, and #cli-tests/* joins the paths the root config already carries. * test: fix the type errors the test suites were hiding Typechecking the tests turned up 1123 errors. Most were ordinary strictness, but some were real: `NodeChange` bound to Figma's plugin typings rather than the Kiwi codec in thirteen .fig tests, materializeInstance was called with six arguments against five so the blobs and source children were dropped, CanvasKit pixels were written to a plain object that never reached WASM, and assertions were made through accessors that do not exist, so they asserted nothing. Fixtures that had quietly lost a required field now carry it, nullable results are narrowed through the existing expectDefined helper rather than assumed, and stand-ins for CanvasKit and the editor go through one named helper instead of an unexplained cast at each site. No test was deleted, skipped, or weakened, and no `any`, non-null assertion, or ts-expect-error was introduced. * docs: record what typechecking the tests established Pins the app program's global types with an assertion rather than a note, since an unpinned types list lets any root @types package decide which platform src/** is judged against. The two environment faults that look like code regressions — Vite's dependency pre-bundle outliving a package rebuild, and heavy .fig suites failing under load — go to the development docs, where an explanation belongs. * fix: align @types/bun and keep node types resolvable when extended The root manifest declared a newer @types/bun than every package, which check:monorepo rejects, and pinning the app program's types left them unresolvable from a config that extends this one out of tree. * fix: fail the test typecheck when the compiler itself fails The gate matched diagnostics by substring, so a compiler or config failure that named no test file printed a pass while having checked nothing. Diagnostics are now split by whether they name a file: an unscoped one is the run failing and stops the gate, a test file's is a finding, and a source file's stays out by design. Also drops the parameter planComponentConstruction never read, and makes the inner-shadow verification script exit non-zero when it renders no image instead of logging and succeeding. * chore: merge master into tests-typecheck
2026-10-05 12:42:38 +00:00
import {
confirmDocumentClose,
type CloseChoice,
type CloseResult
} from '@/app/document/close/controller'
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
test: typecheck the test suites and fix what that found (#896) * build: typecheck the test suites Tests were in no TypeScript program: no tsconfig included tests/** or packages/*/tests/**, and bun strips types without checking them, so a fixture could drop a required field and keep passing until something read it. @types/bun moves to the root because it was installed per package only, and #cli-tests/* joins the paths the root config already carries. * test: fix the type errors the test suites were hiding Typechecking the tests turned up 1123 errors. Most were ordinary strictness, but some were real: `NodeChange` bound to Figma's plugin typings rather than the Kiwi codec in thirteen .fig tests, materializeInstance was called with six arguments against five so the blobs and source children were dropped, CanvasKit pixels were written to a plain object that never reached WASM, and assertions were made through accessors that do not exist, so they asserted nothing. Fixtures that had quietly lost a required field now carry it, nullable results are narrowed through the existing expectDefined helper rather than assumed, and stand-ins for CanvasKit and the editor go through one named helper instead of an unexplained cast at each site. No test was deleted, skipped, or weakened, and no `any`, non-null assertion, or ts-expect-error was introduced. * docs: record what typechecking the tests established Pins the app program's global types with an assertion rather than a note, since an unpinned types list lets any root @types package decide which platform src/** is judged against. The two environment faults that look like code regressions — Vite's dependency pre-bundle outliving a package rebuild, and heavy .fig suites failing under load — go to the development docs, where an explanation belongs. * fix: align @types/bun and keep node types resolvable when extended The root manifest declared a newer @types/bun than every package, which check:monorepo rejects, and pinning the app program's types left them unresolvable from a config that extends this one out of tree. * fix: fail the test typecheck when the compiler itself fails The gate matched diagnostics by substring, so a compiler or config failure that named no test file printed a pass while having checked nothing. Diagnostics are now split by whether they name a file: an unscoped one is the run failing and stops the gate, a test file's is a finding, and a source file's stays out by design. Also drops the parameter planComponentConstruction never read, and makes the inner-shadow verification script exit non-zero when it renders no image instead of logging and succeeding. * chore: merge master into tests-typecheck
2026-10-05 12:42:38 +00:00
test.each<Extract<CloseChoice, CloseResult>>(['cancel', 'discard'])(
'%s does not save the document',
async (choice) => {
let saves = 0
const result = await confirmDocumentClose(
{
hasUnsavedChanges: () => true,
saveFigFile: async () => {
saves++
return true
}
},
async () => choice
)
expect(result).toBe(choice)
expect(saves).toBe(0)
}
)
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
test('clean documents close without prompting', async () => {
expect(
await confirmDocumentClose(
{
hasUnsavedChanges: () => false,
saveFigFile: async () => {
throw new Error('Unexpected save')
}
},
async () => {
throw new Error('Unexpected prompt')
}
)
).toBe('saved')
})
test('a cancelled file picker prevents close', async () => {
expect(
await confirmDocumentClose(
{
hasUnsavedChanges: () => true,
saveFigFile: async () => false
},
async () => 'save'
)
).toBe('cancel')
})
test('edits during a successful write prevent close', async () => {
expect(
await confirmDocumentClose(
{
hasUnsavedChanges: () => true,
saveFigFile: async () => true
},
async () => 'save'
)
).toBe('cancel')
})
test('a successful save of the current revision permits close', async () => {
let dirty = true
expect(
await confirmDocumentClose(
{
hasUnsavedChanges: () => dirty,
saveFigFile: async () => {
dirty = false
return true
}
},
async () => 'save'
)
).toBe('saved')
})
test('write failures propagate without authorizing close', async () => {
await expect(
confirmDocumentClose(
{
hasUnsavedChanges: () => true,
saveFigFile: async () => {
throw new Error('Disk full')
}
},
async () => 'save'
)
).rejects.toThrow('Disk full')
})