From fa9335302cde729cce77e7f42edcaad4ceca8b6a Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 17 Nov 2026 09:40:39 +1300 Subject: [PATCH 1/4] Unit-test run configuration and tree building, cover declaredIn disambiguation Move the run-config store and the tree's sort and relation logic out of vscode-dependent files so they run under plain Node. Add a second fixture declaring the same target on an interface to exercise goToTarget's tie-break. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01G6hKb9Lpz4vBWMgPJS7N6D --- src/extension.ts | 20 +--- src/graph.ts | 27 ++++++ src/runConfig.ts | 83 +--------------- src/runConfigStore.ts | 112 +++++++++++++++++++++ test/fixtures/workspace/build/ICompile.cs | 7 ++ test/integration/extension.test.ts | 24 +++-- test/unit/runConfigStore.test.ts | 113 ++++++++++++++++++++++ test/unit/tree.test.ts | 48 +++++++++ 8 files changed, 328 insertions(+), 106 deletions(-) create mode 100644 src/runConfigStore.ts create mode 100644 test/fixtures/workspace/build/ICompile.cs create mode 100644 test/unit/runConfigStore.test.ts create mode 100644 test/unit/tree.test.ts diff --git a/src/extension.ts b/src/extension.ts index c28d0b1..8eb78fe 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,5 +1,5 @@ import * as vscode from 'vscode'; -import { BuildGraph, GraphSource, Relation, Target, checkCompatibility, findGraphFile, loadGraph } from './model'; +import { BuildGraph, GraphSource, RELATIONS, Relation, Target, checkCompatibility, findGraphFile, hasRelations, loadGraph, relatedTargets, sortTargets } from './model'; import { GraphPanel } from './graphPanel'; import { goToTarget } from './goToTarget'; import { RunConfigStore, RunConfigViewProvider } from './runConfig'; @@ -42,7 +42,7 @@ class TargetItem extends vscode.TreeItem { const lines = [ `**${target.name}**${target.default ? ' _(default target)_' : ''}${target.listed ? '' : ' _(unlisted)_'}`, target.description ?? undefined, - ...(['dependsOn', 'after', 'triggeredBy', 'triggers'] as Relation[]) + ...RELATIONS .filter(r => target[r].length > 0) .map(r => `${RELATION_LABELS[r]}: ${target[r].join(', ')}`), ]; @@ -73,11 +73,8 @@ class FalloutTargetsProvider implements vscode.TreeDataProvider { return this.loadRoots(); } // Children: one entry per related target, recursively expandable. - return (['dependsOn', 'after', 'triggeredBy', 'triggers'] as Relation[]).flatMap(relation => - element.target[relation] - .map(name => this.byName.get(name)) - .filter((t): t is Target => t !== undefined) - .map(t => new TargetItem(t, relation, this.hasRelations(t)))); + return relatedTargets(element.target, this.byName) + .map(({ relation, target }) => new TargetItem(target, relation, hasRelations(target))); } private loadRoots(): TargetItem[] { @@ -95,14 +92,7 @@ class FalloutTargetsProvider implements vscode.TreeDataProvider { } checkCompatibility(this.graph, this.extensionVersion); this.byName = new Map(this.graph.targets.map(t => [t.name, t])); - return this.graph.targets - .slice() - .sort((a, b) => Number(b.listed) - Number(a.listed) || a.name.localeCompare(b.name)) - .map(t => new TargetItem(t, undefined, this.hasRelations(t))); - } - - private hasRelations(target: Target): boolean { - return target.dependsOn.length + target.after.length + target.triggeredBy.length + target.triggers.length > 0; + return sortTargets(this.graph.targets).map(t => new TargetItem(t, undefined, hasRelations(t))); } } diff --git a/src/graph.ts b/src/graph.ts index 1f61f59..ff9b6cc 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -5,6 +5,9 @@ import * as fs from 'fs'; /** How one target relates to another in the build graph. */ export type Relation = 'dependsOn' | 'after' | 'triggeredBy' | 'triggers'; +/** Every relation, in the order the tree shows them as children. */ +export const RELATIONS: readonly Relation[] = ['dependsOn', 'after', 'triggeredBy', 'triggers']; + /** A single build target, as emitted into build-graph.json. */ export interface Target { name: string; @@ -104,3 +107,27 @@ export function toMermaid(graph: BuildGraph): string { lines.push(' classDef unlisted opacity:0.45,stroke-dasharray:3 3'); return lines.join('\n'); } + +/** Whether a target has any relation to expand in the tree. */ +export function hasRelations(target: Target): boolean { + return RELATIONS.some(r => target[r].length > 0); +} + +/** Root order for the tree: listed targets first, then alphabetical. */ +export function sortTargets(targets: readonly Target[]): Target[] { + return targets + .slice() + .sort((a, b) => Number(b.listed) - Number(a.listed) || a.name.localeCompare(b.name)); +} + +/** + * The expandable children of a target: one entry per related target, grouped by relation + * in {@link RELATIONS} order. Names the graph doesn't declare are dropped. + */ +export function relatedTargets(target: Target, byName: ReadonlyMap): { relation: Relation; target: Target }[] { + return RELATIONS.flatMap(relation => + target[relation] + .map(name => byName.get(name)) + .filter((t): t is Target => t !== undefined) + .map(t => ({ relation, target: t }))); +} diff --git a/src/runConfig.ts b/src/runConfig.ts index df1a27c..af7fcf3 100644 --- a/src/runConfig.ts +++ b/src/runConfig.ts @@ -1,86 +1,7 @@ import * as vscode from 'vscode'; +import { RunConfigStore } from './runConfigStore'; -/** A build parameter passed to a local run as `--name value`. */ -export interface Parameter { - name: string; - value: string; -} - -const PARAMS_KEY = 'fallout.parameters'; -const SECRET_NAMES_KEY = 'fallout.secretNames'; -const SECRET_PREFIX = 'fallout.secret.'; - -/** - * Persists the local run configuration: parameters live in workspace state (plain, - * per-workspace); secret *values* live in VS Code's SecretStorage (OS keychain-backed) - * and are never rendered into the webview — only their names are. Parameters become - * CLI args (`--name value`); secrets become environment variables so they don't leak - * into shell history or the process list. - */ -export class RunConfigStore { - private readonly onDidChangeEmitter = new vscode.EventEmitter(); - readonly onDidChange = this.onDidChangeEmitter.event; - - constructor(private readonly context: vscode.ExtensionContext) {} - - getParameters(): Parameter[] { - return this.context.workspaceState.get(PARAMS_KEY, []); - } - - async setParameter(name: string, value: string): Promise { - const params = this.getParameters().filter(p => p.name !== name); - params.push({ name, value }); - params.sort((a, b) => a.name.localeCompare(b.name)); - await this.context.workspaceState.update(PARAMS_KEY, params); - this.onDidChangeEmitter.fire(); - } - - async removeParameter(name: string): Promise { - await this.context.workspaceState.update(PARAMS_KEY, this.getParameters().filter(p => p.name !== name)); - this.onDidChangeEmitter.fire(); - } - - getSecretNames(): string[] { - return this.context.workspaceState.get(SECRET_NAMES_KEY, []); - } - - async setSecret(name: string, value: string): Promise { - await this.context.secrets.store(SECRET_PREFIX + name, value); - if (!this.getSecretNames().includes(name)) { - await this.context.workspaceState.update(SECRET_NAMES_KEY, [...this.getSecretNames(), name].sort()); - } - this.onDidChangeEmitter.fire(); - } - - async removeSecret(name: string): Promise { - await this.context.secrets.delete(SECRET_PREFIX + name); - await this.context.workspaceState.update(SECRET_NAMES_KEY, this.getSecretNames().filter(n => n !== name)); - this.onDidChangeEmitter.fire(); - } - - /** Parameters rendered as a CLI argument string, e.g. `--configuration Release`. */ - buildArgs(): string { - return this.getParameters() - .map(p => `--${p.name} ${quoteArg(p.value)}`) - .join(' '); - } - - /** Resolves all stored secrets into an environment map for a local run. */ - async buildEnv(): Promise> { - const env: Record = {}; - for (const name of this.getSecretNames()) { - const value = await this.context.secrets.get(SECRET_PREFIX + name); - if (value !== undefined) { - env[name] = value; - } - } - return env; - } -} - -function quoteArg(value: string): string { - return /\s/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value; -} +export { Parameter, RunConfigStore } from './runConfigStore'; /** The "Run Configuration" webview view — a form for parameters and secret names. */ export class RunConfigViewProvider implements vscode.WebviewViewProvider { diff --git a/src/runConfigStore.ts b/src/runConfigStore.ts new file mode 100644 index 0000000..d310715 --- /dev/null +++ b/src/runConfigStore.ts @@ -0,0 +1,112 @@ +// Run-configuration persistence: no `vscode` import, so it runs under plain Node (unit tests). +/** A build parameter passed to a local run as `--name value`. */ +export interface Parameter { + name: string; + value: string; +} + +/** The slice of `vscode.Memento` the store needs. */ +export interface StateStore { + get(key: string, defaultValue: T): T; + update(key: string, value: unknown): PromiseLike; +} + +/** The slice of `vscode.SecretStorage` the store needs. */ +export interface SecretStore { + store(key: string, value: string): PromiseLike; + get(key: string): PromiseLike; + delete(key: string): PromiseLike; +} + +/** The slice of `vscode.ExtensionContext` the store needs, so it runs without VS Code. */ +export interface RunConfigContext { + workspaceState: StateStore; + secrets: SecretStore; +} + +const PARAMS_KEY = 'fallout.parameters'; +const SECRET_NAMES_KEY = 'fallout.secretNames'; +const SECRET_PREFIX = 'fallout.secret.'; + +/** + * Persists the local run configuration: parameters live in workspace state (plain, + * per-workspace); secret *values* live in VS Code's SecretStorage (OS keychain-backed) + * and are never rendered into the webview — only their names are. Parameters become + * CLI args (`--name value`); secrets become environment variables so they don't leak + * into shell history or the process list. + */ +export class RunConfigStore { + private readonly listeners = new Set<() => void>(); + + /** Subscribes to changes; the returned handle is structurally a `vscode.Disposable`. */ + readonly onDidChange = (listener: () => void): { dispose(): void } => { + this.listeners.add(listener); + return { dispose: () => { this.listeners.delete(listener); } }; + }; + + constructor(private readonly context: RunConfigContext) {} + + private fire(): void { + for (const listener of [...this.listeners]) { + listener(); + } + } + + getParameters(): Parameter[] { + return this.context.workspaceState.get(PARAMS_KEY, []); + } + + async setParameter(name: string, value: string): Promise { + const params = this.getParameters().filter(p => p.name !== name); + params.push({ name, value }); + params.sort((a, b) => a.name.localeCompare(b.name)); + await this.context.workspaceState.update(PARAMS_KEY, params); + this.fire(); + } + + async removeParameter(name: string): Promise { + await this.context.workspaceState.update(PARAMS_KEY, this.getParameters().filter(p => p.name !== name)); + this.fire(); + } + + getSecretNames(): string[] { + return this.context.workspaceState.get(SECRET_NAMES_KEY, []); + } + + async setSecret(name: string, value: string): Promise { + await this.context.secrets.store(SECRET_PREFIX + name, value); + if (!this.getSecretNames().includes(name)) { + await this.context.workspaceState.update(SECRET_NAMES_KEY, [...this.getSecretNames(), name].sort()); + } + this.fire(); + } + + async removeSecret(name: string): Promise { + await this.context.secrets.delete(SECRET_PREFIX + name); + await this.context.workspaceState.update(SECRET_NAMES_KEY, this.getSecretNames().filter(n => n !== name)); + this.fire(); + } + + /** Parameters rendered as a CLI argument string, e.g. `--configuration Release`. */ + buildArgs(): string { + return this.getParameters() + .map(p => `--${p.name} ${quoteArg(p.value)}`) + .join(' '); + } + + /** Resolves all stored secrets into an environment map for a local run. */ + async buildEnv(): Promise> { + const env: Record = {}; + for (const name of this.getSecretNames()) { + const value = await this.context.secrets.get(SECRET_PREFIX + name); + if (value !== undefined) { + env[name] = value; + } + } + return env; + } +} + +export function quoteArg(value: string): string { + return /\s/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value; +} diff --git a/test/fixtures/workspace/build/ICompile.cs b/test/fixtures/workspace/build/ICompile.cs new file mode 100644 index 0000000..008c79b --- /dev/null +++ b/test/fixtures/workspace/build/ICompile.cs @@ -0,0 +1,7 @@ +// Fixture for goToTarget tests. Not compiled. +// Declares a same-named target on a component interface, so `declaredIn` has to pick. +interface ICompile +{ + Target Compile => _ => _ + .Executes(() => { }); +} diff --git a/test/integration/extension.test.ts b/test/integration/extension.test.ts index e5296a9..6d4696a 100644 --- a/test/integration/extension.test.ts +++ b/test/integration/extension.test.ts @@ -26,16 +26,20 @@ suite('extension host', () => { } }); - test('goToTarget opens Build.cs at the declaration', async () => { - // Same shape as a TargetItem: the command only reads `.target`. - const item = { target: { name: 'Compile', declaredIn: 'Build', default: true, listed: true, dependsOn: [], after: [], triggeredBy: [], triggers: [] } }; - await vscode.commands.executeCommand('fallout.goToTarget', item); - - const editor = await waitFor(() => - vscode.window.activeTextEditor?.document.fileName.endsWith('Build.cs') ? vscode.window.activeTextEditor : undefined); - assert.equal(path.basename(editor.document.fileName), 'Build.cs'); - assert.match(editor.document.lineAt(editor.selection.start.line).text, /Target Compile =>/); - }); + // Build.cs and ICompile.cs both declare `Target Compile`; `declaredIn` has to pick between them. + for (const [declaredIn, file] of [['Build', 'Build.cs'], ['ICompile', 'ICompile.cs']]) { + test(`goToTarget opens ${file} when the target is declared in ${declaredIn}`, async () => { + await vscode.commands.executeCommand('workbench.action.closeAllEditors'); + // Same shape as a TargetItem: the command only reads `.target`. + const item = { target: { name: 'Compile', declaredIn, default: true, listed: true, dependsOn: [], after: [], triggeredBy: [], triggers: [] } }; + await vscode.commands.executeCommand('fallout.goToTarget', item); + + const editor = await waitFor(() => + vscode.window.activeTextEditor?.document.fileName.endsWith('.cs') ? vscode.window.activeTextEditor : undefined); + assert.equal(path.basename(editor.document.fileName), file); + assert.match(editor.document.lineAt(editor.selection.start.line).text, /Target Compile =>/); + }); + } test('showGraph opens the graph panel', async () => { await vscode.commands.executeCommand('fallout.showGraph'); diff --git a/test/unit/runConfigStore.test.ts b/test/unit/runConfigStore.test.ts new file mode 100644 index 0000000..cc2ecb2 --- /dev/null +++ b/test/unit/runConfigStore.test.ts @@ -0,0 +1,113 @@ +import { test } from 'node:test'; +import * as assert from 'node:assert/strict'; +import { RunConfigContext, RunConfigStore, quoteArg } from '../../src/runConfigStore'; + +/** In-memory stand-ins for workspaceState and SecretStorage. */ +function fakeContext() { + const state = new Map(); + const secrets = new Map(); + const context: RunConfigContext = { + workspaceState: { + get: (key: string, defaultValue: T) => (state.has(key) ? state.get(key) : defaultValue) as T, + update: async (key, value) => { state.set(key, value); }, + }, + secrets: { + store: async (key, value) => { secrets.set(key, value); }, + get: async key => secrets.get(key), + delete: async key => { secrets.delete(key); }, + }, + }; + return { context, state, secrets }; +} + +test('quoteArg: leaves plain values alone, quotes whitespace, escapes embedded quotes', () => { + assert.equal(quoteArg('Release'), 'Release'); + assert.equal(quoteArg('a b'), '"a b"'); + assert.equal(quoteArg('say "hi" now'), '"say \\"hi\\" now"'); +}); + +test('buildArgs: renders parameters as --name value, sorted by name', async () => { + const { context } = fakeContext(); + const store = new RunConfigStore(context); + await store.setParameter('verbosity', 'quiet'); + await store.setParameter('configuration', 'Release'); + await store.setParameter('message', 'hello world'); + assert.equal(store.buildArgs(), '--configuration Release --message "hello world" --verbosity quiet'); +}); + +test('buildArgs: empty when there are no parameters', () => { + assert.equal(new RunConfigStore(fakeContext().context).buildArgs(), ''); +}); + +test('setParameter: replaces an existing parameter instead of duplicating it', async () => { + const store = new RunConfigStore(fakeContext().context); + await store.setParameter('configuration', 'Debug'); + await store.setParameter('configuration', 'Release'); + assert.deepEqual(store.getParameters(), [{ name: 'configuration', value: 'Release' }]); +}); + +test('removeParameter: removes only the named parameter', async () => { + const store = new RunConfigStore(fakeContext().context); + await store.setParameter('a', '1'); + await store.setParameter('b', '2'); + await store.removeParameter('a'); + assert.deepEqual(store.getParameters(), [{ name: 'b', value: '2' }]); +}); + +test('secrets: values go to secret storage, only names reach workspace state', async () => { + const { context, state, secrets } = fakeContext(); + const store = new RunConfigStore(context); + await store.setSecret('NuGetApiKey', 's3cret'); + + assert.deepEqual(store.getSecretNames(), ['NuGetApiKey']); + assert.equal(secrets.get('fallout.secret.NuGetApiKey'), 's3cret'); + assert.ok(!JSON.stringify([...state.entries()]).includes('s3cret'), 'secret value leaked into workspace state'); +}); + +test('secrets: names stay unique and sorted', async () => { + const store = new RunConfigStore(fakeContext().context); + await store.setSecret('B', '1'); + await store.setSecret('A', '1'); + await store.setSecret('B', '2'); + assert.deepEqual(store.getSecretNames(), ['A', 'B']); +}); + +test('buildEnv: resolves stored secrets, skips names whose value is gone', async () => { + const { context, secrets } = fakeContext(); + const store = new RunConfigStore(context); + await store.setSecret('A', 'one'); + await store.setSecret('B', 'two'); + secrets.delete('fallout.secret.B'); + assert.deepEqual(await store.buildEnv(), { A: 'one' }); +}); + +test('buildArgs never contains secrets', async () => { + const store = new RunConfigStore(fakeContext().context); + await store.setSecret('NuGetApiKey', 's3cret'); + await store.setParameter('configuration', 'Release'); + assert.ok(!store.buildArgs().includes('s3cret')); +}); + +test('removeSecret: deletes value and name', async () => { + const { context, secrets } = fakeContext(); + const store = new RunConfigStore(context); + await store.setSecret('A', 'one'); + await store.removeSecret('A'); + assert.deepEqual(store.getSecretNames(), []); + assert.equal(secrets.size, 0); +}); + +test('onDidChange: fires on every mutation, stops after dispose', async () => { + const store = new RunConfigStore(fakeContext().context); + let fired = 0; + const subscription = store.onDidChange(() => { fired++; }); + await store.setParameter('a', '1'); + await store.removeParameter('a'); + await store.setSecret('S', 'v'); + await store.removeSecret('S'); + assert.equal(fired, 4); + + subscription.dispose(); + await store.setParameter('b', '2'); + assert.equal(fired, 4); +}); diff --git a/test/unit/tree.test.ts b/test/unit/tree.test.ts new file mode 100644 index 0000000..663d03c --- /dev/null +++ b/test/unit/tree.test.ts @@ -0,0 +1,48 @@ +import { test } from 'node:test'; +import * as assert from 'node:assert/strict'; +import * as path from 'path'; +import { RELATIONS, Target, hasRelations, loadGraph, locateGraphFile, relatedTargets, sortTargets } from '../../src/graph'; + +const target = (name: string, over: Partial = {}): Target => + ({ name, default: false, listed: true, dependsOn: [], after: [], triggeredBy: [], triggers: [], ...over }); + +const names = (targets: Target[]) => targets.map(t => t.name); + +test('sortTargets: listed first, then alphabetical; input is not mutated', () => { + const input = [target('Zed'), target('Hidden', { listed: false }), target('Alpha'), target('Beta', { listed: false })]; + assert.deepEqual(names(sortTargets(input)), ['Alpha', 'Zed', 'Beta', 'Hidden']); + assert.deepEqual(names(input), ['Zed', 'Hidden', 'Alpha', 'Beta']); +}); + +test('hasRelations: true for any relation, false for none', () => { + assert.equal(hasRelations(target('A')), false); + for (const relation of RELATIONS) { + assert.equal(hasRelations(target('A', { [relation]: ['B'] })), true, relation); + } +}); + +test('relatedTargets: groups by relation in tree order', () => { + const a = target('A', { triggers: ['D'], dependsOn: ['B'], after: ['C'], triggeredBy: ['E'] }); + const byName = new Map(['A', 'B', 'C', 'D', 'E'].map(n => [n, n === 'A' ? a : target(n)])); + assert.deepEqual( + relatedTargets(a, byName).map(r => `${r.relation}:${r.target.name}`), + ['dependsOn:B', 'after:C', 'triggeredBy:E', 'triggers:D']); +}); + +test('relatedTargets: drops names the graph does not declare', () => { + const a = target('A', { dependsOn: ['Ghost', 'B'] }); + const byName = new Map([['A', a], ['B', target('B')]]); + assert.deepEqual(relatedTargets(a, byName).map(r => r.target.name), ['B']); +}); + +test('fixture graph: Compile expands to Restore (depends on) and Pack (triggers)', () => { + const fixtures = path.resolve(__dirname, '../../../test/fixtures/workspace'); + const graph = loadGraph(locateGraphFile([fixtures])!); + const byName = new Map(graph.targets.map(t => [t.name, t])); + const compile = byName.get('Compile')!; + + assert.deepEqual( + relatedTargets(compile, byName).map(r => `${r.relation}:${r.target.name}`), + ['dependsOn:Restore', 'triggers:Pack']); + assert.deepEqual(names(sortTargets(graph.targets)), ['Clean', 'Compile', 'Pack', 'Restore', 'Hidden']); +}); From b0ec87903d2f8b73ac7a7c99ae257054edc2b66b Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 17 Nov 2026 09:43:41 +1300 Subject: [PATCH 2/4] Add a contract test against a graph the real build emits The hand-written fixtures can drift from what Fallout writes. The contract test regenerates build-graph.json with this repo's own build and checks the extension's assumptions against it. It already caught that `description` is emitted as null, which the type did not allow. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01G6hKb9Lpz4vBWMgPJS7N6D --- AGENTS.md | 2 +- CONTRIBUTING.md | 2 + package.json | 3 +- src/graph.ts | 3 +- test/contract/graph.contract.test.ts | 113 +++++++++++++++++++++++++++ 5 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 test/contract/graph.contract.test.ts diff --git a/AGENTS.md b/AGENTS.md index dd4f703..1352991 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ The repo holds three things, and they are easy to confuse: - **Extension:** TypeScript 5.9 → `tsc` → `out/`. `strict: true`, CommonJS, ES2022. VS Code engine `^1.85.0`. One runtime dependency: `mermaid`. - **Build:** .NET SDK pinned in `global.json` (`10.0.100`, `rollForward: latestMinor`); Fallout 10.4.0 as the `fallout.globaltool` (`.config/dotnet-tools.json`) and the `Fallout.Common` package reference. - `nuget.config` clears sources and pins nuget.org only, so a machine-level feed can't shadow the pinned Fallout packages. -- **Tests are two layers** (`npm test` runs both; details in [CONTRIBUTING.md](CONTRIBUTING.md#tests)). **Unit** (`npm run test:unit`, `node:test`, plain Node, ~1s) covers `src/graph.ts`, the vscode-free logic that `src/model.ts` re-exports — keep new logic there, not behind a `vscode` import, so it stays testable. **Extension-host** (`npm run test:integration`, `@vscode/test-cli`) launches a real VS Code on `test/fixtures/workspace` and drives the registered commands; it downloads VS Code on first run and opens a window briefly. Neither runs in CI yet, and the graph webview has no test ([#37](https://github.com/Fallout-build/Fallout.Extensions.VSCode/issues/37)). +- **Tests are two layers** (`npm test` runs both; details in [CONTRIBUTING.md](CONTRIBUTING.md#tests)). **Unit** (`npm run test:unit`, `node:test`, plain Node, ~1s) covers `src/graph.ts`, the vscode-free logic that `src/model.ts` re-exports — keep new logic there, not behind a `vscode` import, so it stays testable. **Extension-host** (`npm run test:integration`, `@vscode/test-cli`) launches a real VS Code on `test/fixtures/workspace` and drives the registered commands; it downloads VS Code on first run and opens a window briefly. **Contract** (`npm run test:contract`, needs .NET) regenerates the graph with this repo's own build (`dotnet fallout --plan`) and checks the extension's reading of it; `FALLOUT_GRAPH=` points it at another framework version's graph. It is not part of `npm test`. None of the three run in CI yet, and the graph webview has no test ([#37](https://github.com/Fallout-build/Fallout.Extensions.VSCode/issues/37)). ## Common commands diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d704d9b..df1047f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,10 +75,12 @@ GitHub can't enforce a method per branch, so this is discipline rather than conf npm test # unit + extension-host npm run test:unit # node:test, plain Node, ~1s npm run test:integration # real VS Code (downloaded to .vscode-test/ on first run) +npm run test:contract # needs .NET: regenerates the graph with the real build, then checks it ``` - **Unit** (`test/unit`) covers `src/graph.ts`: graph parsing, discovery, compatibility checks, Mermaid output. Code that must be unit-testable cannot import `vscode` — put it in `graph.ts`; `model.ts` re-exports it. - **Extension-host** (`test/integration`) activates the extension on `test/fixtures/workspace` and runs the commands for real. It briefly opens a VS Code window. +- **Contract** (`test/contract`) runs `dotnet fallout --plan` so Fallout emits a real `build-graph.json`, then checks the extension's types and assumptions against it. Set `FALLOUT_GRAPH=` to check a graph from another framework version. Not part of `npm test`. - Fixtures live in `test/fixtures/`. They are not compiled and not shipped (`.vscodeignore`). - Not covered yet: the graph webview ([#37](https://github.com/Fallout-build/Fallout.Extensions.VSCode/issues/37)). CI does not run the tests yet. diff --git a/package.json b/package.json index 8f06c48..ea57a4e 100644 --- a/package.json +++ b/package.json @@ -199,7 +199,8 @@ "compile:test": "tsc -p tsconfig.test.json", "test:unit": "npm run compile:test && node --test \"out-test/test/unit/**/*.test.js\"", "test:integration": "npm run compile && npm run compile:test && vscode-test", - "test": "npm run test:unit && npm run test:integration" + "test": "npm run test:unit && npm run test:integration", + "test:contract": "npm run compile:test && dotnet fallout --plan && node --test \"out-test/test/contract/**/*.test.js\"" }, "dependencies": { "mermaid": "^11.4.1" diff --git a/src/graph.ts b/src/graph.ts index ff9b6cc..f25422c 100644 --- a/src/graph.ts +++ b/src/graph.ts @@ -11,7 +11,8 @@ export const RELATIONS: readonly Relation[] = ['dependsOn', 'after', 'triggeredB /** A single build target, as emitted into build-graph.json. */ export interface Target { name: string; - description?: string; + /** Emitted as `null` (not omitted) when a target has no description. */ + description?: string | null; default: boolean; listed: boolean; /** Declaring C# type (class or interface) — disambiguates go-to-definition. */ diff --git a/test/contract/graph.contract.test.ts b/test/contract/graph.contract.test.ts new file mode 100644 index 0000000..2d1cb6e --- /dev/null +++ b/test/contract/graph.contract.test.ts @@ -0,0 +1,113 @@ +import { test } from 'node:test'; +import * as assert from 'node:assert/strict'; +import * as fs from 'fs'; +import * as path from 'path'; +import { BuildGraph, RELATIONS, SUPPORTED_SCHEMA_VERSION, compatibilityMessage, loadGraph, locateGraphFile, relatedTargets, toMermaid } from '../../src/graph'; + +// Contract test: the extension's reading of build-graph.json against a graph the real Fallout +// build emitted (`npm run test:contract` regenerates it by running this repo's own build). +// Point FALLOUT_GRAPH at another graph to check a different framework version. +// +// Compiled to out-test/test/contract, so the repo root is three levels up. +const repoRoot = path.resolve(__dirname, '../../..'); + +function emittedGraph() { + const override = process.env.FALLOUT_GRAPH; + const source = override + ? { root: path.dirname(override), file: override } + : locateGraphFile([repoRoot]); + assert.ok(source, 'no build-graph.json found. Run `npm run test:contract` (or any Fallout build) first.'); + return { source, graph: loadGraph(source) as BuildGraph }; +} + +/** The framework line this extension declares in version.json (JSONC, so not JSON.parse). */ +function declaredLine(): string { + const text = fs.readFileSync(path.join(repoRoot, 'version.json'), 'utf8'); + const match = /"version"\s*:\s*"(\d+\.\d+)"/.exec(text); + assert.ok(match, 'could not read "version" from version.json'); + return match[1]; +} + +test('schema version is the one this extension understands', () => { + assert.equal(emittedGraph().graph.version, SUPPORTED_SCHEMA_VERSION); +}); + +test('falloutVersion is present and parses as major.minor[.patch[.height]][-label]', () => { + const { falloutVersion } = emittedGraph().graph; + assert.match(falloutVersion ?? '', /^\d+\.\d+(\.\d+){0,2}(-[\w.]+)?$/); +}); + +test('every target has the shape the extension reads', () => { + const { graph } = emittedGraph(); + assert.ok(Array.isArray(graph.targets) && graph.targets.length > 0, 'targets must be a non-empty array'); + for (const t of graph.targets) { + // The graph webview splits Mermaid node ids on '-', so names must be plain identifiers. + assert.match(t.name, /^[A-Za-z_]\w*$/, `target name ${JSON.stringify(t.name)}`); + assert.equal(typeof t.default, 'boolean', `${t.name}.default`); + assert.equal(typeof t.listed, 'boolean', `${t.name}.listed`); + assert.ok(t.description == null || typeof t.description === 'string', `${t.name}.description`); + assert.ok(t.declaredIn == null || typeof t.declaredIn === 'string', `${t.name}.declaredIn`); + for (const relation of RELATIONS) { + assert.ok(Array.isArray(t[relation]), `${t.name}.${relation} must be an array`); + assert.ok(t[relation].every(n => typeof n === 'string'), `${t.name}.${relation} must hold strings`); + } + } +}); + +test('target names are unique', () => { + const names = emittedGraph().graph.targets.map(t => t.name); + assert.equal(new Set(names).size, names.length); +}); + +test('every relation points at a target the graph declares', () => { + const { graph } = emittedGraph(); + const known = new Set(graph.targets.map(t => t.name)); + for (const t of graph.targets) { + for (const relation of RELATIONS) { + for (const name of t[relation]) { + assert.ok(known.has(name), `${t.name}.${relation} -> unknown target ${name}`); + } + } + } +}); + +test('triggers and triggeredBy are mirror images (toMermaid emits triggers alone)', () => { + const { graph } = emittedGraph(); + for (const t of graph.targets) { + for (const other of t.triggers) { + assert.ok(graph.targets.find(x => x.name === other)?.triggeredBy.includes(t.name), + `${t.name} triggers ${other}, but ${other}.triggeredBy does not list ${t.name}`); + } + for (const other of t.triggeredBy) { + assert.ok(graph.targets.find(x => x.name === other)?.triggers.includes(t.name), + `${t.name} is triggeredBy ${other}, but ${other}.triggers does not list ${t.name}`); + } + } +}); + +test('the tree can expand every target without dropping a relation', () => { + const { graph } = emittedGraph(); + const byName = new Map(graph.targets.map(t => [t.name, t])); + for (const t of graph.targets) { + const declared = RELATIONS.reduce((n, r) => n + t[r].length, 0); + assert.equal(relatedTargets(t, byName).length, declared, t.name); + } +}); + +test('toMermaid yields one node per target and no edge to an unknown node', () => { + const { graph } = emittedGraph(); + const lines = toMermaid(graph).split('\n'); + const nodes = new Set(lines.map(l => /^ {2}(\w+)\["/.exec(l)?.[1]).filter(Boolean)); + assert.equal(nodes.size, graph.targets.length); + for (const edge of lines.map(l => /^ {2}(\w+) (?:-->|-\.->|==>) (\w+)$/.exec(l)).filter(Boolean)) { + assert.ok(nodes.has(edge![1]) && nodes.has(edge![2]), `edge ${edge![0].trim()} references an unknown node`); + } +}); + +test('no compatibility warning when the extension targets the graph\'s framework line', () => { + const { graph } = emittedGraph(); + if (process.env.FALLOUT_GRAPH) { + return; // a graph from another framework version is expected to warn + } + assert.equal(compatibilityMessage(graph, `${declaredLine()}.0`), undefined); +}); From 9d276f5b6dcfad3ce571c97a48e026a0e41170e2 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 17 Nov 2026 09:48:35 +1300 Subject: [PATCH 3/4] Test the graph webview in a browser, and fix node clicks running the wrong target Move the graph page HTML into a vscode-free module and load it in Chrome or Edge via Playwright with acquireVsCodeApi stubbed. The test found that clicking a node posted target "flowchart": Mermaid 11 prefixes node ids with the render id, so splitting on the first dash picked the wrong segment. The page now matches the target name explicitly. Closes #37 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01G6hKb9Lpz4vBWMgPJS7N6D --- AGENTS.md | 2 +- CONTRIBUTING.md | 6 +- package-lock.json | 14 ++++ package.json | 6 +- src/graphPage.ts | 69 ++++++++++++++++ src/graphPanel.ts | 56 +------------ test/webview/graphPage.test.ts | 140 +++++++++++++++++++++++++++++++++ tsconfig.test.json | 1 + 8 files changed, 235 insertions(+), 59 deletions(-) create mode 100644 src/graphPage.ts create mode 100644 test/webview/graphPage.test.ts diff --git a/AGENTS.md b/AGENTS.md index 1352991..d5214ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ The repo holds three things, and they are easy to confuse: - **Extension:** TypeScript 5.9 → `tsc` → `out/`. `strict: true`, CommonJS, ES2022. VS Code engine `^1.85.0`. One runtime dependency: `mermaid`. - **Build:** .NET SDK pinned in `global.json` (`10.0.100`, `rollForward: latestMinor`); Fallout 10.4.0 as the `fallout.globaltool` (`.config/dotnet-tools.json`) and the `Fallout.Common` package reference. - `nuget.config` clears sources and pins nuget.org only, so a machine-level feed can't shadow the pinned Fallout packages. -- **Tests are two layers** (`npm test` runs both; details in [CONTRIBUTING.md](CONTRIBUTING.md#tests)). **Unit** (`npm run test:unit`, `node:test`, plain Node, ~1s) covers `src/graph.ts`, the vscode-free logic that `src/model.ts` re-exports — keep new logic there, not behind a `vscode` import, so it stays testable. **Extension-host** (`npm run test:integration`, `@vscode/test-cli`) launches a real VS Code on `test/fixtures/workspace` and drives the registered commands; it downloads VS Code on first run and opens a window briefly. **Contract** (`npm run test:contract`, needs .NET) regenerates the graph with this repo's own build (`dotnet fallout --plan`) and checks the extension's reading of it; `FALLOUT_GRAPH=` points it at another framework version's graph. It is not part of `npm test`. None of the three run in CI yet, and the graph webview has no test ([#37](https://github.com/Fallout-build/Fallout.Extensions.VSCode/issues/37)). +- **Tests are four layers** (`npm test` runs unit, webview and extension-host; details in [CONTRIBUTING.md](CONTRIBUTING.md#tests)). **Unit** (`npm run test:unit`, `node:test`, plain Node, ~1s) covers `src/graph.ts`, the vscode-free logic that `src/model.ts` re-exports — keep new logic there, not behind a `vscode` import, so it stays testable. **Webview** (`npm run test:webview`, `playwright-core`) loads the graph page from `src/graphPage.ts` in an installed Chrome or Edge (`PLAYWRIGHT_CHANNEL` overrides) with `acquireVsCodeApi` stubbed — keep the page HTML in that vscode-free file. **Extension-host** (`npm run test:integration`, `@vscode/test-cli`) launches a real VS Code on `test/fixtures/workspace` and drives the registered commands; it downloads VS Code on first run and opens a window briefly. **Contract** (`npm run test:contract`, needs .NET) regenerates the graph with this repo's own build (`dotnet fallout --plan`) and checks the extension's reading of it; `FALLOUT_GRAPH=` points it at another framework version's graph. It is not part of `npm test`. None of the three run in CI yet. ## Common commands diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index df1047f..0a5d846 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,17 +72,19 @@ GitHub can't enforce a method per branch, so this is discipline rather than conf ## Tests ```bash -npm test # unit + extension-host +npm test # unit + webview + extension-host npm run test:unit # node:test, plain Node, ~1s +npm run test:webview # graph page in Chrome/Edge via Playwright, no VS Code npm run test:integration # real VS Code (downloaded to .vscode-test/ on first run) npm run test:contract # needs .NET: regenerates the graph with the real build, then checks it ``` - **Unit** (`test/unit`) covers `src/graph.ts`: graph parsing, discovery, compatibility checks, Mermaid output. Code that must be unit-testable cannot import `vscode` — put it in `graph.ts`; `model.ts` re-exports it. +- **Webview** (`test/webview`) loads the graph page (`src/graphPage.ts`) in an installed Chrome or Edge with `acquireVsCodeApi` stubbed, and checks rendering, edge styles and the `ready` / `graph` / `run` messages. Set `PLAYWRIGHT_CHANNEL` to pick another browser channel. - **Extension-host** (`test/integration`) activates the extension on `test/fixtures/workspace` and runs the commands for real. It briefly opens a VS Code window. - **Contract** (`test/contract`) runs `dotnet fallout --plan` so Fallout emits a real `build-graph.json`, then checks the extension's types and assumptions against it. Set `FALLOUT_GRAPH=` to check a graph from another framework version. Not part of `npm test`. - Fixtures live in `test/fixtures/`. They are not compiled and not shipped (`.vscodeignore`). -- Not covered yet: the graph webview ([#37](https://github.com/Fallout-build/Fallout.Extensions.VSCode/issues/37)). CI does not run the tests yet. +- Not covered: the Run Configuration webview, and terminal runs. CI does not run the tests yet. ## Releases diff --git a/package-lock.json b/package-lock.json index 3982fb7..88ff757 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,6 +20,7 @@ "@vscode/vsce": "^3.2.0", "mocha": "^12.0.3", "ovsx": "^0.10.0", + "playwright-core": "^1.65.1", "typescript": "^5.9.3" }, "engines": { @@ -5759,6 +5760,19 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/pluralize": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", diff --git a/package.json b/package.json index ea57a4e..b63277f 100644 --- a/package.json +++ b/package.json @@ -199,8 +199,9 @@ "compile:test": "tsc -p tsconfig.test.json", "test:unit": "npm run compile:test && node --test \"out-test/test/unit/**/*.test.js\"", "test:integration": "npm run compile && npm run compile:test && vscode-test", - "test": "npm run test:unit && npm run test:integration", - "test:contract": "npm run compile:test && dotnet fallout --plan && node --test \"out-test/test/contract/**/*.test.js\"" + "test": "npm run test:unit && npm run test:webview && npm run test:integration", + "test:contract": "npm run compile:test && dotnet fallout --plan && node --test \"out-test/test/contract/**/*.test.js\"", + "test:webview": "npm run compile:test && node --test \"out-test/test/webview/**/*.test.js\"" }, "dependencies": { "mermaid": "^11.4.1" @@ -214,6 +215,7 @@ "@vscode/vsce": "^3.2.0", "mocha": "^12.0.3", "ovsx": "^0.10.0", + "playwright-core": "^1.65.1", "typescript": "^5.9.3" } } diff --git a/src/graphPage.ts b/src/graphPage.ts new file mode 100644 index 0000000..7c5267b --- /dev/null +++ b/src/graphPage.ts @@ -0,0 +1,69 @@ +// The graph webview's page, as a pure function so it runs outside VS Code (webview tests). + +export interface GraphPageOptions { + /** CSP nonce for the inline script and the Mermaid bundle. */ + nonce: string; + /** The webview's `cspSource`: the origin Mermaid is served from. */ + cspSource: string; + /** URL of `mermaid.min.js`. */ + mermaidUri: string; +} + +export function graphHtml({ nonce, cspSource, mermaidUri }: GraphPageOptions): string { + // style-src 'unsafe-inline' is required: Mermaid injects its own + + +
+ solid → depends on  •  dashed → runs after  •  + thick → triggers  •  bold border = default target  •  + click a target to run it +
+
+ + + +`; +} diff --git a/src/graphPanel.ts b/src/graphPanel.ts index 35a9476..414c60e 100644 --- a/src/graphPanel.ts +++ b/src/graphPanel.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode'; import { BuildGraph, toMermaid } from './model'; +import { graphHtml } from './graphPage'; /** Singleton webview panel rendering the build graph with Mermaid. */ export class GraphPanel { @@ -52,60 +53,7 @@ export class GraphPanel { const webview = this.panel.webview; const mermaidUri = webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, 'node_modules', 'mermaid', 'dist', 'mermaid.min.js')); const nonce = getNonce(); - // style-src 'unsafe-inline' is required: Mermaid injects its own - - -
- solid → depends on  •  dashed → runs after  •  - thick → triggers  •  bold border = default target  •  - click a target to run it -
-
- - - -`; + return graphHtml({ nonce, cspSource: webview.cspSource, mermaidUri: mermaidUri.toString() }); } } diff --git a/test/webview/graphPage.test.ts b/test/webview/graphPage.test.ts new file mode 100644 index 0000000..6d6463b --- /dev/null +++ b/test/webview/graphPage.test.ts @@ -0,0 +1,140 @@ +import { after, before, test } from 'node:test'; +import * as assert from 'node:assert/strict'; +import * as fs from 'fs'; +import * as path from 'path'; +import { Browser, Page, chromium } from 'playwright-core'; +import { graphHtml } from '../../src/graphPage'; +import { loadGraph, locateGraphFile, toMermaid } from '../../src/graph'; + +// Loads the real webview page outside VS Code: Mermaid is served from node_modules, and +// `acquireVsCodeApi` is stubbed to record what the page posts back to the extension. +// Uses an installed Chrome or Edge (override with PLAYWRIGHT_CHANNEL), so nothing is downloaded. +// +// Compiled to out-test/test/webview, so the repo root is three levels up. +const repoRoot = path.resolve(__dirname, '../../..'); +const mermaidJs = fs.readFileSync(path.join(repoRoot, 'node_modules', 'mermaid', 'dist', 'mermaid.min.js')); +const ORIGIN = 'http://webview.test'; +const NONCE = 'test-nonce'; + +const definition = toMermaid(loadGraph(locateGraphFile([path.join(repoRoot, 'test', 'fixtures', 'workspace')])!)); + +let browser: Browser; + +before(async () => { + const channels = process.env.PLAYWRIGHT_CHANNEL ? [process.env.PLAYWRIGHT_CHANNEL] : ['chrome', 'msedge']; + const errors: string[] = []; + for (const channel of channels) { + try { + browser = await chromium.launch({ channel }); + return; + } catch (e) { + errors.push(`${channel}: ${(e as Error).message.split('\n')[0]}`); + } + } + throw new Error(`no browser to run the webview tests. Install Chrome or Edge, or set PLAYWRIGHT_CHANNEL.\n${errors.join('\n')}`); +}); + +after(async () => { await browser?.close(); }); + +/** Opens the page with the vscode API stubbed; returns it plus the messages it has posted. */ +async function openPage(): Promise<{ page: Page; posted: () => Promise<{ type: string; target?: string }[]>; consoleErrors: string[] }> { + const page = await browser.newPage(); + const consoleErrors: string[] = []; + page.on('pageerror', e => consoleErrors.push(e.message)); + page.on('console', m => { if (m.type() === 'error') { consoleErrors.push(m.text()); } }); + + await page.addInitScript(() => { + (window as any).__posted = []; + (window as any).acquireVsCodeApi = () => ({ postMessage: (m: unknown) => (window as any).__posted.push(m) }); + }); + await page.route(`${ORIGIN}/**`, route => { + const url = new URL(route.request().url()); + return url.pathname === '/mermaid.min.js' + ? route.fulfill({ body: mermaidJs, contentType: 'text/javascript' }) + : route.fulfill({ body: graphHtml({ nonce: NONCE, cspSource: ORIGIN, mermaidUri: `${ORIGIN}/mermaid.min.js` }), contentType: 'text/html' }); + }); + await page.goto(`${ORIGIN}/`); + return { page, posted: () => page.evaluate(() => (window as any).__posted), consoleErrors }; +} + +/** What the extension does: post a `graph` message to the page, then wait for the SVG. */ +async function sendGraph(page: Page, def: string): Promise { + await page.evaluate(d => window.postMessage({ type: 'graph', definition: d }, '*'), def); + await page.waitForSelector('#graph svg g.node'); +} + +test('posts ready on load, without console errors (CSP, Mermaid load)', async () => { + const { page, posted, consoleErrors } = await openPage(); + try { + assert.deepEqual(await posted(), [{ type: 'ready' }]); + assert.deepEqual(consoleErrors, []); + } finally { + await page.close(); + } +}); + +test('a graph message renders one node per target', async () => { + const { page } = await openPage(); + try { + await sendGraph(page, definition); + const labels = await page.locator('#graph g.node').allTextContents(); + assert.deepEqual(labels.map(l => l.trim()).sort(), ['Clean', 'Compile', 'Hidden', 'Pack', 'Restore']); + } finally { + await page.close(); + } +}); + +test('edges render solid (depends on), dashed (runs after) and thick (triggers)', async () => { + const { page } = await openPage(); + try { + await sendGraph(page, definition); + const count = (selector: string) => page.locator(`#graph path.flowchart-link${selector}`).count(); + // Fixture: Restore runs after Clean (dashed); Compile depends on Restore (solid) and + // triggers Pack (thick). Mermaid draws `-.->` with its "dotted" pattern class, and + // repeats the solid classes on every edge, so solid means "not dotted, not thick". + assert.equal(await count('.edge-pattern-dotted'), 1, 'dashed'); + assert.equal(await count('.edge-thickness-thick'), 1, 'thick'); + assert.equal(await count(':not(.edge-pattern-dotted):not(.edge-thickness-thick)'), 1, 'solid'); + } finally { + await page.close(); + } +}); + +test('the default target is styled bold, unlisted targets are faded', async () => { + const { page } = await openPage(); + try { + await sendGraph(page, definition); + const strokeWidth = (name: string) => page.locator('#graph g.node', { hasText: name }).locator('rect, polygon').first() + .evaluate(el => getComputedStyle(el).strokeWidth); + assert.equal(await strokeWidth('Compile'), '3px'); + assert.notEqual(await strokeWidth('Pack'), '3px'); + assert.equal(await page.locator('#graph g.node.unlisted').count(), 1); + } finally { + await page.close(); + } +}); + +test('clicking a target posts run with its name (not a fragment of the node id)', async () => { + const { page, posted } = await openPage(); + try { + await sendGraph(page, definition); + await page.locator('#graph g.node', { hasText: 'Compile' }).click(); + const messages = await posted(); + assert.deepEqual(messages.at(-1), { type: 'run', target: 'Compile' }); + } finally { + await page.close(); + } +}); + +test('a second graph message replaces the first', async () => { + const { page } = await openPage(); + try { + await sendGraph(page, definition); + await page.evaluate(() => window.postMessage({ type: 'graph', definition: 'flowchart TD\n Only["Only"]' }, '*')); + await page.waitForFunction(() => document.querySelectorAll('#graph g.node').length === 1); + assert.equal((await page.locator('#graph g.node').textContent())?.trim(), 'Only'); + assert.equal(await page.locator('#graph svg').count(), 1); + } finally { + await page.close(); + } +}); diff --git a/tsconfig.test.json b/tsconfig.test.json index 02560f1..e0ad52c 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -2,6 +2,7 @@ "extends": "./tsconfig.json", "compilerOptions": { "rootDir": ".", + "lib": ["ES2022", "DOM"], "outDir": "out-test", "types": ["node", "mocha"] }, From 9a8127e81223820069ae5c4d21de083c990594c2 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 17 Nov 2026 10:03:08 +1300 Subject: [PATCH 4/4] Run the test suites in the PR gate Add ITestVsix to Fallout.Vsce: it runs the extension's npm test scripts, and wraps the ones that launch VS Code in xvfb-run on a Linux box without a display. The gate now invokes TestVsix before PackVsix, and caches the downloaded VS Code. A test runner script lists test files explicitly, since `node --test ` differs between Node versions and the generated workflow installs none. Also make the goToTarget test wait for the selection, not just the editor: the command is fire-and-forget, and the first run through the build caught the race. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01G6hKb9Lpz4vBWMgPJS7N6D --- .fallout/build.schema.json | 1 + .github/workflows/build.yml | 7 ++-- AGENTS.md | 6 ++-- CONTRIBUTING.md | 4 +-- build/Build.CI.GitHubActions.cs | 5 ++- build/Build.cs | 2 +- docs/ci.md | 7 ++-- package.json | 7 ++-- plugins/Fallout.Vsce/ITestVsix.cs | 54 ++++++++++++++++++++++++++++++ plugins/Fallout.Vsce/README.md | 2 +- test/integration/extension.test.ts | 18 ++++++---- test/run-node-tests.js | 32 ++++++++++++++++++ 12 files changed, 122 insertions(+), 23 deletions(-) create mode 100644 plugins/Fallout.Vsce/ITestVsix.cs create mode 100644 test/run-node-tests.js diff --git a/.fallout/build.schema.json b/.fallout/build.schema.json index 05c35ae..9812b5f 100644 --- a/.fallout/build.schema.json +++ b/.fallout/build.schema.json @@ -28,6 +28,7 @@ "PackVsix", "PublishVsix", "RestoreVsix", + "TestVsix", "VerifyVsixCredentials" ] }, diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fb528cd..2867b97 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,12 +39,13 @@ jobs: fetch-depth: 0 repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }} ref: ${{ github.head_ref }} - - name: 'Cache: .fallout/temp, ~/.nuget/packages' + - name: 'Cache: .fallout/temp, ~/.nuget/packages, .vscode-test' uses: actions/cache@v6 with: path: | .fallout/temp ~/.nuget/packages + .vscode-test key: ${{ runner.os }}-${{ hashFiles('**/global.json', '**/*.csproj', '**/Directory.Packages.props') }} - name: 'Setup: .NET SDK' uses: actions/setup-dotnet@v6 @@ -52,5 +53,5 @@ jobs: global-json-file: global.json - name: 'Restore: dotnet tools' run: dotnet tool restore - - name: 'Run: PackVsix' - run: dotnet fallout PackVsix + - name: 'Run: TestVsix, PackVsix' + run: dotnet fallout TestVsix PackVsix diff --git a/AGENTS.md b/AGENTS.md index d5214ba..90a55f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,13 +27,13 @@ The repo holds three things, and they are easy to confuse: - **Extension:** TypeScript 5.9 → `tsc` → `out/`. `strict: true`, CommonJS, ES2022. VS Code engine `^1.85.0`. One runtime dependency: `mermaid`. - **Build:** .NET SDK pinned in `global.json` (`10.0.100`, `rollForward: latestMinor`); Fallout 10.4.0 as the `fallout.globaltool` (`.config/dotnet-tools.json`) and the `Fallout.Common` package reference. - `nuget.config` clears sources and pins nuget.org only, so a machine-level feed can't shadow the pinned Fallout packages. -- **Tests are four layers** (`npm test` runs unit, webview and extension-host; details in [CONTRIBUTING.md](CONTRIBUTING.md#tests)). **Unit** (`npm run test:unit`, `node:test`, plain Node, ~1s) covers `src/graph.ts`, the vscode-free logic that `src/model.ts` re-exports — keep new logic there, not behind a `vscode` import, so it stays testable. **Webview** (`npm run test:webview`, `playwright-core`) loads the graph page from `src/graphPage.ts` in an installed Chrome or Edge (`PLAYWRIGHT_CHANNEL` overrides) with `acquireVsCodeApi` stubbed — keep the page HTML in that vscode-free file. **Extension-host** (`npm run test:integration`, `@vscode/test-cli`) launches a real VS Code on `test/fixtures/workspace` and drives the registered commands; it downloads VS Code on first run and opens a window briefly. **Contract** (`npm run test:contract`, needs .NET) regenerates the graph with this repo's own build (`dotnet fallout --plan`) and checks the extension's reading of it; `FALLOUT_GRAPH=` points it at another framework version's graph. It is not part of `npm test`. None of the three run in CI yet. +- **Tests are four layers** (`npm test` runs unit, webview and extension-host; details in [CONTRIBUTING.md](CONTRIBUTING.md#tests)). **Unit** (`npm run test:unit`, `node:test`, plain Node, ~1s) covers `src/graph.ts`, the vscode-free logic that `src/model.ts` re-exports — keep new logic there, not behind a `vscode` import, so it stays testable. **Webview** (`npm run test:webview`, `playwright-core`) loads the graph page from `src/graphPage.ts` in an installed Chrome or Edge (`PLAYWRIGHT_CHANNEL` overrides) with `acquireVsCodeApi` stubbed — keep the page HTML in that vscode-free file. **Extension-host** (`npm run test:integration`, `@vscode/test-cli`) launches a real VS Code on `test/fixtures/workspace` and drives the registered commands; it downloads VS Code on first run and opens a window briefly. **Contract** (`npm run test:contract`, needs .NET) regenerates the graph with this repo's own build (`dotnet fallout --plan`) and checks the extension's reading of it; `FALLOUT_GRAPH=` points it at another framework version's graph. It is not part of `npm test`. **The PR gate runs all four** (`dotnet fallout TestVsix PackVsix`; the contract check there reuses the graph the run itself emitted, so it skips the regeneration). ## Common commands ```bash ./build.sh # default target: PackVsix (./build.ps1 on Windows) -./build.sh PackVsix # what the PR gate runs -> fallout.vsix +./build.sh TestVsix PackVsix # what the PR gate runs: all test suites, then -> fallout.vsix ./build.sh --plan # what would run, without running it ./build.sh --help # list all targets and parameters @@ -87,7 +87,7 @@ Mermaid edge semantics **match the framework's `--plan` HTML** — solid = execu ## Useful pointers -- **`build/Build.cs` is small on purpose.** Reusable target logic belongs in the plugin's components (`IHasVsix` / `IPackVsix` / `IPublishVsix`), which mirror `Fallout.Components`' `IRestore` / `IPack` / `IPublish` — registries declared as data, narrowed per run by a CLI selector, validated up front. +- **`build/Build.cs` is small on purpose.** Reusable target logic belongs in the plugin's components (`IHasVsix` / `IPackVsix` / `ITestVsix` / `IPublishVsix`), which mirror `Fallout.Components`' `IRestore` / `IPack` / `IPublish` — registries declared as data, narrowed per run by a CLI selector, validated up front. - **`ovsx` ignores `--pre-release` for a prepackaged `.vsix`** (it reads the manifest), and `vsce publish --pre-release` on a `--packagePath` is only an *assertion* against the package. The bit set at package time is what decides. - **Tool resolution prefers `node_modules/.bin` over `PATH`**, since both CLIs are conventionally dev dependencies. On Windows it must pick the `.cmd` shim — invoking the extensionless script there starts a shell, not the tool. - **Installing is out of scope by design.** The build packages and publishes; it never touches your editor. A manually installed `.vsix` doesn't auto-update anyway — VS Code only tracks versions for extensions it obtained from a gallery (see [#6](https://github.com/Fallout-build/Fallout.Extensions.VSCode/issues/6)). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a5d846..4d0f00b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,7 +32,7 @@ Contributions are welcome. As a community, we want to help each other, provide c - Branch from `develop`. Name it `feature/`, `bugfix/`, `chore/`, or `docs/`. - Make sure your employer allows the contribution. -- Build it the way CI does: `./build.sh PackVsix` (or `./build.ps1 PackVsix` on Windows). The bootstrappers are thin — they provision .NET if needed, run `dotnet tool restore`, then `dotnet fallout "$@"`. The `fallout.globaltool` version is pinned in `.config/dotnet-tools.json`. +- Build it the way CI does: `./build.sh TestVsix PackVsix` (or `./build.ps1 TestVsix PackVsix` on Windows). The bootstrappers are thin — they provision .NET if needed, run `dotnet tool restore`, then `dotnet fallout "$@"`. The `fallout.globaltool` version is pinned in `.config/dotnet-tools.json`. - **Not running `npm test`** — it must pass, and new logic should come with a test (see [Tests](#tests)). Anything the tests can't reach (the graph webview, terminal runs) still needs F5 in an Extension Development Host or a sideloaded `.vsix`; say in the PR how you verified. ### When writing the PR @@ -84,7 +84,7 @@ npm run test:contract # needs .NET: regenerates the graph with the real buil - **Extension-host** (`test/integration`) activates the extension on `test/fixtures/workspace` and runs the commands for real. It briefly opens a VS Code window. - **Contract** (`test/contract`) runs `dotnet fallout --plan` so Fallout emits a real `build-graph.json`, then checks the extension's types and assumptions against it. Set `FALLOUT_GRAPH=` to check a graph from another framework version. Not part of `npm test`. - Fixtures live in `test/fixtures/`. They are not compiled and not shipped (`.vscodeignore`). -- Not covered: the Run Configuration webview, and terminal runs. CI does not run the tests yet. +- Not covered: the Run Configuration webview, and terminal runs. The PR gate runs all four suites before packaging, so `./build.sh TestVsix` is the local equivalent. ## Releases diff --git a/build/Build.CI.GitHubActions.cs b/build/Build.CI.GitHubActions.cs index e677780..07e8b95 100644 --- a/build/Build.CI.GitHubActions.cs +++ b/build/Build.CI.GitHubActions.cs @@ -36,7 +36,10 @@ // more clever here (negations, directory carve-outs) makes the two sets drift, and a // gap between them means a PR blocked forever on a required check that never fires. OnPullRequestExcludePaths = ["**/*.md"], - InvokedTargets = [nameof(IPackVsix.PackVsix)], + // Tests first: a red suite should stop the gate before anything is packaged. + InvokedTargets = [nameof(ITestVsix.TestVsix), nameof(IPackVsix.PackVsix)], + // VS Code (~150 MB) is downloaded once by the extension-host tests; keep it between runs. + CacheIncludePatterns = [".fallout/temp", "~/.nuget/packages", ".vscode-test"], PublishArtifacts = false)] partial class Build { diff --git a/build/Build.cs b/build/Build.cs index 53aa2de..c48374d 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -15,7 +15,7 @@ // // Registry tokens are read from the environment by the CLIs themselves (VSCE_PAT / OVSX_PAT); // this build never handles them, so they stay out of process argument lists and logs. -partial class Build : FalloutBuild, IPublishVsix +partial class Build : FalloutBuild, IPublishVsix, ITestVsix { public static int Main() => Execute(x => ((IPackVsix)x).PackVsix); diff --git a/docs/ci.md b/docs/ci.md index d9576ed..2f0fefd 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -8,7 +8,7 @@ The governing principle: **the build is defined in C#, not in YAML.** Every work | File | Trigger | Does | Generated? | |---|---|---|---| -| `build.yml` | PR to `develop`, `main`, `support/*` | `PackVsix` — the required check | **Yes**, from `[GitHubActions]` | +| `build.yml` | PR to `develop`, `main`, `support/*` | `TestVsix` then `PackVsix` — the required check | **Yes**, from `[GitHubActions]` | | `build-skip.yml` | PR touching only `**/*.md` | Nothing; reports the same check | No | | `nightly.yml` | push to `develop` | Packs, publishes the rolling `nightly` release | No | | `publish.yml` | `v*` tag push, or dispatch | Packs, releases, optionally promotes to marketplaces | No | @@ -16,7 +16,7 @@ The governing principle: **the build is defined in C#, not in YAML.** Every work ```mermaid flowchart LR PR["Pull request"] --> G{"Only
*.md?"} - G -->|No| B["build.yml
PackVsix"] + G -->|No| B["build.yml
TestVsix + PackVsix"] G -->|Yes| S["build-skip.yml
no-op"] B --> C(["ubuntu-latest ✓"]) S --> C @@ -96,7 +96,7 @@ The promotion jobs publish the exact artifact `pack` produced (`--skip PackVsix` There is no separate CI script. The runner invokes the same targets you do: ```bash -./build.ps1 PackVsix # what the PR gate runs +./build.ps1 TestVsix PackVsix # what the PR gate runs dotnet fallout --plan # what would run, without running it dotnet fallout VerifyVsixCredentials # proves marketplace tokens, publishes nothing ``` @@ -108,4 +108,5 @@ To run the extension itself rather than the build, see [developing.md](developin - **`PublicRelease: true`** is set on any job that checks out a tag. A detached HEAD matches none of `version.json`'s branch refspecs, so without it Nerdbank.GitVersioning appends a git-height suffix and the marketplace version stops being a clean triple. - **`fetch-depth: 0`** is required wherever the version is computed — NB.GV needs full history. - **Boolean workflow inputs arrive as strings** from the REST API, and therefore from `gh workflow run`. Conditions compare against both `true` and `'true'`; a bare `== true` silently skips while reporting success. +- **The gate runs the tests on the runner's own tools.** `ITestVsix` runs the npm test scripts: unit, webview (the preinstalled Chrome), extension-host (a real VS Code, under `xvfb-run` when there is no display, cached in `.vscode-test`), and the contract check against the graph that run emitted. `test/run-node-tests.js` lists test files explicitly because `node --test ` differs between Node versions and the generated workflow installs none. - **`--skip PackVsix` prunes the whole upstream chain**, `RestoreVsix` included — nothing else needs it, so Fallout skips it too. The promotion jobs therefore install the Node toolchain themselves: `vsce` and `ovsx` are dev dependencies, and `IHasVsix.ResolveNodeTool` looks in `node_modules/.bin` before `PATH`. Without that step `PublishVsix` fails resolving its tools before it reaches a registry — which is exactly how the first promotion of v10.4.31 failed. diff --git a/package.json b/package.json index b63277f..d23eba5 100644 --- a/package.json +++ b/package.json @@ -197,11 +197,12 @@ "compile": "tsc -p ./", "watch": "tsc -watch -p ./", "compile:test": "tsc -p tsconfig.test.json", - "test:unit": "npm run compile:test && node --test \"out-test/test/unit/**/*.test.js\"", + "test:unit": "npm run compile:test && node test/run-node-tests.js out-test/test/unit", "test:integration": "npm run compile && npm run compile:test && vscode-test", "test": "npm run test:unit && npm run test:webview && npm run test:integration", - "test:contract": "npm run compile:test && dotnet fallout --plan && node --test \"out-test/test/contract/**/*.test.js\"", - "test:webview": "npm run compile:test && node --test \"out-test/test/webview/**/*.test.js\"" + "test:contract": "npm run compile:test && dotnet fallout --plan && node test/run-node-tests.js out-test/test/contract", + "test:webview": "npm run compile:test && node test/run-node-tests.js out-test/test/webview", + "test:contract:check": "npm run compile:test && node test/run-node-tests.js out-test/test/contract" }, "dependencies": { "mermaid": "^11.4.1" diff --git a/plugins/Fallout.Vsce/ITestVsix.cs b/plugins/Fallout.Vsce/ITestVsix.cs new file mode 100644 index 0000000..1f28015 --- /dev/null +++ b/plugins/Fallout.Vsce/ITestVsix.cs @@ -0,0 +1,54 @@ +using System.Collections.Generic; +using System.Linq; +using Fallout.Common; +using Fallout.Common.Tooling; +using Fallout.Common.Utilities; +using static Fallout.Common.Tools.Npm.NpmTasks; + +namespace Fallout.Vsce; + +/// +/// Runs a VS Code extension's test suites through its own npm scripts. +/// +/// As with compilation, the suites stay described in package.json; this component only +/// decides which scripts the build runs, and in what environment. Each script compiles what it +/// needs, so the only prerequisite is the restored toolchain. +/// +public interface ITestVsix : IPackVsix +{ + /// + /// npm scripts to run, in order. Defaults to the suites that need nothing beyond Node and a + /// browser: unit, webview, extension-host, and the contract check against the graph this + /// very build has just emitted. + /// + IReadOnlyCollection VsixTestScripts => + ["test:unit", "test:webview", "test:integration", "test:contract:check"]; + + /// + /// Scripts that launch a real VS Code and so need a display. On Linux without one, they run + /// under xvfb-run; elsewhere they run as is. + /// + IReadOnlyCollection VsixDisplayScripts => ["test:integration"]; + + /// Runs every script in , stopping at the first failure. + Target TestVsix => _ => _ + .DependsOn(RestoreVsix) + .Executes(() => + { + foreach (var script in VsixTestScripts) + { + Serilog.Log.Information("Running npm script {Script}", script); + if (VsixDisplayScripts.Contains(script) + && EnvironmentInfo.IsLinux + && EnvironmentInfo.GetVariable("DISPLAY").IsNullOrEmpty()) + { + ProcessTasks.StartProcess("xvfb-run", $"-a npm run {script}", VsixDirectory) + .AssertZeroExitCode(); + } + else + { + Npm($"run {script}", workingDirectory: VsixDirectory); + } + } + }); +} diff --git a/plugins/Fallout.Vsce/README.md b/plugins/Fallout.Vsce/README.md index 9f43957..d3c1ff5 100644 --- a/plugins/Fallout.Vsce/README.md +++ b/plugins/Fallout.Vsce/README.md @@ -15,7 +15,7 @@ VsceTasks.VscePackage(_ => _ .EnablePreRelease()); ``` -**Components** — `IHasVsix`, `IPackVsix`, `IPublishVsix`, mirroring `Fallout.Components`' `IRestore` / `IPack` / `IPublish`. Registries are declared as data and narrowed per run, exactly as `IPublish` does for NuGet feeds: +**Components** — `IHasVsix`, `IPackVsix`, `ITestVsix`, `IPublishVsix`, mirroring `Fallout.Components`' `IRestore` / `IPack` / `IPublish`. Registries are declared as data and narrowed per run, exactly as `IPublish` does for NuGet feeds: ```csharp class Build : FalloutBuild, IPublishVsix diff --git a/test/integration/extension.test.ts b/test/integration/extension.test.ts index 6d4696a..c0f0955 100644 --- a/test/integration/extension.test.ts +++ b/test/integration/extension.test.ts @@ -34,10 +34,16 @@ suite('extension host', () => { const item = { target: { name: 'Compile', declaredIn, default: true, listed: true, dependsOn: [], after: [], triggeredBy: [], triggers: [] } }; await vscode.commands.executeCommand('fallout.goToTarget', item); - const editor = await waitFor(() => - vscode.window.activeTextEditor?.document.fileName.endsWith('.cs') ? vscode.window.activeTextEditor : undefined); + // The command is fire-and-forget, and the editor becomes active before its selection + // is applied, so wait for the final state rather than the first sign of an editor. + const editor = await waitFor(() => { + const active = vscode.window.activeTextEditor; + return active + && path.basename(active.document.fileName) === file + && /Target Compile =>/.test(active.document.lineAt(active.selection.start.line).text) + ? active : undefined; + }, `${file} open with the selection on "Target Compile =>"`); assert.equal(path.basename(editor.document.fileName), file); - assert.match(editor.document.lineAt(editor.selection.start.line).text, /Target Compile =>/); }); } @@ -45,12 +51,12 @@ suite('extension host', () => { await vscode.commands.executeCommand('fallout.showGraph'); const tab = await waitFor(() => vscode.window.tabGroups.all .flatMap(g => g.tabs) - .find(t => t.label === 'Fallout Build Graph')); + .find(t => t.label === 'Fallout Build Graph'), 'a tab labelled "Fallout Build Graph"'); assert.equal(tab.label, 'Fallout Build Graph'); }); }); -async function waitFor(probe: () => T | undefined, timeoutMs = 15000): Promise { +async function waitFor(probe: () => T | undefined, what: string, timeoutMs = 15000): Promise { const deadline = Date.now() + timeoutMs; for (;;) { const value = probe(); @@ -58,7 +64,7 @@ async function waitFor(probe: () => T | undefined, timeoutMs = 15000): Promis return value; } if (Date.now() > deadline) { - throw new Error('timed out waiting for condition'); + throw new Error(`timed out waiting for ${what}`); } await new Promise(r => setTimeout(r, 100)); } diff --git a/test/run-node-tests.js b/test/run-node-tests.js new file mode 100644 index 0000000..feaae09 --- /dev/null +++ b/test/run-node-tests.js @@ -0,0 +1,32 @@ +// Runs `node --test` over every *.test.js under a directory. +// +// Explicit file arguments behave the same on every Node version; directory and glob arguments +// to `--test` do not (Node 20 recurses into a directory, Node 22 treats it as a file, globs +// need 21+). CI runs on whatever Node the runner image ships, so don't depend on either. +// +// Usage: node test/run-node-tests.js (e.g. out-test/test/unit) +const { readdirSync, statSync } = require('node:fs'); +const { join } = require('node:path'); +const { spawnSync } = require('node:child_process'); + +function testFiles(dir) { + return readdirSync(dir).flatMap(name => { + const full = join(dir, name); + if (statSync(full).isDirectory()) { + return testFiles(full); + } + return name.endsWith('.test.js') ? [full] : []; + }); +} + +const dir = process.argv[2]; +if (!dir) { + console.error('usage: node test/run-node-tests.js '); + process.exit(2); +} +const files = testFiles(dir); +if (files.length === 0) { + console.error(`no *.test.js files under ${dir} (did the tests compile?)`); + process.exit(1); +} +process.exit(spawnSync(process.execPath, ['--test', ...files], { stdio: 'inherit' }).status ?? 1);