Make Git a native feature with an off switch
- Add the native feature runtime in src/lib/features/: the catalog, the switches, the first-start migration, the loader, and the feature sessions. - Add Settings → Features and the features settings section. - Add features_legacy. It reads the old plugin packages and changes nothing. - Move Git from the plugin into src/lib/features/git/, on host internals. - Remove api.git, the git contribution key, and the SDK Git types. - Add pnpm check:features. It fails when a feature module loads at start. - Update the tests, the menu inventory, the docs, and UI-055.
This commit is contained in:
@@ -195,7 +195,7 @@ function installMock(options, commands) {
|
||||
if (target !== pageId) channel.postMessage({ event, payload, target });
|
||||
};
|
||||
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
|
||||
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language"];
|
||||
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"];
|
||||
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
|
||||
const settingsFile = () => readJson(SETTINGS_FILE, null);
|
||||
const snapshot = () => {
|
||||
@@ -223,6 +223,10 @@ function installMock(options, commands) {
|
||||
// src-tauri/src/browser_engine.rs. Tests of the engine setup replace it.
|
||||
browser_engine_status: () => ({ state: "installed", version: "0.1.8", bytes: 160612374, received: 0, error: null }),
|
||||
settings_read: () => snapshot(),
|
||||
// src-tauri/src/features.rs: no old plugin package of a native feature is installed.
|
||||
features_legacy: () => [],
|
||||
// The editor asks for the Git line of the cursor while the Git feature is on. Tests of Git replace it.
|
||||
git_blame: () => null,
|
||||
settings_migrate: ({ sections }) => {
|
||||
if (!settingsFile()) localStorage.setItem(SETTINGS_FILE, JSON.stringify({ schema: 1, revision: 1, ...sections }));
|
||||
return snapshot();
|
||||
|
||||
@@ -13,6 +13,12 @@ await runSmoke("appearance/density", async ({ page }) => {
|
||||
files: { "note.md": "# 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" },
|
||||
}),
|
||||
plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }),
|
||||
// The Git feature asks the host for the line history. The test turns the answer on with `blameOn`.
|
||||
git_blame: ({ path, line }) => {
|
||||
if (!window.blameOn) return null;
|
||||
window.blameCalls.push({ path, line });
|
||||
return { commit: "123456789abcdef", author: "UI test", date: "2026-10-07T12:34:00Z", summary: `Changed line ${line}` };
|
||||
},
|
||||
}),
|
||||
});
|
||||
const row = page.locator('[data-tree-rel="note.md"]');
|
||||
@@ -40,14 +46,7 @@ await runSmoke("appearance/density", async ({ page }) => {
|
||||
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 page.evaluate(() => { window.blameCalls = []; window.blameOn = true; });
|
||||
await line.click();
|
||||
await page.locator(".line-history").waitFor();
|
||||
assert.match(await page.locator(".line-history").getAttribute("title"), /Line 5 · UI test/);
|
||||
@@ -77,7 +76,8 @@ await runSmoke("appearance/density", async ({ page }) => {
|
||||
await view().press("ArrowRight");
|
||||
await page.locator(".source-editor .cm-content").waitFor();
|
||||
await page.locator(".line-history").waitFor();
|
||||
await page.evaluate(() => window.removeGit());
|
||||
// Git off removes the line history at once.
|
||||
await page.evaluate(() => { window.blameOn = false; window.__TEST__.writeSettings("features", { git: false }); });
|
||||
await page.locator(".line-history").waitFor({ state: "hidden" });
|
||||
await view().press("Home");
|
||||
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
|
||||
|
||||
@@ -27,7 +27,7 @@ await runSmoke('browser/builtin', async ({ page }) => {
|
||||
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.__TEST__.cleanups.push(id); };
|
||||
}});
|
||||
api.registerView({ id:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git sidebar fixture'; }});
|
||||
api.registerView({ id:'sidebar', title:'Sidebar fixture', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Plugin sidebar fixture'; }});
|
||||
}`;
|
||||
},
|
||||
browser_request: ({ session, command, args }) => {
|
||||
@@ -70,8 +70,8 @@ await runSmoke('browser/builtin', async ({ page }) => {
|
||||
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
|
||||
await page.waitForFunction(() => window.__TEST__.mounts.includes('board-b') && window.__TEST__.cleanups.includes('board-a'));
|
||||
assert.deepEqual(await editorKeys(module), before);
|
||||
await page.getByRole('button', { name: 'Source control', exact: true }).click();
|
||||
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
|
||||
await page.getByRole('button', { name: 'Sidebar fixture', exact: true }).click();
|
||||
await page.getByText('Plugin sidebar fixture', { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// The native Git feature: the module loads only at first need, the Source control pane stages, unstages, and commits,
|
||||
// the diff and graph tabs open, errors show in the pane, and Off removes the feature at once.
|
||||
// It replaces plugins/gitToolbar, which loaded the old Git plugin from its sibling checkout.
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("features/git", async ({ page }) => {
|
||||
const output = await outputDir("features/git");
|
||||
await mockTauri(page, {
|
||||
commands: test => {
|
||||
// The handlers run in the page, so the history is defined here.
|
||||
const commits = [
|
||||
{ id: "c3".padEnd(40, "3"), parents: ["c1".padEnd(40, "1"), "c2".padEnd(40, "2")], refs: ["HEAD -> main"], summary: "Merge the feature", author: "Ada", date: "2026-10-29" },
|
||||
{ id: "c2".padEnd(40, "2"), parents: ["c1".padEnd(40, "1")], refs: ["feature"], summary: "Add the feature", author: "Ada", date: "2026-10-28" },
|
||||
{ id: "c1".padEnd(40, "1"), parents: [], refs: [], summary: "First commit", author: "Ada", date: "2026-10-27" },
|
||||
];
|
||||
test.git = { calls: [], changes: [
|
||||
{ path: "staged.md", index: "M", worktree: " " },
|
||||
{ path: "changed.md", index: " ", worktree: "M" },
|
||||
{ path: "new.md", index: "?", worktree: "?" },
|
||||
] };
|
||||
const record = (command, value) => { test.git.calls.push([command, value]); return null; };
|
||||
return {
|
||||
...test.workspace({ root: "C:\\git-feature", files: { "staged.md": "A\n", "changed.md": "B\n", "new.md": "C\n" } }),
|
||||
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
|
||||
spelling_menu_install: () => null,
|
||||
"plugin:window|is_maximized": () => false,
|
||||
git_status: () => ({ available: true, repository: true, branch: "main", changes: test.git.changes }),
|
||||
git_diff: ({ path, staged }) => `diff --git a/${path} b/${path}\n@@ -1 +1 @@\n-old line\n+new line${staged ? " (staged)" : ""}`,
|
||||
git_stage: ({ paths }) => record("stage", paths),
|
||||
git_unstage: ({ paths }) => record("unstage", paths),
|
||||
git_commit: ({ message }) => record("commit", message),
|
||||
git_push: () => { throw "The branch has no upstream branch."; },
|
||||
git_pull: () => record("pull", null),
|
||||
git_graph: () => ({ commits }),
|
||||
git_commit_details: ({ commit }) => ({ id: commit, parents: commits.find(item => item.id === commit).parents, author: "Ada", date: "2026-10-29", message: "Details", files: [{ path: "one.md", status: "M" }, { path: "two.md", status: "A" }] }),
|
||||
git_commit_diff: ({ path }) => `@@ -0,0 +1 @@\n+${path}`,
|
||||
};
|
||||
},
|
||||
});
|
||||
await page.goto(smokeUrl);
|
||||
await page.locator('[data-tree-rel="staged.md"]').waitFor();
|
||||
const loaded = () => page.evaluate(() => performance.getEntriesByType("resource").some(entry => new URL(entry.name).pathname === "/src/lib/features/git/index.ts"));
|
||||
assert.equal(await loaded(), false, "The Git module does not load before first need");
|
||||
|
||||
const sourceControl = page.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
|
||||
await sourceControl.click();
|
||||
const pane = page.locator(".source-control");
|
||||
await pane.getByText("main", { exact: true }).waitFor();
|
||||
assert.equal(await loaded(), true, "The Source control pane loads the Git module");
|
||||
await pane.getByRole("heading", { name: "Staged changes (1)", exact: true }).waitFor();
|
||||
await pane.getByRole("heading", { name: "Changes (2)", exact: true }).waitFor();
|
||||
|
||||
await pane.getByRole("button", { name: "Stage new.md", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.git.calls.some(([command]) => command === "stage"));
|
||||
assert.deepEqual(await page.evaluate(() => window.__TEST__.git.calls.at(-1)), ["stage", ["new.md"]]);
|
||||
await pane.getByRole("button", { name: "Unstage all", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.git.calls.some(([command]) => command === "unstage"));
|
||||
assert.deepEqual(await page.evaluate(() => window.__TEST__.git.calls.at(-1)), ["unstage", ["staged.md"]]);
|
||||
|
||||
const message = pane.getByRole("textbox", { name: "Commit message", exact: true });
|
||||
const commit = pane.getByRole("button", { name: "Commit staged", exact: true });
|
||||
assert.equal(await commit.isDisabled(), true, "Commit waits for a message");
|
||||
await message.fill("Write the notes");
|
||||
await message.press("Control+Enter");
|
||||
await pane.getByText("Commit created.", { exact: true }).waitFor();
|
||||
assert.deepEqual(await page.evaluate(() => window.__TEST__.git.calls.at(-1)), ["commit", "Write the notes"]);
|
||||
|
||||
await pane.getByRole("button", { name: "Push to the upstream branch", exact: true }).click();
|
||||
await pane.locator(".notice.error", { hasText: "no upstream branch" }).waitFor();
|
||||
|
||||
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);
|
||||
await page.waitForTimeout(100);
|
||||
await pane.screenshot({ path: path.join(output, `source-control-${theme}.png`) });
|
||||
}
|
||||
|
||||
await pane.getByRole("button", { name: /^changed\.md — Modified$/ }).click();
|
||||
const diff = page.locator(".git-diff");
|
||||
await diff.getByText("changed.md · Working tree", { exact: true }).waitFor();
|
||||
await diff.locator(".line.add", { hasText: "+new line" }).waitFor();
|
||||
assert.equal(await diff.locator(".line.remove").count(), 1);
|
||||
await page.screenshot({ path: path.join(output, "diff-tab.png") });
|
||||
|
||||
await pane.getByRole("button", { name: "Show Git graph", exact: true }).click();
|
||||
const graph = page.locator(".git-graph");
|
||||
const options = graph.getByRole("option");
|
||||
await options.first().waitFor();
|
||||
assert.equal(await options.count(), 3);
|
||||
assert.equal(await options.first().getAttribute("aria-selected"), "true");
|
||||
await graph.getByRole("button", { name: "one.md", exact: false }).first().waitFor();
|
||||
await options.first().focus();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.waitForFunction(() => document.activeElement?.getAttribute("aria-selected") === "true" && document.activeElement?.textContent?.includes("Add the feature"));
|
||||
await graph.locator(".line.add", { hasText: "+one.md" }).waitFor();
|
||||
assert.equal(await graph.locator("path.boundary").count(), 0, "The full history has no dashed boundary line");
|
||||
await page.screenshot({ path: path.join(output, "graph-tab.png") });
|
||||
await page.setViewportSize({ width: 640, height: 720 });
|
||||
await page.screenshot({ path: path.join(output, "graph-tab-640.png") });
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
// Off closes the Git tabs and the pane, and removes the button. The feature can start again.
|
||||
await page.evaluate(() => window.__TEST__.writeSettings("features", { git: false }));
|
||||
await sourceControl.waitFor({ state: "detached" });
|
||||
await graph.waitFor({ state: "detached" });
|
||||
await diff.waitFor({ state: "detached" });
|
||||
await pane.waitFor({ state: "detached" });
|
||||
await page.evaluate(() => window.__TEST__.writeSettings("features", { git: true }));
|
||||
await sourceControl.click();
|
||||
await pane.getByText("main", { exact: true }).waitFor();
|
||||
console.log("PASS: Git loads at first need, stages, unstages, commits, shows errors, diffs, and the graph, and Off removes it");
|
||||
}, { timeout: 60000 });
|
||||
@@ -0,0 +1,65 @@
|
||||
// Settings → Features: the switch of each native feature, the migration default, search, keyboard use, both themes, and narrow windows.
|
||||
// A switch in the Settings window changes the main window at once.
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("features/settings", async ({ browser }) => {
|
||||
const output = await outputDir("features/settings");
|
||||
const context = await browser.newContext({ viewport: { width: 1152, height: 815 } });
|
||||
await mockTauri(context, {
|
||||
commands: test => ({
|
||||
...test.workspace({ root: "C:\\features-settings", files: { "note.md": "# Note\n" } }),
|
||||
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
|
||||
"plugin:window|is_maximized": () => false,
|
||||
}),
|
||||
});
|
||||
const main = await openPage(context, { timeout: 10000 });
|
||||
await main.goto(smokeUrl);
|
||||
await main.locator('[data-tree-rel="note.md"]').waitFor();
|
||||
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
|
||||
await sourceControl.waitFor();
|
||||
// Without an old package, the migration stores the default of each feature.
|
||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true });
|
||||
|
||||
const settings = await openPage(context, { timeout: 10000 });
|
||||
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
|
||||
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
|
||||
await settings.getByRole("button", { name: "Features", exact: true }).click();
|
||||
await settings.getByRole("heading", { name: "Features", exact: true }).waitFor();
|
||||
const git = settings.getByRole("switch", { name: "Git", exact: true });
|
||||
assert.equal(await git.isChecked(), true);
|
||||
assert.match(await git.getAttribute("aria-describedby"), /feature-git-description/);
|
||||
|
||||
await git.click();
|
||||
await sourceControl.waitFor({ state: "detached" });
|
||||
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false });
|
||||
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
|
||||
await git.focus();
|
||||
await settings.keyboard.press("Space");
|
||||
await sourceControl.waitFor();
|
||||
assert.equal(await git.isChecked(), true);
|
||||
|
||||
// The settings search finds the page by the name and the words of a feature.
|
||||
const search = settings.getByRole("textbox", { name: "Search settings", exact: true });
|
||||
await search.fill("source control");
|
||||
assert.deepEqual(await settings.locator('nav[aria-label="Settings categories"] button').allInnerTexts(), ["Features"]);
|
||||
await search.fill("");
|
||||
|
||||
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 : 520 });
|
||||
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `No horizontal scroll at ${width} pixels`);
|
||||
const row = settings.locator(".setting-row", { has: git });
|
||||
const box = await row.boundingBox();
|
||||
const toggle = await git.boundingBox();
|
||||
assert(toggle.x + toggle.width <= box.x + box.width + 1, "The switch stays inside its row");
|
||||
await settings.screenshot({ path: path.join(output, `features-${theme}-${width}.png`) });
|
||||
}
|
||||
}
|
||||
await git.focus();
|
||||
assert.equal(await git.evaluate(node => node.matches(":focus-visible")), true);
|
||||
await settings.screenshot({ path: path.join(output, "features-focus.png") });
|
||||
console.log("PASS: the Features page turns Git off and on in another window, with search, keyboard, both themes, and narrow widths");
|
||||
}, { timeout: 60000 });
|
||||
@@ -1,76 +0,0 @@
|
||||
// Git plugin sidebar toolbar: the Graph control is icon-only, keeps its accessible name, shows hover and focus tooltips in both themes, and opens Graph.
|
||||
// @requires repo:RuneStone_Git/src
|
||||
// The source loads from the sibling RuneStone_Git checkout (RUNESTONE_PLUGIN_REPOS) without building a plugin ZIP.
|
||||
// Its "@runestone/plugin-sdk" imports resolve to this repository's SDK build (packages/plugin-sdk/dist), which the runner builds.
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { mockTauri, outputDir, pluginRepo, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
const sdkImport = /(\bfrom\s*|\bimport\s*\(\s*)(["'])@runestone\/plugin-sdk(?:\/([a-z-]+))?\2/g;
|
||||
const resolveSdk = source => source.replace(sdkImport, (_, keyword, quote, entry) => `${keyword}${quote}/__runestone_sdk/${entry || "index"}.js${quote}`);
|
||||
|
||||
const name = "plugins/gitToolbar";
|
||||
await runSmoke(name, async ({ page }) => {
|
||||
const output = await outputDir(name);
|
||||
const source = pluginRepo("RuneStone_Git");
|
||||
const files = new Map(await Promise.all(["view.js", "model.js"].map(async file => [file, resolveSdk(await readFile(path.join(source, "src", file), "utf8"))])));
|
||||
const css = await readFile(path.join(source, "src", "style.css"), "utf8");
|
||||
await page.route("**/__git_source/*", route => route.fulfill({ contentType: "text/javascript", body: files.get(new URL(route.request().url()).pathname.split("/").pop()) || "" }));
|
||||
await page.route("**/__runestone_sdk/*", async route => {
|
||||
const file = path.join(repoRoot, "packages/plugin-sdk/dist", path.basename(new URL(route.request().url()).pathname));
|
||||
await route.fulfill({ contentType: "text/javascript", body: await readFile(file, "utf8") });
|
||||
});
|
||||
await mockTauri(page, {
|
||||
commands: test => ({
|
||||
...test.workspace({ root: "C:\\git-toolbar", files: { "notes/draft.md": "Before.\n" } }),
|
||||
plugins_snapshot: () => ({ plugins: [], issues: [] }),
|
||||
spelling_menu_install: () => null,
|
||||
}),
|
||||
});
|
||||
await page.goto(smokeUrl);
|
||||
await page.locator('[data-tree-rel="notes"]').waitFor();
|
||||
await page.evaluate(async css => {
|
||||
const { mountSidebar } = await import("/__git_source/view.js");
|
||||
const container = document.createElement("div");
|
||||
container.id = "git-smoke";
|
||||
container.style.cssText = "position:fixed;inset:45px 0 0 0;z-index:1000;background:var(--rs-bg)";
|
||||
document.body.append(container);
|
||||
window.gitGraphOpens = 0;
|
||||
window.disposeGitSmoke = mountSidebar(container, {
|
||||
workspace: {},
|
||||
git: { status: async () => ({ available: true, repository: true, branch: "main", changes: [] }), pull: async () => {}, push: async () => {} },
|
||||
openView: () => window.gitGraphOpens++,
|
||||
}, css, () => {});
|
||||
}, css);
|
||||
const graph = page.locator("#git-smoke").getByRole("button", { name: "Graph", exact: true });
|
||||
// The plugin shows the shared host tooltip (a `.rs-tooltip` popover from `data-tooltip`) instead of a title and its own tooltip span.
|
||||
// RuneStone_Git/src/view.js: button() sets data-tooltip and aria-label; tooltipScope() shows the popover on hover and focus.
|
||||
const tooltip = page.locator(".rs-tooltip:popover-open");
|
||||
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);
|
||||
await graph.waitFor();
|
||||
assert.equal(await graph.locator("svg").count(), 1);
|
||||
assert.equal(await graph.getAttribute("title"), null);
|
||||
assert.equal(await graph.getAttribute("data-tooltip"), "Graph");
|
||||
assert.equal(await graph.evaluate(node => [...node.childNodes].filter(child => child.nodeType === Node.TEXT_NODE && child.textContent.trim()).length), 0);
|
||||
assert.equal(await graph.locator(":scope > :not(.rs-git-icon)").count(), 0, "Graph has no visible text label");
|
||||
await page.mouse.move(800, 800);
|
||||
await graph.evaluate(node => node.blur());
|
||||
assert.equal(await tooltip.count(), 0);
|
||||
await graph.hover();
|
||||
await tooltip.waitFor();
|
||||
assert.equal(await tooltip.innerText(), "Graph");
|
||||
await page.mouse.move(800, 800);
|
||||
await page.keyboard.press("Tab");
|
||||
await graph.focus();
|
||||
assert.equal(await graph.evaluate(node => node.matches(":focus-visible")), true);
|
||||
await tooltip.waitFor();
|
||||
assert.equal(await tooltip.innerText(), "Graph");
|
||||
await page.screenshot({ path: path.join(output, `git-toolbar-${theme}.png`) });
|
||||
}
|
||||
await graph.click();
|
||||
assert.equal(await page.evaluate(() => window.gitGraphOpens), 1);
|
||||
await page.evaluate(() => window.disposeGitSmoke());
|
||||
console.log("PASS: icon-only Graph control with accessible name, hover and focus tooltips in both themes, and Graph opens");
|
||||
}, { timeout: 15000 });
|
||||
@@ -1,24 +1,13 @@
|
||||
// Tree rename undo and redo keep folders expanded; New note templates, Git plug-in navigation, and detached tab layout isolation.
|
||||
// @requires repo:RuneStone_Git/dist
|
||||
// Tree rename undo and redo keep folders expanded; New note templates, native Git navigation, and detached tab layout isolation.
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { mockTauri, openPage, outputDir, pluginRepo, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
||||
|
||||
const gitRoot = path.join(pluginRepo('RuneStone_Git'), 'dist');
|
||||
const git = {
|
||||
manifest: JSON.parse(await readFile(path.join(gitRoot, 'plugin.json'), 'utf8')),
|
||||
code: await readFile(path.join(gitRoot, 'main.js'), 'utf8'),
|
||||
css: (await readFile(path.join(gitRoot, 'style.css'))).toString('base64'),
|
||||
};
|
||||
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
||||
|
||||
await runSmoke('tree/renameUndo', async ({ browser }) => {
|
||||
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
|
||||
await mockTauri(context, {
|
||||
strict: false,
|
||||
state: git,
|
||||
commands: test => {
|
||||
const git = test.state;
|
||||
const ws = test.workspace({
|
||||
root: 'C:\\host-todo-test',
|
||||
files: {
|
||||
@@ -46,10 +35,8 @@ await runSmoke('tree/renameUndo', async ({ browser }) => {
|
||||
},
|
||||
workspace_delete: ({ rel }) => { files.delete(rel); },
|
||||
workspace_search: () => [],
|
||||
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] }),
|
||||
plugins_load: () => git.code,
|
||||
plugins_asset: () => git.css,
|
||||
plugins_data: () => 'null',
|
||||
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
|
||||
git_status: () => ({ available: true, repository: true, branch: 'main', changes: [] }),
|
||||
'plugin:window|is_maximized': () => false,
|
||||
'plugin:dialog|message': () => 'Ok',
|
||||
};
|
||||
@@ -116,13 +103,15 @@ await runSmoke('tree/renameUndo', async ({ browser }) => {
|
||||
await page.waitForFunction(count => window.__TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
|
||||
await page.getByRole('button', { name: 'Source control', exact: true }).waitFor();
|
||||
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
const graph = page.getByRole('menuitem', { name: /Show Git graph/ });
|
||||
// Git is a native feature: no plug-in menu lists it, and its graph command is in the command palette.
|
||||
assert.equal(await page.getByRole('button', { name: 'Plug-in views', exact: true }).count(), 0);
|
||||
// The new note keeps the focus in its name field. Move the focus out of it before the palette shortcut.
|
||||
await page.evaluate(() => (document.activeElement instanceof HTMLElement) && document.activeElement.blur());
|
||||
await page.keyboard.press('Control+Shift+P');
|
||||
await page.getByRole('textbox', { name: 'Find a command', exact: true }).fill('Git graph');
|
||||
const graph = page.locator('#command-results .rs-picker-row', { hasText: 'Show Git graph' });
|
||||
await graph.waitFor();
|
||||
assert.equal(await page.getByRole('menuitem', { name: /source control/i }).count(), 0);
|
||||
const graphIcon = await graph.locator('.action-icon').innerHTML();
|
||||
const expectedIcon = await page.evaluate(async () => (await import('/src/lib/ui/actionIcons.ts')).actionIcon('git').innerHTML);
|
||||
assert.equal(graphIcon, expectedIcon, 'The real Git graph command uses the shared Git icon');
|
||||
assert.match(await graph.innerText(), /Git/);
|
||||
await shot(page, 'real-git-command-dark.png');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.evaluate(async () => {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// The native feature runtime: the catalog, the switches, the migration from old plugin packages, the loader, and the session.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { FEATURES, featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
|
||||
import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts";
|
||||
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
|
||||
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
|
||||
import { FeatureSession } from "../../../src/lib/features/session.ts";
|
||||
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
|
||||
import { get } from "svelte/store";
|
||||
|
||||
test("each feature keeps the ID of its old plugin package as its owner ID", () => {
|
||||
assert.equal(featureEntry("git").owner, "runestone.git");
|
||||
assert.equal(featureOfOwner("runestone.git")?.id, "git");
|
||||
assert.equal(featureOfOwner("runestone.csv-viewer"), undefined);
|
||||
assert.equal(new Set(FEATURES.map(feature => feature.owner)).size, FEATURES.length);
|
||||
const git = featureEntry("git");
|
||||
assert.deepEqual(git.views.map(view => [view.id, view.placement]), [["source-control", "sidebar"], ["diff", "editor"], ["graph", "editor"]]);
|
||||
assert.equal(git.views[0].title(), "Source control");
|
||||
assert.deepEqual(git.commands.map(command => [command.id, command.view]), [["graph", "graph"]]);
|
||||
});
|
||||
|
||||
test("switches keep known booleans only, and missing keys take the default", () => {
|
||||
assert.deepEqual(storedSwitches({ git: false, terminal: true, other: "yes" }), { git: false });
|
||||
assert.deepEqual(storedSwitches(null), {});
|
||||
assert.deepEqual(storedSwitches(["git"]), {});
|
||||
assert.deepEqual(switchesFrom(undefined), { git: true });
|
||||
assert.deepEqual(switchesFrom({ git: false }), { git: false });
|
||||
assert.deepEqual(switchesFrom({ git: "false" }), { git: true });
|
||||
});
|
||||
|
||||
test("an installed package gives its state, and without a package the default applies", () => {
|
||||
const git = featureEntry("git");
|
||||
const legacy = (installed: boolean, enabled: boolean): LegacyPlugin => ({ id: "runestone.git", installed, enabled, settings: null });
|
||||
assert.equal(legacySwitch(git, undefined), true);
|
||||
assert.equal(legacySwitch(git, legacy(false, false)), true);
|
||||
assert.equal(legacySwitch(git, legacy(true, false)), false);
|
||||
assert.equal(legacySwitch(git, legacy(true, true)), true);
|
||||
});
|
||||
|
||||
test("the migration asks only for features without a switch, and keeps other keys", async () => {
|
||||
const writes: unknown[] = [];
|
||||
const asked: string[][] = [];
|
||||
const host = (stored: unknown, packages: LegacyPlugin[]) => ({
|
||||
read: () => stored,
|
||||
write: async (value: unknown) => { writes.push(value); },
|
||||
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
|
||||
});
|
||||
assert.deepEqual(await migrateFeatures(host({ future: 1 }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }])), ["git"]);
|
||||
assert.deepEqual(asked, [["runestone.git"]]);
|
||||
assert.deepEqual(writes, [{ future: 1, git: false }]);
|
||||
assert.deepEqual(await migrateFeatures(host({ git: true }, [])), []);
|
||||
assert.equal(asked.length, 1, "A stored switch needs no package read.");
|
||||
assert.equal(writes.length, 1);
|
||||
});
|
||||
|
||||
test("a failed package read writes nothing, so the next start tries again", async () => {
|
||||
const writes: unknown[] = [];
|
||||
const error = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } });
|
||||
assert.deepEqual(result, []);
|
||||
assert.deepEqual(writes, []);
|
||||
} finally { console.error = error; }
|
||||
});
|
||||
|
||||
test("the loader imports a feature one time, reports a failure, and tries again after it", async () => {
|
||||
let calls = 0;
|
||||
const module: FeatureModule = { start: () => ({ mount: () => () => {}, dispose() {} }) };
|
||||
await assert.rejects(loadFeature("git", async () => { calls++; throw new Error("chunk missing"); }), /chunk missing/);
|
||||
assert.match(get(featureErrors).git ?? "", /chunk missing/);
|
||||
assert.equal(featureRequested("git"), false);
|
||||
const first = loadFeature("git", async () => { calls++; return module; });
|
||||
const second = loadFeature("git", async () => { calls++; return module; });
|
||||
assert.equal(await first, module);
|
||||
assert.equal(await second, module);
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(featureRequested("git"), true);
|
||||
assert.equal(get(featureErrors).git, undefined);
|
||||
});
|
||||
|
||||
function fakeContext(opened: string[] = []): FeatureContext {
|
||||
return { openView: id => { opened.push(id); }, openFile: async () => {}, onWorkspaceChange: () => () => {} };
|
||||
}
|
||||
|
||||
test("a feature session shows its views and commands without loading the feature", async () => {
|
||||
let loads = 0;
|
||||
const opened: string[] = [];
|
||||
const session = new FeatureSession(featureEntry("git"), fakeContext(opened), async () => { loads++; throw new Error("not loaded"); });
|
||||
assert.deepEqual([...session.views.keys()], ["source-control", "diff", "graph"]);
|
||||
assert.equal(session.views.get("source-control")?.navigation, true);
|
||||
assert.equal(session.views.get("diff")?.launcher, false);
|
||||
assert.equal(session.views.get("graph")?.title, "Git graph");
|
||||
assert.equal(session.views.get("diff")?.saveTabState?.(), undefined);
|
||||
await session.run("graph");
|
||||
await session.launch("source-control");
|
||||
assert.deepEqual(opened, ["graph", "source-control"]);
|
||||
assert.equal(loads, 0, "Commands and navigation do not load the feature.");
|
||||
await session.stop();
|
||||
});
|
||||
|
||||
test("the first mount starts one instance, and stop disposes it", async () => {
|
||||
const events: string[] = [];
|
||||
let starts = 0;
|
||||
const instance: FeatureInstance = {
|
||||
mount: (view, element) => { events.push(`mount ${view}`); element.textContent = view; return () => { events.push(`unmount ${view}`); }; },
|
||||
saveTabState: view => ({ view }),
|
||||
restoreTabState: (view, state) => { events.push(`restore ${view} ${JSON.stringify(state)}`); },
|
||||
dispose: () => { events.push("dispose"); },
|
||||
};
|
||||
const session = new FeatureSession(featureEntry("git"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
|
||||
const element = { textContent: "", replaceChildren(this: { textContent: string }) { this.textContent = ""; } } as unknown as HTMLElement;
|
||||
const dispose = await session.mount("diff", element);
|
||||
await session.views.get("graph")!.restoreTabState!({ selectedId: "a" });
|
||||
assert.equal(starts, 1);
|
||||
assert.deepEqual(session.views.get("diff")!.saveTabState!(), { view: "diff" });
|
||||
await dispose();
|
||||
assert.equal(element.textContent, "");
|
||||
await session.stop();
|
||||
assert.deepEqual(events, ["mount diff", 'restore graph {"selectedId":"a"}', "unmount diff", "dispose"]);
|
||||
await assert.rejects(session.mount("diff", element), /This feature is off/);
|
||||
});
|
||||
|
||||
test("a failed load leaves no instance, so a later mount tries again", async () => {
|
||||
let attempt = 0;
|
||||
const instance: FeatureInstance = { mount: () => () => {}, dispose() {} };
|
||||
const session = new FeatureSession(featureEntry("git"), fakeContext(), async () => {
|
||||
if (++attempt === 1) throw new Error("offline");
|
||||
return { start: () => instance };
|
||||
});
|
||||
const element = { replaceChildren() {} } as unknown as HTMLElement;
|
||||
await assert.rejects(session.mount("graph", element), /offline/);
|
||||
await session.mount("graph", element);
|
||||
assert.equal(attempt, 2);
|
||||
await assert.rejects(session.mount("missing", element), /This view is unavailable/);
|
||||
await session.stop();
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// The Git feature model. These tests come from the Git plugin (`RuneStone_Git/test/model.test.mjs`).
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { changeLabel, diffLineKind, graphLayout, groups, isConflict, pathsFor } from "../../../src/lib/features/git/model.ts";
|
||||
import type { GitChange, GitGraphCommit } from "../../../src/lib/git/contracts.ts";
|
||||
|
||||
const commit = (id: string, parents: string[]): GitGraphCommit => ({ id, parents, refs: [], summary: id, author: "Test", date: "2026-10-29" });
|
||||
|
||||
test("partially staged files occur in both groups, with conflicts only in working files", () => {
|
||||
const changes: GitChange[] = [
|
||||
{ path: "both.txt", index: "M", worktree: "M" },
|
||||
{ path: "new.txt", index: "?", worktree: "?" },
|
||||
{ path: "conflict.txt", index: "U", worktree: "U" },
|
||||
{ path: "deleted.txt", index: "D", worktree: " " },
|
||||
];
|
||||
assert.deepEqual(groups(changes).staged.map(change => change.path), ["both.txt", "deleted.txt"]);
|
||||
assert.deepEqual(groups(changes).working.map(change => change.path), ["both.txt", "new.txt", "conflict.txt"]);
|
||||
assert.equal(isConflict({ path: "a", index: "A", worktree: "A" }), true);
|
||||
assert.equal(changeLabel(changes[2], false), "Conflict");
|
||||
assert.equal(changeLabel(changes[1], false), "New");
|
||||
assert.equal(changeLabel(changes[3], true), "Deleted");
|
||||
assert.equal(changeLabel({ path: "x", index: "X", worktree: " " }, true), "X");
|
||||
});
|
||||
|
||||
test("rename actions include old and new paths exactly once", () => {
|
||||
assert.deepEqual(pathsFor([{ path: "new.txt", originalPath: "old.txt", index: "R", worktree: " " }, { path: "old.txt", index: "M", worktree: " " }]), ["old.txt", "new.txt"]);
|
||||
});
|
||||
|
||||
test("diff lines get their kind from the first character", () => {
|
||||
assert.deepEqual(["+add", "-remove", "+++ b/file", "--- a/file", "@@ -1 +1 @@", " same", ""].map(diffLineKind),
|
||||
["add", "remove", "context", "context", "range", "context", "context"]);
|
||||
});
|
||||
|
||||
test("graph lanes preserve merge parents, forks, and truncated history", () => {
|
||||
const layout = graphLayout({ commits: [commit("merge", ["main", "feature"]), commit("feature", ["root"]), commit("main", ["root"]), commit("root", ["older"])] });
|
||||
assert.deepEqual(layout.nodes.map(node => node.lane), [0, 1, 0, 1]);
|
||||
assert.equal(layout.edges.length, 5);
|
||||
assert.deepEqual(layout.edges.filter(edge => edge.from === "merge").map(edge => [edge.to, edge.endRow]), [["main", 2], ["feature", 1]]);
|
||||
assert.equal(layout.edges.at(-1)!.outside, true);
|
||||
assert.equal(layout.edges.at(-1)!.endRow, 4);
|
||||
assert.deepEqual(graphLayout({ commits: [] }).nodes, []);
|
||||
assert.deepEqual(graphLayout(null).nodes, []);
|
||||
});
|
||||
|
||||
test("graph track colors survive lane changes, joins, and history boundaries", () => {
|
||||
const history = { commits: [commit("merge", ["main", "feature"]), commit("feature", ["feature-old"]), commit("main", ["root"]), commit("feature-old", ["root"]), commit("root", ["older"])] };
|
||||
const layout = graphLayout(history);
|
||||
const node = (id: string) => layout.nodes.find(item => item.id === id)!;
|
||||
const edge = (from: string, to: string) => layout.edges.find(item => item.from === from && item.to === to)!;
|
||||
assert.notEqual(node("main").color, node("feature").color);
|
||||
assert.equal(node("merge").color, node("main").color);
|
||||
assert.equal(node("feature").color, node("feature-old").color);
|
||||
assert.equal(edge("merge", "feature").color, node("feature").color);
|
||||
assert.equal(edge("feature-old", "root").color, node("feature-old").color);
|
||||
assert.equal(edge("root", "older").color, node("root").color);
|
||||
assert.deepEqual(graphLayout(history), layout);
|
||||
const shifted = graphLayout({ commits: [commit("merge", ["main", "feature"]), commit("main", []), commit("feature", ["feature-old"]), commit("feature-old", [])] });
|
||||
assert.notEqual(shifted.nodes[2].lane, shifted.nodes[3].lane);
|
||||
assert.equal(shifted.nodes[2].color, shifted.nodes[3].color);
|
||||
});
|
||||
|
||||
test("six concurrent graph tracks use six colors before palette reuse", () => {
|
||||
const parents = ["a", "b", "c", "d", "e", "f"];
|
||||
const layout = graphLayout({ commits: [commit("merge", parents), ...parents.map(id => commit(id, []))] });
|
||||
assert.equal(new Set(layout.nodes.slice(1).map(node => node.color)).size, 6);
|
||||
assert.equal(new Set(layout.edges.map(edge => edge.color)).size, 6);
|
||||
});
|
||||
@@ -4,37 +4,21 @@ 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 () => {
|
||||
test("file access stops before plugin cleanup, and plugins get no Git API", async () => {
|
||||
const calls: unknown[] = [];
|
||||
let api!: PluginApi;
|
||||
const registry = new ContributionRegistry();
|
||||
const session = new ExternalSession("test.git", {
|
||||
const session = new ExternalSession("test.files", {
|
||||
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: [] }),
|
||||
commitDetails: async () => { throw new Error("not used"); }, commitDiff: async () => "",
|
||||
},
|
||||
}, () => {}, () => {}, registry);
|
||||
await session.start({ activate(value) { api = value; api.contribute("git", { blame: (path, line) => api.git!.blame(path, line) }); } });
|
||||
}, () => {}, () => {}, new ContributionRegistry());
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
// Git is a native feature of RuneStone. The plugin API has no Git member.
|
||||
assert.equal("git" in api, false);
|
||||
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']);
|
||||
assert.deepEqual(calls, ["notes.md"]);
|
||||
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 () => {
|
||||
|
||||
@@ -6,8 +6,8 @@ import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
|
||||
import type { Contributions } from "../../../src/lib/plugins/contracts.ts";
|
||||
|
||||
// A small test-only package. It contributes a feature, as the optional plugins do.
|
||||
const blame: Contributions["git"] = { blame: async () => null };
|
||||
const activate = (api: PluginApi) => { api.contribute("git", blame); };
|
||||
const terminal: Contributions["terminal"] = { mount: () => ({ update() {}, command() {}, dispose() {} }), shortcut: () => null };
|
||||
const activate = (api: PluginApi) => { api.contribute("terminal", terminal); };
|
||||
|
||||
const services = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
@@ -38,23 +38,22 @@ test("optional workspace creation and reads stop when the plugin is disabled", a
|
||||
});
|
||||
test("core starts without optional features and package contributions end with their session", async () => {
|
||||
assert.equal(pluginHost.get("terminal"), undefined);
|
||||
assert.equal(pluginHost.get("git"), undefined);
|
||||
const registry = new ContributionRegistry();
|
||||
const session = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
|
||||
await session.start({ activate });
|
||||
assert.equal(registry.get("git"), blame);
|
||||
assert.equal(registry.get("terminal"), terminal);
|
||||
await session.stop();
|
||||
assert.equal(registry.get("git"), undefined);
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
const next = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
|
||||
await next.start({ activate });
|
||||
assert.equal(registry.get("git"), blame);
|
||||
assert.equal(registry.get("terminal"), terminal);
|
||||
await next.stop();
|
||||
assert.equal(registry.get("git"), undefined);
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
});
|
||||
|
||||
test("unknown contribution keys are rejected", () => {
|
||||
const registry = new ContributionRegistry();
|
||||
assert.throws(() => registry.register("old", "tableFormulas" as keyof Contributions, blame as never), /Unknown plugin contribution/);
|
||||
for (const key of ["tableFormulas", "git"]) assert.throws(() => registry.register("old", key as keyof Contributions, terminal as never), /Unknown plugin contribution/);
|
||||
});
|
||||
|
||||
test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => {
|
||||
@@ -63,13 +62,13 @@ test("package contribution conflicts preserve the first owner and revoke access
|
||||
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
|
||||
let api!: PluginApi;
|
||||
await first.start({ activate(value) { api = value; activate(api); } });
|
||||
const contribution = registry.get("git");
|
||||
const contribution = registry.get("terminal");
|
||||
await assert.rejects(second.start({ activate }), /already registered/);
|
||||
await second.stop();
|
||||
assert.equal(registry.get("git"), contribution);
|
||||
assert.equal(registry.get("terminal"), contribution);
|
||||
api.onDispose(() => {
|
||||
assert.equal(registry.get("git"), undefined);
|
||||
assert.throws(() => api.contribute("git", contribution!), /disabled/);
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
assert.throws(() => api.contribute("terminal", contribution!), /disabled/);
|
||||
});
|
||||
await first.stop();
|
||||
});
|
||||
@@ -83,5 +82,5 @@ test("partial activation and failed cleanup cannot retain feature contributions"
|
||||
throw new Error("Activation failed");
|
||||
} }), /Activation failed/);
|
||||
await assert.rejects(session.stop(), /Cleanup failed/);
|
||||
assert.equal(registry.get("git"), undefined);
|
||||
assert.equal(registry.get("terminal"), undefined);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { checkChunks, featureModule, staticClosure } from "../../../scripts/featureChunks.mjs";
|
||||
|
||||
const root = "D:/RuneStone/";
|
||||
const chunk = (fileName: string, fields: Record<string, unknown> = {}) => ({ fileName, isEntry: false, isDynamicEntry: false, facadeModuleId: null, imports: [], moduleIds: [], size: 10, ...fields });
|
||||
|
||||
test("the static closure follows imports from each entry, and not dynamic imports", () => {
|
||||
const chunks = [
|
||||
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
|
||||
chunk("node.js", { isEntry: true }),
|
||||
chunk("shared.js", { imports: ["deep.js"] }),
|
||||
chunk("deep.js"),
|
||||
chunk("git.js", { isDynamicEntry: true, imports: ["shared.js"] }),
|
||||
];
|
||||
assert.deepEqual([...staticClosure(chunks)].sort(), ["app.js", "deep.js", "node.js", "shared.js"]);
|
||||
});
|
||||
|
||||
test("feature folders and feature libraries count as feature modules, and the runtime does not", () => {
|
||||
assert.equal(featureModule(`${root}src/lib/features/git/index.ts`), true);
|
||||
assert.equal(featureModule("D:\\RuneStone\\src\\lib\\features\\git\\model.ts"), true);
|
||||
assert.equal(featureModule(`${root}src/lib/features/catalog.ts`), false);
|
||||
assert.equal(featureModule(`${root}node_modules/.pnpm/@[email protected]/node_modules/@xterm/xterm/lib/xterm.mjs`), true);
|
||||
assert.equal(featureModule(`${root}node_modules/pdfjs-dist/build/pdf.mjs`), true);
|
||||
assert.equal(featureModule(`${root}node_modules/svelte/src/index.js`), false);
|
||||
});
|
||||
|
||||
test("a feature module in a start chunk fails, and a separate dynamic chunk passes", () => {
|
||||
const good = [
|
||||
chunk("app.js", { isEntry: true, moduleIds: [`${root}src/lib/features/catalog.ts`] }),
|
||||
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts`, moduleIds: [`${root}src/lib/features/git/index.ts`], size: 2048 }),
|
||||
];
|
||||
assert.deepEqual(checkChunks(good), { problems: [], sizes: { git: 2048 } });
|
||||
const bad = [
|
||||
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
|
||||
chunk("shared.js", { moduleIds: [`${root}src/lib/features/git/model.ts`] }),
|
||||
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts` }),
|
||||
];
|
||||
assert.deepEqual(checkChunks(bad).problems, ["shared.js loads at start and contains src/lib/features/git/model.ts"]);
|
||||
assert.deepEqual(checkChunks([chunk("app.js", { isEntry: true })]).problems, ["No chunk starts at src/lib/features/git/index.ts."]);
|
||||
});
|
||||
@@ -36,20 +36,20 @@ async function hostApi(services: Partial<SessionServices>, views = false) {
|
||||
|
||||
test("feature checks find optional members, and missing members give an update message", () => {
|
||||
const read = async () => new Uint8Array([1]);
|
||||
const api = { workspace: { readBytes: read }, git: { status: async () => ({}) } } as unknown as PluginApi;
|
||||
const api = { workspace: { readBytes: read }, services: { get: () => null } } as unknown as PluginApi;
|
||||
assert.equal(hasFeature(api, "workspace.readBytes"), true);
|
||||
assert.equal(hasFeature(api, "git"), true);
|
||||
assert.equal(hasFeature(api, "git.push"), false);
|
||||
assert.equal(hasFeature(api, "services"), true);
|
||||
assert.equal(hasFeature(api, "workspace.subscribe"), false);
|
||||
assert.equal(hasFeature(api, "pty"), false);
|
||||
assert.deepEqual(missingFeatures(api, ["pty", "workspace.readBytes", "settings.subscribe"]), ["pty", "settings.subscribe"]);
|
||||
assert.equal(requireFeature(api, "git"), (api as unknown as { git: unknown }).git);
|
||||
assert.equal(requireFeature(api, "services"), (api as unknown as { services: unknown }).services);
|
||||
assert.throws(() => requireFeature(api, "pty"), (error: unknown) => error instanceof MissingFeatureError
|
||||
&& error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "pty"
|
||||
&& error.message === "This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature.");
|
||||
assert.throws(() => requireFeatures(api, ["pty", "files", "workspace.readBytes"]), {
|
||||
message: "This plugin needs the terminal API (api.pty) and the folder grant API (api.files). Update RuneStone to a version that has these features.",
|
||||
});
|
||||
assert.doesNotThrow(() => requireFeatures(api, ["git", "workspace.readBytes"]));
|
||||
assert.doesNotThrow(() => requireFeatures(api, ["services", "workspace.readBytes"]));
|
||||
assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError);
|
||||
assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)");
|
||||
assert.equal(API_VERSION, 1);
|
||||
@@ -65,10 +65,9 @@ test("a required function stays bound to its parent object", async () => {
|
||||
test("the current host gives every SDK feature when all services are present", async () => {
|
||||
const pty = { open: async () => {}, write: async () => {}, resize: async () => {}, close: async () => {}, profiles: async () => [], openWindow: async () => {}, dictation: async () => {} };
|
||||
const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} };
|
||||
const git = { status: async () => ({ available: true, repository: true, branch: null, changes: [] }), diff: async () => "", stage: async () => {}, unstage: async () => {}, commit: async () => {}, push: async () => {}, pull: async () => {}, graph: async () => ({ commits: [] }), commitDetails: async () => ({ id: "", parents: [], author: "", date: "", message: "", files: [] }), commitDiff: async () => "", blame: async () => null };
|
||||
const backgrounds = { chooseFolder: async () => null, list: async () => [], read: async () => new Uint8Array() };
|
||||
const { api, session } = await hostApi({
|
||||
pty, files, git, backgrounds, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
|
||||
pty, files, backgrounds, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
|
||||
workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} },
|
||||
settings: { ...base.settings, subscribe: () => () => {} },
|
||||
}, true);
|
||||
@@ -79,7 +78,7 @@ test("the current host gives every SDK feature when all services are present", a
|
||||
test("the host without optional services lacks only the features that depend on them", async () => {
|
||||
const { api, session } = await hostApi({});
|
||||
assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [
|
||||
"backgrounds", "closeView", "completion.transport", "files", "git", "git.commitDetails", "git.commitDiff", "git.graph", "git.pull", "git.push",
|
||||
"backgrounds", "closeView", "completion.transport", "files",
|
||||
"openFile", "pty", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe",
|
||||
"workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe",
|
||||
]);
|
||||
|
||||
@@ -65,5 +65,6 @@ test('Migration keeps renamed theme IDs and a background image data URL', () =>
|
||||
});
|
||||
|
||||
test('Every section has one old key', () => {
|
||||
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.language', 'runestone.settings']);
|
||||
// `runestone.features` came after the settings file. Only the browser preview uses it.
|
||||
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings']);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user