Files
RuneStone/tests/native/treeRename.native.mjs
T
Knotty Wyvern 5d5ba9e1f7 Keep preferences in one settings file and move tab transfer to the host
Keep the user preferences in settings.json in the app config folder.
WebView storage can be lost, and the host cannot read it. The file has
a schema number, a revision number, and one value for each section:
general, appearance, customThemes, customThemesLegacy, and language.
- settings_read gives all sections, the revision, and a one-time
  notice.
- settings_write replaces one section, writes the file atomically, and
  sends settings-changed to all windows. The limit is 8 MiB.
- settings_migrate writes the first file only when no file exists.
- The host moves a damaged file to settings.corrupt-<seconds>.json,
  starts from the defaults, and reports this one time.

Each window loads the sections before its first render. One store in
src/lib/settings/store.ts replaces the storage listeners. When no file
exists, the window normalizes the old localStorage values and migrates
them. The old keys stay in place for one release. The window layout
and the open tabs stay in localStorage on purpose. The browser preview
keeps all preferences in localStorage.

Keep tab transfer offers in host memory, not in localStorage, because
an offer can hold unsaved text. A window takes an offer once. The host
checks the workspace root and a 120 second expiry. When the receiver
accepts the tab, the host sends tab-transfer-accepted to the source
window only. A refused offer stays open, and the source tab stays open.
A new window and a drop on the tab ribbon use one check.

The smoke harness serves the new commands from one shared state for
each browser context. Tests read saved values from the mock settings
file. Rust, unit, and smoke tests cover the changes.
2026-10-27 23:56:00 -07:00

111 lines
8.1 KiB
JavaScript

// Native tree and windows: rename undo keeps folders expanded, Open in new window moves a tab without changing the saved layout,
// 50 MiB of JSON passes through workspace IPC, and a large background image survives a reload.
// Start a debug app with the isolated identifier com.runestone.pass3-test and remote debugging on port 9236:
// set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9236
// pnpm tauri dev --config "{\"identifier\":\"com.runestone.pass3-test\"}"
// Run `node tests/native/treeRename.native.mjs`. NATIVE_CDP_URL (or the older NAVIGATION_NATIVE_CDP) overrides http://127.0.0.1:9236.
// The test opens a workspace in the system temporary folder.
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { outputDir, playwright } from '../smoke/_harness/index.mjs';
const { chromium } = playwright();
const browser = await chromium.connectOverCDP(process.env.NATIVE_CDP_URL || process.env.NAVIGATION_NATIVE_CDP || 'http://127.0.0.1:9236');
const context = browser.contexts()[0];
const page = context.pages().find(page => new URL(page.url()).pathname === '/' && !new URL(page.url()).search);
assert.ok(page, 'The isolated main window must be open.');
page.setDefaultTimeout(20000);
const output = await outputDir('native/treeRename');
// Settings and reload pages use the app's own dev server, not a fixed port.
const origin = new URL(page.url()).origin;
const workspace = join(tmpdir(), 'runestone-pass3-native-workspace');
const results = {};
let detached;
try {
const identity = await page.evaluate(async () => (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
assert.match(identity, /[\\/]com\.runestone\.pass3-test[\\/]?$/);
results.identity = identity;
await mkdir(join(workspace, 'folder', 'nested'), { recursive: true });
await mkdir(join(workspace, 'other'), { recursive: true });
await writeFile(join(workspace, 'folder', 'nested', 'note.md'), '# Native note\n\nText for transfer.\n');
await writeFile(join(workspace, 'other', 'keep.md'), '# Keep');
await page.evaluate(async path => {
await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('workspace_open', { path });
localStorage.setItem('runestone.workbenchLayout', JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 260, rightWidth: 240, leftView: 'files' }));
}, workspace);
await page.reload();
const row = path => page.locator(`[data-tree-rel="${path}"]`);
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
await row('folder/nested/note.md').click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Rename', exact: true }).click();
await page.locator('.tree input').fill('renamed.md'); await page.locator('.tree input').press('Enter');
await row('folder/nested/renamed.md').waitFor();
await row('folder/nested/renamed.md').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/note.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) assert.equal(await row(path).getAttribute('aria-expanded'), 'true');
results.renameUndoPreservesExpandedFolders = true;
await row('folder/nested/note.md').click();
await page.getByRole('tab', { name: /note.md/ }).waitFor();
await page.getByText('Text for transfer.', { exact: true }).waitFor();
const savedLayout = await page.evaluate(() => localStorage.getItem('runestone.workbenchLayout'));
const pending = context.waitForEvent('page');
await page.getByRole('tab', { name: /note.md/ }).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Open in new window', exact: true }).click();
detached = await pending;
await detached.getByRole('tab', { name: /note.md/ }).waitFor();
await detached.evaluate(async () => (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().minimize());
await detached.getByText('Text for transfer.', { exact: true }).waitFor();
assert.ok(detached.url().includes('tabTransfer='));
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
await page.getByRole('tab', { name: /note.md/ }).waitFor({ state: 'detached' });
const sourceClosed = await page.getByRole('tab', { name: /note.md/ }).count() === 0;
await detached.getByRole('button', { name: 'Show outline', exact: true }).click();
assert.equal(await page.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), savedLayout);
await detached.getByRole('button', { name: 'Hide outline', exact: true }).click();
results.nativeTransfer = { sourceClosed, columnsHidden: true, savedLayoutPreserved: true };
for (const mode of ['light', 'dark']) {
await detached.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await detached.screenshot({ path: join(output, `detached-${mode}.png`) });
}
results.imageJsonIpc = await page.evaluate(async () => {
const { invoke } = await import('/node_modules/@tauri-apps/api/core.js');
const bytes = 50 * 1024 * 1024;
const pixel = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII='), char => char.charCodeAt(0));
const blob = new Blob([pixel, new Uint8Array(bytes - pixel.length)], { type: 'image/png' });
const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(blob); });
const contents = JSON.stringify({ schema: 1, data });
const start = performance.now();
await invoke('workspace_write', { rel: '.runestone/pm/images/native-50mib.json', contents });
const written = performance.now();
const read = await invoke('workspace_read', { rel: '.runestone/pm/images/native-50mib.json' });
return { bytes, jsonLength: contents.length, matches: read === contents, writeMs: Math.round(written - start), readMs: Math.round(performance.now() - written) };
});
assert.equal(results.imageJsonIpc.matches, true);
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const largeImage = Buffer.concat([pixel, Buffer.alloc(1_900_000 - pixel.length)]);
await page.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'native-large.png', mimeType: 'image/png', buffer: largeImage });
// The appearance is in the settings file of the host.
await page.waitForFunction(() => window.__TAURI_INTERNALS__.invoke('settings_read').then(file => !!file.sections.appearance?.newTabBackground?.imageId));
await page.goto(`${origin}/`);
// The image is on the work area layer behind the empty tab (src/lib/layout/Workbench.svelte:1258, :1543-1549).
await page.locator('.empty').waitFor();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
await page.reload(); await page.locator('.empty').waitFor();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
results.largeBackground = { bytes: largeImage.length, renderedAfterReload: true };
await page.screenshot({ path: join(output, 'large-background.png') });
await writeFile(join(output, 'results.json'), JSON.stringify(results, null, 2));
console.log(JSON.stringify(results));
} catch (error) {
await writeFile(join(output, 'partial-results.json'), JSON.stringify(results, null, 2));
console.error({ error: String(error), main: await page.locator('body').innerText().catch(() => ''), detached: detached && !detached.isClosed() ? await detached.locator('body').innerText().catch(() => '') : null });
throw error;
} finally {
if (detached && !detached.isClosed()) await detached.evaluate(async () => (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().destroy()).catch(() => {});
await browser.close();
}