feat(lsp): LSP capability seam, generic stdio provider, and lsp tool

Implements the LSP capability seam RFC as three packages: dsh-lsp (the
ctx.lsp interface — provider registry by branded id + exclusive extension
mapping, per-query order-independent selection, closed request/result
vocabulary, LspError taxonomy), dsh-lsp-local (a generic stdio language-server
provider — Content-Length JSON-RPC framing, per-(provider, workspace) process
single-flight, transient didOpen/query/didClose, an abortable per-instance
queue, UTF-16 negotiation, host-namespace source reads outside ctx.fs, and
bounded shutdown/kill teardown), and dsh-tool-lsp (the model-facing lsp tool —
four operations, one-based UTF-16 cursor conversion, workspace-grouped location
rendering, hover capping, a required session workspace, and a timeout budget).

Why: an agent had text search and file reads but no way to identify a program
symbol — follow an alias, connect an interface to implementations, or read an
inferred type — before changing code. Splitting model contract, seam, and local
subprocess behavior keeps the four semantic queries stable across future remote
or sandbox-native providers without leaking a JSON-RPC escape hatch.
This commit is contained in:
Dudu-0223
2026-07-16 12:05:35 +08:00
parent 66b2cfc609
commit d0029d8d60
56 changed files with 4527 additions and 30 deletions

View File

@@ -0,0 +1,73 @@
import { spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import { mkdtemp, mkdir, rm, writeFile, realpath } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
/**
* Keyless built-artifact smoke: plain Node imports `@deepseek-ai/dsh-lsp` and
* `@deepseek-ai/dsh-lsp-local` by name through their exports maps, spawns the fixture server, runs
* one query (exercising real `Content-Length` framing over `lib/index.js`), and disposes (exercising
* subprocess cleanup). Unit tests use `src/`; this pins the downstream `lib/` path. Skips when `lib/`
* is absent; CI runs it after the build.
*/
const pkgDir = fileURLToPath(new URL('..', import.meta.url))
const seamLib = join(pkgDir, '../lsp/lib/index.js')
const built = existsSync(join(pkgDir, 'lib/index.js')) && existsSync(seamLib)
const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
const fixtureServer = fileURLToPath(new URL('./fixture-server.ts', import.meta.url))
const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
let root: string
let ws: string
beforeAll(async () => {
root = await realpath(await mkdtemp(join(tmpdir(), 'lsp-built-')))
ws = join(root, 'ws')
await mkdir(ws)
await writeFile(join(ws, 'a.ts'), 'const x = 1\n')
})
afterAll(async () => {
if (root) await rm(root, { recursive: true, force: true })
})
describe.skipIf(!built)('built lib real load path (plain node)', () => {
it('runs a query through lib/index.js and disposes cleanly, framing over the base protocol', async () => {
const location = JSON.stringify({ uri: pathToFileURL(join(ws, 'a.ts')).href, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 } } })
const script = `
const { Context } = await import('cordis')
const { default: Lsp } = await import('@deepseek-ai/dsh-lsp')
const LspLocal = await import('@deepseek-ai/dsh-lsp-local')
const ctx = new Context()
await ctx.plugin(Lsp)
await ctx.plugin(LspLocal, {
providerId: 'fake',
command: ${JSON.stringify(process.execPath)},
args: ['--import', ${JSON.stringify(tsxLoader)}, ${JSON.stringify(fixtureServer)}],
env: { TSX_TSCONFIG_PATH: ${JSON.stringify(repoTsconfig)}, LSP_FAKE_DEF: ${JSON.stringify(location)} },
extensionToLanguage: { '.ts': 'typescript' },
})
const result = await ctx.lsp.query({ operation: 'definition', filePath: 'a.ts', position: { line: 0, character: 6 }, workspaceRoot: ${JSON.stringify(ws)} })
console.log(JSON.stringify(result))
await ctx.fiber.dispose()
process.exit(0)
`
const child = spawn(process.execPath, ['--input-type=module', '-e', script], { cwd: pkgDir, stdio: ['ignore', 'pipe', 'pipe'] })
let stdout = ''
let stderr = ''
child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf8') })
child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
const exitCode = await new Promise<number | null>(resolve => child.on('close', resolve))
expect(exitCode, `stderr:\n${stderr}`).toBe(0)
const lastLine = stdout.trim().split('\n').at(-1) ?? ''
const result = JSON.parse(lastLine) as { kind: string; locations: unknown[] }
expect(result.kind).toBe('locations')
expect(result.locations).toHaveLength(1)
}, 60_000)
})

View File

@@ -0,0 +1,226 @@
import { afterEach, describe, expect, it } from 'vitest'
import { fileURLToPath } from 'node:url'
import { LspConnection } from '@deepseek-ai/dsh-lsp-local'
const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
const fixtureServer = fileURLToPath(new URL('./fixture-server.ts', import.meta.url))
const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
/** A recorded server→client request the test's handler saw. */
interface SeenRequest { method: string; params: unknown }
let open: LspConnection[] = []
afterEach(async () => {
for (const conn of open) {
conn.kill()
await conn.closed
}
open = []
})
/** Spawn the fixture as a raw connection, with a scripted server-request handler. */
function connect(
env: Record<string, string>,
onServerRequest: (method: string, params: unknown) => Promise<unknown> = () => Promise.resolve(null),
seen?: SeenRequest[],
): LspConnection {
const conn = new LspConnection({
command: process.execPath,
args: ['--import', tsxLoader, fixtureServer],
cwd: process.cwd(),
env: { ...process.env as Record<string, string>, TSX_TSCONFIG_PATH: repoTsconfig, ...env },
maxMessageBytes: 16_000_000,
maxStderrBytes: 100_000,
configuration: { setting: 42 },
}, (method, params) => {
seen?.push({ method, params })
return onServerRequest(method, params)
})
open.push(conn)
return conn
}
describe('LspConnection', () => {
it('completes an initialize request/response round-trip and exposes a pid', async () => {
const conn = connect({})
const result = await conn.request('initialize', { capabilities: {} })
expect(result).toMatchObject({ capabilities: { hoverProvider: true } })
expect(conn.pid).toBeGreaterThan(0)
})
it('rejects a request when the server replies with an error', async () => {
const conn = connect({ LSP_FAKE_ERROR: '1' })
await conn.request('initialize', { capabilities: {} })
await expect(conn.request('textDocument/hover', {})).rejects.toThrow(/server refused the request/)
})
it('answers a server workspace/configuration request from static config', async () => {
const seen: SeenRequest[] = []
const conn = connect(
{ LSP_FAKE_ON_OPEN: 'configuration' },
(method, params) => {
if (method === 'workspace/configuration') {
const items = (params as { items: unknown[] }).items
return Promise.resolve(items.map(() => ({ setting: 42 })))
}
return Promise.resolve(null)
},
seen,
)
await conn.request('initialize', { capabilities: {} })
conn.notify('textDocument/didOpen', { textDocument: { uri: 'file:///x', languageId: 'ts', version: 1, text: '' } })
await waitFor(() => seen.some(s => s.method === 'workspace/configuration'))
expect(seen[0]?.method).toBe('workspace/configuration')
})
it('drops a server→client notification without replying', async () => {
const conn = connect({ LSP_FAKE_ON_OPEN: 'notification' })
await conn.request('initialize', { capabilities: {} })
conn.notify('textDocument/didOpen', { textDocument: { uri: 'file:///x', languageId: 'ts', version: 1, text: '' } })
// No throw and the connection stays usable.
await expect(conn.request('textDocument/hover', {})).resolves.toBeDefined()
})
it('sends an error response when the server-request handler rejects', async () => {
const seen: SeenRequest[] = []
const conn = connect(
{ LSP_FAKE_ON_OPEN: 'applyEdit' },
method => method === 'workspace/applyEdit' ? Promise.reject(new Error('not permitted')) : Promise.resolve(null),
seen,
)
await conn.request('initialize', { capabilities: {} })
conn.notify('textDocument/didOpen', { textDocument: { uri: 'file:///x', languageId: 'ts', version: 1, text: '' } })
await waitFor(() => seen.some(s => s.method === 'workspace/applyEdit'))
// The connection remains healthy after emitting the error response.
await expect(conn.request('textDocument/hover', {})).resolves.toBeDefined()
})
it('fails all pending requests and kills the process on a framing error', async () => {
const conn = connect({ LSP_FAKE_GARBAGE: '1' })
// The garbage byte precedes a valid initialize reply; unframed bytes are tolerated until a
// Content-Length header, so initialize still resolves. This exercises the decoder's resilience.
await expect(conn.request('initialize', { capabilities: {} })).resolves.toBeDefined()
})
it('rejects a new request issued after the process closes', async () => {
const conn = connect({})
await conn.request('initialize', { capabilities: {} })
conn.terminate()
await conn.closed
await expect(conn.request('textDocument/hover', {})).rejects.toThrow(/exited|closed/)
})
it('cancel is a no-op-safe write after close', async () => {
const conn = connect({})
await conn.request('initialize', { capabilities: {} })
conn.terminate()
await conn.closed
expect(() => { conn.cancel(1) }).not.toThrow()
})
it('caps the retained stderr tail', async () => {
const conn = connect({})
await conn.request('initialize', { capabilities: {} })
expect(conn.stderrTail.length).toBeLessThanOrEqual(100_000)
})
})
/** Spawn a raw connection running an inline node script as the "server". */
function connectScript(script: string, maxStderrBytes = 100_000): LspConnection {
const conn = new LspConnection({
command: process.execPath,
args: ['-e', script],
cwd: process.cwd(),
env: { ...process.env as Record<string, string> },
maxMessageBytes: 16_000_000,
maxStderrBytes,
configuration: null,
}, () => Promise.resolve(null))
open.push(conn)
return conn
}
describe('LspConnection edge behavior', () => {
it('fails a request when the command cannot be spawned', async () => {
const conn = new LspConnection({
command: '/definitely/not/a/real/binary/xyz',
args: [],
cwd: process.cwd(),
env: {},
maxMessageBytes: 1000,
maxStderrBytes: 1000,
configuration: null,
}, () => Promise.resolve(null))
open.push(conn)
await expect(conn.request('initialize', {})).rejects.toThrow()
})
it('kills the process and fails pending requests on a framing error', async () => {
// Emit an invalid Content-Length header, corrupting the stream irrecoverably.
const conn = connectScript('process.stdout.write("Content-Length: abc\\r\\n\\r\\n{}"); setInterval(()=>{}, 1000)')
await expect(conn.request('initialize', {})).rejects.toThrow()
})
it('ignores a framed non-object message', async () => {
// Send a framed JSON number and a framed null (both non-objects) then a proper response to id 1.
const script = 'let b=Buffer.alloc(0);'
+ 'const fr=(s)=>{const x=Buffer.from(s);return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};'
+ 'process.stdout.write(fr("42"));process.stdout.write(fr("null"));'
+ 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);const s=b.indexOf("\\r\\n\\r\\n");if(s<0)return;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);const body=JSON.parse(b.toString("utf8",s+4,s+4+len));process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:body.id,result:{ok:true}})));});'
const conn = connectScript(script)
await expect(conn.request('initialize', {})).resolves.toEqual({ ok: true })
})
it('drops a response for an unknown id', async () => {
// Emit a response for id 999 (never sent), then answer our real request.
const script = 'let b=Buffer.alloc(0);'
+ 'const fr=(s)=>{const x=Buffer.from(s);return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};'
+ 'process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:999,result:{stray:true}})));'
+ 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);const s=b.indexOf("\\r\\n\\r\\n");if(s<0)return;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);const body=JSON.parse(b.toString("utf8",s+4,s+4+len));process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:body.id,result:{ok:true}})));});'
const conn = connectScript(script)
await expect(conn.request('initialize', {})).resolves.toEqual({ ok: true })
})
it('caps the retained stderr tail at maxStderrBytes across chunks', async () => {
// Write stderr repeatedly so a later chunk arrives after the cap is already reached.
const conn = connectScript('setInterval(()=>process.stderr.write("E".repeat(200)), 5); setInterval(()=>{}, 1000)', 100)
await waitFor(() => conn.stderrTail.length >= 100)
await new Promise<void>(resolve => setTimeout(resolve, 50))
expect(conn.stderrTail.length).toBe(100)
})
it('rejects with a fallback message when the error response has no message string', async () => {
const script = 'let b=Buffer.alloc(0);'
+ 'const fr=(s)=>{const x=Buffer.from(s);return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};'
+ 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);const s=b.indexOf("\\r\\n\\r\\n");if(s<0)return;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);const body=JSON.parse(b.toString("utf8",s+4,s+4+len));process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:body.id,error:{code:-1}})));});'
const conn = connectScript(script)
await expect(conn.request('initialize', {})).rejects.toThrow(/LSP error response/)
})
it('rejects a pending request when the process exits mid-flight', async () => {
// Never responds, then exits shortly: the pending request must reject on close.
const conn = connectScript('setTimeout(()=>process.exit(0), 100)')
await expect(conn.request('initialize', {})).rejects.toThrow(/exited|closed/)
})
it('ignores a frame that is neither a valid request nor a numeric-id response', async () => {
// A frame with a string id and no method: not dispatchable; the client must ignore it and still
// answer our real request.
const script = 'let b=Buffer.alloc(0);'
+ 'const fr=(s)=>{const x=Buffer.from(s);return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};'
+ 'process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:"str-id"})));'
+ 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);const s=b.indexOf("\\r\\n\\r\\n");if(s<0)return;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);const body=JSON.parse(b.toString("utf8",s+4,s+4+len));process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:body.id,result:{ok:true}})));});'
const conn = connectScript(script)
await expect(conn.request('initialize', {})).resolves.toEqual({ ok: true })
})
})
/** Poll a predicate until it holds or a deadline elapses. */
async function waitFor(predicate: () => boolean, timeoutMs = 3000): Promise<void> {
const start = Date.now()
while (!predicate()) {
if (Date.now() - start > timeoutMs) throw new Error('waitFor timed out')
await new Promise<void>(resolve => setTimeout(resolve, 10))
}
}

View File

@@ -0,0 +1,144 @@
/**
* A scriptable fake LSP server over stdio for lsp-local tests. It speaks the real
* `Content-Length`-framed base protocol so it exercises the client's framing, initialize handshake,
* transient open/close, request mapping, and teardown — without a real language server.
*
* Behavior is driven by env vars so one file backs many scenarios:
* - LSP_FAKE_ENCODING: advertised positionEncoding (default utf-16; "utf-8" forces a mismatch).
* - LSP_FAKE_SYNC: textDocumentSync value as JSON (default 1/Full).
* - LSP_FAKE_CAPS: JSON of extra capability flags merged into the defaults.
* - LSP_FAKE_DEF / LSP_FAKE_REFS / LSP_FAKE_IMPL / LSP_FAKE_HOVER: JSON result per request.
* - LSP_FAKE_HANG: "1" makes textDocument/* requests never respond (for abort/timeout tests).
* - LSP_FAKE_CRASH_ON_OPEN: "1" exits the process when a didOpen arrives (crash test).
* - LSP_FAKE_NO_SHUTDOWN: "1" ignores the shutdown request (forces kill escalation).
* - LSP_FAKE_ON_OPEN: server→client request to emit when a didOpen arrives, one of
* "configuration" | "applyEdit" | "notification" | "unknown"; the reply is logged to stderr.
* - LSP_FAKE_ERROR: "1" answers textDocument/* requests with a JSON-RPC error response.
* - LSP_FAKE_GARBAGE: "1" emits an unframed garbage byte before the initialize reply.
*
* Run: node --import tsx fixture-server.ts
*/
const enc = process.env.LSP_FAKE_ENCODING ?? 'utf-16'
const sync: unknown = process.env.LSP_FAKE_SYNC !== undefined ? JSON.parse(process.env.LSP_FAKE_SYNC) : 1
const extraCaps: unknown = process.env.LSP_FAKE_CAPS !== undefined ? JSON.parse(process.env.LSP_FAKE_CAPS) : {}
const hang = process.env.LSP_FAKE_HANG === '1'
const crashOnOpen = process.env.LSP_FAKE_CRASH_ON_OPEN === '1'
const noShutdown = process.env.LSP_FAKE_NO_SHUTDOWN === '1'
const onOpen = process.env.LSP_FAKE_ON_OPEN
const errorReply = process.env.LSP_FAKE_ERROR === '1'
const garbage = process.env.LSP_FAKE_GARBAGE === '1'
let serverRequestId = 10_000
const pendingServerRequests = new Map<number, string>()
function resultFor(method: string): unknown {
switch (method) {
case 'textDocument/definition': return envJson('LSP_FAKE_DEF', null)
case 'textDocument/references': return envJson('LSP_FAKE_REFS', null)
case 'textDocument/implementation': return envJson('LSP_FAKE_IMPL', null)
case 'textDocument/hover': return envJson('LSP_FAKE_HOVER', null)
default: return null
}
}
function envJson(name: string, fallback: unknown): unknown {
const raw = process.env[name]
return raw === undefined ? fallback : JSON.parse(raw)
}
let buffer = Buffer.alloc(0)
process.stdin.on('data', (chunk: Buffer) => {
buffer = Buffer.concat([buffer, chunk])
for (;;) {
const sep = buffer.indexOf('\r\n\r\n')
if (sep < 0) break
const header = buffer.toString('ascii', 0, sep)
const match = /content-length:\s*(\d+)/i.exec(header)
if (!match) { buffer = buffer.subarray(sep + 4); continue }
const length = Number(match[1])
const start = sep + 4
if (buffer.length < start + length) break
const body = buffer.toString('utf8', start, start + length)
buffer = buffer.subarray(start + length)
handle(JSON.parse(body) as { id?: number; method?: string; params?: unknown; result?: unknown; error?: unknown })
}
})
function handle(message: { id?: number; method?: string; params?: unknown; result?: unknown; error?: unknown }): void {
const { id, method } = message
// A frame with an id but no method is the client's REPLY to a server→client request; log it.
if (method === undefined && id !== undefined && pendingServerRequests.has(id)) {
const kind = pendingServerRequests.get(id)
pendingServerRequests.delete(id)
process.stderr.write(`REPLY ${kind} ${JSON.stringify({ result: message.result, error: message.error })}\n`)
return
}
if (method === 'initialize') {
if (garbage) process.stdout.write('this is not a framed message\r\n')
send({
id,
result: {
capabilities: {
positionEncoding: enc,
textDocumentSync: sync,
definitionProvider: true,
referencesProvider: true,
implementationProvider: true,
hoverProvider: true,
...(extraCaps as Record<string, unknown>),
},
},
})
return
}
if (method === 'shutdown') {
if (noShutdown) return
send({ id, result: null })
return
}
if (method === 'exit') {
process.exit(0)
}
if (method === 'textDocument/didOpen') {
if (crashOnOpen) process.exit(1)
if (onOpen !== undefined) emitServerRequest(onOpen)
return
}
if (method === 'textDocument/didClose' || method === 'initialized') return
if (method?.startsWith('textDocument/')) {
if (hang) return
if (errorReply) { send({ id, error: { code: -32000, message: 'server refused the request' } }); return }
send({ id, result: resultFor(method) })
return
}
// Unknown request with an id: answer null so the client never stalls.
if (id !== undefined) send({ id, result: null })
}
/** Emit a server→client request and log the client's reply to stderr for the test to assert. */
function emitServerRequest(kind: string): void {
if (kind === 'notification') {
send({ method: 'window/logMessage', params: { type: 3, message: 'hello' } })
return
}
const id = serverRequestId++
const method = kind === 'configuration'
? 'workspace/configuration'
: kind === 'applyEdit'
? 'workspace/applyEdit'
: kind === 'lifecycle'
? 'client/registerCapability'
: 'window/showMessageRequest'
const params = kind === 'configuration' ? { items: [{ section: 'a' }, { section: 'b' }] } : {}
pendingServerRequests.set(id, method)
send({ id, method, params })
}
function send(message: Record<string, unknown>): void {
const body = Buffer.from(JSON.stringify({ jsonrpc: '2.0', ...message }), 'utf8')
process.stdout.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, 'ascii'), body]))
}
// Keep the event loop alive.
process.stdin.resume()

View File

@@ -0,0 +1,76 @@
import { describe, expect, it } from 'vitest'
import { encodeMessage, MessageDecoder } from '@deepseek-ai/dsh-lsp-local'
/** Frame a message the way a server would, for decoder round-trips. */
function frame(body: string): Buffer {
return Buffer.concat([Buffer.from(`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n`, 'ascii'), Buffer.from(body, 'utf8')])
}
describe('encodeMessage', () => {
it('prefixes a Content-Length header with the utf-8 byte length', () => {
const buffer = encodeMessage({ jsonrpc: '2.0', method: 'x', params: { s: 'é' } })
const text = buffer.toString('utf8')
const body = '{"jsonrpc":"2.0","method":"x","params":{"s":"é"}}'
expect(text).toBe(`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`)
})
})
describe('MessageDecoder', () => {
it('decodes a single framed message', () => {
const decoder = new MessageDecoder(1_000)
expect(decoder.push(frame('{"id":1,"result":42}'))).toEqual([{ id: 1, result: 42 }])
})
it('decodes multiple messages arriving in one chunk', () => {
const decoder = new MessageDecoder(1_000)
const chunk = Buffer.concat([frame('{"a":1}'), frame('{"b":2}')])
expect(decoder.push(chunk)).toEqual([{ a: 1 }, { b: 2 }])
})
it('reassembles a message split across chunks', () => {
const decoder = new MessageDecoder(1_000)
const full = frame('{"hello":"world"}')
expect(decoder.push(full.subarray(0, 10))).toEqual([])
expect(decoder.push(full.subarray(10))).toEqual([{ hello: 'world' }])
})
it('handles a header split from its body', () => {
const decoder = new MessageDecoder(1_000)
const body = '{"x":1}'
expect(decoder.push(Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, 'ascii'))).toEqual([])
expect(decoder.push(Buffer.from(body, 'utf8'))).toEqual([{ x: 1 }])
})
it('reads a case-insensitive header and ignores other headers', () => {
const decoder = new MessageDecoder(1_000)
const body = '{"ok":true}'
const chunk = Buffer.from(`content-length: ${body.length}\r\nContent-Type: x\r\n\r\n${body}`, 'utf8')
expect(decoder.push(chunk)).toEqual([{ ok: true }])
})
it('rejects a body over the size limit', () => {
const decoder = new MessageDecoder(4)
expect(() => decoder.push(frame('{"big":true}'))).toThrow(/exceeds the 4-byte limit/)
})
it('rejects a missing Content-Length header', () => {
const decoder = new MessageDecoder(1_000)
expect(() => decoder.push(Buffer.from('X: 1\r\n\r\n{}', 'utf8'))).toThrow(/missing Content-Length/)
})
it('rejects a non-numeric Content-Length', () => {
const decoder = new MessageDecoder(1_000)
expect(() => decoder.push(Buffer.from('Content-Length: abc\r\n\r\n{}', 'utf8'))).toThrow(/invalid Content-Length/)
})
it('rejects a header block that never terminates', () => {
const decoder = new MessageDecoder(1_000)
const huge = Buffer.alloc((1 << 16) + 1, 0x41)
expect(() => decoder.push(huge)).toThrow(/exceeded .* bytes without a terminator/)
})
it('rejects a non-JSON body', () => {
const decoder = new MessageDecoder(1_000)
expect(() => decoder.push(frame('not json'))).toThrow(/not valid JSON/)
})
})

View File

@@ -0,0 +1,105 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { realpath } from 'node:fs/promises'
import { canonicalizeWorkspace, readHostSource } from '@deepseek-ai/dsh-lsp-local'
let root: string
let ws: string
beforeEach(async () => {
root = await realpath(await mkdtemp(join(tmpdir(), 'lsp-host-')))
ws = join(root, 'ws')
await mkdir(ws)
})
afterEach(async () => {
await rm(root, { recursive: true, force: true })
})
const BIG = 1_000_000
describe('canonicalizeWorkspace', () => {
it('returns the realpath of a directory', async () => {
expect(await canonicalizeWorkspace(ws)).toBe(ws)
})
it('resolves a symlinked workspace to its target so aliases share identity', async () => {
const link = join(root, 'ws-link')
await symlink(ws, link)
expect(await canonicalizeWorkspace(link)).toBe(ws)
})
it('rejects a missing workspace', async () => {
await expect(canonicalizeWorkspace(join(root, 'nope'))).rejects.toThrow(/cannot be resolved/)
})
it('rejects a non-directory workspace', async () => {
const file = join(root, 'file.txt')
await writeFile(file, 'x')
await expect(canonicalizeWorkspace(file)).rejects.toThrow(/not a directory/)
})
})
describe('readHostSource', () => {
it('reads a relative path against the workspace', async () => {
await writeFile(join(ws, 'a.ts'), 'const x = 1\n')
const source = await readHostSource('a.ts', ws, BIG)
expect(source.canonicalPath).toBe(join(ws, 'a.ts'))
expect(source.text).toBe('const x = 1\n')
})
it('reads an absolute path inside the workspace', async () => {
const abs = join(ws, 'b.ts')
await writeFile(abs, 'b')
const source = await readHostSource(abs, ws, BIG)
expect(source.canonicalPath).toBe(abs)
})
it('accepts a source reached through a symlink that stays inside the workspace', async () => {
await mkdir(join(ws, 'real'))
await writeFile(join(ws, 'real', 'c.ts'), 'c')
await symlink(join(ws, 'real'), join(ws, 'linked'))
const source = await readHostSource('linked/c.ts', ws, BIG)
expect(source.canonicalPath).toBe(join(ws, 'real', 'c.ts'))
})
it('rejects a source whose canonical path escapes the workspace via symlink', async () => {
const outside = join(root, 'outside.ts')
await writeFile(outside, 'secret')
await symlink(outside, join(ws, 'escape.ts'))
await expect(readHostSource('escape.ts', ws, BIG)).rejects.toThrow(/outside the workspace/)
})
it('rejects an absolute source outside the workspace', async () => {
const outside = join(root, 'out.ts')
await writeFile(outside, 'x')
await expect(readHostSource(outside, ws, BIG)).rejects.toThrow(/outside the workspace/)
})
it('rejects a missing source', async () => {
await expect(readHostSource('nope.ts', ws, BIG)).rejects.toThrow(/cannot be resolved/)
})
it('rejects a non-regular source (directory)', async () => {
await mkdir(join(ws, 'dir'))
await expect(readHostSource('dir', ws, BIG)).rejects.toThrow(/not a regular file/)
})
it('treats the workspace root itself as inside, then rejects it as non-regular', async () => {
// filePath '.' canonicalizes to the workspace dir: isInside's identity branch is taken, and the
// directory then fails the regular-file check.
await expect(readHostSource('.', ws, BIG)).rejects.toThrow(/not a regular file/)
})
it('rejects an oversized source', async () => {
await writeFile(join(ws, 'big.ts'), 'x'.repeat(100))
await expect(readHostSource('big.ts', ws, 10)).rejects.toThrow(/over the 10-byte limit/)
})
it('rejects a non-UTF-8 source', async () => {
await writeFile(join(ws, 'bin.ts'), Buffer.from([0xff, 0xfe, 0x00]))
await expect(readHostSource('bin.ts', ws, BIG)).rejects.toThrow(/not valid UTF-8/)
})
})

View File

@@ -0,0 +1,184 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mkdtemp, mkdir, rm, writeFile, realpath } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL, fileURLToPath } from 'node:url'
import { LspInstance } from '@deepseek-ai/dsh-lsp-local'
import type { InstanceSpec } from '@deepseek-ai/dsh-lsp-local/src/instance.ts'
import type { LspProviderQuery } from '@deepseek-ai/dsh-lsp'
const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
const fixtureServer = fileURLToPath(new URL('./fixture-server.ts', import.meta.url))
const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
let root: string
let ws: string
let live: LspInstance[] = []
beforeEach(async () => {
root = await realpath(await mkdtemp(join(tmpdir(), 'lsp-inst-')))
ws = join(root, 'ws')
await mkdir(ws)
await writeFile(join(ws, 'a.ts'), 'const x = 1\n')
})
afterEach(async () => {
for (const instance of live) await instance.dispose()
live = []
await rm(root, { recursive: true, force: true })
})
function makeInstance(env: Record<string, string> = {}, overrides: Partial<InstanceSpec> = {}): LspInstance {
const instance = new LspInstance({
command: process.execPath,
args: ['--import', tsxLoader, fixtureServer],
cwd: ws,
env: { ...process.env as Record<string, string>, TSX_TSCONFIG_PATH: repoTsconfig, ...env },
configuration: { setting: 42 },
initializationOptions: { init: true },
maxMessageBytes: 16_000_000,
maxStderrBytes: 100_000,
maxDocumentBytes: 4_000_000,
shutdownTimeoutMs: 200,
killGraceMs: 200,
...overrides,
})
live.push(instance)
return instance
}
function query(operation: LspProviderQuery['operation'] = 'definition'): LspProviderQuery {
return { operation, filePath: 'a.ts', position: { line: 0, character: 6 }, workspaceRoot: ws, languageId: 'typescript' }
}
/** Build an instance whose "server" is an inline node script (for teardown-escalation control). */
function scriptInstance(script: string, overrides: Partial<InstanceSpec> = {}): LspInstance {
const instance = new LspInstance({
command: process.execPath,
args: ['-e', script],
cwd: ws,
env: { ...process.env as Record<string, string> },
configuration: null,
initializationOptions: null,
maxMessageBytes: 16_000_000,
maxStderrBytes: 100_000,
maxDocumentBytes: 4_000_000,
shutdownTimeoutMs: 150,
killGraceMs: 150,
...overrides,
})
live.push(instance)
return instance
}
/** An inline server that answers initialize + definition and echoes a location. */
const RESPONDING_SERVER =
'let b=Buffer.alloc(0);'
+ 'const fr=(o)=>{const x=Buffer.from(JSON.stringify({jsonrpc:"2.0",...o}));return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};'
+ 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);for(;;){const s=b.indexOf("\\r\\n\\r\\n");if(s<0)break;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);if(b.length<s+4+len)break;const m=JSON.parse(b.toString("utf8",s+4,s+4+len));b=b.subarray(s+4+len);'
+ 'if(m.method==="initialize")process.stdout.write(fr({id:m.id,result:{capabilities:{positionEncoding:"utf-16",textDocumentSync:1,definitionProvider:true}}}));'
+ 'else if(m.method==="textDocument/definition")process.stdout.write(fr({id:m.id,result:null}));'
+ '}});'
const locJson = () => JSON.stringify({ uri: pathToFileURL(join(ws, 'a.ts')).href, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 } } })
describe('LspInstance server-request handling', () => {
it('answers workspace/configuration with the static config per item', async () => {
const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'configuration', LSP_FAKE_DEF: locJson() })
// The query drives didOpen, which makes the fake emit workspace/configuration; a healthy answer
// keeps the query working.
await expect(instance.query(query('definition'))).resolves.toMatchObject({ kind: 'locations' })
})
it('accepts a lifecycle client/registerCapability request', async () => {
const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'lifecycle', LSP_FAKE_DEF: 'null' })
await expect(instance.query(query('definition'))).resolves.toEqual({ kind: 'locations', locations: [] })
})
it('rejects a workspace/applyEdit request but keeps serving', async () => {
const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'applyEdit', LSP_FAKE_DEF: 'null' })
await expect(instance.query(query('definition'))).resolves.toEqual({ kind: 'locations', locations: [] })
})
it('rejects an unknown server request but keeps serving', async () => {
const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'unknown', LSP_FAKE_DEF: 'null' })
await expect(instance.query(query('definition'))).resolves.toEqual({ kind: 'locations', locations: [] })
})
})
describe('LspInstance query and abort', () => {
it('sends includeDeclaration for references', async () => {
const instance = makeInstance({ LSP_FAKE_REFS: JSON.stringify([JSON.parse(locJson())]) })
await expect(instance.query(query('references'))).resolves.toMatchObject({ kind: 'locations' })
})
it('rejects a query aborted before it starts', async () => {
const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
const controller = new AbortController()
controller.abort(new Error('pre-abort'))
await expect(instance.query(query('definition'), controller.signal)).rejects.toThrow(/pre-abort/)
})
it('cancels an in-flight request on abort and rejects', async () => {
const instance = makeInstance({ LSP_FAKE_HANG: '1' })
const controller = new AbortController()
// Warm the instance first so the abort lands during the hanging request, not during startup.
const pending = instance.query(query('definition'), controller.signal)
await new Promise<void>(resolve => setTimeout(resolve, 300))
controller.abort(new Error('mid-flight'))
await expect(pending).rejects.toThrow(/mid-flight/)
})
it('rejects when the server lacks the operation capability', async () => {
const instance = makeInstance({ LSP_FAKE_CAPS: JSON.stringify({ definitionProvider: false }), LSP_FAKE_DEF: 'null' })
await expect(instance.query(query('definition'))).rejects.toThrow(/does not support definition/)
})
it('propagates a server error response even when a signal is supplied (not an abort)', async () => {
// A live signal is passed, but the request fails for a server reason; the catch must rethrow
// without treating it as an abort.
const instance = makeInstance({ LSP_FAKE_ERROR: '1' })
const controller = new AbortController()
await expect(instance.query(query('definition'), controller.signal)).rejects.toThrow(/server refused/)
})
})
describe('LspInstance disposal', () => {
it('is idempotent — a second dispose awaits close without error', async () => {
const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
await instance.query(query('definition'))
await instance.dispose()
await expect(instance.dispose()).resolves.toBeUndefined()
})
it('rejects a query after disposal', async () => {
const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
await instance.query(query('definition'))
await instance.dispose()
await expect(instance.query(query('definition'))).rejects.toThrow(/disposed/)
})
it('reports dead after the process closes', async () => {
const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
await instance.query(query('definition'))
await instance.dispose()
expect(instance.dead).toBe(true)
})
it('escalates to SIGKILL when the server ignores shutdown and SIGTERM', async () => {
// Server answers initialize, ignores shutdown, and traps SIGTERM so only SIGKILL stops it.
const script = RESPONDING_SERVER + 'process.on("SIGTERM",()=>{});'
const instance = scriptInstance(script, { shutdownTimeoutMs: 100, killGraceMs: 100 })
await instance.query(query('definition'))
await expect(instance.dispose()).resolves.toBeUndefined()
})
it('carries a non-Error abort reason as a generic aborted error', async () => {
const instance = makeInstance({ LSP_FAKE_HANG: '1' })
const controller = new AbortController()
const pending = instance.query(query('definition'), controller.signal)
await new Promise<void>(resolve => setTimeout(resolve, 200))
controller.abort('a string reason, not an Error')
await expect(pending).rejects.toThrow(/aborted/)
})
})

View File

@@ -0,0 +1,200 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { realpath } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL, fileURLToPath } from 'node:url'
import { Context } from 'cordis'
import Lsp, { type LspQueryRequest, type LspQueryResult } from '@deepseek-ai/dsh-lsp'
import { deadline } from '@deepseek-ai/dsh-timeout'
import * as LspLocal from '@deepseek-ai/dsh-lsp-local'
import type { Config } from '@deepseek-ai/dsh-lsp-local'
const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
const fixtureServer = fileURLToPath(new URL('./fixture-server.ts', import.meta.url))
const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
let root: string
let ws: string
beforeEach(async () => {
root = await realpath(await mkdtemp(join(tmpdir(), 'lsp-local-')))
ws = join(root, 'ws')
await mkdir(ws)
await writeFile(join(ws, 'a.ts'), 'const x = 1\nconst y = x\n')
})
afterEach(async () => {
await rm(root, { recursive: true, force: true })
})
/** Mount the real seam + lsp-local plugin driving the fake server with the given env. */
async function mount(fakeEnv: Record<string, string> = {}, overrides: Partial<Config> = {}): Promise<Context> {
const ctx = new Context()
await ctx.plugin(Lsp)
await ctx.plugin(LspLocal, {
providerId: 'fake',
command: process.execPath,
args: ['--import', tsxLoader, fixtureServer],
env: { TSX_TSCONFIG_PATH: repoTsconfig, ...fakeEnv },
extensionToLanguage: { '.ts': 'typescript' },
...overrides,
})
return ctx
}
function query(operation: LspQueryRequest['operation'], filePath = 'a.ts'): LspQueryRequest {
return { operation, filePath, position: { line: 0, character: 6 }, workspaceRoot: ws }
}
/** A single Location JSON pointing into the workspace. */
function locationJson(line: number): unknown {
return { uri: pathToFileURL(join(ws, 'a.ts')).href, range: { start: { line, character: 0 }, end: { line, character: 3 } } }
}
describe('lsp-local end to end over a fake server', () => {
it('resolves definition to normalized locations', async () => {
const ctx = await mount({ LSP_FAKE_DEF: JSON.stringify(locationJson(0)) })
const result = await ctx.lsp.query(query('definition'))
expect(result).toEqual<LspQueryResult>({
kind: 'locations',
locations: [{ uri: pathToFileURL(join(ws, 'a.ts')).href, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 } } }],
})
await ctx.fiber.dispose()
})
it('maps a LocationLink for implementation', async () => {
const link = { targetUri: pathToFileURL(join(ws, 'a.ts')).href, targetSelectionRange: { start: { line: 1, character: 0 }, end: { line: 1, character: 2 } } }
const ctx = await mount({ LSP_FAKE_IMPL: JSON.stringify([link]) })
const result = await ctx.lsp.query(query('implementation'))
expect(result).toMatchObject({ kind: 'locations', locations: [{ range: { start: { line: 1, character: 0 } } }] })
await ctx.fiber.dispose()
})
it('returns references (server includes the declaration)', async () => {
const ctx = await mount({ LSP_FAKE_REFS: JSON.stringify([locationJson(0), locationJson(1)]) })
const result = await ctx.lsp.query(query('references'))
expect(result).toMatchObject({ kind: 'locations' })
if (result.kind !== 'locations') throw new Error('expected locations')
expect(result.locations).toHaveLength(2)
await ctx.fiber.dispose()
})
it('normalizes a hover MarkupContent', async () => {
const ctx = await mount({ LSP_FAKE_HOVER: JSON.stringify({ contents: { kind: 'markdown', value: 'docs' } }) })
const result = await ctx.lsp.query(query('hover'))
expect(result).toEqual({ kind: 'hover', hover: { contents: 'docs' } })
await ctx.fiber.dispose()
})
it('returns an empty locations result for a null definition', async () => {
const ctx = await mount({ LSP_FAKE_DEF: 'null' })
expect(await ctx.lsp.query(query('definition'))).toEqual({ kind: 'locations', locations: [] })
await ctx.fiber.dispose()
})
it('returns a null hover for a null result', async () => {
const ctx = await mount({ LSP_FAKE_HOVER: 'null' })
expect(await ctx.lsp.query(query('hover'))).toEqual({ kind: 'hover', hover: null })
await ctx.fiber.dispose()
})
it('rejects a non-utf-16 position encoding at initialize', async () => {
const ctx = await mount({ LSP_FAKE_ENCODING: 'utf-8', LSP_FAKE_DEF: 'null' })
await expect(ctx.lsp.query(query('definition'))).rejects.toThrow(/unsupported position encoding/)
await ctx.fiber.dispose()
})
it('rejects a server without transient-open sync (None)', async () => {
const ctx = await mount({ LSP_FAKE_SYNC: '0', LSP_FAKE_DEF: 'null' })
await expect(ctx.lsp.query(query('definition'))).rejects.toThrow(/transient textDocument\/didOpen/)
await ctx.fiber.dispose()
})
it('accepts openClose options sync', async () => {
const ctx = await mount({ LSP_FAKE_SYNC: JSON.stringify({ openClose: true, change: 2 }), LSP_FAKE_DEF: 'null' })
expect(await ctx.lsp.query(query('definition'))).toEqual({ kind: 'locations', locations: [] })
await ctx.fiber.dispose()
})
it('fails a query for an unsupported operation', async () => {
const ctx = await mount({ LSP_FAKE_CAPS: JSON.stringify({ hoverProvider: false }), LSP_FAKE_DEF: 'null' })
await expect(ctx.lsp.query(query('hover'))).rejects.toThrow(/does not support hover/)
await ctx.fiber.dispose()
})
it('rejects a source outside the workspace before startup', async () => {
const outside = join(root, 'out.ts')
await writeFile(outside, 'x')
const ctx = await mount({ LSP_FAKE_DEF: 'null' })
await expect(ctx.lsp.query({ ...query('definition'), filePath: outside })).rejects.toThrow(/outside the workspace/)
await ctx.fiber.dispose()
})
it('serializes queries through one instance and runs them in order', async () => {
const ctx = await mount({ LSP_FAKE_DEF: JSON.stringify(locationJson(0)) })
const results = await Promise.all([
ctx.lsp.query(query('definition')),
ctx.lsp.query(query('definition')),
ctx.lsp.query(query('definition')),
])
for (const result of results) expect(result).toMatchObject({ kind: 'locations' })
await ctx.fiber.dispose()
})
it('aborts an in-flight query when the signal fires', async () => {
const ctx = await mount({ LSP_FAKE_HANG: '1' })
const controller = new AbortController()
const pending = ctx.lsp.query(query('definition'), controller.signal)
controller.abort(new Error('caller cancelled'))
await expect(pending).rejects.toThrow(/cancelled/)
await ctx.fiber.dispose()
})
it('classifies a timeout deadline as the abort reason', async () => {
const ctx = await mount({ LSP_FAKE_HANG: '1' })
using d = deadline(undefined, 50, 'TEST_TIMEOUT')
await expect(ctx.lsp.query(query('definition'), d.signal)).rejects.toThrow(/TEST_TIMEOUT/)
await ctx.fiber.dispose()
})
it('fails the active query when the server crashes on open, and replaces it next query', async () => {
const ctx = await mount({ LSP_FAKE_CRASH_ON_OPEN: '1', LSP_FAKE_DEF: 'null' }, { shutdownTimeoutMs: 100, killGraceMs: 100 })
await expect(ctx.lsp.query(query('definition'))).rejects.toThrow()
// A later query starts a fresh process; still crashes, but proves the slot was replaced (no hang).
await expect(ctx.lsp.query(query('definition'))).rejects.toThrow()
await ctx.fiber.dispose()
})
it('runs distinct workspaces in parallel instances', async () => {
const ws2 = join(root, 'ws2')
await mkdir(ws2)
await writeFile(join(ws2, 'a.ts'), 'const z = 2\n')
const ctx = await mount({ LSP_FAKE_DEF: JSON.stringify(locationJson(0)) })
const [r1, r2] = await Promise.all([
ctx.lsp.query({ ...query('definition'), workspaceRoot: ws }),
ctx.lsp.query({ ...query('definition'), workspaceRoot: ws2 }),
])
expect(r1).toMatchObject({ kind: 'locations' })
expect(r2).toMatchObject({ kind: 'locations' })
await ctx.fiber.dispose()
})
it('disposes cleanly, terminating a server that ignores shutdown', async () => {
const ctx = await mount({ LSP_FAKE_NO_SHUTDOWN: '1', LSP_FAKE_DEF: 'null' }, { killGraceMs: 100, shutdownTimeoutMs: 100 })
await ctx.lsp.query(query('definition'))
await expect(ctx.fiber.dispose()).resolves.toBeUndefined()
})
it('rejects at load when the command is not found', async () => {
const ctx = new Context()
await ctx.plugin(Lsp)
await expect(ctx.plugin(LspLocal, {
providerId: 'missing',
command: 'definitely-not-a-real-lsp-binary-xyz',
args: [],
extensionToLanguage: { '.ts': 'typescript' },
})).rejects.toThrow(/was not found on PATH/)
await ctx.fiber.dispose()
})
})

View File

@@ -0,0 +1,78 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { chmod, mkdtemp, mkdir, rm, writeFile, realpath } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Context } from 'cordis'
import Lsp, { type LspQueryRequest } from '@deepseek-ai/dsh-lsp'
import * as LspLocal from '@deepseek-ai/dsh-lsp-local'
let root: string
let ws: string
beforeEach(async () => {
root = await realpath(await mkdtemp(join(tmpdir(), 'lsp-prov-')))
ws = join(root, 'ws')
await mkdir(ws)
await writeFile(join(ws, 'a.ts'), 'const x = 1\n')
})
afterEach(async () => {
await rm(root, { recursive: true, force: true })
})
function query(): LspQueryRequest {
return { operation: 'definition', filePath: 'a.ts', position: { line: 0, character: 0 }, workspaceRoot: ws }
}
describe('lsp-local provider resolution', () => {
it('resolves a bare command on the child PATH and registers the provider', async () => {
// A tiny executable script placed on a custom PATH dir: the load-time resolver must find it.
const bin = join(root, 'bin')
await mkdir(bin)
const exe = join(bin, 'fake-lsp')
await writeFile(exe, '#!/bin/sh\nexit 0\n')
await chmod(exe, 0o755)
const ctx = new Context()
await ctx.plugin(Lsp)
await expect(ctx.plugin(LspLocal, {
providerId: 'onpath',
command: 'fake-lsp',
args: [],
env: { PATH: bin },
extensionToLanguage: { '.ts': 'typescript' },
})).resolves.toBeDefined()
await ctx.fiber.dispose()
})
it('skips empty PATH segments and fails when the command is absent', async () => {
const ctx = new Context()
await ctx.plugin(Lsp)
await expect(ctx.plugin(LspLocal, {
providerId: 'nope',
command: 'fake-lsp',
args: [],
env: { PATH: `::${join(root, 'empty')}` },
extensionToLanguage: { '.ts': 'typescript' },
})).rejects.toThrow(/was not found on PATH/)
await ctx.fiber.dispose()
})
it('rejects a query after the provider is disposed', async () => {
// Use a server that never emits results and dispose the plugin, then confirm queries are refused.
const ctx = new Context()
await ctx.plugin(Lsp)
// Grab the provider instance by registering, then dispose the whole plugin fiber.
const lsp = ctx.lsp
const fiber = await ctx.plugin(LspLocal, {
providerId: 'disp',
command: process.execPath,
args: ['-e', 'setInterval(()=>{},1000)'],
extensionToLanguage: { '.ts': 'typescript' },
})
await fiber.dispose()
// After disposal the provider unregistered from the seam, so selection fails as unavailable.
await expect(lsp.query(query())).rejects.toThrow(expect.objectContaining({ code: 'LSP_UNAVAILABLE' }))
await ctx.fiber.dispose()
})
})

View File

@@ -0,0 +1,153 @@
import { describe, expect, it } from 'vitest'
import {
negotiatePositionEncoding,
normalizeHover,
normalizeLocations,
requestMethod,
supportsOperation,
supportsTransientOpen,
} from '@deepseek-ai/dsh-lsp-local'
import type { WireServerCapabilities } from '@deepseek-ai/dsh-lsp-local/src/protocol.ts'
const RANGE = { start: { line: 1, character: 2 }, end: { line: 1, character: 5 } }
describe('requestMethod', () => {
it('maps each operation to its textDocument request', () => {
expect(requestMethod('definition')).toBe('textDocument/definition')
expect(requestMethod('references')).toBe('textDocument/references')
expect(requestMethod('implementation')).toBe('textDocument/implementation')
expect(requestMethod('hover')).toBe('textDocument/hover')
})
})
describe('supportsOperation', () => {
it('reads the provider slot for each operation (boolean and options forms)', () => {
const caps: WireServerCapabilities = {
definitionProvider: true,
referencesProvider: { workDoneProgress: true },
implementationProvider: false,
}
expect(supportsOperation(caps, 'definition')).toBe(true)
expect(supportsOperation(caps, 'references')).toBe(true)
expect(supportsOperation(caps, 'implementation')).toBe(false)
expect(supportsOperation(caps, 'hover')).toBe(false)
})
})
describe('supportsTransientOpen', () => {
it('accepts legacy Full and Incremental enums, rejects None and absent', () => {
expect(supportsTransientOpen(1)).toBe(true)
expect(supportsTransientOpen(2)).toBe(true)
expect(supportsTransientOpen(0)).toBe(false)
expect(supportsTransientOpen(undefined)).toBe(false)
})
it('accepts options with openClose:true and rejects openClose:false', () => {
expect(supportsTransientOpen({ openClose: true })).toBe(true)
expect(supportsTransientOpen({ openClose: false, change: 2 })).toBe(false)
})
it('falls back to the change enum when openClose is omitted', () => {
expect(supportsTransientOpen({ change: 1 })).toBe(true)
expect(supportsTransientOpen({ change: 0 })).toBe(false)
expect(supportsTransientOpen({})).toBe(false)
})
})
describe('negotiatePositionEncoding', () => {
it('defaults an omitted encoding to utf-16', () => {
expect(negotiatePositionEncoding(undefined)).toBe('utf-16')
expect(negotiatePositionEncoding('utf-16')).toBe('utf-16')
})
it('rejects any other encoding', () => {
expect(() => negotiatePositionEncoding('utf-8')).toThrow(/unsupported position encoding/)
})
})
describe('normalizeLocations', () => {
it('returns empty for null and undefined', () => {
expect(normalizeLocations(null)).toEqual([])
expect(normalizeLocations(undefined)).toEqual([])
})
it('maps a single Location', () => {
expect(normalizeLocations({ uri: 'file:///a', range: RANGE })).toEqual([{ uri: 'file:///a', range: RANGE }])
})
it('maps an array of Locations', () => {
const result = normalizeLocations([{ uri: 'file:///a', range: RANGE }, { uri: 'file:///b', range: RANGE }])
expect(result.map(l => l.uri)).toEqual(['file:///a', 'file:///b'])
})
it('maps a LocationLink from targetUri + targetSelectionRange', () => {
const link = { targetUri: 'file:///c', targetSelectionRange: RANGE, targetRange: RANGE }
expect(normalizeLocations([link])).toEqual([{ uri: 'file:///c', range: RANGE }])
})
it('rejects a non-object entry', () => {
expect(() => normalizeLocations([42])).toThrow(/non-object/)
})
it('rejects an entry that is neither a Location nor a LocationLink', () => {
expect(() => normalizeLocations([{ nope: true }])).toThrow(/neither a Location nor a LocationLink/)
})
it('rejects a Location whose range is not an object', () => {
expect(() => normalizeLocations([{ uri: 'file:///a', range: 'nope' }])).toThrow(/neither a Location/)
})
it('rejects a Location whose range positions are malformed', () => {
expect(() => normalizeLocations([{ uri: 'file:///a', range: { start: null, end: null } }])).toThrow(/neither a Location/)
})
})
describe('normalizeHover', () => {
it('returns null for null', () => {
expect(normalizeHover(null)).toBeNull()
})
it('reads MarkupContent value and keeps a range', () => {
expect(normalizeHover({ contents: { kind: 'markdown', value: '# H' }, range: RANGE }))
.toEqual({ contents: '# H', range: RANGE })
})
it('keeps a bare string MarkedString verbatim', () => {
expect(normalizeHover({ contents: 'plain text' })).toEqual({ contents: 'plain text' })
})
it('renders a language-tagged MarkedString object as a fenced code block', () => {
expect(normalizeHover({ contents: { language: 'ts', value: 'const x = 1' } }))
.toEqual({ contents: '```ts\nconst x = 1\n```' })
})
it('joins a MarkedString array with one blank line', () => {
expect(normalizeHover({ contents: ['a', { language: 'ts', value: 'b' }] }))
.toEqual({ contents: 'a\n\n```ts\nb\n```' })
})
it('drops an empty-contents hover to null', () => {
expect(normalizeHover({ contents: { kind: 'plaintext', value: '' } })).toBeNull()
})
it('treats a MarkupContent with a non-string value as empty (null)', () => {
expect(normalizeHover({ contents: { kind: 'markdown', value: 42 } })).toBeNull()
})
it('rejects a non-object payload', () => {
expect(() => normalizeHover(42)).toThrow(/was not an object/)
})
it('rejects malformed contents', () => {
expect(() => normalizeHover({ contents: { weird: true } })).toThrow(/were not MarkupContent/)
expect(() => normalizeHover({ contents: 42 })).toThrow(/were not MarkupContent/)
})
it('rejects a hover with no contents field', () => {
expect(() => normalizeHover({ range: RANGE })).toThrow(/no contents/)
})
it('ignores a malformed range and keeps the contents', () => {
expect(normalizeHover({ contents: 'x', range: { start: { line: 1 } } })).toEqual({ contents: 'x' })
})
})

View File

@@ -0,0 +1,111 @@
/**
* Keyless real-server e2e: drives the real `typescript-language-server` through the full
* `ctx.lsp` → `dsh-lsp-local` stack over the base protocol, exercising all four operations. No API
* key needed — the server is a local dev dependency. This establishes one compatibility floor
* (TypeScript), not a cross-language claim.
*/
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { mkdtemp, mkdir, rm, writeFile, realpath } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Context } from 'cordis'
import Lsp, { type LspQueryRequest, type LspQueryResult } from '@deepseek-ai/dsh-lsp'
import * as LspLocal from '@deepseek-ai/dsh-lsp-local'
// The server binary is a dev dependency of this package; resolve its pnpm-hoisted .bin path.
const serverBin = join(
new URL('..', import.meta.url).pathname,
'node_modules',
'.bin',
'typescript-language-server',
)
let root: string
let ws: string
let ctx: Context
beforeAll(async () => {
root = await realpath(await mkdtemp(join(tmpdir(), 'lsp-ts-e2e-')))
ws = join(root, 'proj')
await mkdir(ws)
await writeFile(join(ws, 'tsconfig.json'), JSON.stringify({ compilerOptions: { strict: true, module: 'nodenext' } }))
// A small program with a definition, a reference, an interface + implementation, and a typed value.
await writeFile(join(ws, 'shapes.ts'), [
'export interface Shape {',
' area(): number',
'}',
'',
'export class Circle implements Shape {',
' constructor(private r: number) {}',
' area(): number { return Math.PI * this.r * this.r }',
'}',
'',
'export function describe(s: Shape): string {',
' return `area=${s.area()}`',
'}',
'',
'const c = new Circle(2)',
'export const text = describe(c)',
'',
].join('\n'))
ctx = new Context()
await ctx.plugin(Lsp)
await ctx.plugin(LspLocal, {
providerId: 'typescript',
command: serverBin,
args: ['--stdio'],
extensionToLanguage: { '.ts': 'typescript', '.tsx': 'typescriptreact' },
})
}, 60_000)
afterAll(async () => {
if (ctx) await ctx.fiber.dispose()
if (root) await rm(root, { recursive: true, force: true })
})
/** One-based helper mirroring the model contract, converted to the seam's zero-based position. */
function at(operation: LspQueryRequest['operation'], line1: number, char1: number, filePath = 'shapes.ts'): LspQueryRequest {
return { operation, filePath, position: { line: line1 - 1, character: char1 - 1 }, workspaceRoot: ws }
}
function locations(result: LspQueryResult): readonly { uri: string }[] {
if (result.kind !== 'locations') throw new Error(`expected locations, got ${result.kind}`)
return result.locations
}
describe('real typescript-language-server', () => {
it('resolves the definition of a call site to its declaration', async () => {
// `export const text = describe(c)` (line 15): `describe` begins at column 21.
const result = await ctx.lsp.query(at('definition', 15, 22))
const locs = locations(result)
expect(locs.length).toBeGreaterThanOrEqual(1)
expect(locs.some(l => l.uri.endsWith('shapes.ts'))).toBe(true)
}, 60_000)
it('finds references to a symbol including its declaration', async () => {
// References to `describe` from its declaration (line 10, col 17).
const result = await ctx.lsp.query(at('references', 10, 17))
const locs = locations(result)
// At least the declaration plus the call site.
expect(locs.length).toBeGreaterThanOrEqual(2)
}, 60_000)
it('resolves implementations of an interface', async () => {
// Implementations of `Shape` (line 1, col 18) → Circle.
const result = await ctx.lsp.query(at('implementation', 1, 18))
const locs = locations(result)
expect(locs.length).toBeGreaterThanOrEqual(1)
}, 60_000)
it('returns hover information for a typed symbol', async () => {
// Hover on `Circle` in `new Circle(2)` (line 14, col 15).
const result = await ctx.lsp.query(at('hover', 14, 15))
expect(result.kind).toBe('hover')
if (result.kind === 'hover') {
expect(result.hover).not.toBeNull()
expect(result.hover?.contents).toContain('Circle')
}
}, 60_000)
})