Update editor, workspace, Git services, appearance, and project guides

This commit is contained in:
Knotty Wyvern
2026-10-11 09:41:16 -07:00
parent a8b1defb9d
commit 909894b9c8
153 changed files with 7967 additions and 775 deletions
+199
View File
@@ -0,0 +1,199 @@
// Run against the development server with an isolated browser storage context.
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
const findings = [];
const output = ".audit";
await mkdir(output, { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = "C:\\appearance-smoke";
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
const callbacks = new Map();
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
const secondSettings = await context.newPage();
for (const page of [main, settings, secondSettings]) {
page.setDefaultTimeout(10000);
page.on("pageerror", error => errors.push(error.message));
}
await main.goto(origin);
await main.getByText("appearance-smoke", { exact: true }).waitFor();
async function openCode(index) {
await main.keyboard.press("Control+p");
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".monaco-editor textarea").waitFor();
await main.waitForFunction(async file => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.uri.path.endsWith(file));
}, `theme-${index}.py`);
await main.locator(".view-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
async function editorIds() {
return main.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
}
async function syntaxColors() {
return main.locator(".view-line span").evaluateAll(spans => Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
})));
}
async function waitForSyntax(expected = null) {
await main.waitForFunction(expected => {
const spans = [...document.querySelectorAll(".view-line span")];
const colors = Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
}));
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
}, expected);
}
async function openAppearance(page) {
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await page.getByRole("combobox", { name: "Color theme", exact: true }).waitFor();
}
await openCode(0);
await openAppearance(settings);
await openAppearance(secondSettings);
async function expectAppearance(theme, mode) {
for (const page of [settings, secondSettings, main]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
}
assert.equal(await secondSettings.getByRole("combobox", { name: "Color theme", exact: true }).inputValue(), theme);
assert.equal(await secondSettings.getByRole("combobox", { name: "Appearance", exact: true }).inputValue(), mode);
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-bg");
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === expected);
});
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
}
let nextCode = 1;
const backgrounds = new Set();
for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds();
await settings.getByRole("combobox", { name: "Color theme", exact: true }).selectOption(theme);
if (theme !== "sakura") await settings.getByRole("combobox", { name: "Appearance", exact: true }).selectOption(mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
await openCode(nextCode++);
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode });
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}.png` });
await main.screenshot({ path: `${output}/appearance-editor-${theme}-${mode}.png` });
if (theme === 'sakura') {
const keywordColor = await main.locator('.view-line span').evaluateAll(spans => {
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === 'def');
return keyword ? getComputedStyle(keyword).color : null;
});
assert.equal(keywordColor, 'rgb(152, 85, 108)', 'Sakura keywords use Plum Wine');
}
const typography = await settings.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
heading: getComputedStyle(document.querySelector('h2')).fontFamily,
prose: getComputedStyle(document.documentElement).getPropertyValue('--rs-font-prose').trim(),
}));
if (theme === 'claude') {
assert.match(typography.body, /Lora.*Georgia/);
assert.match(typography.prose, /Lora.*Georgia/);
assert.match(typography.heading, /Poppins.*Arial/);
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-accent').trim()), '#d97757');
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new Monaco editors`);
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
assert.deepEqual(await settings.getByRole('combobox', { name: 'Color theme', exact: true }).locator('option').evaluateAll(options => options.map(option => option.value)), ['default', 'claude', 'sakura']);
assert.equal(await settings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true);
assert.equal(await secondSettings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
});
assert.deepEqual(sakura, { bg: '#fefcfc', border: '#f8dbe6', selection: '#ffc9dc', 'bg-active': '#dbeacb', 'syntax-parameter': '#cb6b91', 'syntax-keyword': '#98556c', 'syntax-local': '#618c71', 'syntax-static': '#69a2bd', 'syntax-instance': '#607fa9', 'syntax-global': '#687788' });
for (const [theme, savedMode, expectedTheme, mode] of [
['gpt', 'light', 'default', 'light'],
['terminal', 'dark', 'default', 'dark'],
['sakura', 'dark', 'sakura', 'light'],
]) {
await settings.evaluate(value => localStorage.setItem('runestone.appearance', JSON.stringify(value)), { theme, mode: savedMode });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await expectAppearance(expectedTheme, mode);
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance'))), { theme: expectedTheme, mode });
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
}
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
await settings.setViewportSize({ width: 1100, height: 780 });
await settings.getByRole('combobox', { name: 'Color theme', exact: true }).selectOption(theme);
if (theme !== 'sakura') await settings.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption(mode);
await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport');
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area');
for (const name of ['Color theme', 'Appearance']) {
const control = settings.getByRole('combobox', { name, exact: true });
await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, `${name} remains reachable at 360px`);
}
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}-360.png` });
}
assert.deepEqual(errors, []);
assert.deepEqual(findings, [], 'Appearance findings');
await context.close();
console.log('Appearance smoke passed: supported palettes, modes, light-only Sakura, migration, persistence, typography, cross-window sync, Monaco updates, and narrow settings.');
} catch (error) {
console.error('Browser errors:', errors);
for (const [index, page] of browser.contexts().flatMap(context => context.pages()).entries()) {
await page.screenshot({ path: `${output}/appearance-failure-${index}.png` }).catch(() => {});
}
throw error;
} finally { await browser.close(); }
+21
View File
@@ -0,0 +1,21 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseAppearance, normalizeAppearance, THEMES } from '../src/lib/theme/appearance.ts';
test('Removed palettes preserve the saved mode with the default palette', () => {
for (const theme of ['gpt', 'terminal', 'unknown']) {
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme: 'default', mode });
}
}
assert.deepEqual(THEMES, ['default', 'claude', 'sakura']);
});
test('Sakura cannot restore or save a dark appearance', () => {
assert.deepEqual(parseAppearance('{"theme":"sakura","mode":"dark"}'), { theme: 'sakura', mode: 'light' });
assert.deepEqual(normalizeAppearance({ theme: 'sakura', mode: 'dark' }), { theme: 'sakura', mode: 'light' });
});
test('Malformed storage returns a valid default appearance', () => {
for (const raw of [null, '', '{', 'null', '42', '[]']) {
assert.deepEqual(parseAppearance(raw), { theme: 'default', mode: 'dark' });
}
});
+139
View File
@@ -0,0 +1,139 @@
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
const runtime = path.resolve('../RuneStone_Browser');
const require = createRequire(path.join(runtime, 'package.json'));
const { chromium } = require('playwright');
const electron = require('electron');
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
let sequence = 0, page, pendingFrame, painting = false;
const pending = new Map();
const commands = [];
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
const ready = new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
});
});
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
const errors = [];
try {
await ready;
page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
page.on('pageerror', error => errors.push(error.message));
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map(); let next = 0;
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
throw Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0);
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
await page.waitForTimeout(3000);
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
await evaluate('window.testAnimate=false;true;');
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
await page.locator('.surface img').waitFor();
const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`);
await page.keyboard.press('Escape');
await page.waitForTimeout(150);
const stopped = await evaluate('scrollY');
await page.waitForTimeout(200);
assert.equal(await evaluate('scrollY'), stopped);
assert.equal(await page.locator('.scroll-anchor').count(), 0);
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
await page.waitForTimeout(100);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.click(x, y, { button: 'left' });
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
await page.mouse.click(x, y, { button: 'middle' });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
const beforeMotion = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i=0;i<500;i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX:x+i%20, clientY:y, bubbles:true })); }, { x,y });
await page.waitForTimeout(100);
const motionCount = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length - beforeMotion;
assert.ok(motionCount < 10, `Pointer bursts must not queue hundreds of native calls: ${motionCount}`);
await mkdir('output', { recursive: true });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
await page.mouse.click(x, y, { button: 'middle' });
await page.screenshot({ path: `output/browser-interaction-${theme}.png` });
await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 420, height: 650 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await page.setViewportSize({ width: 1280, height: 800 });
await page.keyboard.press('Control+t');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
assert.deepEqual(errors, []);
await writeFile('output/browser-interaction.json', JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, passed: ['Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer bursts coalesce', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
console.log('PASS browser UI with real Electron pages, autoscroll cleanup, pointer coalescing and center new-tab action');
} finally {
await browser.close();
await rpc('shutdown').catch(() => {}); child.kill();
}
+213
View File
@@ -0,0 +1,213 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from 'node:module';
import { mkdir } from 'node:fs/promises';
import assert from 'node:assert/strict';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1100, height: 850 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
const data = {
user: {
profileId: 'user',
cookies: [
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
],
history: [
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
],
},
work: {
profileId: 'work',
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
},
};
const check = window.webDataTest = { data, snapshot, calls: [], hold: [], pending: [], failNext: {} };
let sequence = 0;
const callbacks = new Map();
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'web-data-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
if (args.session !== 'web-data-session') throw Error('Missing browser session');
const operation = args.command, details = args.args || {}, key = `${operation}:${details.profileId}`;
check.calls.push({ operation, ...details });
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
if (operation === 'webData') return nextData;
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
return structuredClone(snapshot);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
});
const section = page.getByRole('region', { name: 'Individual web data', exact: true });
const profile = page.getByRole('combobox', { name: 'Profile', exact: true });
const kind = section.getByRole('combobox', { name: 'Web data type', exact: true });
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
const workCookie = () => section.getByRole('button', { name: 'Remove cookie session from work.example at /account', exact: true });
const settle = () => section.locator('.entries[aria-busy="false"]').waitFor();
async function hold(key) { await page.evaluate(key => { window.webDataTest.hold.push(key); }, key); }
async function pending(key) { await page.waitForFunction(key => window.webDataTest.pending.some(item => item.key === key), key); }
async function release(key, error) {
await page.evaluate(({ key, error }) => {
const check = window.webDataTest;
check.hold = check.hold.filter(item => item !== key);
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
if (!item) throw Error('No pending request for ' + key);
if (error) item.reject(Error(error)); else item.resolve();
}, { key, error });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
try {
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await personalCookie().waitFor();
assert.equal(await section.locator('.entry').count(), 3);
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
await filter.fill('PERSONAL.EXAMPLE');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('/settings');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('no matches');
await section.getByText('No matching cookies.', { exact: true }).waitFor();
await filter.fill('session');
await personalCookie().click();
await settle();
await section.getByText('No matching cookies.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
await kind.selectOption('history');
await filter.fill('GUIDE');
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
await settle();
await section.getByText('No matching history.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.webDataTest.data.work.history.length), 1);
await filter.fill('another.example/document');
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
assert.equal(await section.locator('.entry').count(), 1);
await profile.selectOption('work');
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await kind.selectOption('cookies');
await workCookie().waitFor();
// A delayed successful response from the previous profile must not replace the current rows.
await hold('webData:work');
await refresh.click();
await pending('webData:work');
assert.equal(await workCookie().isDisabled(), true);
await profile.selectOption('user');
await settle();
await release('webData:work');
assert.equal(await workCookie().count(), 0);
assert.equal(await section.locator('.entry').count(), 2);
// The same guard must ignore an old request error.
await hold('webData:user');
await refresh.click();
await pending('webData:user');
await profile.selectOption('work');
await workCookie().waitFor();
await settle();
await release('webData:user', 'Stale personal error');
assert.equal(await section.getByRole('alert').count(), 0);
assert.equal(await refresh.isEnabled(), true);
// Removal finishes for its original profile without refreshing the selected profile.
await hold('removeCookie:work');
await workCookie().click();
await pending('removeCookie:work');
await profile.selectOption('user');
await settle();
const readsBefore = await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length);
await release('removeCookie:work');
assert.equal(await profile.inputValue(), 'user');
assert.equal(await section.locator('.entry').count(), 2);
assert.equal(await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length), readsBefore);
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 0);
await page.evaluate(() => { window.webDataTest.failNext['webData:user'] = 'Cannot read personal data'; });
await refresh.click();
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
assert.equal(await refresh.isEnabled(), true);
await refresh.click();
await settle();
assert.equal(await section.getByRole('alert').count(), 0);
await page.evaluate(() => { window.webDataTest.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
await unnamed.click();
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
assert.equal(await unnamed.isEnabled(), true);
await unnamed.click();
await settle();
assert.equal(await unnamed.count(), 0);
assert.equal(await section.getByRole('alert').count(), 0);
assert.deepEqual(await page.evaluate(() => window.webDataTest.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
assert.equal(await page.evaluate(() => window.webDataTest.calls.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
for (const dataType of ['cookies', 'history']) {
await kind.selectOption(dataType);
await section.scrollIntoViewIfNeeded();
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-web-data-${dataType}-${theme}.png` });
const overflow = await section.evaluate(node => {
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
});
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
}));
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
await filter.focus();
await page.keyboard.press('Tab');
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
}
}
assert.deepEqual(errors, []);
console.log('PASS: cookie/history lists and removal, filters, profile isolation, stale success/error/removal guards, recovery, open-tab preservation, and 360px controls in both themes.');
} catch (error) {
console.error(await page.locator('body').innerText());
console.error('Page errors:', errors);
throw error;
} finally { await browser.close(); }
+106
View File
@@ -0,0 +1,106 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(); let next = 0;
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
window.builtinCheck = { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'window-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [
{ manifest: { schemaVersion: 1, id: 'org.test.boards', name: 'Boards', author: 'Test', description: '', version: '0.1.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'fixture', enabled: true, installedAt: 1, path: '', error: null, removal: false },
...(window.builtinCheck.legacy && !window.builtinCheck.removed ? [{ manifest: { schemaVersion: 1, id: 'runestone.browser', name: 'Browser', author: 'Test', description: '', version: '0.1.6', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'old', enabled: true, installedAt: 1, path: '', error: null, removal: false }] : [])
] };
if (command === 'plugins_load') {
window.builtinCheck.loads.push(args.id);
if (args.id === 'runestone.browser') throw Error('The old browser package must not load');
return `export function activate(api) {
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
window.builtinCheck.mounts.push(id); el.textContent = id;
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
return () => { window.builtinCheck.cleanups.push(id); };
}});
api.registerView({ id:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git sidebar fixture'; }});
}`;
}
if (command === 'browser_request') {
if (args.session !== 'window-session') throw Error('Missing browser session');
window.builtinCheck.commands.push(args.command);
if (args.command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (args.command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.args.tabId);
if (args.command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.args.tabId); tab.url = args.args.input; tab.title = 'Example'; }
if (args.command === 'settings') Object.assign(snapshot.settings, args.args);
return structuredClone(snapshot);
}
if (command.startsWith('plugin:window|')) return false;
throw Error('Unhandled IPC: ' + command);
}
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5174');
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.waitForFunction(() => window.builtinCheck.commands.includes('navigate'));
assert.equal(await page.getByRole('combobox', { name: 'Browser profile' }).inputValue(), 'user');
await page.evaluate(async () => { window.builtinCheck.legacy = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
assert.equal(await page.evaluate(() => window.builtinCheck.loads.includes('runestone.browser')), false);
await page.evaluate(async () => { window.builtinCheck.removed = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
await page.evaluate(async () => { const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); openPluginView('org.test.boards', 'board-a'); });
const before = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
await page.getByRole('button', { name: 'Select board B' }).click();
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
await page.waitForFunction(() => window.builtinCheck.mounts.includes('board-b') && window.builtinCheck.cleanups.includes('board-a'));
const after = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
assert.deepEqual(after, before);
await page.getByRole('button', { name: 'Source control', exact: true }).click();
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: `.audit/cards-2026-10-08-next/builtin-browser-${theme}.png` });
}
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:5174') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.getByRole('button', { name: 'Save browser settings' }).waitFor({ state: 'visible' });
assert.equal(await page.getByRole('combobox', { name: 'Profile', exact: true }).inputValue(), 'user');
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-settings-${theme}.png` });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
}
assert.deepEqual(errors, []);
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
} catch (error) {
console.error(await page.evaluate(async () => {
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
return { state: window.builtinCheck, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
}), errors);
throw error;
} finally { await browser.close(); }
+15
View File
@@ -0,0 +1,15 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseCustomTheme } from "../src/lib/theme/customThemes.ts";
const palette = { bg: "#123", text: "#abcdef", accent: "#AABBCC" };
const theme = { schema: 1, id: "my-theme", name: "My theme", light: palette, dark: palette };
test("theme files accept explicit color tokens in both appearances", () => {
assert.deepEqual(parseCustomTheme(theme), theme);
});
test("theme files reject CSS injection, unknown tokens, and incomplete palettes", () => {
for (const dark of [{ ...palette, bg: "url(https://invalid.test)" }, { ...palette, position: "fixed" }, { bg: "#000" }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, dark }));
}
assert.throws(() => parseCustomTheme({ ...theme, id: "../unsafe" }));
});
+142
View File
@@ -0,0 +1,142 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-files-smoke";
const files = new Map([
["note.md", "Mispelled text.\n\n| Word | Value |\n| --- | --- |\n| Speling | Other |\n"],
["hello.txt", "print('hello')\n"],
["notes/existing.md", "Existing note"],
]);
window.editorFilesTest = { files, calls: [] };
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
window.editorFilesTest.calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "editor-files-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length), name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") {
if (files.has(args.rel)) throw new Error("path already exists");
files.set(args.rel, ""); return;
}
if (command === "workspace_rename") {
if (files.has(args.to)) throw new Error("destination already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === "workspace_search") return [];
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const row = name => page.locator(`[data-tree-rel="${name}"]`);
async function enterName(name) {
await page.locator("#text-request").fill(name);
await page.getByRole("button", { name: "Continue", exact: true }).click();
}
async function modelDetails() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await row("note.md").waitFor();
await page.getByRole("button", { name: "New file", exact: true }).click();
await enterName("LICENSE");
await row("LICENSE").waitFor();
await page.evaluate(() => window.editorFilesTest.files.set("LICENSE", "Keep this content"));
await page.getByRole("button", { name: "New file", exact: true }).click();
await enterName("LICENSE");
await page.getByText("path already exists", { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.get("LICENSE")), "Keep this content");
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("LICENSE 2")), false);
await row("notes").click({ button: "right" });
await page.getByRole("menuitem", { name: "New file…", exact: true }).click();
await enterName("hello_world.py");
await row("notes/hello_world.py").waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("notes/hello_world.py.md")), false);
await row("hello.txt").dblclick();
await page.waitForFunction(() => !!document.querySelector(".monaco-editor .view-line"));
await row("hello.txt").click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
assert.equal(await row("hello.txt").locator("input.rename").inputValue(), "hello.txt");
await row("hello.txt").locator("input.rename").fill("hello.py");
await page.keyboard.press("Enter");
await row("hello.py").waitFor();
await page.waitForFunction(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.getLanguageId() === "python");
});
const code = await modelDetails();
assert.equal(code.value, "print('hello')\n");
assert.equal(code.fontSize, 13);
await page.keyboard.press("Control+e");
assert.equal((await modelDetails()).fontSize, code.fontSize, "Code size stays the same in both layouts");
await row("note.md").dblclick();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerTest = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
const nativeAllowed = await page.evaluate(() => {
window.writerTest.dispatch({ selection: { anchor: 3 } });
const line = document.querySelector(".cm-line"), rect = line.getBoundingClientRect();
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: rect.left + 15, clientY: rect.top + 5 });
line.dispatchEvent(event);
return !event.defaultPrevented;
});
assert.equal(nativeAllowed, true, "The native spelling menu is available on plain text");
assert.equal(await page.getByRole("menu").count(), 0);
await page.evaluate(() => { window.writerTest.focus(); });
await page.keyboard.press("Shift+F10");
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.evaluate(() => window.writerTest.dispatch({ selection: { anchor: 0, head: 9 } }));
await page.getByText("Mispelled text.", { exact: true }).click({ button: "right" });
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.locator(".live-writer td").first().click({ button: "right" });
await page.getByRole("menu", { name: "Table actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.locator(".writer-cell-editor").click();
await page.keyboard.press("ArrowRight");
assert.equal(await page.locator(".writer-cell-editor p").evaluate(node => {
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
node.dispatchEvent(event);
return !event.defaultPrevented;
}), true, "Active table text permits the native spelling menu");
await page.locator(".cm-line").first().click();
}
assert.deepEqual(errors, []);
console.log("PASS: exact filenames, extensionless creation, extension rename and language, equal code font sizes, native spelling event, shared selection and table menus in both themes");
} finally { await browser.close(); }
+152
View File
@@ -0,0 +1,152 @@
import { createRequire } from "node:module";
import { mkdir } from "node:fs/promises";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, permissions: ["clipboard-read", "clipboard-write"] });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-interactions-smoke";
const files = new Map([
["note.md", "# Stack\n\nHardware can be reused.\nAssume speeds of 1 Gb/s.\n\n## Hardware\n\n### Router\n\n- [ ] First task\n- [ ] Second task\n\n[Local](other.md) and [Web](https://example.com) and [[other|Wiki]]\n\n```sh\npnpm install --frozen-lockfile\npnpm check\npnpm test\n```\n\n" + Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.\n\n`).join("") + "```js\nconst preserve = 42;\nconsole.log(preserve);\n```\n"],
["other.md", "# Other document\n\nKeep the original tab.\n"],
]);
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
window.editorTest = { files, calls: [], emit };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.editorTest.calls.push({ command, args });
if (command === "plugin:event|listen") { const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; }
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "editor-interactions-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".runestone/")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:opener|open_url" || command.startsWith("spelling_menu_")) return;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerView = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function top() {
await writer();
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); window.writerView.scrollDOM.scrollTop = 0; });
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.locator('[data-tree-rel="note.md"]').dblclick();
await writer();
const code = page.locator(".writer-code-line").filter({ hasText: "pnpm install" });
await code.scrollIntoViewIfNeeded();
const points = await page.evaluate(() => {
const view = window.writerView, from = view.state.doc.toString().indexOf("pnpm install");
return { from: view.coordsAtPos(from), to: view.coordsAtPos(from + 12) };
});
await page.mouse.move(points.from.left + 1, (points.from.top + points.from.bottom) / 2);
await page.mouse.down();
await page.mouse.move(points.to.left, (points.to.top + points.to.bottom) / 2, { steps: 8 });
await page.mouse.up();
assert.match(await page.evaluate(() => { const view = window.writerView; return view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to); }), /pnpm install/);
await page.getByRole("button", { name: "Copy code", exact: true }).first().click();
assert.equal((await page.evaluate(() => navigator.clipboard.readText())).replace(/\r\n/g, "\n"), "pnpm install --frozen-lockfile\npnpm check\npnpm test\n");
console.log("PASS: first drag selects code and the copy button copies only the code body");
await page.evaluate(() => { const view = window.writerView; view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("preserve =") + 5 }, scrollIntoView: true }); view.focus(); });
await page.keyboard.type("X");
await page.waitForTimeout(250);
const saved = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
assert.ok(saved.scroll > 1000);
await page.locator('[data-tree-rel="other.md"]').dblclick();
await writer();
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await writer();
await page.waitForTimeout(250);
const restored = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
assert.equal(restored.head, saved.head);
assert.equal(restored.doc, saved.doc);
assert.ok(Math.abs(restored.caret.top - saved.caret.top) < 3, JSON.stringify({ saved, restored }));
await page.evaluate(() => { window.dispatchEvent(new Event("blur")); window.dispatchEvent(new Event("focus")); });
await page.waitForTimeout(150);
assert.equal(await page.evaluate(() => window.writerView.state.selection.main.head), saved.head);
console.log("PASS: code edit, caret, and scroll survive tab and window focus changes");
await top();
await page.locator('.writer-link[data-href="other.md"]').click({ modifiers: ["Control"] });
await page.getByRole("tab", { name: "other.md", exact: true }).waitFor();
assert.equal(await page.getByRole("tab", { name: "note.md", exact: true }).count(), 1);
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await top();
await page.locator('.writer-link[data-href="https://example.com"]').click({ modifiers: ["Control"] });
await page.waitForFunction(() => window.editorTest.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
const linkPoint = await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
const position = view.getModel().getPositionAt(view.getValue().indexOf("[Local]") + 3);
view.revealPositionInCenter(position);
view.setPosition(position); view.focus();
return position;
});
await page.waitForTimeout(300);
const point = await page.evaluate(async position => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected), rect = view.getDomNode().getBoundingClientRect(), coords = view.getScrolledVisiblePosition(position);
return { x: rect.left + coords.left + 2, y: rect.top + coords.top + coords.height / 2 };
}, linkPoint);
await page.keyboard.down("Control"); await page.mouse.click(point.x, point.y); await page.keyboard.up("Control");
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.includes("other.md"));
console.log("PASS: Writer and IDE Ctrl+click open workspace links while retaining the source tab");
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await page.keyboard.press("Control+e");
await top();
await mkdir(".audit", { recursive: true });
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { applyAppearance, parseAppearance } = await import("/src/lib/theme/appearance.ts");
applyAppearance({ ...parseAppearance(null), mode });
}, theme);
const writing = await page.locator(".writer-h1").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
await page.screenshot({ path: `.audit/editor-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
const reading = await page.locator(".reading h1:not(.document-title)").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
assert.deepEqual(writing, reading);
await page.screenshot({ path: `.audit/reader-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await top();
}
await page.setViewportSize({ width: 640, height: 750 });
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.screenshot({ path: ".audit/editor-typography-narrow.png" });
assert.ok(await page.locator(".cm-content").evaluate(node => node.getBoundingClientRect().width <= node.closest(".cm-scroller").getBoundingClientRect().width + 1));
const spelling = await page.evaluate(async () => {
const { isSpellingTarget } = await import("/src/lib/editor/spellingMenu.ts");
const area = document.createElement("textarea"); area.spellcheck = true; document.body.append(area);
const active = isSpellingTarget(area); area.readOnly = true; const readOnly = isSpellingTarget(area); area.remove();
return { active, readOnly };
});
assert.deepEqual(spelling, { active: true, readOnly: false });
assert.deepEqual(errors, []);
console.log("PASS: shared heading typography in both themes, narrow Writer, and textarea spelling target");
} finally { await browser.close(); }
+23
View File
@@ -0,0 +1,23 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentLinks, documentLinkAt } from "../src/lib/editor/documentLinks.ts";
test("document links keep complete source ranges and decode Markdown destinations", () => {
const source = '[Local](<notes/two words.md> "Title") and [Web](https://example.com/a_(b)) and [[Another note|Alias]]';
const links = documentLinks(source);
assert.deepEqual(links.map(link => [link.kind, link.target]), [["md", "notes/two words.md"], ["md", "https://example.com/a_(b)"], ["wiki", "Another note"]]);
for (const link of links) {
assert.equal(documentLinkAt(source, link.from + 2)?.target, link.target);
assert.equal(documentLinkAt(source, link.to - 1)?.target, link.target);
}
});
test("literal code and images cannot become document links", () => {
const source = '![Image](image.png) `https://example.com`\n\n```md\n[Hidden](hidden.md)\n[[Hidden]]\n```\n\n[Open](open.md)';
assert.deepEqual(documentLinks(source).map(link => link.target), ["open.md"]);
});
test("bare and angle links omit prose punctuation and preserve balanced parentheses", () => {
const source = 'Go to https://example.com/a_(b). Next (<https://example.org>). Mail <mailto:[email protected]>.';
assert.deepEqual(documentLinks(source).map(link => link.target), ["https://example.com/a_(b)", "https://example.org", "mailto:[email protected]"]);
});
+6 -4
View File
@@ -183,15 +183,17 @@ try {
}, "../attachments/typed.svg");
await page.locator('img[alt="Wiki image"]').waitFor();
await save();
await page.getByRole("button", { name: "Read", exact: true }).click();
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Edit", exact: true }).focus();
await page.keyboard.press("ArrowRight");
await page.locator(".md-page .md-image-frame").first().hover();
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
await page.keyboard.press("Escape");
// Source mode uses the same drop flow; the batch is one undo step.
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Read", exact: true }).focus();
await page.keyboard.press("Home");
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor textarea").waitFor();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
@@ -213,7 +215,7 @@ try {
await page.evaluate(() => { window.__TEST__.failWrite = false; });
// File drops over a rendered widget are handled by the editor's capture listener.
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
+152
View File
@@ -0,0 +1,152 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../node_modules/playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\kanban-smoke';
const files = new Map([['a.md', '# Alpha\n\nTemplate body.\n'], ['b.md', '# Beta\n'], ['folder/keep.md', '# Keep\n'], ['.runestone/config.json', '{}']]);
const calls = [], callbacks = new Map(); let id = 0;
window.workspaceSmoke = { files, calls, transfer: null };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: callback => { callbacks.set(++id, callback); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === 'plugin:event|listen') return ++id;
if (command === 'plugin:event|unlisten' || command === 'spelling_menu_install' || command === 'spelling_menu_uninstall') return;
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'kanban-smoke', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw Error('File missing'); return files.get(args.rel); }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error('Save conflict');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw Error('Exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : ''; const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/') && !args.showInternal)) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw Error('Destination exists');
const matches = [...files].filter(([path]) => path === args.from || path.startsWith(args.from + '/'));
if (!matches.length) throw Error('Source missing');
for (const [path, contents] of matches) { files.delete(path); files.set(args.to + path.slice(args.from.length), contents); }
return;
}
if (command === 'workspace_copy') {
const path = (args.parent ? args.parent + '/' : '') + args.rel.split('/').pop();
if (files.has(path)) throw Error('Destination exists');
files.set(path, files.get(args.rel)); return { rel_path: path, name: path.split('/').pop(), kind: 'file' };
}
if (command === 'workspace_open_window') { window.workspaceSmoke.transfer = args.transfer; return; }
if (command === 'workspace_abs_path') return root + '\\' + args.rel;
if (command === 'workspace_recent') return [root];
if (command === 'workspace_search') return [];
if (command === 'plugin:dialog|message') return 'Cancel';
if (command === 'plugins_snapshot') return { plugins: [], issues: [] };
if (command.startsWith('plugin:window|') || command === 'workspace_open_terminal' || command === 'workspace_open_default') return;
if (command === 'browser_stop') return;
throw Error('Unhandled IPC: ' + command);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
page.setDefaultTimeout(15000);
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const menu = label => page.getByRole('menuitem', { name: label, exact: true });
try {
await page.goto(url);
await row('a.md').click();
await page.locator('.cm-content').waitFor();
await page.locator('.mode-switcher').first().hover();
await page.waitForFunction(() => document.querySelector('.mode-switcher')?.classList.contains('expanded'), null, { timeout: 500 });
await page.mouse.move(500, 400);
await row('a.md').click({ button: 'right' });
await menu('Save as template').click();
await page.getByRole('textbox', { name: 'Template name' }).fill('Meeting');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('.runestone/templates/Meeting.md'));
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.getByRole('button', { name: 'New note', exact: true }).click();
await menu('Meeting').click();
await page.getByRole('tab', { name: /Meeting/ }).waitFor();
assert.equal(await page.evaluate(() => window.workspaceSmoke.files.get('Meeting.md')), '# Alpha\n\nTemplate body.\n');
const before = await page.getByRole('tab', { selected: true }).getAttribute('data-path');
await page.keyboard.press('Control+Tab');
assert.notEqual(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
await page.keyboard.press('Control+Shift+Tab');
assert.equal(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
await row('b.md').click({ button: 'right' }); await menu('Cut').click();
await row('folder').click({ button: 'right' }); await menu('Paste').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await row('folder').click({ button: 'right' }); await menu('Undo file move').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
await row('folder').click({ button: 'right' }); await menu('Redo file move').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await row('folder').focus();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
const sourceBox = await row('b.md').boundingBox(), folderBox = await row('folder').boundingBox();
await page.mouse.move(sourceBox.x + 50, sourceBox.y + sourceBox.height / 2);
await page.mouse.down();
await page.mouse.move(folderBox.x + 70, folderBox.y + folderBox.height / 2, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await page.keyboard.press('Control+z');
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
await row('folder').click({ button: 'right' }); await menu('Open in terminal').click();
assert.ok(await page.evaluate(() => window.workspaceSmoke.calls.some(call => call.command === 'workspace_open_terminal' && call.args.rel === 'folder')));
await page.keyboard.press('Control+,');
const settingsPage = await context.newPage();
await settingsPage.goto(url + '/?settingsWindow=true');
await settingsPage.getByRole('switch', { name: 'Show .runestone folder' }).check();
await settingsPage.getByRole('button', { name: 'Appearance', exact: true }).click();
const theme = { schema: 1, id: 'smoke', name: 'Smoke theme', light: { bg: '#fefefe', text: '#222222', accent: '#334499' }, dark: { bg: '#181820', text: '#eeeeee', accent: '#aabbff' } };
await settingsPage.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: 'smoke.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(theme)) });
await settingsPage.waitForFunction(() => document.documentElement.dataset.palette === 'custom:smoke');
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#181820');
await settingsPage.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption('light');
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#fefefe');
await mkdir('.audit', { recursive: true });
await settingsPage.screenshot({ path: '.audit/kanban-custom-theme-light.png' });
await settingsPage.close();
await row('.runestone').waitFor();
await page.getByRole('tab', { name: /Meeting/ }).click();
const editor = page.locator('.cm-content'); await editor.click(); await page.keyboard.press('Control+End'); await page.keyboard.type('Unsaved transfer');
await page.getByRole('tab', { name: /Meeting/ }).click({ button: 'right' });
await menu('Open in new window').click();
await page.waitForFunction(() => window.workspaceSmoke.transfer);
const token = await page.evaluate(() => window.workspaceSmoke.transfer);
const target = await context.newPage();
target.on('pageerror', error => errors.push(error.message));
await target.goto(url + '/?tabTransfer=' + token);
await target.getByRole('tab', { name: /Meeting/ }).waitFor();
await target.waitForFunction(() => document.querySelector('.cm-content')?.textContent.includes('Unsaved transfer'));
await page.getByRole('tab', { name: /Meeting/ }).waitFor({ state: 'detached' });
await page.evaluate(() => { window.workspaceSmoke.transfer = null; });
const draggedTab = page.getByRole('tab').first();
const draggedPath = await draggedTab.getAttribute('data-path');
const tabBox = await draggedTab.boundingBox();
await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
await page.mouse.down();
await page.mouse.move(1480, 180, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => window.workspaceSmoke.transfer);
assert.notEqual(await page.evaluate(() => window.workspaceSmoke.transfer), token);
assert.equal(await page.locator(`[role="tab"][data-path="${draggedPath}"]`).count(), 1, 'Keep the source tab until the new window accepts it');
assert.equal(errors.length, 0, errors.join('\n'));
console.log('PASS: templates, tab shortcuts, move undo/redo, terminal action, internal folder, theme import, and acknowledged unsaved tab transfer');
} finally { await browser.close(); }
+28 -1
View File
@@ -2,10 +2,37 @@ import assert from "node:assert/strict";
import test from "node:test";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "../src/lib/editor/markdownTable.ts";
import { tableCellMarkdown, extractedCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml } from "../src/lib/workspace/noteHtml.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
const table = "| Ticker | Notes |\n| :--- | ---: |\n| IBKR.US | First<br>Second |";
test("prose directly after a table stays outside the table and its edit range", () => {
for (const eol of ["\n", "\r\n"]) {
const body = table.replaceAll("\n", eol);
const tail = `${eol}Plain text${eol}More text with an escaped \\| pipe${eol}# Heading`;
const source = body + tail;
assert.equal(parseMarkdownTable(source)?.end, body.length);
assert.equal(parseMarkdownTable(source)?.rows.length, 3);
assert.equal(appendTableRow(source), body + `${eol}| | |` + tail);
assert.equal(appendTableColumn(source), appendTableColumn(body) + tail);
assert.equal(replaceTableCell(source, 3, 0, "changed"), source);
const html = renderMarkdownHtml(source, new Map());
assert.equal((html.match(/<tr>/g) || []).length, 2);
assert.match(html, /<\/table>[\s\S]*<p>Plain text/);
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections[0].end, body.length + eol.length);
assert.equal(source.slice(sections[1].start).startsWith("Plain text"), true);
}
});
test("table boundaries distinguish escaped pipes from delimiters and work in nested blocks", () => {
const body = "| A | B |\n| --- | --- |\nOne | Two\n| short |\n| escaped \\| pipe | value |\n| even \\\\| delimiter |";
assert.equal(parseMarkdownTable(body + "\nProse \\| literal")?.rows.length, 6);
assert.equal((renderMarkdownHtml(body + "\nProse \\| literal", new Map()).match(/<tr>/g) || []).length, 5);
assert.match(renderMarkdownHtml("> | A |\n> | --- |\n> | B |\n> Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
assert.match(renderMarkdownHtml("- Item\n\n | A |\n | --- |\n | B |\n Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
});
test("extracted cell text keeps formatting and literal code while converting actual line breaks", () => {
assert.equal(extractedCellMarkdown([
{ type: "text", text: "Title", marks: [{ type: "bold" }] },
+71 -5
View File
@@ -16,12 +16,15 @@ await page.addInitScript(() => {
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
@@ -65,7 +68,10 @@ try {
await tab.waitFor();
await page.locator(".cm-content").waitFor();
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
await row.focus();
await row.click({ button: "right" });
const file = menu("File actions");
@@ -105,7 +111,8 @@ try {
await page.keyboard.press("ArrowLeft");
assert.equal(await item("Move tab").evaluate(node => node === document.activeElement), true);
await dismiss();
await page.getByText("Original text.", { exact: true }).click({ button: "right" });
await page.getByText("Original text.", { exact: true }).click();
await page.keyboard.press("Shift+F10");
const editor = menu("Markdown text actions");
assert.deepEqual(await metrics(editor), reference, "Editor and file menus share styles");
await item("Paragraph").focus();
@@ -116,6 +123,55 @@ try {
await page.locator(".live-writer td").first().click({ button: "right" });
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
await dismiss();
await page.getByText("Original text.", { exact: true }).click({ button: "right" });
await page.evaluate(() => window.spellingTest.emit({ request: "spelling-1", items: [
{ id: 71, name: "suggestion", label: "Original", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 72, name: "addToDictionary", label: "Add to dictionary", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 0, name: "", label: "", shortcut: "", kind: 3, enabled: false, checked: false, children: [] },
{ id: 73, name: "cut", label: "Cu&t", shortcut: "Ctrl+X", kind: 0, enabled: false, checked: false, children: [] },
{ id: 74, name: "copy", label: "&Copy", shortcut: "Ctrl+C", kind: 0, enabled: true, checked: false, children: [] },
{ id: 75, name: "spellCheck", label: "Spell check", shortcut: "", kind: 1, enabled: true, checked: true, children: [] },
] }));
const spelling = menu("Spelling actions");
await spelling.waitFor();
assert.deepEqual(await metrics(spelling), reference, "Spelling and file menus share styles");
assert.equal(await item("Add to dictionary").locator("svg.action-icon").count(), 1);
assert.equal(await page.getByRole("menuitemcheckbox", { name: "Spell check" }).getAttribute("aria-checked"), "true");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
assert.equal(await item("Copy Ctrl+C").evaluate(node => node === document.activeElement), true, "Spelling keyboard navigation skips disabled commands");
await page.screenshot({ path: ".audit/menu-spelling-" + theme + ".png" });
await page.keyboard.press("Home");
await page.keyboard.press("Enter");
await spelling.waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "spelling-1", command: 71 });
assert.equal(await page.locator(".cm-content").evaluate(node => node === document.activeElement), true);
async function emitSpelling(request) {
await page.evaluate(request => window.spellingTest.emit({ request, items: [
{ id: 81, name: "suggestion", label: "Replacement", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
] }), request);
await spelling.waitFor();
}
await emitSpelling("cancel");
await dismiss();
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "cancel", command: null });
await emitSpelling("outside");
await row.click();
await spelling.waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "outside", command: null });
await emitSpelling("old");
await emitSpelling("new");
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null });
await dismiss();
await page.evaluate(() => {
const input = document.createElement("input");
input.spellcheck = false;
document.body.append(input);
input.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
window.spellingTest.emit({ request: "ordinary-input", items: [] });
input.remove();
});
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "ordinary-input", command: null, fallback: true });
}
await page.setViewportSize({ width: 420, height: 320 });
await page.evaluate(async () => {
@@ -124,7 +180,10 @@ try {
{ label: "Without icon", run: () => {} },
{ label: "With icon", icon: "copy", run: () => {} },
{ label: "Unavailable", icon: "trash", disabled: true },
{ label: "More", icon: "plus", children: Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })) },
{ label: "More", icon: "plus", children: [
{ label: "Languages", children: [{ label: "English", checked: true, run: () => {} }] },
...Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })),
] },
], () => root.remove(), "Edge test");
});
const edge = menu("Edge test");
@@ -135,6 +194,13 @@ try {
assert.equal(await item("More").evaluate(node => node === document.activeElement), true, "Keyboard skips disabled rows");
await page.keyboard.press("ArrowRight");
const sub = menu("More");
await page.keyboard.press("ArrowRight");
assert.equal(await sub.isVisible(), true, "Nested submenus keep the parent visible");
assert.equal(await menu("Languages").isVisible(), true);
assert.equal(await page.getByRole("menuitemcheckbox", { name: "English" }).evaluate(node => node === document.activeElement), true);
await page.keyboard.press("ArrowLeft");
assert.equal(await menu("Languages").isVisible(), false);
assert.equal(await item("Languages").evaluate(node => node === document.activeElement), true);
for (const panel of [edge, sub]) {
const bounds = await panel.boundingBox();
assert.ok(bounds.x >= 8 && bounds.y >= 8 && bounds.x + bounds.width <= 412 && bounds.y + bounds.height <= 312);
+145
View File
@@ -0,0 +1,145 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function open(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expectedLength: expected.length, actualLength: (await writer()).length, errors }); throw error; }
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5173');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
const formatted = '# Copied heading\n\n## Links\n\n[Reference](https://example.com) and [[second|Another note]]\n\n**Bold**, *italic*, and `code`.\n\n- A list item\n';
await page.evaluate(text => { window.__TEST__.files.set('notes/source.md', text); window.__TEST__.files.set('notes/pasted.md', ''); }, formatted);
await open('source.md');
await writer();
await page.locator('.cm-content').click();
await page.keyboard.press('Control+a');
await page.keyboard.press('Control+c');
await open('pasted.md');
await writer();
for (let iteration = 0; iteration < 12; iteration++) {
await page.locator('.cm-content').click();
await page.keyboard.press('Control+a');
await page.keyboard.press('Backspace');
await expectWriter('');
await page.keyboard.press('Control+v');
await expectWriter(formatted);
assert.equal(await page.locator('.live-writer .cm-editor').count(), 1, 'One mounted editor');
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('notes/pasted.md').replace(/\r\n?/g, '\n')), formatted);
if (iteration === 5) {
await page.keyboard.press('Control+e');
await page.locator('.monaco-editor textarea').waitFor();
await page.keyboard.press('Control+e');
await expectWriter(formatted);
}
await open('second.md');
await writer();
await page.getByRole('tab', { name: 'pasted.md', exact: true }).click();
await expectWriter(formatted);
}
// Clipboard formats can use different line endings than the destination.
for (const lineBreak of ['\n', '\r\n', '\r']) {
await page.evaluate(({ text, lineBreak }) => {
const view = window.__WRITER__;
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
const clipboardData = new DataTransfer();
clipboardData.setData('text/plain', text.replace(/\n/g, lineBreak));
view.contentDOM.dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData }));
}, { text: formatted, lineBreak });
await expectWriter(formatted);
assert.equal(await page.evaluate(() => window.__WRITER__.state.doc.lines), formatted.split('\n').length);
await page.keyboard.press('Control+s');
const synchronized = await page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const model = monaco.editor.getModels().find(model => model.uri.path.endsWith('/pasted.md'));
const source = window.__WRITER__.state.doc.sliceString(0, undefined, model.getEOL());
return source === model.getValue() && source === window.__TEST__.files.get('notes/pasted.md');
});
assert.equal(synchronized, true, 'Writer, model, and saved source agree');
}
assert.deepEqual(errors, []);
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, IDE reopen, and LF/CRLF/CR clipboard replacement');
} finally { await browser.close(); }
+24 -25
View File
@@ -14,7 +14,7 @@ await context.addInitScript(() => {
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" });
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("runestone.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("org.example.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const modules = {
"runestone.local-autocomplete": `export function activate(api) {
window.accessTest = { mounts: 0, disposed: 0, settings: 0 };
@@ -26,11 +26,11 @@ await context.addInitScript(() => {
container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value });
return () => { window.accessTest.disposed++; };
}});
api.registerCommand({ id: 'configure', title: 'Configure local autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'configure', title: 'Configure Local Autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } });
}`,
"runestone.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', run() {
"org.example.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run() {
const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id);
}});
}`,
@@ -46,6 +46,8 @@ await context.addInitScript(() => {
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === 'plugin:event|unlisten') { callbacks.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop') return;
if (command === 'workspace_last_path') return null;
if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: plugins.map(manifest => ({ manifest, hash: 'test', enabled: !(manifest.id === 'runestone.local-autocomplete' && localStorage.getItem('disabled')), installedAt: 1, path: 'C:/test/plugins/' + manifest.id, error: null, removal: false })) };
if (command === 'plugins_load') return modules[args.id];
@@ -66,29 +68,26 @@ const main = await context.newPage(), settings = await context.newPage();
for (const page of [main, settings]) { page.setDefaultTimeout(10000); page.on('pageerror', error => errors.push(error.message)); }
try {
await main.goto(origin);
const open = main.getByRole('button', { name: 'Open tab or view', exact: true });
await open.click();
const menu = main.getByRole('menu', { name: 'Open tab or view', exact: true });
await menu.waitFor();
assert.equal(await menu.getByRole('menuitem').count(), 3);
assert.equal(await menu.getByText('Local Autocomplete').count(), 0);
await open.click(); await menu.waitFor({ state: 'detached' });
await open.focus(); await main.keyboard.press('Enter'); await main.keyboard.press('End'); await main.keyboard.press('Escape');
assert(await open.evaluate(element => element === document.activeElement));
await open.click(); await menu.getByRole('menuitem', { name: /New browser tab/ }).click();
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).waitFor();
assert.equal(await main.getByRole('button', { name: 'Open tab or view', exact: true }).count(), 0);
assert.equal(await main.getByRole('button', { name: 'Commands', exact: true }).count(), 0);
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).click();
await main.getByText('Task content', { exact: true }).waitFor();
await main.evaluate(async () => {
const { runPluginCommand } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
await runPluginCommand('org.example.browser', 'new-tab');
});
await main.getByText('Browser content', { exact: true }).waitFor();
await open.click(); assert.equal(await menu.getByRole('menuitem').count(), 3);
await menu.getByRole('menuitem', { name: /Task summary/ }).click();
await main.evaluate(async () => {
const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
openPluginView('org.example.tasks', 'dialog');
});
await main.getByRole('dialog', { name: 'Task summary' }).waitFor();
await main.keyboard.press('Escape');
await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu.png' }); await main.keyboard.press('Escape');
await main.evaluate(() => document.documentElement.dataset.theme = 'light');
await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu-light.png' }); await main.keyboard.press('Escape');
await main.evaluate(() => document.documentElement.dataset.theme = 'dark');
await main.getByRole('button', { name: 'Commands', exact: true }).click();
await main.getByRole('menuitem', { name: /Failed command/ }).click();
await main.getByRole('alert').filter({ hasText: 'Command failed for test' }).waitFor();
await main.getByRole('button', { name: 'Dismiss', exact: true }).click();
for (const theme of ['dark', 'light']) {
await main.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await main.screenshot({ path: `.audit/plugin-access-${theme}.png` });
}
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).click();
await settings.getByRole('textbox', { name: 'Model', exact: true }).fill('unsaved-model');
@@ -109,7 +108,7 @@ try {
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).waitFor({ state: 'detached' });
await main.getByRole('button', { name: 'Commands', exact: true }).waitFor({ state: 'detached' });
assert.deepEqual(errors, []);
console.log('Plugin access smoke passed: launchers, dynamic tabs, keyboard focus, dialog, settings search, stable forms, cross-window settings, disable cleanup.');
console.log('Plugin access smoke passed: compact header, navigation, dynamic tabs, dialog, settings search, stable forms, cross-window settings, disable cleanup.');
} catch (error) {
await settings.screenshot({ path: '.audit/plugin-access-failure.png' });
console.log(await settings.locator('body').innerText(), await settings.evaluate(() => window.accessTest), errors);
+59
View File
@@ -0,0 +1,59 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../src/lib/plugins/registry.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
test("Git and file access stop before plugin cleanup", async () => {
const calls: unknown[] = [];
let api!: PluginApi;
const registry = new ContributionRegistry();
const session = new ExternalSession("test.git", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
openFile: async path => { calls.push(path); },
git: {
status: async () => ({ available: true, repository: true, branch: "main", changes: [] }),
diff: async (path, staged) => { calls.push([path, staged]); return "diff"; },
stage: async paths => { calls.push(paths); }, unstage: async paths => { calls.push(paths); },
commit: async message => { calls.push(message); }, blame: async () => null,
push: async () => { calls.push('push'); }, pull: async () => { calls.push('pull'); }, graph: async () => ({ commits: [] }),
},
}, () => {}, () => {}, registry);
await session.start({ activate(value) { api = value; api.contribute("git", { blame: (path, line) => api.git!.blame(path, line) }); } });
await api.openFile!("notes.md");
assert.equal(await api.git!.diff("notes.md", true), "diff");
await api.git!.stage(["notes.md"]);
assert.deepEqual(calls, ["notes.md", ["notes.md", true], ["notes.md"]]);
await api.git!.push();
await api.git!.pull();
assert.deepEqual(await api.git!.graph(), { commits: [] });
assert.deepEqual(calls.slice(-2), ['push', 'pull']);
await session.stop();
assert.equal(registry.get("git"), undefined);
assert.throws(() => api.openFile!("notes.md"), /disabled/);
for (const action of [() => api.git!.push(), () => api.git!.pull(), () => api.git!.graph()]) assert.throws(action, /disabled/);
for (const action of [() => api.git!.status(), () => api.git!.diff("a", false), () => api.git!.stage(["a"]), () => api.git!.unstage(["a"]), () => api.git!.commit("a"), () => api.git!.blame("a", 1)]) assert.throws(action, /disabled/);
});
test("view replacement rejects unknown destinations and stops after disposal", async () => {
let api!: PluginApi;
const calls: unknown[] = [];
const session = new ExternalSession("test.boards", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
}, () => {}, () => {}, new ContributionRegistry(), undefined, undefined, undefined,
(current, next) => calls.push([current, next]), (document, next) => calls.push([document, next]));
await session.start({ activate(value) {
api = value;
for (const id of ["a", "b"]) api.registerView({ id, title: id, placement: "editor", mount() {} });
api.registerView({ id: "sidebar", title: "Sidebar", placement: "sidebar", navigation: true, icon: "git", mount() {} });
} });
api.replaceView!("a", "b");
api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "b");
assert.deepEqual(calls, [["a", "b"], [{ id: "legacy", path: "Board.md" }, "b"]]);
assert.throws(() => api.replaceView!("missing", "b"), /Unknown/);
assert.throws(() => api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "missing"), /Unknown/);
await session.stop();
assert.throws(() => api.replaceView!("a", "b"), /disabled/);
});
+4 -2
View File
@@ -167,8 +167,10 @@ try {
assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
await settingsPage.screenshot({ path: '.audit/plugin-manager-installed.png' });
await settingsPage.keyboard.press('Escape');
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
await page.getByRole('button', { name: /Show workspace overview/ }).click();
await page.evaluate(async pluginId => {
const { runPluginCommand } = await import('/src/lib/plugins/external.ts');
await runPluginCommand(pluginId, 'show-overview');
}, manifest.id);
const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true });
await view.getByText(/files and folders in this workspace/).waitFor();
await view.getByRole('button', { name: 'Close plugin view', exact: true }).click();
+60 -1
View File
@@ -111,6 +111,62 @@ try {
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
await page.goto(url);
await page.getByText("plugin-tab-workspace", { exact: true }).waitFor();
await tab("New tab").waitFor();
for (const close of ["button", "middle", "shortcut", "all"]) {
const before = await tab("New tab").getAttribute("data-path");
if (close === "button") await page.getByRole("button", { name: "Close New tab", exact: true }).click();
if (close === "middle") await tab("New tab").click({ button: "middle" });
if (close === "shortcut") await page.keyboard.press("Control+w");
if (close === "all") {
await menu("New tab");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
}
await page.waitForFunction(before => {
const tabs = document.querySelectorAll('.header [role="tab"]');
return tabs.length === 1 && tabs[0].getAttribute("data-path") !== before;
}, before);
assert.equal(await tab("New tab").getAttribute("aria-selected"), "true");
}
for (const name of ["a.md", "b.md", "c.md", "note-0.md"]) await openFile(name);
await page.getByRole("textbox", { name: "Writing editor", exact: true }).filter({ hasText: "# note-0.md" }).waitFor();
for (const width of [880, 1280, 1440]) {
await page.setViewportSize({ width, height: 1000 });
await settle();
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
const dimensions = await page.locator(".header").evaluate(header => {
const bar = header.querySelector('[role="tablist"]');
const rows = [...bar.querySelectorAll(".tab")];
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]');
const bounds = bar.getBoundingClientRect();
return {
overflow: bar.scrollWidth - bar.clientWidth,
left: bounds.left,
navigationRight: header.querySelector(".header-left").getBoundingClientRect().right,
tabWidth: Math.min(...rows.map(row => row.getBoundingClientRect().width)),
gap: plus.getBoundingClientRect().left - Math.min(bounds.right, rows.at(-1).getBoundingClientRect().right),
fits: header.scrollWidth <= header.clientWidth,
};
});
if (width >= 1280) assert.ok(dimensions.overflow <= 1, JSON.stringify(dimensions));
assert.ok(Math.abs(dimensions.left - dimensions.navigationRight) <= 2, JSON.stringify(dimensions));
assert.ok(dimensions.tabWidth >= 96, JSON.stringify(dimensions));
assert.ok(dimensions.gap >= 0 && dimensions.gap <= 8, JSON.stringify(dimensions));
assert.ok(dimensions.fits);
const plus = page.getByRole("button", { name: "New tab (Ctrl T)", exact: true });
await plus.evaluate(button => button.blur());
await plus.focus();
await page.locator('[role="tooltip"]:popover-open').filter({ hasText: "New tab (Ctrl T)" }).waitFor();
await page.keyboard.press("Escape");
await mkdir(".audit", { recursive: true });
await page.locator(".header").screenshot({ path: `.audit/compact-tabs-${width}-${theme}.png` });
}
}
await menu("note-0.md");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
await tab("New tab").waitFor();
assert.deepEqual(await order(), ["New tab"]);
console.log("PASS: the last tab becomes a new tab, tabs retain usable widths, and the adjacent plus button has a focus tooltip");
await openFile("a.md");
await openFile("b.md");
await openView("Overview");
@@ -232,7 +288,9 @@ try {
await settingsPage.close();
await page.goto(`${url}?no-workspace`);
await tab("New tab").waitFor();
await openView("Overview");
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
await openView("Browser");
await drag("Browser", "Overview");
assert.deepEqual(await order(), ["Browser", "Overview"]);
@@ -242,7 +300,8 @@ try {
await tab("Browser").click({ button: "middle" });
assert.deepEqual(await order(), ["Overview"]);
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
assert.equal(await page.getByRole("tab").count(), 0);
await tab("New tab").waitFor();
assert.deepEqual(await order(), ["New tab"]);
assert.deepEqual(errors, []);
console.log("PASS: plugin tabs reorder and close without an open workspace");
} catch (error) {
+4 -4
View File
@@ -7,15 +7,15 @@ test("missing or damaged preferences keep safe defaults", () => {
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
}
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds })), { autosaveEnabled: false, autosaveSeconds: 5 });
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10 });
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false });
});
test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds };
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false };
saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
}
@@ -25,7 +25,7 @@ test("invalid changes never reach storage and storage failures reach the caller"
let writes = 0;
const storage = { setItem: () => { writes++; } };
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds }));
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds, showInternalFolder: false }));
}
assert.equal(writes, 0);
assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/);
+109
View File
@@ -0,0 +1,109 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
await mkdir(".audit", { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1152, height: 815 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
const callbacks = new Map();
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:/RuneStone/plugins", plugins: Array.from({ length: 7 }, (_, index) => ({
manifest: { schemaVersion: 1, id: `org.example.plugin-${index}`, name: `Example plugin ${index + 1}`, author: "RuneStone Team", description: "A plugin description with enough text to check readable wrapping.", version: "0.1.1", apiVersion: 1, entry: "main.js", access: "full-app" },
enabled: false, hash: "test", installedAt: 1791390000000, path: `D:/RuneStone/plugins/plugin-${index}`, error: null, removal: false,
})) };
if (command === "workspace_last_path") return null;
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
for (const page of [main, settings]) {
page.setDefaultTimeout(7000);
page.on("pageerror", error => errors.push(error.message));
}
await main.goto(origin);
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
const header = settings.locator("dialog > header");
const mainHeader = main.locator(".header");
assert.equal((await header.boundingBox()).height, (await mainHeader.boundingBox()).height, "Settings and main title bars share their height");
for (const name of ["Minimize window", "Maximize window", "Close window"]) {
const a = await main.getByRole("button", { name, exact: true }).boundingBox();
const b = await settings.getByRole("button", { name, exact: true }).boundingBox();
assert.equal(a.width, b.width);
assert.equal(a.height, b.height, `${name} has the same dimensions in both windows`);
}
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("switch", { name: "Example plugin 1", exact: true }).waitFor();
const content = settings.locator(".content");
const pluginRows = content.locator(".row");
assert.equal(await pluginRows.count(), 7);
for (const theme of ["dark", "light"]) {
await settings.evaluate(value => document.documentElement.dataset.theme = value, theme);
for (const width of [1152, 540, 360]) {
await settings.setViewportSize({ width, height: width === 1152 ? 815 : 420 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
assert(await content.evaluate(element => element.scrollWidth <= element.clientWidth), "The plugin content does not scroll horizontally");
const rows = await pluginRows.evaluateAll(elements => elements.map(element => element.getBoundingClientRect().height));
if (width === 1152) {
assert(rows.every(height => height <= 100), `Desktop plugin rows stay compact: ${rows}`);
const count = await pluginRows.evaluateAll(elements => {
const container = elements[0].closest(".content").getBoundingClientRect();
return elements.filter(element => element.getBoundingClientRect().bottom <= container.bottom).length;
});
assert(count >= 5, `At least five complete plugin rows fit at the screenshot size, got ${count}`);
}
const copy = pluginRows.first().locator(".plugin-copy");
const controls = pluginRows.first().locator(".controls");
const a = await copy.boundingBox(), b = await controls.boundingBox();
assert(a.x + a.width <= b.x + 1 || a.y + a.height <= b.y + 1, "Plugin text does not overlap its actions");
for (const button of await controls.getByRole("button").all()) {
const bounds = await button.boundingBox();
assert(bounds.width >= 28 && bounds.height >= 28);
assert(await button.getAttribute("aria-label"));
}
await settings.screenshot({ path: `.audit/settings-density-${theme}-${width}.png` });
}
}
await settings.setViewportSize({ width: 540, height: 420 });
await settings.getByRole("button", { name: "Install from Git link", exact: true }).click();
const install = settings.getByRole("dialog", { name: "Install from Git link", exact: true });
await install.waitFor();
assert(await install.getByRole("textbox", { name: "Repository link", exact: true }).isVisible());
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Cancel");
await settings.keyboard.press("Escape");
await install.waitFor({ state: "detached" });
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Install from Git link");
await settings.getByRole("button", { name: "General", exact: true }).click();
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
await settings.evaluate(async () => {
const { pluginTools } = await import("/src/lib/plugins/external.ts");
pluginTools.set(Array.from({ length: 12 }, (_, index) => ({ owner: "org.example.plugin-0", id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: "settings" })));
});
await settings.setViewportSize({ width: 360, height: 420 });
const sidebar = settings.locator("dialog aside");
assert((await sidebar.boundingBox()).height <= 154, "Many plugin categories leave space for setting controls");
assert(await sidebar.evaluate(element => element.scrollWidth <= element.clientWidth));
await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).scrollIntoViewIfNeeded();
const category = await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).boundingBox();
const navigation = await sidebar.boundingBox();
assert(category.y >= navigation.y && category.y + category.height <= navigation.y + navigation.height, "Every plugin category remains reachable");
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
assert.deepEqual(errors, []);
console.log("Settings density smoke passed: matching title bars and window controls, seven plugin rows, compact layout, readable text, accessible actions, both themes, narrow layouts, Git dialog focus, and many plugin categories.");
} finally { await browser.close(); }
+96
View File
@@ -0,0 +1,96 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import { mkdirSync, readFileSync } from "node:fs";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
mkdirSync(".audit", { recursive: true });
const settingsCapability = JSON.parse(readFileSync(new URL("../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
assert.deepEqual(settingsCapability.windows, ["settings-main", "settings-workspace-*"]);
for (const action of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert(settingsCapability.permissions.includes(`core:window:allow-${action}`));
}
const errors = [];
try {
const context = await browser.newContext({ viewport: { width: 920, height: 650 } });
await context.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map();
const listeners = new Map();
window.__TEST__ = { calls: [], maximized: false, fail: "", resize: () => callbacks.get(listeners.get("tauri://resize"))?.({ payload: {} }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "settings-main" }, currentWebview: { label: "settings-main" } },
transformCallback: callback => { const id = callbacks.size + 1; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.__TEST__.calls.push(command);
if (window.__TEST__.fail === command) throw new Error("Window action failed");
if (command === "plugins_snapshot") return { root: "D:\\SettingsTest\\plugins", plugins: [] };
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return args.handler; }
if (command === "plugin:window|is_maximized") return window.__TEST__.maximized;
if (command === "plugin:window|toggle_maximize") window.__TEST__.maximized = !window.__TEST__.maximized;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const page = await context.newPage();
page.on("pageerror", error => errors.push(error.message));
page.setDefaultTimeout(5000);
await page.goto(`${url}/?settingsWindow=true`);
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.waitFor();
assert.equal(await dialog.getByRole("button", { name: /^Close/ }).count(), 1);
assert(await dialog.locator("header[data-tauri-drag-region] h1[data-tauri-drag-region]").isVisible());
assert.equal(await dialog.locator(".window-controls [data-tauri-drag-region]").count(), 0);
const calls = () => page.evaluate(() => window.__TEST__.calls);
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
assert((await calls()).includes("plugin:window|minimize"));
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Restore window", exact: true }).focus();
await page.keyboard.press("Enter");
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
await page.evaluate(() => { window.__TEST__.maximized = true; window.__TEST__.resize(); });
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Close window", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
await page.keyboard.press("Space");
const beforeEscape = (await calls()).filter(command => command === "plugin:window|close").length;
assert.equal(beforeEscape, 1);
await page.getByRole("textbox", { name: "Search settings" }).focus();
await page.keyboard.press("Escape");
assert.equal((await calls()).filter(command => command === "plugin:window|close").length, beforeEscape + 1);
await page.mouse.move(400, 180);
for (const theme of ["dark", "light"]) {
await page.evaluate(value => document.documentElement.setAttribute("data-theme", value), theme);
for (const size of [{ width: 920, height: 650 }, { width: 540, height: 420 }]) {
await page.setViewportSize(size);
assert(await dialog.evaluate(element => element.scrollWidth === element.clientWidth));
for (const label of ["Minimize window", "Restore window", "Close window"]) {
const button = dialog.getByRole("button", { name: label, exact: true });
const bounds = await button.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= size.width && bounds.height >= 28);
assert.notEqual(await button.evaluate(element => getComputedStyle(element).borderTopLeftRadius), "0px");
}
await page.screenshot({ path: `.audit/settings-window-${theme}-${size.width}.png` });
}
}
await page.evaluate(() => { window.__TEST__.fail = "plugin:window|minimize"; });
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
await dialog.getByRole("alert").filter({ hasText: "Window action failed" }).waitFor();
await page.evaluate(() => { window.__TEST__.fail = ""; });
await page.getByRole("button", { name: "Minimize window", exact: true }).focus();
await page.keyboard.press("Shift+Tab");
assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Restore defaults");
await page.keyboard.press("Tab");
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Minimize window");
const web = await browser.newPage();
await web.goto(`${url}/?settingsWindow=true`);
await web.getByRole("button", { name: "Close settings", exact: true }).waitFor();
assert.equal(await web.getByRole("group", { name: "Window controls" }).count(), 0);
assert.deepEqual(errors, []);
console.log("Settings window smoke passed: scoped permissions, drag regions, minimize, maximize, restore, resize, close, Escape, keyboard focus, tooltips, errors, both themes, narrow layout, and browser fallback.");
} finally { await browser.close(); }
+2 -1
View File
@@ -65,6 +65,7 @@ try {
if (command === "workspace_last_path") return null;
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugin:window|close") { window.settingsTest.closes++; return; }
throw new Error(`Unexpected IPC: ${command}`);
},
@@ -84,7 +85,7 @@ try {
await desktop.getByText(/Could not open settings: .*Native window creation failed/).waitFor();
await desktop.goto(`${origin}/?settingsWindow=true`);
await desktop.getByRole("heading", { name: "General", exact: true }).waitFor();
await desktop.getByRole("button", { name: "Close settings", exact: true }).click();
await desktop.getByRole("button", { name: "Close window", exact: true }).click();
assert.equal(await desktop.evaluate(() => window.settingsTest.closes), 1);
assert.deepEqual(errors, []);
console.log("Settings window smoke passed: preview fallback, standalone layout, two-way save sync, persistence, failed saves, native open requests, and close.");
+66
View File
@@ -0,0 +1,66 @@
// Use a debug app with TAURI_CONFIG identifier com.runestone.spelling-test,
// a hidden window, and a separate WEBVIEW2_USER_DATA_FOLDER outside Vite's watch paths.
// Set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9224 before launch.
// The normal app identifier is rejected before this test writes any workspace files.
import { createRequire } from "node:module";
import { mkdir, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || "http://127.0.0.1:9224");
const page = browser.contexts()[0].pages()[0];
page.setDefaultTimeout(15000);
try {
await page.goto(process.env.SPELLING_APP_URL || "http://localhost:1420");
const data = await page.evaluate(async () => {
const { appDataDir } = await import("/node_modules/@tauri-apps/api/path.js");
return appDataDir();
});
assert.match(data, /[\\/]com\.runestone\.spelling-test[\\/]?$/, "Use the isolated spelling-test app identifier");
const workspace = resolve(process.env.SPELLING_WORKSPACE || ".audit/spelling-workspace");
await mkdir(workspace, { recursive: true });
await writeFile(resolve(workspace, "Spelling.md"), "# Spelling\n\nI recieved a letter.\n");
await page.evaluate(async path => {
const { invoke } = await import("/node_modules/@tauri-apps/api/core.js");
await invoke("workspace_open", { path });
}, workspace);
await page.reload();
await page.locator('[data-tree-rel="Spelling.md"]').click();
const editor = page.locator(".cm-content");
await editor.waitFor();
const line = page.getByText("I recieved a letter.", { exact: true });
const rect = await line.boundingBox();
await line.click();
const before = await editor.innerText();
await page.keyboard.press("End");
await page.keyboard.type(" TEST");
assert.notEqual(await editor.innerText(), before);
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
const menu = page.getByRole("menu", { name: "Spelling actions", exact: true });
await menu.waitFor();
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/spelling-native.png" });
await menu.getByRole("menuitem", { name: "Undo Ctrl+Z", exact: true }).click();
await page.waitForFunction(expected => document.querySelector(".cm-content")?.innerText === expected, before);
console.log("PASS: real WebView2 command dispatch through the shared menu restores the editor text.");
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
await menu.waitFor();
const suggestion = menu.getByRole("menuitem", { name: "received", exact: true });
if (await suggestion.count()) {
await suggestion.click();
await page.waitForFunction(() => document.querySelector(".cm-content")?.innerText.includes("I received a letter."));
await page.keyboard.press("Control+z");
await page.waitForFunction(() => document.querySelector(".cm-content")?.innerText.includes("I recieved a letter."));
console.log("PASS: native spelling correction and editor undo.");
} else {
await page.keyboard.press("Escape");
assert.notEqual(process.env.REQUIRE_NATIVE_SUGGESTIONS, "1", "The test WebView2 profile supplied no spelling suggestions");
console.log("SKIP: native spelling correction. This WebView2 profile supplied no suggestions. Desktop acceptance is still required.");
}
} finally {
await page.keyboard.press("Escape").catch(() => {});
await browser.close();
}
+3 -5
View File
@@ -74,9 +74,7 @@ async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("Home");
await page.locator(".monaco-editor textarea").waitFor();
}
@@ -108,7 +106,7 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['drag.md'] });
}, source);
await quickOpen('drag.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
assert.equal(await page.locator('.table-drag-row[data-index="0"]').count(), 0);
await page.mouse.move(5, 5);
@@ -202,7 +200,7 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['long.md'] });
});
await quickOpen('long.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
await grip('row', 1);
const scroller = await page.locator('.live-writer .cm-scroller').boundingBox();
+63 -1
View File
@@ -1,3 +1,4 @@
import { mockFeaturePlugins } from "./pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
@@ -70,6 +71,8 @@ await page.addInitScript(() => {
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
@@ -286,6 +289,65 @@ try {
assert.equal(await edit.count(), 0);
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
// Focusing empty and filled cells must not resize rows or columns.
const stableSource = '# Stable table\n\n| Column 2 | Column 1 | | |\n| --- | --- | --- | --- |\n| 2cm | Value | | |\n| text | 123 | | |\n| | | | |\n| LongUnbrokenCellValue | **Bold**<br>Two lines | A longer sentence wraps in a narrow table. | `code` |\n\nParagraph one.\nParagraph two.\n';
const dimensions = () => table.evaluate(el => [...el.rows].map(row => [...row.cells].map(cell => {
const rect = cell.getBoundingClientRect();
return { width: rect.width, height: rect.height };
})));
async function stableDimensions(expected, label) {
const actual = await dimensions();
for (let r = 0; r < expected.length; r++) for (let c = 0; c < expected[r].length; c++) {
for (const axis of ['width', 'height']) assert.ok(Math.abs(expected[r][c][axis] - actual[r][c][axis]) < 1,
`${label}: row ${r}, column ${c} ${axis} changed from ${expected[r][c][axis]} to ${actual[r][c][axis]}`);
}
}
for (const theme of ['dark', 'light']) for (const width of [1440, 800]) {
await page.setViewportSize({ width, height: 1000 });
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
const name = `stable-${theme}-${width}.md`;
await page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
}, { name, text: stableSource });
await quickOpen(name);
await table.waitFor();
const initial = await dimensions();
for (const [r, c] of [[1, 3], [2, 3], [3, 3], [0, 0], [1, 0], [1, 1], [4, 0], [4, 1], [4, 2], [4, 3], [2, 1]]) {
await at(r, c);
await stableDimensions(initial, `${theme} ${width} focus ${r},${c}`);
}
await arrow('Tab', 2, 2);
await stableDimensions(initial, `${theme} ${width} Tab`);
await arrow('ArrowDown', 3, 2);
await stableDimensions(initial, `${theme} ${width} ArrowDown`);
await page.keyboard.press('Escape');
await stableDimensions(initial, `${theme} ${width} blur`);
// Delete the blank line through the prose editor, then save and undo/redo.
await page.locator('.cm-line').filter({ hasText: 'Paragraph one.' }).click();
await page.keyboard.press('Home');
await page.keyboard.press('Backspace');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table tr').length === 5 &&
[...document.querySelectorAll('.cm-line')].some(line => line.textContent === 'Paragraph one.'));
await page.keyboard.press('Control+s');
const joined = stableSource.replace('\n\nParagraph one.', '\nParagraph one.');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, source }) => window.__TEST__.files.get(name) === source, { name, source: stableSource });
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
assert.equal(await table.locator('tr').count(), 5);
await at(1, 0);
await edit.fill('updated');
await page.keyboard.press('Escape');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined.replace('| 2cm |', '| updated |'), { name, joined });
}
await page.setViewportSize({ width: 1440, height: 1000 });
// A line break in a tall table keeps the caret and viewport in the active cell.
const tallSource = '# Tall table\n\nBefore.\n\n| Name | Value |\n| --- | --- |\n' +
Array.from({ length: 45 }, (_, i) => `| Row ${i + 1} | |`).join('\n') + '\n\nAfter.\n';
@@ -342,7 +404,7 @@ try {
await page.waitForFunction(({ name, expected }) => window.__TEST__.files.get(name) === expected, { name, expected });
}
assert.deepEqual(errors, []);
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, line breaks and scrolling in tall tables, save, undo/redo, Tab and Escape');
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, line breaks and scrolling in tall tables, save, undo/redo, Tab and Escape, stable cell dimensions and table/prose boundaries in both themes at wide/narrow widths');
} catch (error) {
await page.screenshot({ path: '.audit/table-navigation-failure.png' });
throw error;
+20
View File
@@ -0,0 +1,20 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { moveMarks, replayMoveMarks } from "../src/lib/workspace/treeMoveHistory.ts";
test("move undo preserves later bookmarks, pins, and new files", () => {
const before = { pins: ["notes/a.md"], bookmarks: [], order: { notes: ["a.md", "b.md"], archive: [] as string[] } };
const after = moveMarks(before, "notes/a.md", "archive/a.md");
const current = { ...after, bookmarks: ["other.md"], pins: [...after.pins, "b.md"], order: { ...after.order, notes: [...after.order.notes, "new.md"] } };
const undo = replayMoveMarks(current, before, after, [{ from: "notes/a.md", to: "archive/a.md" }], false);
assert.deepEqual(undo.pins, ["notes/a.md", "b.md"]);
assert.deepEqual(undo.bookmarks, ["other.md"]);
assert.deepEqual(undo.order.notes, ["a.md", "b.md", "new.md"]);
assert.deepEqual(undo.order.archive, []);
});
test("folder moves retain nested marks and custom order", () => {
const marks = { pins: ["old/child.md"], bookmarks: ["old/deep/file.md"], order: { old: ["child.md"], "old/deep": ["file.md"] } };
const next = moveMarks(marks, "old", "new/old");
assert.deepEqual(next.pins, ["new/old/child.md"]);
assert.deepEqual(next.bookmarks, ["new/old/deep/file.md"]);
assert.deepEqual(next.order["new/old/deep"], ["file.md"]);
});
+2 -1
View File
@@ -82,7 +82,8 @@ try {
await row('src').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'src']);
assert.equal(await row('src').getAttribute('aria-expanded'), 'false');
assert.equal(await page.getByRole('tab').count(), 0);
assert.equal(await page.getByRole('tab').count(), 1);
assert.equal(await page.getByRole('tab', { name: 'New tab', exact: true }).count(), 1);
await row('notes').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes/second.md', 'src']);
assert.equal(await row('notes').getAttribute('aria-expanded'), 'true');
+104
View File
@@ -0,0 +1,104 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note with a short paragraph.\n\nA second paragraph.\n\n| Name | Value |\n| --- | --- |\n| Alpha | 12 |\n| Beta | 24 |\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const page = await context.newPage();
page.setDefaultTimeout(30000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const url = process.env.SMOKE_URL || "http://127.0.0.1:5174";
const row = page.locator('[data-tree-rel="note.md"]');
try {
await page.goto(url);
await row.waitFor();
await row.click();
await page.locator('.writer-table table').waitFor();
const alignment = await page.evaluate(() => ({header:document.querySelector('.header-left').getBoundingClientRect().right, content:document.querySelector('.center').getBoundingClientRect().left}));
assert.ok(Math.abs(alignment.header - alignment.content) <= 1, JSON.stringify(alignment));
const table = await page.locator('.writer-table table').evaluate(el => ({width:el.getBoundingClientRect().width, heights:[...el.rows].map(row=>row.getBoundingClientRect().height), radius:getComputedStyle(el.parentElement).borderRadius}));
assert.ok(table.width < 400, JSON.stringify(table));
assert.ok(table.heights.every(height => height <= 36), JSON.stringify(table));
assert.equal(table.radius, '0px');
await row.focus();
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'visible');
await page.locator('.cm-content').click({position:{x:80,y:100}});
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'hidden');
assert.equal(await row.getAttribute('aria-selected'), 'true');
const line = page.locator('.cm-line').filter({hasText:'A second paragraph.'});
await line.hover();
assert.equal(await line.evaluate(el=>getComputedStyle(el,'::before').width), '3px');
assert.equal(await page.locator('.line-history').count(),0);
await page.evaluate(async()=>{
const {pluginHost}=await import('/src/lib/plugins/registry.ts');
window.blameCalls=[];
window.removeGit=pluginHost.register('ui-test','git',{blame:async(path,line)=>{
window.blameCalls.push({path,line});
return {commit:'123456789abcdef',author:'UI test',date:'2026-10-07T12:34:00Z',summary:`Changed line ${line}`};
}});
});
await line.click();
await page.locator('.line-history').waitFor();
assert.match(await page.locator('.line-history').getAttribute('title'), /Line 5 · UI test/);
await page.keyboard.type('x');
await page.locator('.line-history').waitFor({state:'hidden'});
await page.keyboard.press('Control+z');
await page.locator('.line-history').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const tab = await page.locator('.tab.active').evaluate(el=>({background:getComputedStyle(el).backgroundColor,border:getComputedStyle(el).borderBottomColor,shadow:getComputedStyle(el).boxShadow}));
const pane = await page.locator('.chrome-bar').evaluate(el=>getComputedStyle(el).backgroundColor);
assert.equal(tab.background,pane);
assert.equal(tab.border,'rgba(0, 0, 0, 0)');
assert.equal(tab.shadow,'none');
await line.hover();
await page.screenshot({path:`.audit/ui-cards/writer-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('ArrowRight');
await page.locator('.md-page .reading').waitFor();
const paragraph=page.locator('.md-page p').filter({hasText:'A second paragraph.'});
await paragraph.hover();
assert.equal(await paragraph.evaluate(el=>getComputedStyle(el,'::before').width),'3px');
assert.ok((await page.locator('.md-page table').boundingBox()).width<400);
await page.screenshot({path:`.audit/ui-cards/read-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('Home');
}
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('Home');
await page.locator('.monaco-editor').waitFor();
await page.locator('.line-history').waitFor();
await page.evaluate(()=>window.removeGit());
await page.locator('.line-history').waitFor({state:'hidden'});
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('End');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:760,height:640});
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const dimensions=await page.locator('.header-left .icon-btn').evaluateAll(els=>els.map(el=>({width:el.getBoundingClientRect().width,svg:el.querySelector('svg').getBoundingClientRect().width})));
assert.ok(dimensions.every(size=>size.width>=28 && size.svg>=16),JSON.stringify(dimensions));
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
await page.screenshot({path:`.audit/ui-cards/narrow-${theme}.png`});
}
assert.deepEqual(errors,[]);
console.log('PASS: pane-aligned ribbon, compact square tables, focus-only tree border, joined tabs, Writer/Read hover marker, Git line slot lifecycle, both themes and narrow width');
} finally {await browser.close();}
+175
View File
@@ -0,0 +1,175 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function open(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expected, actual: await writer(), errors }); throw error; }
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await open('welcome.md');
const original = await writer();
await page.locator('.cm-content').click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' first edit');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+s');
await open('second.md');
await writer();
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
console.log('PASS: saved Writer edit survives tab switch with undo and redo');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
assert.equal(await page.evaluate(() => window.__WRITER__.state.selection.main.head), (original + ' first edit').length);
console.log('PASS: Writer undo and redo survive window focus refresh and restore the caret');
await page.keyboard.press('Control+e');
await page.locator('.monaco-editor textarea').waitFor();
await page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
editor.setPosition({ lineNumber: editor.getModel().getLineCount(), column: editor.getModel().getLineMaxColumn(editor.getModel().getLineCount()) });
editor.focus();
window.__IDE__ = editor;
});
await page.keyboard.type(' second edit');
assert.equal(await page.evaluate(() => window.__IDE__.getDomNode()?.isConnected), true, 'Typing keeps the same IDE editor mounted');
assert.equal(await page.evaluate(() => window.__IDE__.getValue()), original + ' first edit second edit');
await page.keyboard.press('Control+e');
await expectWriter(original + ' first edit second edit');
await page.locator('.cm-content').click();
await page.keyboard.press('Control+z');
await expectWriter(original + ' first edit second');
await page.keyboard.press('Control+z');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second edit');
console.log('PASS: Writer undo includes edits from IDE mode');
const tableSource = '# Table\n\n| A | B |\n| --- | --- |\n| One | Two |\n\nTail.\n';
await page.evaluate(source => {
window.__TEST__.files.set('table.md', source);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table.md'] });
}, tableSource);
await open('table.md');
await writer();
const cells = page.locator('.writer-table tbody td');
await cells.nth(0).click();
await page.keyboard.press('Control+a');
await page.keyboard.type('Alpha');
await cells.nth(1).click();
await page.keyboard.press('Control+a');
await page.keyboard.type('Beta');
await page.keyboard.press('Escape');
const editedTable = await writer();
assert.ok(editedTable.includes('Alpha') && editedTable.includes('Beta'));
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
await writer();
await page.getByRole('tab', { name: 'table.md', exact: true }).click();
await writer();
await page.keyboard.press('Control+z');
await expectWriter(editedTable.replace('Beta', 'Two'));
await page.keyboard.press('Control+z');
await expectWriter(tableSource);
await page.keyboard.press('Control+y');
await expectWriter(editedTable.replace('Beta', 'Two'));
await page.keyboard.press('Control+y');
await expectWriter(editedTable);
console.log('PASS: table cell typing stays grouped per cell across tab switches');
assert.deepEqual(errors, []);
} finally { await browser.close(); }
+95
View File
@@ -0,0 +1,95 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note.\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const errors = [];
context.on("page", page => page.on("pageerror", error => errors.push(error.message)));
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
let page = await context.newPage();
page.setDefaultTimeout(5000);
async function ready() { await page.getByRole("button", { name: /^(Hide|Show) outline$/ }).waitFor(); }
async function reopen() {
await page.close();
page = await context.newPage();
page.setDefaultTimeout(5000);
await page.goto(url);
await ready();
}
async function resize(index, x) {
const box = await page.locator(".gutter-v").nth(index).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + 60);
await page.mouse.down();
await page.mouse.move(x, box.y + 60);
await page.mouse.up();
}
async function widths() {
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
}
try {
await page.goto(url);
await ready();
await page.getByText("LayoutTest", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.md" }).click();
await page.locator(".cm-content").waitFor();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
assert.equal(await page.locator(".right").count(), 0);
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
assert.equal(await page.locator(".right").count(), 0);
console.log("PASS: hidden outline stays hidden across Writer and IDE changes");
await page.reload();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
assert.equal(await page.locator(".right").count(), 0);
await reopen();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
console.log("PASS: hidden outline survives reload and window reopen");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
await resize(0, 330);
await resize(1, 970);
const resized = await widths();
assert.deepEqual(resized, ["330px", "310px"]);
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await reopen();
assert.deepEqual(await widths(), resized);
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Hide outline", exact: true }).waitFor();
console.log("PASS: resized sidebars and chosen navigation view survive reopen");
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await reopen();
assert.equal(await page.locator(".left, .right").count(), 0);
await page.keyboard.press("Control+b");
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
assert.deepEqual(await widths(), resized);
console.log("PASS: collapsed sidebars retain their sizes and navigation view");
assert.deepEqual(errors, []);
} finally { await browser.close(); }
+30
View File
@@ -0,0 +1,30 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout } from "../src/lib/workspace/workbenchLayout.ts";
test("missing and damaged layouts use defaults", () => {
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
assert.deepEqual(parseWorkbenchLayout(raw), DEFAULT_WORKBENCH_LAYOUT);
}
});
test("invalid layout fields do not discard valid collapsed states", () => {
for (const leftWidth of [0, -1, 159, 481, "260", null]) {
assert.deepEqual(parseWorkbenchLayout(JSON.stringify({ leftOpen: false, rightOpen: false, leftWidth, rightWidth: 320, leftView: "unknown" })), {
...DEFAULT_WORKBENCH_LAYOUT, leftOpen: false, rightOpen: false, rightWidth: 320,
});
}
assert.deepEqual(parseWorkbenchLayout('{"leftOpen":"false","rightOpen":0}'), DEFAULT_WORKBENCH_LAYOUT);
});
test("layout survives storage round trips with hidden panels and all navigation views", () => {
const store = new Map<string, string>();
for (const leftView of ["files", "search", "bookmarks"] as const) {
for (const leftWidth of [160, 321.5, 480]) {
const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView };
saveWorkbenchLayout({ setItem: (key, value) => { store.set(key, value); } }, layout);
assert.deepEqual(parseWorkbenchLayout(store.get(WORKBENCH_LAYOUT_KEY)!), layout);
}
}
assert.throws(() => saveWorkbenchLayout({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_WORKBENCH_LAYOUT }), /Storage unavailable/);
});