From fe4c3e0e733fa89ff1394b56ab5a387401336d12 Mon Sep 17 00:00:00 2001 From: Christian Findlay <16697547+MelbourneDeveloper@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:27:26 +1100 Subject: [PATCH 1/6] Attach reliability: twenty consecutive attaches to one running process each pause it and detach without killing it; the attach suite's shared helpers move into debug-attach-kit --- docs/plans/DEBUGGING-PLAN.md | 7 +- .../src/test/suite/debug-attach-e2e.test.ts | 170 ++---------------- .../vscode/src/test/suite/debug-attach-kit.ts | 166 +++++++++++++++++ .../debug-attach-reliability-e2e.test.ts | 98 ++++++++++ src/editors/vscode/test-chunks.json | 3 +- 5 files changed, 283 insertions(+), 161 deletions(-) create mode 100644 src/editors/vscode/src/test/suite/debug-attach-kit.ts create mode 100644 src/editors/vscode/src/test/suite/debug-attach-reliability-e2e.test.ts diff --git a/docs/plans/DEBUGGING-PLAN.md b/docs/plans/DEBUGGING-PLAN.md index cf7ea737..e7af0d4d 100644 --- a/docs/plans/DEBUGGING-PLAN.md +++ b/docs/plans/DEBUGGING-PLAN.md @@ -643,8 +643,9 @@ waiting; a debug run never writes the result cache. `dap-router.ts` `onChildGone` (idempotent), `dap-wire.ts:143` `watchDeath`, `child-signal.ts:28` `signalChild`; tests `debug-adapter-startup.test.ts` (all seven cases) -- [ ] Attach reliability: ≥95% success rate across 20 consecutive attach attempts — attach is - red (§4.3) +- [x] Attach reliability: ≥95% success rate across 20 consecutive attach attempts — each + attach pauses the live thread and detaches without killing the process; test + `debug-attach-reliability-e2e.test.ts` (20/20 locally on macOS ARM64) - [ ] Full E2E test suite passes in CI on Linux x64, macOS ARM64, Windows x64 ### 4.14 Fixed on this branch @@ -789,7 +790,7 @@ Goal: Replace netcoredbg with a C# Tier 4 sidecar achieving full vsdbg parity. C - [ ] Implement `attach`: `DbgShim.RegisterForRuntimeStartup` (race-free; no `0x80070057`) - [ ] Implement attach-by-name: resolve PID then attach - [ ] Implement child process auto-attach via `ICorDebugManagedCallback::CreateProcess` -- [ ] E2E test: reliable attach — 20 consecutive attaches succeed (regression for netcoredbg issue #205 scenario) +- [x] E2E test: reliable attach — 20 consecutive attaches succeed (regression for netcoredbg issue #205 scenario): `debug-attach-reliability-e2e.test.ts` ### 5.4 Full Breakpoint Implementation diff --git a/src/editors/vscode/src/test/suite/debug-attach-e2e.test.ts b/src/editors/vscode/src/test/suite/debug-attach-e2e.test.ts index 16a1f937..807d6b49 100644 --- a/src/editors/vscode/src/test/suite/debug-attach-e2e.test.ts +++ b/src/editors/vscode/src/test/suite/debug-attach-e2e.test.ts @@ -10,179 +10,35 @@ // makes it an attach. It sleeps long enough to be caught, so nothing about this // suite is a race against process startup. import * as assert from 'node:assert/strict'; -import { spawn, type ChildProcess } from 'node:child_process'; import * as vscode from 'vscode'; -import { MODE, type DebugFixture } from './debug-fixture-programs'; import { - CMD_STOP, - assertStopReason, - methodOf, - localsOf, - stackFrames, - variableNamed, -} from './debug-drive-kit'; + attachConfig, + attachStackUnwalkable, + isAlive, + killSpawned, + pauseAttached, + startAliveOutside, + walkAttachedStack, +} from './debug-attach-kit'; +import { MODE } from './debug-fixture-programs'; +import { CMD_STOP, assertStopReason, methodOf, localsOf, variableNamed } from './debug-drive-kit'; import { assertCleanSession, stopDebuggee, useDebuggee, debugTest } from './debug-suite-kit'; import { assertPauseFor, refusedLaunch, startAttached } from './debug-flow-kit'; -import { DEBUG_TYPE_ID } from './run-debug-kit'; import { commandTokens, isProcessAlive, matchesProcessName, resolveAttachTarget, } from '../../attach-target.js'; -import { deepEq, eq, neq, pollUntilResult, requireAt, sleep } from './test-helpers'; -import { DEBUG_TEST_MS, PROCESS_START_MS, QUIET_MS, SETTLE_MS } from './test-timeouts'; - -/** A running debuggee the test owns, plus the output it has produced. */ -interface RunningDebuggee { - readonly child: ChildProcess; - readonly pid: number; - readonly output: () => string; -} - -/** Every child this suite spawned, so teardown can never leak one. */ -const spawned: ChildProcess[] = []; - -/** Start the fixture assembly outside the debugger and wait until it is alive. */ -async function startOutsideDebugger(dll: string, cwd: string): Promise { - let text = ''; - const child = spawn('dotnet', [dll, MODE.wait], { cwd, stdio: ['ignore', 'pipe', 'pipe'] }); - spawned.push(child); - child.stdout?.on('data', (chunk: Buffer) => (text += chunk.toString('utf8'))); - child.stderr?.on('data', (chunk: Buffer) => (text += chunk.toString('utf8'))); - const pid = child.pid ?? 0; - assert.ok(pid > 0, 'the fixture process must start outside the debugger before an attach'); - await pollUntilResult( - async () => text, - (seen) => seen.includes('boxed=8'), - PROCESS_START_MS, - 100, - ); - assert.ok( - text.includes('boxed=8'), - `the debuggee must be running before an attach; saw: ${text}`, - ); - return { child, pid, output: () => text }; -} - -/** The attach configuration of [DEBUG-FEATURES-LAUNCH]'s schema block. */ -function attachConfig(extra: Record): vscode.DebugConfiguration { - return { - type: DEBUG_TYPE_ID, - request: 'attach', - name: 'Attach to Process', - justMyCode: true, - ...extra, - }; -} - -/** Start the fixture outside the debugger, asserted ALIVE: the premise of every attach. */ -async function startAliveOutside(fixture: DebugFixture, why: string): Promise { - const running = await startOutsideDebugger(fixture.dll, fixture.dir); - assert.ok(isAlive(running.pid), why); - return running; -} - -/** True while the process is still alive — signal 0 probes without signalling. */ -function isAlive(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -/** - * True when an attach session shows netcoredbg's broken attach stack walk. - * - * Upstream defect (Samsung/netcoredbg #199, #205): the `attach` request ACKs, - * `threads` eventually lists the paused thread and the `pause` stop arrives, - * but `stackTrace` answers an empty frame list forever — the ICorDebug stack - * walk never engages for a process netcoredbg did not launch itself. No - * SharpLsp-side fix exists: the frames are simply not reported. [DEBUG-GAPS] - * "Attach error `0x80070057`" documents the refusal half of the same defect; - * the retry the spec commits to recovers the refusal, not this. - */ -function attachStackUnwalkable(frames: readonly { readonly id: number }[]): boolean { - return frames.length === 0 || frames.every((frame) => frame.id <= 0); -} - -/** - * Read the stack, treating the upstream attach defect as "unwalkable". - * - * netcoredbg's broken attach stack walk shows up two ways: frames that carry no - * usable id, and — on the Windows runner — a `stackTrace` request that fails - * outright with 0x80070057 (E_INVALIDARG). Both are the same upstream defect and - * get the same treatment the suite already documents below. Every other error - * still propagates: a swallowed `stackTrace` failure would hide a real one. - */ -async function walkAttachedStack( - session: vscode.DebugSession, - threadId: number, -): Promise>> { - try { - return await stackFrames(session, threadId); - } catch (error) { - if (String(error).includes('0x80070057')) return []; - throw error; - } -} - -/** Wait for attach configuration to finish, then issue the headless Pause gesture. */ -async function pauseAttached(session: vscode.DebugSession): Promise { - const threadId = await pollUntilResult( - async () => { - try { - const threads: unknown = await session.customRequest('threads'); - if (typeof threads !== 'object' || threads === null) return 0; - const listed: unknown = (threads as Record)['threads']; - if (!Array.isArray(listed)) return 0; - const first = listed[0]; - return typeof first === 'object' && first !== null - ? Number((first as Record)['id'] ?? 0) - : 0; - } catch { - // The session object exists before netcoredbg has finished attaching. - return 0; - } - }, - (candidate) => candidate > 0, - 60_000, - 100, - ); - assert.ok(threadId > 0, 'an attached process must expose a live thread before it can be paused'); - await session.customRequest('pause', { threadId }); - return threadId; -} +import { deepEq, eq, neq, requireAt, sleep } from './test-helpers'; +import { DEBUG_TEST_MS, QUIET_MS } from './test-timeouts'; suite('Debug attach — taking control of a process that is already running', () => { const debuggee = useDebuggee('debug-attach-cs-', 'csharp'); teardown(async function () { - // Killing is asynchronous, and this suite resolves debuggees BY NAME. - // - // Signalling and moving on let the next test spawn a second `StepTarget` - // while the previous one was still dying, so a name that must resolve to - // exactly one pid briefly matched two and the attach refused to start. - // Wait for each child to actually be gone ([DIST-CI-VSIX-SHARDS-TIMEOUTS]). this.timeout(DEBUG_TEST_MS); - const killed: number[] = []; - while (spawned.length > 0) { - const child = spawned.pop(); - if (child?.exitCode === null) { - child.kill('SIGKILL'); - if (child.pid !== undefined) killed.push(child.pid); - } - } - for (const pid of killed) { - await pollUntilResult( - async () => isAlive(pid), - (alive) => !alive, - SETTLE_MS, - 50, - ); - } + await killSpawned(); }); // Implements [DEBUG-FEATURES-LAUNCH] "Attach to running process by PID | P1". diff --git a/src/editors/vscode/src/test/suite/debug-attach-kit.ts b/src/editors/vscode/src/test/suite/debug-attach-kit.ts new file mode 100644 index 00000000..14348356 --- /dev/null +++ b/src/editors/vscode/src/test/suite/debug-attach-kit.ts @@ -0,0 +1,166 @@ +// What every attach suite shares: a debuggee started OUTSIDE the debugger, the +// attach configuration of [DEBUG-FEATURES-LAUNCH]'s schema, the headless Pause +// gesture, and the teardown that never leaks a spawned process. +import * as assert from 'node:assert/strict'; +import { spawn, type ChildProcess } from 'node:child_process'; +import type * as vscode from 'vscode'; +import { MODE, type DebugFixture } from './debug-fixture-programs'; +import { stackFrames } from './debug-drive-kit'; +import { DEBUG_TYPE_ID } from './run-debug-kit'; +import { pollUntilResult } from './test-helpers'; +import { PROCESS_START_MS, SETTLE_MS } from './test-timeouts'; + +/** A running debuggee the test owns, plus the output it has produced. */ +export interface RunningDebuggee { + readonly child: ChildProcess; + readonly pid: number; + readonly output: () => string; +} + +/** Every child this suite spawned, so teardown can never leak one. */ +export const spawned: ChildProcess[] = []; + +/** Start the fixture assembly outside the debugger and wait until it is alive. */ +export async function startOutsideDebugger(dll: string, cwd: string): Promise { + let text = ''; + const child = spawn('dotnet', [dll, MODE.wait], { cwd, stdio: ['ignore', 'pipe', 'pipe'] }); + spawned.push(child); + child.stdout?.on('data', (chunk: Buffer) => (text += chunk.toString('utf8'))); + child.stderr?.on('data', (chunk: Buffer) => (text += chunk.toString('utf8'))); + const pid = child.pid ?? 0; + assert.ok(pid > 0, 'the fixture process must start outside the debugger before an attach'); + await pollUntilResult( + async () => text, + (seen) => seen.includes('boxed=8'), + PROCESS_START_MS, + 100, + ); + assert.ok( + text.includes('boxed=8'), + `the debuggee must be running before an attach; saw: ${text}`, + ); + return { child, pid, output: () => text }; +} + +/** The attach configuration of [DEBUG-FEATURES-LAUNCH]'s schema block. */ +export function attachConfig(extra: Record): vscode.DebugConfiguration { + return { + type: DEBUG_TYPE_ID, + request: 'attach', + name: 'Attach to Process', + justMyCode: true, + ...extra, + }; +} + +/** Start the fixture outside the debugger, asserted ALIVE: the premise of every attach. */ +export async function startAliveOutside( + fixture: DebugFixture, + why: string, +): Promise { + const running = await startOutsideDebugger(fixture.dll, fixture.dir); + assert.ok(isAlive(running.pid), why); + return running; +} + +/** True while the process is still alive — signal 0 probes without signalling. */ +export function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +/** + * True when an attach session shows netcoredbg's broken attach stack walk. + * + * Upstream defect (Samsung/netcoredbg #199, #205): the `attach` request ACKs, + * `threads` eventually lists the paused thread and the `pause` stop arrives, + * but `stackTrace` answers an empty frame list forever — the ICorDebug stack + * walk never engages for a process netcoredbg did not launch itself. No + * SharpLsp-side fix exists: the frames are simply not reported. [DEBUG-GAPS] + * "Attach error `0x80070057`" documents the refusal half of the same defect; + * the retry the spec commits to recovers the refusal, not this. + */ +export function attachStackUnwalkable(frames: readonly { readonly id: number }[]): boolean { + return frames.length === 0 || frames.every((frame) => frame.id <= 0); +} + +/** + * Read the stack, treating the upstream attach defect as "unwalkable". + * + * netcoredbg's broken attach stack walk shows up two ways: frames that carry no + * usable id, and — on the Windows runner — a `stackTrace` request that fails + * outright with 0x80070057 (E_INVALIDARG). Both are the same upstream defect and + * get the same treatment the suite already documents below. Every other error + * still propagates: a swallowed `stackTrace` failure would hide a real one. + */ +export async function walkAttachedStack( + session: vscode.DebugSession, + threadId: number, +): Promise>> { + try { + return await stackFrames(session, threadId); + } catch (error) { + if (String(error).includes('0x80070057')) return []; + throw error; + } +} + +/** Wait for attach configuration to finish, then issue the headless Pause gesture. */ +export async function pauseAttached(session: vscode.DebugSession): Promise { + const threadId = await pollUntilResult( + async () => { + try { + const threads: unknown = await session.customRequest('threads'); + if (typeof threads !== 'object' || threads === null) return 0; + const listed: unknown = (threads as Record)['threads']; + if (!Array.isArray(listed)) return 0; + const first = listed[0]; + return typeof first === 'object' && first !== null + ? Number((first as Record)['id'] ?? 0) + : 0; + } catch { + // The session object exists before netcoredbg has finished attaching. + return 0; + } + }, + (candidate) => candidate > 0, + 60_000, + 100, + ); + assert.ok(threadId > 0, 'an attached process must expose a live thread before it can be paused'); + await session.customRequest('pause', { threadId }); + return threadId; +} + +/** + * Kill every child the attach suites spawned and wait until each is gone. + * + * Killing is asynchronous, and this suite resolves debuggees BY NAME. + * + * Signalling and moving on let the next test spawn a second `StepTarget` + * while the previous one was still dying, so a name that must resolve to + * exactly one pid briefly matched two and the attach refused to start. + * Wait for each child to actually be gone ([DIST-CI-VSIX-SHARDS-TIMEOUTS]). + */ +export async function killSpawned(): Promise { + const killed: number[] = []; + while (spawned.length > 0) { + const child = spawned.pop(); + if (child?.exitCode === null) { + child.kill('SIGKILL'); + if (child.pid !== undefined) killed.push(child.pid); + } + } + for (const pid of killed) { + await pollUntilResult( + async () => isAlive(pid), + (alive) => !alive, + SETTLE_MS, + 50, + ); + } +} diff --git a/src/editors/vscode/src/test/suite/debug-attach-reliability-e2e.test.ts b/src/editors/vscode/src/test/suite/debug-attach-reliability-e2e.test.ts new file mode 100644 index 00000000..b0d18d1a --- /dev/null +++ b/src/editors/vscode/src/test/suite/debug-attach-reliability-e2e.test.ts @@ -0,0 +1,98 @@ +// Attach reliability: twenty consecutive attaches to ONE long-running process. +// netcoredbg's attach is known to refuse intermittently (Samsung/netcoredbg +// #205, `0x80070057`), and [DEBUG-GAPS] commits SharpLsp to absorb that with +// retries. Each attach must be accepted, pause the live thread, and detach +// without killing the process, so the twenty-first attach finds it alive. +// +// Implements the "Attach reliability" P1 row of [DEBUG-FEATURES-LAUNCH]. +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { + attachConfig, + isAlive, + killSpawned, + pauseAttached, + startAliveOutside, +} from './debug-attach-kit'; +import type { DapRecorder } from './debug-dap-kit'; +import { CMD_STOP, assertStopReason } from './debug-drive-kit'; +import { startAttached } from './debug-flow-kit'; +import { assertCleanSession, stopDebuggee, useDebuggee } from './debug-suite-kit'; +import { eq, sleep } from './test-helpers'; +import { DEBUG_TEST_MS, QUIET_MS } from './test-timeouts'; + +/** Consecutive attaches the plan's reliability row asks for. */ +const ATTEMPTS = 20; + +/** At least 95% of them must succeed. */ +const REQUIRED = Math.ceil(ATTEMPTS * 0.95); + +/** Why one attach failed, or `undefined` when it attached, paused and detached. */ +async function attachOnce( + folder: vscode.WorkspaceFolder, + pid: number, + recorder: DapRecorder, +): Promise { + const before = recorder.stops().length; + try { + const session = await startAttached( + folder, + attachConfig({ processId: pid }), + 'refused', + 'no session', + ); + eq(Number(session.configuration['processId']), pid, 'each attach aims at the same pid'); + await pauseAttached(session); + await recorder.waitForStops(before + 1); + return undefined; + } catch (error) { + return String(error); + } finally { + await vscode.commands.executeCommand(CMD_STOP); + await stopDebuggee(); + } +} + +suite('Debug attach — twenty consecutive attaches to one running process', () => { + const debuggee = useDebuggee('debug-attach-twenty-', 'csharp'); + + teardown(async function () { + this.timeout(DEBUG_TEST_MS); + await killSpawned(); + }); + + test('at least 19 of 20 attaches pause the live process, and every detach leaves it running', async function () { + this.timeout(DEBUG_TEST_MS * ATTEMPTS); + const { fixture, folder, recorder } = debuggee(); + const running = await startAliveOutside( + fixture, + 'the process is alive before the first attach', + ); + + const failures: string[] = []; + for (let attempt = 1; attempt <= ATTEMPTS; attempt += 1) { + const failure = await attachOnce(folder, running.pid, recorder); + if (failure !== undefined) failures.push(`attempt ${String(attempt)}: ${failure}`); + assert.ok( + isAlive(running.pid), + `attempt ${String(attempt)} detached without killing the process`, + ); + eq( + vscode.debug.activeDebugSession, + undefined, + `attempt ${String(attempt)} left no session behind`, + ); + } + + assert.ok( + ATTEMPTS - failures.length >= REQUIRED, + `${String(REQUIRED)} of ${String(ATTEMPTS)} attaches must succeed; failures: ${failures.join(' | ')}`, + ); + const stops = recorder.stops(); + assert.ok(stops.length >= REQUIRED, 'every successful attach recorded its own pause'); + for (const stop of stops) assertStopReason(stop, 'pause', 'an attach pause'); + await sleep(QUIET_MS); + assert.ok(isAlive(running.pid), 'twenty detaches later, the process is still the user’s'); + assertCleanSession(debuggee(), 'twenty consecutive attaches'); + }); +}); diff --git a/src/editors/vscode/test-chunks.json b/src/editors/vscode/test-chunks.json index 7e6c30a9..1504d17a 100644 --- a/src/editors/vscode/test-chunks.json +++ b/src/editors/vscode/test-chunks.json @@ -122,7 +122,8 @@ "debug-fsharp-stepping-e2e.test.js", "debug-fsharp-inspection-e2e.test.js", "debug-hot-reload-e2e.test.js", - "debug-attach-e2e.test.js" + "debug-attach-e2e.test.js", + "debug-attach-reliability-e2e.test.js" ] }, "debug-tests": { From 2e8d72a084b9eeb39682b153b30f0b9f72d43c0d Mon Sep 17 00:00:00 2001 From: Christian Findlay <16697547+MelbourneDeveloper@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:39:45 +1100 Subject: [PATCH 2/6] SIDECAR-LIFECYCLE-PLAN: the 64MiB pre-allocation frame check is kept and tested in both tiers --- docs/plans/SIDECAR-LIFECYCLE-PLAN.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/plans/SIDECAR-LIFECYCLE-PLAN.md b/docs/plans/SIDECAR-LIFECYCLE-PLAN.md index 21df146e..2a876c0e 100644 --- a/docs/plans/SIDECAR-LIFECYCLE-PLAN.md +++ b/docs/plans/SIDECAR-LIFECYCLE-PLAN.md @@ -484,7 +484,9 @@ item and its required evidence are complete. - [ ] Poison and restart when a written request cannot be drained within its 120s/600s budget. - [ ] Distinguish clean EOF between frames from truncated length/payload EOF and classify the latter as a protocol failure. -- [ ] Keep the 64MiB frame check before allocation in Rust and .NET. +- [x] Keep the 64MiB frame check before allocation in Rust and .NET — `transport.rs` `MAX_FRAME_LEN` + (test `rejects_oversized_frame_length`), `FramedTransport.cs` `MaxFrameLength` (tests + `ReadFrameAsync_rejects_oversized_length_prefix`, `WriteFrameAsync_rejects_oversized_payload`). - [ ] Add a real wrong-ID scenario proving the stale response reaches neither current nor next caller. - [ ] Add a real notification-before-response scenario proving both are delivered correctly. From 4dce2231d572ccf4893a065d78b8130ce68a7a74 Mon Sep 17 00:00:00 2001 From: Christian Findlay <16697547+MelbourneDeveloper@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:41:57 +1100 Subject: [PATCH 3/6] Sidecar endpoints carry 64 OS-CSPRNG bits: the IPC token XORs a getrandom nonce into the root/pid/counter hash, 16 hex digits, so no local process can predict and pre-bind it --- Cargo.lock | 1 + docs/plans/SIDECAR-LIFECYCLE-PLAN.md | 3 ++ src/sharplsp/Cargo.toml | 3 ++ src/sharplsp/src/sidecar/manager/launch.rs | 46 ++++++++++++++++++++-- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ed658e9c..17ea8cef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2131,6 +2131,7 @@ dependencies = [ "crossbeam-channel", "dashmap", "flate2", + "getrandom 0.4.3", "globset", "lsp-profiler", "lsp-profiler-dotnet", diff --git a/docs/plans/SIDECAR-LIFECYCLE-PLAN.md b/docs/plans/SIDECAR-LIFECYCLE-PLAN.md index 2a876c0e..9faca80b 100644 --- a/docs/plans/SIDECAR-LIFECYCLE-PLAN.md +++ b/docs/plans/SIDECAR-LIFECYCLE-PLAN.md @@ -438,6 +438,9 @@ item and its required evidence are complete. ### 11.5 Endpoint leases and READY `[SIDECAR-PLAN-CHECKLIST-STARTUP]` - [ ] Generate at least 64 unpredictable bits from the OS CSPRNG for every spawn attempt. + Progress: every MANAGER's endpoint now carries 64 `getrandom` bits (`launch.rs` + `endpoint_nonce`, test `endpoint_tokens_are_unpredictable_and_constant_length`); a fresh + nonce per restart lands with the per-generation endpoint item below. - [ ] Include language, host PID, generation, and nonce in a length-bounded platform endpoint. - [ ] Create/use a validated owner-only Unix runtime directory and keep socket mode `0600`. - [ ] Keep `PipeOptions.CurrentUserOnly` and a single named-pipe server instance on Windows. diff --git a/src/sharplsp/Cargo.toml b/src/sharplsp/Cargo.toml index ccc53b61..9c295d8b 100644 --- a/src/sharplsp/Cargo.toml +++ b/src/sharplsp/Cargo.toml @@ -19,6 +19,9 @@ shipwright = "0.11" shipwright-manifest = "0.11" # Implements the executable packaging contract [BINARY-RUST]. +# OS CSPRNG for unpredictable sidecar endpoints [SIDECAR-STARTUP-ENDPOINT] +getrandom = "0.4" + # LSP lsp-server = "0.10" lsp-types = "0.97" diff --git a/src/sharplsp/src/sidecar/manager/launch.rs b/src/sharplsp/src/sidecar/manager/launch.rs index b40772bd..c2576d75 100644 --- a/src/sharplsp/src/sidecar/manager/launch.rs +++ b/src/sharplsp/src/sidecar/manager/launch.rs @@ -161,9 +161,10 @@ static IPC_SEQUENCE: AtomicU64 = AtomicU64::new(0); /// before READY; on Unix it deletes and steals the live socket. Folding the /// process id and a monotonic counter into the hash keeps the token short /// (constant length, so it never trips the Unix socket-path limit) while making -/// it unique across hosts (pid) and within a host (counter). It is computed once -/// per manager and reused across restarts, so a restart keeps its own endpoint. -// TODO [SIDECAR-STARTUP-ENDPOINT]: generate a fresh OS-CSPRNG nonce for every spawn generation. +/// it unique across hosts (pid) and within a host (counter). 64 OS-CSPRNG bits +/// are folded in, so no other local process can predict the endpoint and bind it +/// first. It is computed once per manager and reused across restarts, so a +/// restart keeps its own endpoint. [SIDECAR-STARTUP-ENDPOINT] fn unique_endpoint_token(workspace_root: &Path) -> String { let sequence = IPC_SEQUENCE.fetch_add(1, Ordering::Relaxed); let key = format!( @@ -172,7 +173,19 @@ fn unique_endpoint_token(workspace_root: &Path) -> String { std::process::id(), sequence ); - format!("{:x}", fxhash(key.as_bytes())) + format!( + "{:016x}", + u64::from(fxhash(key.as_bytes())) ^ endpoint_nonce() + ) +} + +/// 64 unpredictable bits from the OS CSPRNG. Its failure is logged, never +/// silent, and leaves the hash alone: still unique, only predictable. +fn endpoint_nonce() -> u64 { + getrandom::u64().unwrap_or_else(|error| { + warn!(%error, "OS CSPRNG unavailable; the sidecar endpoint is predictable"); + 0 + }) } /// Build a platform-appropriate IPC path for a sidecar. @@ -228,3 +241,28 @@ pub(super) fn fxhash(bytes: &[u8]) -> u32 { } hash } + +#[cfg(test)] +mod tests { + use super::{endpoint_nonce, unique_endpoint_token}; + use std::collections::HashSet; + use std::path::Path; + + /// [SIDECAR-STARTUP-ENDPOINT]: every token carries fresh CSPRNG bits at a + /// constant length, so it is unpredictable and never trips the socket-path limit. + #[test] + fn endpoint_tokens_are_unpredictable_and_constant_length() { + let nonces: HashSet = (0..64).map(|_| endpoint_nonce()).collect(); + assert_eq!(nonces.len(), 64, "every nonce is fresh"); + assert!(!nonces.contains(&0), "the CSPRNG answered"); + let root = Path::new("/workspace"); + let tokens: HashSet = (0..64).map(|_| unique_endpoint_token(root)).collect(); + assert_eq!(tokens.len(), 64, "the same root never repeats a token"); + assert!( + tokens + .iter() + .all(|token| token.len() == 16 && token.bytes().all(|b| b.is_ascii_hexdigit())), + "every token is 16 hex digits" + ); + } +} From 0b0210c81abf1284b97b0d5ee9aef643b52be859 Mon Sep 17 00:00:00 2001 From: Christian Findlay <16697547+MelbourneDeveloper@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:54:46 +1100 Subject: [PATCH 4/6] Test Explorer tags a row fsharp when an .fsproj built it, not when its name looks like Expecto or FsCheck (#604): every F# test is tagged, no C# test is; the name-guessing helpers are deleted --- docs/plans/CSDEVKIT-PARITY-PLAN.md | 2 +- src/editors/vscode/src/test-items.ts | 19 ++++--- src/editors/vscode/src/test-language.ts | 53 +++++++++++++++++++ src/editors/vscode/src/test-targets.ts | 9 ---- .../vscode/src/test/suite/netfx-test-kit.ts | 11 ++-- .../test/suite/real-repo-netfx-fsharp.test.ts | 4 +- .../src/test/suite/real-repo-netfx-kit.ts | 4 +- .../test/suite/test-explorer-assert-kit.ts | 22 ++++++-- .../src/test/suite/test-explorer-e2e.test.ts | 26 +++++---- .../suite/test-explorer-frameworks.test.ts | 29 +++++----- .../test-explorer-fsharp-frameworks.test.ts | 11 ++-- .../src/test/suite/test-explorer-kit.ts | 30 ++++++++--- .../test/suite/test-explorer-netfx.test.ts | 19 ++++--- .../test/suite/test-explorer-windows.test.ts | 3 +- .../src/test/suite/test-language.test.ts | 46 ++++++++++++++++ .../src/test/suite/testing-lens-e2e.test.ts | 13 +---- src/editors/vscode/src/testing.ts | 1 - src/editors/vscode/test-chunks.json | 1 + 18 files changed, 221 insertions(+), 82 deletions(-) create mode 100644 src/editors/vscode/src/test-language.ts create mode 100644 src/editors/vscode/src/test/suite/test-language.test.ts diff --git a/docs/plans/CSDEVKIT-PARITY-PLAN.md b/docs/plans/CSDEVKIT-PARITY-PLAN.md index e4308c32..10171b0e 100644 --- a/docs/plans/CSDEVKIT-PARITY-PLAN.md +++ b/docs/plans/CSDEVKIT-PARITY-PLAN.md @@ -299,7 +299,7 @@ Features users expect within the first day of use. - [x] Editor decorations (green play button, red/green/skip indicators), spec `[TEST-STATUS-LENS]` - [x] Expecto discovery, runs and debugging — `test-explorer-fsharp-frameworks.test.ts` (list paths with spaces and nesting; pass, fail with the expectation's message, `ptestCase` skipped) and `debug-test-expecto-e2e.test.ts` - [x] FsCheck property tests run-verified — `test-explorer-fsharp-frameworks.test.ts` *FsCheck: a property that holds passes, a falsified one fails with its counterexample, a skipped one is skipped* (FsCheck.Xunit 3.6.0) - - [ ] The `fsharp` tag derived from the project's language instead of the test name (today a real Expecto id is untagged and a C# `PropertyTests` is tagged F#) — [#604](https://github.com/Nimblesite/SharpLsp/issues/604) + - [x] The `fsharp` tag derived from the project's language instead of the test name — [#604](https://github.com/Nimblesite/SharpLsp/issues/604); `test-language.ts` `projectLanguageOf` (the listing's project, else the nearest project file above the assembly), proven by `test-explorer-fsharp-frameworks.test.ts` (every Expecto and FsCheck row tagged), `test-explorer-frameworks.test.ts` (F# xUnit/NUnit/MSTest tagged, C# untagged) and `test-language.test.ts` (a C# `PropertyTests` stays C#). Close #604 only after the released binaries prove it. - [x] Code coverage integration, spec `[TEST-COVERAGE]` - [x] **P2.3: Build Integration** diff --git a/src/editors/vscode/src/test-items.ts b/src/editors/vscode/src/test-items.ts index 6749832f..cd3f759e 100644 --- a/src/editors/vscode/src/test-items.ts +++ b/src/editors/vscode/src/test-items.ts @@ -17,7 +17,7 @@ import * as vscode from 'vscode'; import { compareFrameworks, frameworkSummary, TFM_TAG_PREFIX } from './test-frameworks.js'; import type { FrameworkBuild, TestAssemblyListing, TestLocation } from './test-listing-model.js'; -import { isExpectoTest, isFsCheckTest } from './test-targets.js'; +import { projectLanguageOf } from './test-language.js'; /** * Id prefix marking the row that explains WHY discovery failed. Error rows are @@ -49,23 +49,25 @@ function rangeFor(context: ItemContext, fullName: string): vscode.Range | undefi } /** - * Build a TestItem for a fully-qualified name, tagging F# tests and, in a - * multi-targeted project, each framework it is built for ([NETFX-TEST-DISCOVERY]). + * Build a TestItem for a fully-qualified name, tagging the tests an `.fsproj` + * built (#604) and, in a multi-targeted project, each framework it is built for + * ([NETFX-TEST-DISCOVERY]). */ export function makeTestItem( context: ItemContext, fullName: string, frameworks: readonly string[] = [], + fsharp = false, ): vscode.TestItem { const parts = fullName.split('.'); const label = parts.at(-1) ?? fullName; const item = context.controller.createTestItem(fullName, label, uriFor(context, fullName)); item.description = fullName; item.range = rangeFor(context, fullName); - const fsharp = isExpectoTest(fullName) || isFsCheckTest(fullName) ? ['fsharp'] : []; - item.tags = [...fsharp, ...frameworks.map((each) => `${TFM_TAG_PREFIX}${each}`)].map( - (id) => new vscode.TestTag(id), - ); + item.tags = [ + ...(fsharp ? ['fsharp'] : []), + ...frameworks.map((each) => `${TFM_TAG_PREFIX}${each}`), + ].map((id) => new vscode.TestTag(id)); return item; } @@ -131,6 +133,7 @@ export function makeAssemblyItem( const builds = assembly.frameworks ?? []; if (builds.length > 1) root.description = frameworkSummary(builds); const frameworks = frameworksByTest(builds); + const fsharp = projectLanguageOf(assembly) === 'fsharp'; const namespaces = new Map(); const classes = new Map(); for (const fqn of assembly.names) { @@ -148,7 +151,7 @@ export function makeAssemblyItem( label: classLabel, }); } - parent.children.add(makeTestItem(context, fqn, frameworks.get(fqn))); + parent.children.add(makeTestItem(context, fqn, frameworks.get(fqn), fsharp)); } return root; } diff --git a/src/editors/vscode/src/test-language.ts b/src/editors/vscode/src/test-language.ts new file mode 100644 index 00000000..17ee2ffd --- /dev/null +++ b/src/editors/vscode/src/test-language.ts @@ -0,0 +1,53 @@ +/** + * The language of the project that built a test assembly, so the Testing view + * tags every F# test `fsharp` — xUnit, NUnit, MSTest, Expecto and FsCheck alike + * — and no C# test, whatever the tests are called (#604). + * + * The project is the one the listing names, else the nearest project file above + * the assembly's output folder (`bin///`). Nothing found is + * `undefined`: the row is left untagged rather than guessed. + * + * Implements [TEST-EXPLORER]. + */ + +import * as fs from 'node:fs'; +import { directoryOf, hasExtension, isProjectFile, joinPath } from './paths'; +import type { TestAssemblyListing } from './test-listing-model.js'; + +/** A .NET project language a test can be written in. */ +export type ProjectLanguage = 'fsharp' | 'csharp'; + +/** How many folders above the assembly a project file may sit (`bin//`, plus RID). */ +const MAX_LEVELS = 5; + +/** The language of the project that built `assembly`, when one can be found. */ +export function projectLanguageOf(assembly: TestAssemblyListing): ProjectLanguage | undefined { + const project = assembly.projectFile ?? nearestProject(directoryOf(assembly.path)); + if (project === undefined) return undefined; + return hasExtension(project, '.fsproj') ? 'fsharp' : 'csharp'; +} + +/** The first project file in `dir` or the folders above it, within {@link MAX_LEVELS}. */ +function nearestProject(dir: string): string | undefined { + let current = dir; + for (let level = 0; level <= MAX_LEVELS; level += 1) { + const found = projectFilesIn(current); + if (found.length > 0) return found.find((file) => hasExtension(file, '.fsproj')) ?? found[0]; + const parent = directoryOf(current); + if (parent === current) return undefined; + current = parent; + } + return undefined; +} + +/** The project files directly inside `dir`; none when it cannot be read. */ +function projectFilesIn(dir: string): string[] { + try { + return fs + .readdirSync(dir) + .filter((name) => isProjectFile(name)) + .map((name) => joinPath(dir, name)); + } catch { + return []; + } +} diff --git a/src/editors/vscode/src/test-targets.ts b/src/editors/vscode/src/test-targets.ts index f074f323..22477621 100644 --- a/src/editors/vscode/src/test-targets.ts +++ b/src/editors/vscode/src/test-targets.ts @@ -58,15 +58,6 @@ export function runCwd(): string | undefined { return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; } -/** True when a test name matches Expecto naming conventions. */ -export function isExpectoTest(name: string): boolean { - return name.includes('Expecto') || name.includes('testCase') || name.includes('testList'); -} - -/** True when a test name matches FsCheck property-test conventions. */ -export function isFsCheckTest(name: string): boolean { - return name.includes('FsCheck') || name.includes('Property'); -} /** * The filter ids a run uses. "Run everything, nothing excluded" is how VS Code * expresses ▶ on the root of the Testing view; passing NO filter then runs every diff --git a/src/editors/vscode/src/test/suite/netfx-test-kit.ts b/src/editors/vscode/src/test/suite/netfx-test-kit.ts index 09545085..b1fbdb97 100644 --- a/src/editors/vscode/src/test/suite/netfx-test-kit.ts +++ b/src/editors/vscode/src/test/suite/netfx-test-kit.ts @@ -11,6 +11,7 @@ // // Observes [NETFX-TEST-DISCOVERY], [NETFX-TEST-RESULTS], [NETFX-TEST-PROFILES] // and [NETFX-SCOPE]. +import { languageTags } from './test-explorer-kit'; import * as assert from 'node:assert/strict'; import * as fs from 'node:fs'; import * as path from 'node:path'; @@ -177,7 +178,11 @@ export function frameworkTagsOf(item: vscode.TestItem): string[] { } /** `item` is tagged for EXACTLY `tfms`: one `tfm:` tag each, nothing else. */ -export function assertTaggedFor(item: vscode.TestItem, tfms: readonly string[]): void { +export function assertTaggedFor( + item: vscode.TestItem, + tfms: readonly string[], + fsharp = false, +): void { const ids = item.tags.map((tag) => tag.id); assert.deepStrictEqual( frameworkTagsOf(item), @@ -187,8 +192,8 @@ export function assertTaggedFor(item: vscode.TestItem, tfms: readonly string[]): assert.strictEqual(new Set(ids).size, ids.length, `${item.id}: no framework is tagged twice`); assert.deepStrictEqual( ids.filter((id) => !id.startsWith(TFM_TAG)), - [], - `${item.id}: tfm tags only`, + languageTags(fsharp), + `${item.id}: tfm tags plus its project's language tag only (#604)`, ); assert.strictEqual(item.children.size, 0, `${item.id}: a tagged row is a TEST, never a group`); } diff --git a/src/editors/vscode/src/test/suite/real-repo-netfx-fsharp.test.ts b/src/editors/vscode/src/test/suite/real-repo-netfx-fsharp.test.ts index c37f3024..017f2079 100644 --- a/src/editors/vscode/src/test/suite/real-repo-netfx-fsharp.test.ts +++ b/src/editors/vscode/src/test/suite/real-repo-netfx-fsharp.test.ts @@ -273,14 +273,14 @@ suite('Real repo .NET Framework — GitReader (F#)', () => { const item = findItem(api().testController.items, id); assert.ok(item, `${id} is a row, spaces and # verbatim`); assert.strictEqual(item.label, id.slice(GLOB_CLASS.length + 1), `${id}: its method`); - assertTaggedFor(item, runnable); + assertTaggedFor(item, runnable, true); } }); test('running the GlobTests class: every test passes, and a framework with no runtime is logged, not failed', async function () { this.timeout(REAL_REPO_MS); const anyTest = GLOB_IDS[0] ?? ''; - await runClass({ anyTest, count: GLOB_TEST_COUNT, declared: TESTS.available }); + await runClass({ anyTest, count: GLOB_TEST_COUNT, declared: TESTS.available, fsharp: true }); assert.strictEqual(classRowOf(api(), anyTest).label, 'GlobTests', 'the F# type is the class'); }); diff --git a/src/editors/vscode/src/test/suite/real-repo-netfx-kit.ts b/src/editors/vscode/src/test/suite/real-repo-netfx-kit.ts index c1585521..e1889096 100644 --- a/src/editors/vscode/src/test/suite/real-repo-netfx-kit.ts +++ b/src/editors/vscode/src/test/suite/real-repo-netfx-kit.ts @@ -125,6 +125,8 @@ export interface Corpus { */ export interface CorpusClassRun extends Omit { readonly tagged?: readonly string[]; + /** The class is in an .fsproj, so its rows carry `fsharp` too (#604). */ + readonly fsharp?: boolean; } /** The Test Explorer and this agent's runtimes, read once; the tree is cleared after. */ @@ -171,7 +173,7 @@ export function useCorpus( await assertClassRunPasses(api(), { ...run, installed: installed() }); const tagged = run.tagged ?? runnableOf(run.declared, installed()); for (const test of rootsOf(classRowOf(api(), run.anyTest).children)) { - assertTaggedFor(test, tagged); + assertTaggedFor(test, tagged, run.fsharp === true); } }; return { repoDir, api, installed, discovered, runClass }; diff --git a/src/editors/vscode/src/test/suite/test-explorer-assert-kit.ts b/src/editors/vscode/src/test/suite/test-explorer-assert-kit.ts index f53c7627..1b2bf77a 100644 --- a/src/editors/vscode/src/test/suite/test-explorer-assert-kit.ts +++ b/src/editors/vscode/src/test/suite/test-explorer-assert-kit.ts @@ -5,6 +5,7 @@ // `--filter` argument shapes, green-outcome loops and discovery preconditions — // so a suite asserts more by calling one function than by duplicating its body // ([TEST-REACTIVITY], [TEST-RUN-TRX], [TEST-FILTER-ESCAPE]). +import { languageTags } from './test-explorer-kit'; import * as assert from 'node:assert/strict'; import * as vscode from 'vscode'; import type { SharpLspExtensionApi } from '../../extension.js'; @@ -308,19 +309,30 @@ export function assertLensReported(api: SharpLspExtensionApi, id: string, why: s /** * A settled tree's row census: groups share ONE discovery-target uri, tests - * point at `fileCount` declaring files with unique descriptions, and no row - * carries a framework tag. + * point at `fileCount` declaring files with unique descriptions, and only + * the tests an .fsproj built carry a tag: `fsharp`. */ export function assertSnapshotUriShape( groups: readonly TestItemSnapshot[], tests: readonly TestItemSnapshot[], - options: { readonly fileCount: number; readonly why: string }, + options: { + readonly fileCount: number; + readonly why: string; + /** Ids an .fsproj built: exactly these carry the `fsharp` tag (#604). */ + readonly fsharp?: ReadonlySet; + }, ): void { assert.deepStrictEqual( - [...groups, ...tests].flatMap((row) => row.tags), + groups.flatMap((row) => row.tags), [], - `${options.why}: no row carries a framework tag — that tag is reserved for Expecto/FsCheck naming`, + `${options.why}: no group row carries a tag`, ); + for (const row of tests) + assert.deepStrictEqual( + row.tags, + languageTags(options.fsharp?.has(row.id) === true), + `${options.why}: ${row.id} carries its project's language tag and no framework tag`, + ); assert.strictEqual( new Set(groups.map((row) => row.uriPath)).size, 1, diff --git a/src/editors/vscode/src/test/suite/test-explorer-e2e.test.ts b/src/editors/vscode/src/test/suite/test-explorer-e2e.test.ts index 5291e37b..9ddd7b5a 100644 --- a/src/editors/vscode/src/test/suite/test-explorer-e2e.test.ts +++ b/src/editors/vscode/src/test/suite/test-explorer-e2e.test.ts @@ -56,6 +56,7 @@ import { collectLeafIds, assertLeavesAre, assertPlainLeaf, + languageTags, announcedPair, rootsOf, discoverSolution, @@ -257,6 +258,9 @@ function assertLeavesAreTests(group: vscode.TestItem, prefix: string): void { /** The fixture's eleven FQNs as a set, for membership assertions. */ const EXPECTED_SET = new Set(EXPECTED); +/** The pair's ids the .fsproj built: exactly these carry the `fsharp` tag (#604). */ +const FS_IDS = new Set(EXPECTED.filter((id) => id.startsWith('Fs.'))); + /** The two texts a depth-4 leaf check names itself with, per walking site. */ const LEAF_TEXT = { hierarchy: { @@ -504,11 +508,12 @@ function assertRenderedRows(items: vscode.TestItemCollection, anchor: string): v sorted(EXPECTED), 'the rendered TEST rows are exactly the fixtures’ eleven names', ); - for (const snapshot of leaves) assertPlainLeaf(snapshot, anchor); + for (const snapshot of leaves) assertPlainLeaf(snapshot, anchor, FS_IDS.has(snapshot.id)); for (const snapshot of groups) assertGroupSnapshot(snapshot, anchor); assertSnapshotUriShape(groups, leaves, { fileCount: 2, why: 'the rendered rows of the settled fixture tree', + fsharp: FS_IDS, }); assert.deepStrictEqual( groups.map((snapshot) => snapshot.childCount).sort((a, b) => a - b), @@ -639,7 +644,7 @@ suite('Test Explorer e2e — real C#/F# discovery', () => { await activateOnFixture(); assertSettledTree('item-shape discovery'); // The spaced F# name keeps its spaces all the way into the rendered label. - const spaced = assertLeafItem(api.testController.items, FS_FACT_SPACED); + const spaced = assertLeafItem(api.testController.items, FS_FACT_SPACED, ['fsharp']); assert.strictEqual( spaced.label, 'adds two numbers with spaces', @@ -657,7 +662,8 @@ suite('Test Explorer e2e — real C#/F# discovery', () => { 'Tests.fs', 'the spaced F# test is revealed at the .fs file that declares it', ); - for (const expected of EXPECTED) assertLeafItem(api.testController.items, expected); + for (const expected of EXPECTED) + assertLeafItem(api.testController.items, expected, languageTags(FS_IDS.has(expected))); assert.strictEqual( findItem(api.testController.items, 'Cs.Xunit.Fixtures.CalculatorTests.Nope'), undefined, @@ -696,7 +702,7 @@ suite('Test Explorer e2e — real C#/F# discovery', () => { [FS_FIXTURE.passing, CS.passing, FS_FACT_SPACED, FS_MIXED_THEORY, CS_MIXED_THEORY], 'discovered', ); - assertLeafItem(api.testController.items, FS_MIXED_THEORY); + assertLeafItem(api.testController.items, FS_MIXED_THEORY, ['fsharp']); assertLeafItem(api.testController.items, CS_MIXED_THEORY); }); @@ -720,7 +726,7 @@ suite('Test Explorer e2e — real C#/F# discovery', () => { // row again: the refresh replaces the tree, never collapses or appends. assertSettledTree('testing.refreshTests'); assertContainsAll(refreshed, [FS_FACT_SPACED, FS_MIXED_THEORY, CS_MIXED_THEORY], 'refreshed'); - assertLeafItem(api.testController.items, FS_FACT_SPACED); + assertLeafItem(api.testController.items, FS_FACT_SPACED, ['fsharp']); assertLeafItem(api.testController.items, CS.parameterized); }); @@ -1070,9 +1076,9 @@ suite('Test Explorer e2e — real C#/F# discovery', () => { for (const snapshot of snapshotItems(api.testController.items).filter( (s) => s.childCount === 0, )) { - assertPlainLeaf(snapshot, root); + assertPlainLeaf(snapshot, root, FS_IDS.has(snapshot.id)); } - assertLeafItem(api.testController.items, FS_FACT_SPACED); + assertLeafItem(api.testController.items, FS_FACT_SPACED, ['fsharp']); }); test('the solution the fixture builds is the shape the CLI produces, not a hand-written one', async function () { @@ -1577,8 +1583,8 @@ suite('Test Explorer e2e — real C#/F# discovery', () => { !leaf.canResolveChildren, `a leaf resolves no children: ${fqn}`, [...leaf.tags].map((tag) => tag.id), - [], - `a plain xUnit test carries no framework tag: ${fqn}`, + languageTags(FS_IDS.has(fqn)), + `an xUnit test carries its project's language tag and no framework tag: ${fqn}`, ); assertDeclaredInside(leaf.uri?.fsPath, root, `leaf ${fqn}`); } @@ -1592,7 +1598,7 @@ suite('Test Explorer e2e — real C#/F# discovery', () => { ); assert.ok(!spaced.label.includes('.'), "a leaf label never keeps the FQN's dots"); assertLeafItem(api.testController.items, CS.passing); - assertLeafItem(api.testController.items, FS_FIXTURE.passing); + assertLeafItem(api.testController.items, FS_FIXTURE.passing, ['fsharp']); }); test('the tree is structurally pure: 4 levels, nothing deeper, nothing misplaced', async function () { diff --git a/src/editors/vscode/src/test/suite/test-explorer-frameworks.test.ts b/src/editors/vscode/src/test/suite/test-explorer-frameworks.test.ts index 2670d950..e6fc92ca 100644 --- a/src/editors/vscode/src/test/suite/test-explorer-frameworks.test.ts +++ b/src/editors/vscode/src/test/suite/test-explorer-frameworks.test.ts @@ -28,8 +28,6 @@ import { import { escapeFilterValue, filterClause, filterExpression } from '../../test-filter.js'; import { buildFilterArgs, - isExpectoTest, - isFsCheckTest, type CachedTestResult, type SharpLspTestController, } from '../../testing.js'; @@ -38,6 +36,7 @@ import { FRAMEWORK_FIXTURES, type FrameworkFixture } from './test-explorer-fixtu import { assertLeafItem, collectLeafIds, + languageTags, discoverSolution, findItem, nextResultsChange, @@ -109,6 +108,11 @@ function assertLanguagePartition( /** Every name the six-project solution must expose, F# fixtures first. */ const ALL_EXPECTED: readonly string[] = FRAMEWORK_FIXTURES.flatMap(fqnsOf); +/** The ids an .fsproj built: exactly these carry the `fsharp` tag (#604). */ +const FS_IDS: ReadonlySet = new Set( + FRAMEWORK_FIXTURES.filter((fixture) => fixture.language === 'fsharp').flatMap(fqnsOf), +); + /** The theories whose rows DISAGREE — one pass, one fail, under one FQN. */ const MIXED_THEORIES: readonly string[] = FRAMEWORK_FIXTURES.flatMap( (one) => one.mixedParameterized ?? [], @@ -261,15 +265,9 @@ function assertXunitVisible(fixture: FrameworkFixture, displayNames: readonly st /** Every property a discovered item hands the Testing view. */ function assertItemShape(snapshot: TestItemSnapshot, anchor: string): void { - assertPlainLeaf(snapshot, anchor); - assert.ok( - !isExpectoTest(snapshot.id), - `${snapshot.id} is not an Expecto name, which is WHY it is untagged`, - ); - assert.ok( - !isFsCheckTest(snapshot.id), - `${snapshot.id} is not an FsCheck name, which is WHY it is untagged`, - ); + // #604: the language of the project that built it decides the tag — every + // F# row of xUnit, NUnit and MSTest carries `fsharp`, no C# row does. + assertPlainLeaf(snapshot, anchor, FS_IDS.has(snapshot.id)); } /** The fixture file of `key` really is on disk at `dir`. */ @@ -316,7 +314,7 @@ function assertShapeSurvives( `${why}: ${fqn} must appear exactly once in the tree`, ); assert.strictEqual( - assertLeafItem(items, fqn).label, + assertLeafItem(items, fqn, languageTags(FS_IDS.has(fqn))).label, label, `${why}: ${fqn} must render as '${label}'`, ); @@ -692,6 +690,7 @@ suite('Test Explorer e2e — xUnit, NUnit and MSTest across C# and F#', () => { assertSnapshotUriShape(groupSnapshots, testSnapshots, { fileCount: 6, why: 'the rendered rows of the six-fixture framework tree', + fsharp: FS_IDS, }); assert.strictEqual( testSnapshots.reduce((sum, snapshot) => sum + snapshot.childCount, 0), @@ -715,7 +714,11 @@ suite('Test Explorer e2e — xUnit, NUnit and MSTest across C# and F#', () => { ); for (const fixture of FRAMEWORK_FIXTURES) assertProjectOnDisk(fixture, dirFor(fixture), root); for (const fixture of FRAMEWORK_FIXTURES) - assertLeafItem(api.testController.items, fixture.parameterized); + assertLeafItem( + api.testController.items, + fixture.parameterized, + languageTags(fixture.language === 'fsharp'), + ); }); test('the three awkward FQN shapes survive discovery verbatim', async function () { diff --git a/src/editors/vscode/src/test/suite/test-explorer-fsharp-frameworks.test.ts b/src/editors/vscode/src/test/suite/test-explorer-fsharp-frameworks.test.ts index 3596697c..e9db9c0e 100644 --- a/src/editors/vscode/src/test/suite/test-explorer-fsharp-frameworks.test.ts +++ b/src/editors/vscode/src/test/suite/test-explorer-fsharp-frameworks.test.ts @@ -121,15 +121,20 @@ suite('Test Explorer e2e — Expecto and FsCheck (F#)', () => { [...ALL].sort(), 'exactly the seven tests of the two projects, nothing invented and nothing lost', ); - for (const id of EXPECTO_ALL) assertLeafItem(api.testController.items, id); - // No tag assertion for FsCheck rows: its `fsharp` tag is guessed from the - // name today (#604), and this module's name happens to contain "FsCheck". + for (const id of EXPECTO_ALL) assertLeafItem(api.testController.items, id, ['fsharp']); for (const id of ALL) { const item = findItem(api.testController.items, id); assert.ok(item, `${id} is in the tree`); assert.strictEqual(item.id, id, `${id} is its own id, verbatim`); assert.strictEqual(item.children.size, 0, `${id} is a runnable leaf`); assert.ok(item.label.length > 0, `${id} has a label to render`); + // #604: the tag comes from the .fsproj that built the test, never from a + // guess at its name — an Expecto list path names no framework at all. + assert.deepStrictEqual( + item.tags.map((tag) => tag.id), + ['fsharp'], + `${id} was built by an .fsproj, so it carries the fsharp tag and nothing else`, + ); } assert.ok( leaves.every((id) => !id.endsWith('.dll') && !id.includes(' -> ')), diff --git a/src/editors/vscode/src/test/suite/test-explorer-kit.ts b/src/editors/vscode/src/test/suite/test-explorer-kit.ts index 1d2afed1..68c988e5 100644 --- a/src/editors/vscode/src/test/suite/test-explorer-kit.ts +++ b/src/editors/vscode/src/test/suite/test-explorer-kit.ts @@ -125,17 +125,27 @@ export function assertDeclaredInside( assert.ok(['.cs', '.fs'].includes(path.extname(file)), `${id} is declared in C# or F#: ${file}`); } +/** The tags a test row of a project in that language carries: `fsharp` for an .fsproj (#604). */ +export function languageTags(fsharp: boolean): string[] { + return fsharp ? ['fsharp'] : []; +} + /** - * A plain (untagged) discovered test row: the FQN as description, the last - * dotted segment as label, a leaf, carrying a uri declared inside `anchor`. + * A plain discovered test row: the FQN as description, the last dotted segment + * as label, a leaf, carrying a uri declared inside `anchor`, tagged with its + * project's language and nothing else. */ -export function assertPlainLeaf(snapshot: TestItemSnapshot, anchor: string): void { +export function assertPlainLeaf(snapshot: TestItemSnapshot, anchor: string, fsharp = false): void { const { id, label } = snapshot; assert.strictEqual(snapshot.description, id, `the description is the whole FQN: ${id}`); assert.strictEqual(label, id.split('.').at(-1), `the label is the last dotted segment of ${id}`); assert.ok(label.length > 0 && id.endsWith(label), `${id} must end with a non-empty label`); assert.strictEqual(snapshot.childCount, 0, `a discovered TEST is a leaf: ${id}`); - assert.deepStrictEqual(snapshot.tags, [], `a plain test carries no framework tag: ${id}`); + assert.deepStrictEqual( + snapshot.tags, + languageTags(fsharp), + `a plain test carries its project's language tag and no framework tag: ${id}`, + ); assertDeclaredInside(snapshot.uriPath, anchor, id); } @@ -174,7 +184,11 @@ export function findItem( } /** Every property one leaf item exposes, asserted against its own FQN. */ -export function assertLeafItem(items: vscode.TestItemCollection, id: string): vscode.TestItem { +export function assertLeafItem( + items: vscode.TestItemCollection, + id: string, + tags: readonly string[] = [], +): vscode.TestItem { const item = findItem(items, id); assert.ok(item, `findItem must resolve ${id}`); assert.strictEqual(item.id, id, `the id is the fully-qualified name, verbatim: ${id}`); @@ -187,7 +201,11 @@ export function assertLeafItem(items: vscode.TestItemCollection, id: string): vs assert.ok(!item.canResolveChildren, `a leaf test resolves no children: ${id}`); assert.strictEqual(item.children.size, 0, `${id} must have no children`); assert.strictEqual(item.error, undefined, `${id} must not carry a discovery error`); - assert.strictEqual(item.tags.length, 0, `${id} carries no framework tag`); + assert.deepStrictEqual( + item.tags.map((tag) => tag.id), + [...tags], + `${id} carries exactly the tags of its project's language (#604)`, + ); return item; } diff --git a/src/editors/vscode/src/test/suite/test-explorer-netfx.test.ts b/src/editors/vscode/src/test/suite/test-explorer-netfx.test.ts index 1bfd63bc..23588237 100644 --- a/src/editors/vscode/src/test/suite/test-explorer-netfx.test.ts +++ b/src/editors/vscode/src/test/suite/test-explorer-netfx.test.ts @@ -240,7 +240,7 @@ suite('Test Explorer — one project built for .NET Framework AND .NET', () => { ); const [item] = itemsFor(api, [SINGLE_ID]); assert.ok(item, `${SINGLE_ID} is a row`); - assertTaggedFor(item, []); + assertTaggedFor(item, [], true); assert.strictEqual(item.description, SINGLE_ID, 'its description is its plain FQN, as before'); }); @@ -258,13 +258,18 @@ suite('Test Explorer — one project built for .NET Framework AND .NET', () => { test('tags: every framework whose assembly lists a test, and no other', function () { const everywhere: (keyof NetfxIds)[] = ['passes', 'failsOnNetfx', 'failsOnNet472', 'skipped']; - for (const shape of everywhere) { - for (const item of itemsFor(api, idsOf(FIXTURES, shape))) assertTaggedFor(item, declared); - } - for (const item of itemsFor(api, idsOf(FIXTURES, 'net48Only'))) { - assertTaggedFor(item, ['net48']); + // #604: every F# row also carries `fsharp`, from the .fsproj that built it. + for (const fixture of FIXTURES) { + const fsharp = fixture.language === 'fsharp'; + for (const shape of everywhere) { + for (const item of itemsFor(api, idsOf([fixture], shape))) + assertTaggedFor(item, declared, fsharp); + } + for (const item of itemsFor(api, idsOf([fixture], 'net48Only'))) + assertTaggedFor(item, ['net48'], fsharp); + for (const item of itemsFor(api, idsOf([fixture], 'modernOnly'))) + assertTaggedFor(item, modern, fsharp); } - for (const item of itemsFor(api, idsOf(FIXTURES, 'modernOnly'))) assertTaggedFor(item, modern); }); test('a run merges each test across frameworks, prefixing every failure with the frameworks that failed', async function () { diff --git a/src/editors/vscode/src/test/suite/test-explorer-windows.test.ts b/src/editors/vscode/src/test/suite/test-explorer-windows.test.ts index 02b5cb74..cebd2ca5 100644 --- a/src/editors/vscode/src/test/suite/test-explorer-windows.test.ts +++ b/src/editors/vscode/src/test/suite/test-explorer-windows.test.ts @@ -236,7 +236,8 @@ suite('Test Explorer e2e — Windows-hostile paths, encodings and filter grammar ); } for (const snapshot of testSnapshots) { - assertPlainLeaf(snapshot, hostileDir); + // #604: the pair's F# half (`Fs.` ids) was built by an .fsproj. + assertPlainLeaf(snapshot, hostileDir, snapshot.id.startsWith('Fs.')); } const spaced = findItem(api.testController.items, FS_FACT_SPACED); assert.ok(spaced, `${FS_FACT_SPACED} must resolve by id`); diff --git a/src/editors/vscode/src/test/suite/test-language.test.ts b/src/editors/vscode/src/test/suite/test-language.test.ts new file mode 100644 index 00000000..14ff8b6e --- /dev/null +++ b/src/editors/vscode/src/test/suite/test-language.test.ts @@ -0,0 +1,46 @@ +// The language of the project that built a test assembly decides its Testing +// view tag (#604): real project folders, one per case — a C# test named like a +// property test, an F# Expecto list path, a listing that names its project, and +// an assembly no project owns. +// +// Covers [TEST-EXPLORER]. +import * as assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { projectLanguageOf } from '../../test-language.js'; + +suite("Test Explorer — a test row's language comes from its project (#604)", () => { + test('C#, F#, a named project and no project each resolve as built, never from the name', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'slsp-language-')); + try { + const project = (dir: string, file: string): string => { + fs.mkdirSync(path.join(root, dir, 'bin', 'Debug', 'net10.0'), { recursive: true }); + fs.writeFileSync(path.join(root, dir, file), ''); + return path.join(root, dir, 'bin', 'Debug', 'net10.0', `${dir}.dll`); + }; + const listing = (dllPath: string, projectFile?: string) => ({ + name: path.basename(dllPath, '.dll'), + path: dllPath, + names: [], + ...(projectFile === undefined ? {} : { projectFile }), + }); + const csharp = project('PropertyTests', 'PropertyTests.csproj'); + const fsharp = project('calculator', 'calculator.fsproj'); + assert.equal(projectLanguageOf(listing(csharp)), 'csharp', 'a C# "Property" test stays C#'); + assert.equal(projectLanguageOf(listing(fsharp)), 'fsharp', 'an Expecto list path is F#'); + assert.equal( + projectLanguageOf(listing(csharp, path.join(root, 'Real.fsproj'))), + 'fsharp', + 'the project a listing names wins over the folder walk', + ); + assert.equal( + projectLanguageOf(listing(path.join(root, 'nowhere', 'Lost.dll'))), + undefined, + 'no project found is no language, never a guess', + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/src/editors/vscode/src/test/suite/testing-lens-e2e.test.ts b/src/editors/vscode/src/test/suite/testing-lens-e2e.test.ts index 97e18847..e97a26c3 100644 --- a/src/editors/vscode/src/test/suite/testing-lens-e2e.test.ts +++ b/src/editors/vscode/src/test/suite/testing-lens-e2e.test.ts @@ -20,7 +20,7 @@ import * as assert from 'node:assert/strict'; import * as fs from 'node:fs'; import * as path from 'node:path'; import * as vscode from 'vscode'; -import { buildFilterArgs, isExpectoTest, isFsCheckTest } from '../../testing.js'; +import { buildFilterArgs } from '../../testing.js'; import type { CachedTestResult } from '../../testing.js'; import { batchAssemblies, @@ -532,17 +532,6 @@ suite('Testing module e2e — run/debug commands and helpers', () => { !isDiscoveredTestLine('Proj -> C:\\out\\Proj.dll'), 'the MSBuild output mapping is never a test name', ); - - // The same addTestItem tagging logic (Expecto || FsCheck => F#). - const isFsharp = (name: string): boolean => isExpectoTest(name) || isFsCheckTest(name); - assert.ok(isFsharp('MyLib.Tests.testCase')); - assert.ok(isFsharp('MyLib.Tests.testList')); - assert.ok(isFsharp('MyLib.Expecto.Foo')); - assert.ok(isFsharp('MyLib.FsCheck.Prop')); - assert.ok(isFsharp('MyLib.Property.Roundtrip')); - assert.ok(!isFsharp('Sample.Tests.CalculatorTests.Adds_TwoNumbers')); - assert.ok(!isExpectoTest('FsCheck')); - assert.ok(!isFsCheckTest('Expecto')); }); test('buildFilterArgs assembles the dotnet --filter clause for selected tests', async function () { diff --git a/src/editors/vscode/src/testing.ts b/src/editors/vscode/src/testing.ts index b4dfb4dd..63fc2d9a 100644 --- a/src/editors/vscode/src/testing.ts +++ b/src/editors/vscode/src/testing.ts @@ -38,7 +38,6 @@ import { } from './test-framework-runs'; export { buildFilterArgs } from './test-execution'; -export { isExpectoTest, isFsCheckTest } from './test-targets'; export type { CachedTestResult } from './test-reporting'; /** What one discovery sweep collected across every target. */ diff --git a/src/editors/vscode/test-chunks.json b/src/editors/vscode/test-chunks.json index 1504d17a..80fe0ed2 100644 --- a/src/editors/vscode/test-chunks.json +++ b/src/editors/vscode/test-chunks.json @@ -166,6 +166,7 @@ "test-explorer-glued-banners.test.js", "test-explorer-names.test.js", "testing-lens-e2e.test.js", + "test-language.test.js", "testing-lens-status.test.js", "test-explorer-coverage.test.js", "test-coverage-parser.test.js", From 60a4ca3fd9fc085393580b63a9321348deb0521b Mon Sep 17 00:00:00 2001 From: Christian Findlay <16697547+MelbourneDeveloper@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:58:26 +1100 Subject: [PATCH 5/6] =?UTF-8?q?A=20failed=20workspace=20restore=20names=20?= =?UTF-8?q?its=20cause:=20the=20error=20carries=20the=20SDK's=20own=20erro?= =?UTF-8?q?r=20lines=20(NU1101=20=E2=80=A6)=20instead=20of=20only=20the=20?= =?UTF-8?q?project=20path;=20the=20C#=20gate=20is=20proven=20to=20open=20n?= =?UTF-8?q?o=20workspace=20until=20the=20project=20is=20repaired?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/DIAGNOSTICS-PLAN.md | 2 +- .../WorkspaceRestoreGateTests.cs | 76 +++++++++++++++++++ .../WorkspaceRestore.cs | 29 +++++-- 3 files changed, 100 insertions(+), 7 deletions(-) create mode 100644 src/sidecars/SharpLsp.Sidecar.CSharp.Tests/WorkspaceRestoreGateTests.cs diff --git a/docs/plans/DIAGNOSTICS-PLAN.md b/docs/plans/DIAGNOSTICS-PLAN.md index 7c6a1c8d..8f0a063d 100644 --- a/docs/plans/DIAGNOSTICS-PLAN.md +++ b/docs/plans/DIAGNOSTICS-PLAN.md @@ -78,7 +78,7 @@ Full branch CI is not green. The normal release host, sidecars, packaged extensi - [x] Prove unopened default Razor SDK components participate in workspace pulls, map CS0029 to the component source and clear after a compiler-verified disk repair. - [x] Respect NoWarn, source suppressions, analyzer opt-out and effective severity without suppressing compiler errors. - [x] Prove actual generated-source and global/project diagnostic errors remain visible at their owning project with a zero-length 0:0 range: real FS0084, CS5001 and generated CS0029 editor cases pass in the verified 61-case combined suite, with exact counts and SDK build oracles (8b325497, 57e4a445). -- [ ] Apply the NuGet restore gate before compiler workspace creation; surface restore failures honestly. +- [x] Apply the NuGet restore gate before compiler workspace creation; surface restore failures honestly — the failure names the SDK's own `error` lines (`WorkspaceRestore.cs` `RestoreErrors`); `WorkspaceRestoreGateTests` (C#: no workspace after a failed restore, the missing package named, a repair opens it) and `FSharpWorkspaceRestoreEndToEndTests.fs` (F#). - [ ] Preserve F# FSharpLint/FSharp.Analyzers.SDK and SharpLsp static analyzer behavior. - [x] Supply codeDescription URLs ([#343](https://github.com/Nimblesite/SharpLsp/issues/343)): each C# finding's descriptor `HelpLinkUri` and FSharpLint's per-rule page; F# compiler codes carry none. - [x] Supply unnecessary tags where specified. — [DIAG-CATEGORIES-TAGS] (#390): `Unnecessary` and `Deprecated` from both sidecars, passed through by the host — `diagnostic_tags.rs` diff --git a/src/sidecars/SharpLsp.Sidecar.CSharp.Tests/WorkspaceRestoreGateTests.cs b/src/sidecars/SharpLsp.Sidecar.CSharp.Tests/WorkspaceRestoreGateTests.cs new file mode 100644 index 00000000..8bd119a8 --- /dev/null +++ b/src/sidecars/SharpLsp.Sidecar.CSharp.Tests/WorkspaceRestoreGateTests.cs @@ -0,0 +1,76 @@ +using SharpLsp.Sidecar.Common; +using SharpLsp.Sidecar.CSharp.Workspace; + +#pragma warning disable CA1515 // Types can be internal +#pragma warning disable RS1035 // File IO is banned for analyzers — these are tests +#pragma warning disable CS0618 // Obsolete OpenAsync placeholder + +namespace SharpLsp.Sidecar.CSharp.Tests; + +/// +/// [DIAG-RESTORE] The NuGet restore gate runs BEFORE the compiler workspace exists: a project +/// whose restore fails opens nothing and says why, instead of loading a workspace whose every +/// package reference is an unresolved-type error. Repairing the project lets the same manager +/// open it. The failing package comes from an empty local feed, so the failure is offline +/// and deterministic. +/// +public sealed class WorkspaceRestoreGateTests : IDisposable +{ + private const string MissingPackage = "SharpLsp.Restore.Gate.Missing"; + + private readonly string _root = NativePaths.Temp($"sharplsp-restore-gate-{Guid.NewGuid():N}"); + private readonly WorkspaceManager _manager = new(); + private string ProjectPath => NativePaths.Join(_root, "Gated.csproj"); + + public void Dispose() + { + _manager.Dispose(); + if (Directory.Exists(_root)) + { + Directory.Delete(_root, true); + } + } + + [Fact] + public async Task A_failed_restore_opens_no_workspace_and_says_why_and_a_repair_opens_it() + { + var feed = NativePaths.Join(_root, "feed"); + _ = Directory.CreateDirectory(feed); + await File.WriteAllTextAsync( + NativePaths.Join(_root, "nuget.config"), + $""" + + + + + + + """ + ); + await File.WriteAllTextAsync(NativePaths.Join(_root, "Gated.cs"), "class Gated { }"); + await File.WriteAllTextAsync(ProjectPath, ProjectXml(MissingPackage)); + + // Interaction 1 — the restore fails, so the workspace is never created. + var refused = await _manager.OpenAsync(ProjectPath); + Assert.True(refused.IsError, "a project whose restore failed must not open"); + var reason = refused.Match(_ => string.Empty, error => error); + Assert.False(string.IsNullOrWhiteSpace(reason), "the failure says why"); + Assert.Contains(MissingPackage, reason, StringComparison.Ordinal); + Assert.False(_manager.IsLoaded, "no compiler workspace exists after a failed restore"); + + // Interaction 2 — the repaired project restores and opens on the same manager. + await File.WriteAllTextAsync(ProjectPath, ProjectXml(null)); + var opened = await _manager.OpenAsync(ProjectPath); + Assert.False(opened.IsError, opened.Match(_ => "ok", error => error)); + Assert.True(_manager.IsLoaded, "the repaired project loads"); + } + + private static string ProjectXml(string? package) + { + var reference = package is null + ? string.Empty + : $""; + return "net10.0" + + $"Library{reference}"; + } +} diff --git a/src/sidecars/SharpLsp.Sidecar.Common/WorkspaceRestore.cs b/src/sidecars/SharpLsp.Sidecar.Common/WorkspaceRestore.cs index 6acd6c54..8ad988da 100644 --- a/src/sidecars/SharpLsp.Sidecar.Common/WorkspaceRestore.cs +++ b/src/sidecars/SharpLsp.Sidecar.Common/WorkspaceRestore.cs @@ -135,16 +135,33 @@ private static RestoreResult CompletedRestore(string project, RestoreResult resu { return RememberedRestore(project, result); } - Log.Warning( - "Package restore failed for {Project}: {Detail}", - project, - result.Match(_ => string.Empty, detail => detail) - ); + var detail = result.Match(_ => string.Empty, failure => failure); + Log.Warning("Package restore failed for {Project}: {Detail}", project, detail); return RestoreResult.Failure( - $"Package restore failed for {project}; run dotnet restore manually." + $"Package restore failed for {project}: {RestoreErrors(detail)}; run dotnet restore manually." ); } + /// Longest restore output the failure message quotes when it names no error line. + private const int TailLength = 500; + + /// + /// Why a restore failed, in the SDK's own words: its distinct error lines + /// (NU1101: Unable to find package …), else the tail of its output. [DIAG-RESTORE] + /// + private static string RestoreErrors(string detail) + { + var errors = detail + .Split('\n') + .Select(line => line.Trim()) + .Where(line => line.Contains(" error ", StringComparison.Ordinal)) + .Distinct(StringComparer.Ordinal) + .ToArray(); + return errors.Length > 0 ? string.Join("; ", errors) + : detail.Length > TailLength ? detail[^TailLength..].Trim() + : detail.Trim(); + } + private static RestoreResult RememberedRestore(string project, RestoreResult result) { // Successful SDK evaluation proves the complete surviving graph. [DIAG-RESTORE] From 934c96432c6de34ae88cfd970d093f01d1307c85 Mon Sep 17 00:00:00 2001 From: Christian Findlay <16697547+MelbourneDeveloper@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:28:27 +1100 Subject: [PATCH 6/6] A test-debug run that ends before VS Code opens its terminal closes that terminal on open, instead of firing the close before anyone listens and leaving a ghost terminal beside the next run --- src/editors/vscode/src/test-debug.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/editors/vscode/src/test-debug.ts b/src/editors/vscode/src/test-debug.ts index 1f1bfb6c..0209b535 100644 --- a/src/editors/vscode/src/test-debug.ts +++ b/src/editors/vscode/src/test-debug.ts @@ -119,6 +119,10 @@ class DebugRunTerminal implements vscode.Pseudoterminal { this.writeEmitter.fire(this.buffered); this.buffered = ''; } + // A run that ended before VS Code opened the terminal fired its close into + // the void: VS Code only listens once it has opened the pty. Close now, or + // the terminal outlives its run as a ghost beside the next one. + if (this.ended) this.closeEmitter.fire(); } /** VS Code's notice that the USER disposed the terminal. */ @@ -146,7 +150,7 @@ class DebugRunTerminal implements vscode.Pseudoterminal { public end(): void { if (this.ended) return; this.ended = true; - this.closeEmitter.fire(); + if (this.opened) this.closeEmitter.fire(); } }