diff --git a/packages/vscode/AGENTS.md b/packages/vscode/AGENTS.md index 9c9f69e..ff01d96 100644 --- a/packages/vscode/AGENTS.md +++ b/packages/vscode/AGENTS.md @@ -17,7 +17,7 @@ One extension replacing the standalone `rstack.rslint` and `rstack.rstest` exten 4. **Status aggregation** — stacks own no UI chrome; they report to the shell's single status bar item, which always exists. Upstream's plugin-host failure toast becomes a status verdict (adaptation 7). Rslint LSP tracing shares the **Rstack: Rslint** Output channel to preserve the four-channel cap; see `stacks/lint/index.ts`. In CI the test stack's `MasterLogger` also mirrors every entry to stderr (`RSTACK_E2E_MIRROR_LOGS=1`, set by `e2e/rstest/runTest.ts`) — the output channel is unreadable there; rationale in `stacks/test/logger.ts`. 5. **Worker-cwd decoupling** (test) — a project's cwd is explicit, not derived from the config file path; for native configs behavior stays byte-identical to upstream. 6. **Node runtime selection** (lint, test, fmt) — the Node a project-loading child process runs on is a **User Node runtime** chosen by the extension against one uniform floor, never assumed from PATH; the recovery path is the user's own shell, and the dividing line is the **load bound** (terms in GLOSSARY.md; the full rule and rationale in `docs/adr/0001-node-runtime-selection.md`). All three callers — the lint worker, the rstest worker and the `rs fmt --lsp` server — take the decision from the one shared module (`shared/nodeResolution.ts`) and share one escape hatch, the resource-scoped `rstack.nodeExecutable` (`shared/nodeExecutableSetting.ts`); each appends its own consequence to the shared preflight message. -7. **Lint worker and Rstack bridge** — the extension host is only Rslint's language client. One vscode-free, editor-shipped lint worker per **Lint runtime** (one Rslint core inside one workspace folder — GLOSSARY.md) runs on the User Node runtime, owns the Go LSP plus all five reverse requests, and derives the binary/config/plugin pieces from one explicit `@rslint/core` directory. Upstream's `CoreResolver` loads that core in the extension host; ours only walks to the directory (`fs.stat` + `package.json` + semver) and hands the path to the worker, and its `CoreInstallation` therefore carries paths, not module factories; upstream's installation cache goes with the module loading it memoized (`clear()` is a no-op kept for the `RuntimeManager` contract). A bridged runtime passes only rstack's published `dist/rslintConfig.js` shim; neither the extension nor the worker re-implements Rstack config semantics. Because every supported config protocol locks `configPath` per process, the shim is part of the runtime key (`folder + core identity + shim`), which upstream — having no bridge — keys on the core alone. Why: `docs/adr/0003-lint-through-editor-worker.md`. The worker also sends the editor-only `rstack/rslintConfigDependency` notification (`stacks/lint/worker/configDependencyProtocol.ts`) when config loading finds a missing package. `ConfigTransactionAdapter` rewrites only that classified `rslint/loadConfigs` candidate's error message to its first line, so Go cannot echo a require stack beside the single warning. An initialized client whose initial configRefresh rejects with that verdict stays available for retry, rather than propagating a generic startup crash through RuntimeManager. Plugin-host startup failures use a separate, unclassified `plugin` verdict on `rstack/rslintConfigDependency`, report `disabled` (a plugin could not be loaded), and recover through the dependency poll. A bridged runtime whose Rstack config has no `define.lint()` gets a third verdict, `unconfigured` (#93; why it exists: the lint-shim gotcha below). It reports `not-detected` with the detail `no define.lint() in rstack.config.*` and one `info` line per episode. Why `not-detected`: the shim's refusal is a late detection signal, and `not-detected` is the status bar's word for "this tool has no configuration here"; `running` would show a green Rslint that lints nothing. The worker stays alive underneath — the state/process decoupling `running: idle` makes in the other direction — and there is no poll because `isFailedStackState` excludes `not-detected`; not `crashed`, no warning. A folder whose only runtimes are unconfigured folds to that `not-detected`; a healthy runtime beside it (a native `rslint.config.*`) wins, since the folder is linting. The `not-detected` detail exists for this verdict: detection never sets one, so only a stack with a runtime-level "nothing configured" verdict renders it, as one hover notice row. That grey `not-detected` is a runtime-level verdict and lives with the runtime: only the shim can decide it, and persisting it per folder would need its own invalidation on the bridged config watcher, so an unconfigured folder reads `running: idle` on startup and after its last document closes, until a document opens a runtime again. Adding `define.lint()` recovers to plain `running` in the same worker through the bridged `rstack.config.*` watcher, without a restart. +7. **Lint worker and Rstack bridge** — the extension host is only Rslint's language client. One vscode-free, editor-shipped lint worker per **Lint runtime** (one Rslint core inside one workspace folder — GLOSSARY.md) runs on the User Node runtime, owns the Go LSP plus all five reverse requests (and the worker-to-Go `rslint/typeService` queries backing type-aware ESLint plugins), and derives the binary/config/plugin pieces from one explicit `@rslint/core` directory. Upstream's `CoreResolver` loads that core in the extension host; ours only walks to the directory (`fs.stat` + `package.json` + semver) and hands the path to the worker, and its `CoreInstallation` therefore carries paths, not module factories; upstream's installation cache goes with the module loading it memoized (`clear()` is a no-op kept for the `RuntimeManager` contract). A bridged runtime passes only rstack's published `dist/rslintConfig.js` shim; neither the extension nor the worker re-implements Rstack config semantics. Because every supported config protocol locks `configPath` per process, the shim is part of the runtime key (`folder + core identity + shim`), which upstream — having no bridge — keys on the core alone. Why: `docs/adr/0003-lint-through-editor-worker.md`. The worker also sends the editor-only `rstack/rslintConfigDependency` notification (`stacks/lint/worker/configDependencyProtocol.ts`) when config loading finds a missing package. `ConfigTransactionAdapter` rewrites only that classified `rslint/loadConfigs` candidate's error message to its first line, so Go cannot echo a require stack beside the single warning. An initialized client whose initial configRefresh rejects with that verdict stays available for retry, rather than propagating a generic startup crash through RuntimeManager. Plugin-host startup failures use a separate, unclassified `plugin` verdict on `rstack/rslintConfigDependency`, report `disabled` (a plugin could not be loaded), and recover through the dependency poll. A bridged runtime whose Rstack config has no `define.lint()` gets a third verdict, `unconfigured` (#93; why it exists: the lint-shim gotcha below). It reports `not-detected` with the detail `no define.lint() in rstack.config.*` and one `info` line per episode. Why `not-detected`: the shim's refusal is a late detection signal, and `not-detected` is the status bar's word for "this tool has no configuration here"; `running` would show a green Rslint that lints nothing. The worker stays alive underneath — the state/process decoupling `running: idle` makes in the other direction — and there is no poll because `isFailedStackState` excludes `not-detected`; not `crashed`, no warning. A folder whose only runtimes are unconfigured folds to that `not-detected`; a healthy runtime beside it (a native `rslint.config.*`) wins, since the folder is linting. The `not-detected` detail exists for this verdict: detection never sets one, so only a stack with a runtime-level "nothing configured" verdict renders it, as one hover notice row. That grey `not-detected` is a runtime-level verdict and lives with the runtime: only the shim can decide it, and persisting it per folder would need its own invalidation on the bridged config watcher, so an unconfigured folder reads `running: idle` on startup and after its last document closes, until a document opens a runtime again. Adding `define.lint()` recovers to plain `running` in the same worker through the bridged `rstack.config.*` watcher, without a restart. 8. **Self-documenting Rslint diagnostics** — client-side providers parse Inline directives into per-rule hover, DocumentLink and underline-decoration affordances (the hover renders `Rslint(rule-id)`, the shape VS Code gives the published diagnostics), and the router enriches today's `[rule-id] message` diagnostics with a derived Rule docs link. No rule metadata or network lookup is bundled (ADR 0004). The hover provider yields whenever the owning language client's resolved capabilities advertise `hoverProvider`; an optional `Rslint.onClosed` hook identity-safely prunes the controller's capability mirror; the diagnostic synthesis is removed once upstream publishes `code` / `codeDescription` natively. 9. **Color env parity with the CLI** (test) — upstream hard-codes `FORCE_COLOR: '1'` into the worker's spawn env; ours mirrors the CLI's `getForceColorEnv` (rstest `packages/core/src/utils/logger.ts`) instead (`stacks/test/shared/colorEnv.ts`): the master injects `FORCE_COLOR=1` into the composed spawn env only when neither `FORCE_COLOR` nor `NO_COLOR` is already set (marking the injection with `RSTACK_FORCE_COLOR_INJECTED`), and the worker retracts the marked injection right after config load if the config set `NO_COLOR` — the CLI's own decision point. Otherwise a project whose config sets `process.env.NO_COLOR` (rstack-cli does) hits Node's "'NO_COLOR' env is ignored" warning in every pool process. A user-set `FORCE_COLOR` beside a config-set `NO_COLOR` still warns, exactly as the bare CLI does. diff --git a/packages/vscode/src/stacks/lint/worker/PluginLintPool.ts b/packages/vscode/src/stacks/lint/worker/PluginLintPool.ts index ebd131b..3962241 100644 --- a/packages/vscode/src/stacks/lint/worker/PluginLintPool.ts +++ b/packages/vscode/src/stacks/lint/worker/PluginLintPool.ts @@ -12,6 +12,43 @@ type PluginHostFactory = ( onLog: (record: { level: string; source: string; text: string }) => void, ) => Promise; +type FallbackTypeServiceTransport = ( + request: unknown, + signal?: AbortSignal, +) => Promise<{ status?: 'closed' | 'cancelled' }>; + +// Use `@rslint/core >= 0.11.0`'s 4th `typeServices` parameter type when +// declared; fall back to a structurally compatible shape under `< 0.11.0`. +export type PluginTypeServiceTransport = PluginLintHost['lint'] extends ( + req: any, + signal: any, + attachments: any, + typeServices: infer Transport, +) => any + ? unknown extends Transport + ? FallbackTypeServiceTransport + : NonNullable + : FallbackTypeServiceTransport; + +export type PluginLintRequest = EslintPluginLintRequest & { + retiredTypeServices?: readonly string[]; +}; + +type LintHostWithTypeServices = { + lint( + req: EslintPluginLintRequest, + signal?: AbortSignal, + attachments?: undefined, + typeServices?: PluginTypeServiceTransport, + ): Promise; +}; + +function isRetirementOnlyRequest(request: PluginLintRequest): boolean { + return ( + request.files.length === 0 && (request.retiredTypeServices?.length ?? 0) > 0 + ); +} + const MAX_GRACE_GENERATIONS = 1; export class PluginLintPool { @@ -182,8 +219,9 @@ export class PluginLintPool { } async lint( - request: EslintPluginLintRequest, + request: PluginLintRequest, token?: CancellationToken, + typeServiceTransport?: PluginTypeServiceTransport, ): Promise { if (this.disposed) return { results: [] }; @@ -196,6 +234,7 @@ export class PluginLintPool { state = this.generations.get(request.generation); } if (request.generation && !state) { + if (isRetirementOnlyRequest(request)) return { results: [] }; throw new Error( `unknown ESLint-plugin config generation: ${request.generation}`, ); @@ -203,7 +242,9 @@ export class PluginLintPool { if (!state) return { results: [] }; const host = state.host; if (!host) { - if (token?.isCancellationRequested) return { results: [] }; + if (token?.isCancellationRequested || isRetirementOnlyRequest(request)) { + return { results: [] }; + } const generation = request.generation ?? this.activeGeneration; throw new Error( `LSP pluginLint requested for config generation ${JSON.stringify(generation)} without an activated plugin host`, @@ -224,7 +265,13 @@ export class PluginLintPool { } signal = controller.signal; } - return await host.lint(request, signal); + const lintHost: LintHostWithTypeServices = host; + return await lintHost.lint( + request, + signal, + undefined, + typeServiceTransport, + ); } finally { cancellationSubscription?.dispose(); state.activeLints--; diff --git a/packages/vscode/src/stacks/lint/worker/index.ts b/packages/vscode/src/stacks/lint/worker/index.ts index 313fcb7..9d7816a 100644 --- a/packages/vscode/src/stacks/lint/worker/index.ts +++ b/packages/vscode/src/stacks/lint/worker/index.ts @@ -3,8 +3,8 @@ import type { ActivateConfigsRequest, LoadConfigsRequest, } from '@rslint/core/config-loader'; -import type { EslintPluginLintRequest } from '@rslint/core/eslint-plugin'; import { + CancellationTokenSource, createMessageConnection, type CancellationToken, type MessageConnection, @@ -14,7 +14,11 @@ import { withProcessExitAsThrow, type ConfigTransactionControlRequest, } from './ConfigTransactionAdapter'; -import { PluginLintPool } from './PluginLintPool'; +import { + PluginLintPool, + type PluginLintRequest, + type PluginTypeServiceTransport, +} from './PluginLintPool'; import { stampConfigRefresh, type ConfigRefreshParams, @@ -140,6 +144,45 @@ function forwardRequest( : target.sendRequest(method, params, token); } +type TypeServiceRequest = Parameters[0]; +type TypeServiceResponse = Awaited>; + +export function createTypeServiceTransport( + goConnection: Pick, +): PluginTypeServiceTransport { + return async ( + request: TypeServiceRequest, + signal?: AbortSignal, + ): Promise => { + // Short-circuit before sending: vscode-jsonrpc's pre-cancelled token + // uses Event.None and never emits $/cancelRequest for the request. + if (signal?.aborted) { + return { status: 'cancelled' }; + } + if (!signal) { + return goConnection.sendRequest( + 'rslint/typeService', + request, + ); + } + const tokenSource = new CancellationTokenSource(); + const onAbort = (): void => { + tokenSource.cancel(); + }; + signal.addEventListener('abort', onAbort, { once: true }); + try { + return await goConnection.sendRequest( + 'rslint/typeService', + request, + tokenSource.token, + ); + } finally { + signal.removeEventListener('abort', onAbort); + tokenSource.dispose(); + } + }; +} + interface EditorProxyOptions { readonly protocolVersion: number; readonly configPath?: string; @@ -227,6 +270,7 @@ export async function runLintWorker( logger, installation.createPluginLintHost, ); + const typeServiceTransport = createTypeServiceTransport(goConnection); let configDependencyFailure: ConfigDependencyFailure | undefined; let configError: string | undefined; let unconfigured = false; @@ -302,7 +346,11 @@ export async function runLintWorker( case 'rslint/abortConfigs': return adapter.abortConfigs(params as ConfigTransactionControlRequest); case 'rslint/pluginLint': - return pluginLintPool.lint(params as EslintPluginLintRequest, token); + return pluginLintPool.lint( + params as PluginLintRequest, + token, + typeServiceTransport, + ); default: return forwardRequest(editorConnection, method, params, token); } diff --git a/packages/vscode/tests/stacks/lint/pluginLintPool.test.ts b/packages/vscode/tests/stacks/lint/pluginLintPool.test.ts index e37d716..b4f446b 100644 --- a/packages/vscode/tests/stacks/lint/pluginLintPool.test.ts +++ b/packages/vscode/tests/stacks/lint/pluginLintPool.test.ts @@ -1,5 +1,10 @@ import { expect, it, rs } from '@rstest/core'; -import { PluginLintPool } from '../../../src/stacks/lint/worker/PluginLintPool'; +import { CancellationTokenSource } from 'vscode-jsonrpc/node'; +import { + PluginLintPool, + type PluginLintRequest, + type PluginTypeServiceTransport, +} from '../../../src/stacks/lint/worker/PluginLintPool'; import { WorkerLogger } from '../../../src/stacks/lint/worker/logger'; it('logs the full error once per failure episode and again after recovery then re-failure', async () => { @@ -68,3 +73,143 @@ it('preserves a failure across prepare abort and restores it after commit rollba await pool.dispose(); } }); + +const lintRequest = ( + generation: string, + overrides?: Partial, +): PluginLintRequest => ({ + generation, + files: [], + rules: {}, + collectFixes: false, + ...overrides, +}); + +it('forwards typeServiceTransport as the 4th host.lint argument and preserves request fields intact', async () => { + const descriptors = [ + { configPath: '/project/rslint.config.mjs', configDirectory: '/project' }, + ]; + const lint = rs.fn(async (..._args: unknown[]) => ({ results: [] })); + const pool = new PluginLintPool(new WorkerLogger(), async () => ({ + lint, + shutdown: async () => {}, + })); + const transport: PluginTypeServiceTransport = async () => ({ + status: 'closed', + }); + const tokenSource = new CancellationTokenSource(); + try { + await pool.prepare(descriptors, 'typed', 'gen-1'); + await pool.commit('gen-1'); + + const file = { + path: '/project/src/index.ts', + frame: 'AA==', + typeServices: { + session: 'session-1', + binding: { generation: 1, sourceFileName: '/project/src/index.ts' }, + }, + }; + const request = lintRequest('gen-1', { + files: [file], + retiredTypeServices: ['session-0'], + }); + + await pool.lint(request, tokenSource.token, transport); + + expect(lint).toHaveBeenCalledTimes(1); + const [ + receivedReq, + receivedSignal, + receivedAttachments, + receivedTransport, + ] = lint.mock.calls[0]; + expect(receivedReq).toBe(request); + expect(receivedSignal).toBeInstanceOf(AbortSignal); + expect(receivedAttachments).toBeUndefined(); + expect(receivedTransport).toBe(transport); + } finally { + tokenSource.dispose(); + await pool.dispose(); + } +}); + +it('forwards retirement-only requests to an active host without short-circuiting', async () => { + const descriptors = [ + { configPath: '/project/rslint.config.mjs', configDirectory: '/project' }, + ]; + const lint = rs.fn(async (..._args: unknown[]) => ({ results: [] })); + const pool = new PluginLintPool(new WorkerLogger(), async () => ({ + lint, + shutdown: async () => {}, + })); + const transport: PluginTypeServiceTransport = async () => ({ + status: 'closed', + }); + try { + await pool.prepare(descriptors, 'typed', 'gen-1'); + await pool.commit('gen-1'); + + const retirementRequest = lintRequest('gen-1', { + retiredTypeServices: ['session-1'], + }); + + const result = await pool.lint(retirementRequest, undefined, transport); + expect(result).toEqual({ results: [] }); + expect(lint).toHaveBeenCalledTimes(1); + expect(lint.mock.calls[0][0]).toBe(retirementRequest); + expect(lint.mock.calls[0][3]).toBe(transport); + } finally { + await pool.dispose(); + } +}); + +it('returns empty results for late retirement-only requests on evicted or hostless generations', async () => { + const descriptors = [ + { configPath: '/project/rslint.config.mjs', configDirectory: '/project' }, + ]; + const pool = new PluginLintPool( + new WorkerLogger(), + async () => ({ + lint: async () => ({ results: [] }), + shutdown: async () => {}, + }), + 0, + ); + try { + // Keep gen-1 active while aborting gen-2 so gen-2 is evicted (!state) + // and cannot accidentally fall back to activeState. + await pool.prepare(descriptors, 'fp-1', 'gen-1'); + await pool.commit('gen-1'); + await pool.prepare(descriptors, 'fp-2', 'gen-2'); + await pool.abort('gen-2'); + + // Evicted generation (!state): retirement-only succeeds cleanly. + expect( + await pool.lint( + lintRequest('gen-2', { retiredTypeServices: ['session-2'] }), + ), + ).toEqual({ results: [] }); + + // Non-retirement empty request on an unknown generation still throws. + await expect(pool.lint(lintRequest('gen-2'))).rejects.toThrow( + /unknown ESLint-plugin config generation/, + ); + + // Native-only generation (!state.host): retirement-only succeeds cleanly. + await pool.prepare([], 'empty', 'gen-empty'); + await pool.commit('gen-empty'); + expect( + await pool.lint( + lintRequest('gen-empty', { retiredTypeServices: ['session-old'] }), + ), + ).toEqual({ results: [] }); + + // Non-retirement request on a hostless generation still throws. + await expect(pool.lint(lintRequest('gen-empty'))).rejects.toThrow( + /without an activated plugin host/, + ); + } finally { + await pool.dispose(); + } +}); diff --git a/packages/vscode/tests/stacks/lint/worker.test.ts b/packages/vscode/tests/stacks/lint/worker.test.ts index 3c71bc9..ed19ff0 100644 --- a/packages/vscode/tests/stacks/lint/worker.test.ts +++ b/packages/vscode/tests/stacks/lint/worker.test.ts @@ -26,7 +26,10 @@ import { CONFIG_PROCESS_EXIT_CODE, type ConfigDependencyStatusNotification, } from '../../../src/stacks/lint/worker/configDependencyProtocol'; -import { registerEditorProxy } from '../../../src/stacks/lint/worker/index'; +import { + createTypeServiceTransport, + registerEditorProxy, +} from '../../../src/stacks/lint/worker/index'; const fakeGoSource = String.raw` let buffer = Buffer.alloc(0); @@ -587,3 +590,125 @@ describe('lint worker bridged shim refusal (#93)', () => { expect(seam.exit).toBe(realExit); }); }); + +describe('lint worker typeService transport', () => { + function createConnectionPair() { + const clientToServer = new PassThrough(); + const serverToClient = new PassThrough(); + const client = createMessageConnection( + serverToClient, + clientToServer, + NullLogger, + ); + const server = createMessageConnection( + clientToServer, + serverToClient, + NullLogger, + ); + return { + client, + server, + dispose() { + client.dispose(); + server.dispose(); + clientToServer.destroy(); + serverToClient.destroy(); + }, + }; + } + + it('forwards rslint/typeService requests and returns responses verbatim', async () => { + const pair = createConnectionPair(); + const received: unknown[] = []; + try { + pair.server.onRequest('rslint/typeService', (params: unknown) => { + received.push(params); + if (received.length === 1) { + return { packets: ['AQID'] }; + } + return { status: 'closed' }; + }); + pair.server.listen(); + pair.client.listen(); + + const transport = createTypeServiceTransport(pair.client); + const firstRequest = { + session: 'session-1', + generation: 1, + open: true, + projection: '/project/src/index.ts', + }; + const controller = new AbortController(); + const firstResponse = await transport(firstRequest, controller.signal); + expect(firstResponse).toEqual({ packets: ['AQID'] }); + + // Calling without a signal also works and returns failure statuses verbatim. + const secondRequest = { + session: 'session-1', + generation: 1, + }; + const secondResponse = await transport(secondRequest); + expect(secondResponse).toEqual({ status: 'closed' }); + + expect(received).toEqual([firstRequest, secondRequest]); + + // Aborting after settlement is a no-op (listener was cleaned up). + controller.abort(); + } finally { + pair.dispose(); + } + }); + + it('propagates AbortSignal cancellation to Go via JSON-RPC $/cancelRequest', async () => { + const pair = createConnectionPair(); + const requestReceived = Promise.withResolvers(); + const cancellationObserved = Promise.withResolvers(); + try { + pair.server.onRequest( + 'rslint/typeService', + (_params: unknown, token) => + new Promise((resolve) => { + requestReceived.resolve(); + token.onCancellationRequested(() => { + cancellationObserved.resolve(); + resolve({ status: 'cancelled' }); + }); + }), + ); + pair.server.listen(); + pair.client.listen(); + + const transport = createTypeServiceTransport(pair.client); + const controller = new AbortController(); + const pending = transport( + { session: 'session-1', generation: 1, open: true }, + controller.signal, + ); + + await requestReceived.promise; + controller.abort(); + await cancellationObserved.promise; + + expect(await pending).toEqual({ status: 'cancelled' }); + } finally { + pair.dispose(); + } + }); + + it('short-circuits a pre-aborted AbortSignal without sending a request', async () => { + const sendRequest = rs.fn(); + const transport = createTypeServiceTransport({ + sendRequest: sendRequest as never, + }); + const controller = new AbortController(); + controller.abort(); + + const response = await transport( + { session: 'session-1', generation: 1, open: true }, + controller.signal, + ); + + expect(response).toEqual({ status: 'cancelled' }); + expect(sendRequest).not.toHaveBeenCalled(); + }); +});