Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
213 changes: 212 additions & 1 deletion src/tools/lsp/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { join } from "node:path"
import { join, resolve } from "node:path"
import { tmpdir } from "node:os"
import { pathToFileURL } from "node:url"

import { describe, it, expect, spyOn, mock, beforeEach, afterEach } from "bun:test"

Expand Down Expand Up @@ -257,4 +258,214 @@ describe("LSPClient", () => {
}
})
})

describe("diagnostics", () => {
it("polls diagnosticsStore when pull fails and push arrives during poll window", async () => {
// #given
const dir = mkdtempSync(join(tmpdir(), "lsp-diagnostics-test-"))
const filePath = join(dir, "test.ts")
writeFileSync(filePath, "const a = 1\n")

const originalSetTimeout = globalThis.setTimeout
globalThis.setTimeout = ((fn: (...args: unknown[]) => void, _ms?: number) => {
fn()
return 0 as unknown as ReturnType<typeof setTimeout>
}) as typeof setTimeout

const server: ResolvedServer = {
id: "typescript",
command: ["typescript-language-server", "--stdio"],
extensions: [".ts"],
priority: 0,
}

const client = new LSPClient(dir, server)

// Mock sendRequest to throw (pull fails)
const sendRequestSpy = spyOn(
client as unknown as { sendRequest: (m: string, p?: unknown) => Promise<unknown> },
"sendRequest"
)
sendRequestSpy.mockImplementation(async () => {
throw new Error("pull not supported")
})

// Mock openFile to avoid actual file operations
const openFileSpy = spyOn(client, "openFile")
openFileSpy.mockImplementation(async () => {})

try {
// #when
const expectedDiagnostics = [{ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } }, message: "error" }]
const absPath = resolve(filePath)
const uri = pathToFileURL(absPath).href

// Pre-populate store to simulate push notification that arrived before poll
;(client as unknown as { diagnosticsStore: Map<string, unknown> }).diagnosticsStore.set(uri, expectedDiagnostics)

const result = await client.diagnostics(filePath)

// #then
expect(result.items).toEqual(expectedDiagnostics)
} finally {
globalThis.setTimeout = originalSetTimeout
sendRequestSpy.mockRestore()
openFileSpy.mockRestore()
rmSync(dir, { recursive: true, force: true })
}
})

it("returns empty array when pull fails and no push arrives within timeout", async () => {
// #given
const dir = mkdtempSync(join(tmpdir(), "lsp-diagnostics-timeout-test-"))
const filePath = join(dir, "test.ts")
writeFileSync(filePath, "const a = 1\n")

const originalSetTimeout = globalThis.setTimeout
globalThis.setTimeout = ((fn: (...args: unknown[]) => void, _ms?: number) => {
fn()
return 0 as unknown as ReturnType<typeof setTimeout>
}) as typeof setTimeout

const dateNowSpy = spyOn(Date, "now")
let callCount = 0
dateNowSpy.mockImplementation(() => {
callCount++
return callCount <= 2 ? 0 : 10_000
})

const server: ResolvedServer = {
id: "typescript",
command: ["typescript-language-server", "--stdio"],
extensions: [".ts"],
priority: 0,
}

const client = new LSPClient(dir, server)

// Mock sendRequest to throw (pull fails)
const sendRequestSpy = spyOn(
client as unknown as { sendRequest: (m: string, p?: unknown) => Promise<unknown> },
"sendRequest"
)
sendRequestSpy.mockImplementation(async () => {
throw new Error("pull not supported")
})

// Mock openFile to avoid actual file operations
const openFileSpy = spyOn(client, "openFile")
openFileSpy.mockImplementation(async () => {})

try {
// #when
const result = await client.diagnostics(filePath)

// #then
expect(result.items).toEqual([])
} finally {
globalThis.setTimeout = originalSetTimeout
dateNowSpy.mockRestore()
sendRequestSpy.mockRestore()
openFileSpy.mockRestore()
rmSync(dir, { recursive: true, force: true })
}
})

it("returns empty diagnostics immediately when push delivers clean file during poll", async () => {
// #given
const dir = mkdtempSync(join(tmpdir(), "lsp-diagnostics-empty-test-"))
const filePath = join(dir, "test.ts")
writeFileSync(filePath, "const a = 1\n")

const originalSetTimeout = globalThis.setTimeout
globalThis.setTimeout = ((fn: (...args: unknown[]) => void, _ms?: number) => {
fn()
return 0 as unknown as ReturnType<typeof setTimeout>
}) as typeof setTimeout

const server: ResolvedServer = {
id: "typescript",
command: ["typescript-language-server", "--stdio"],
extensions: [".ts"],
priority: 0,
}

const client = new LSPClient(dir, server)

const sendRequestSpy = spyOn(
client as unknown as { sendRequest: (m: string, p?: unknown) => Promise<unknown> },
"sendRequest"
)
sendRequestSpy.mockImplementation(async () => {
throw new Error("pull not supported")
})

const openFileSpy = spyOn(client, "openFile")
openFileSpy.mockImplementation(async () => {})

try {
// #when
const absPath = resolve(filePath)
const uri = pathToFileURL(absPath).href
;(client as unknown as { diagnosticsStore: Map<string, unknown[]> }).diagnosticsStore.set(uri, [])

const result = await client.diagnostics(filePath)

// #then
expect(result.items).toEqual([])
} finally {
globalThis.setTimeout = originalSetTimeout
sendRequestSpy.mockRestore()
openFileSpy.mockRestore()
rmSync(dir, { recursive: true, force: true })
}
})

it("returns pull result immediately without polling when pull succeeds", async () => {
// #given
const dir = mkdtempSync(join(tmpdir(), "lsp-diagnostics-pull-success-test-"))
const filePath = join(dir, "test.ts")
writeFileSync(filePath, "const a = 1\n")

const server: ResolvedServer = {
id: "typescript",
command: ["typescript-language-server", "--stdio"],
extensions: [".ts"],
priority: 0,
}

const client = new LSPClient(dir, server)

const pullDiagnostics = [{ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } }, message: "pull error" }]

// Mock sendRequest to return diagnostics (pull succeeds)
const sendRequestSpy = spyOn(
client as unknown as { sendRequest: (m: string, p?: unknown) => Promise<unknown> },
"sendRequest"
)
sendRequestSpy.mockImplementation(async () => ({
items: pullDiagnostics,
}))

// Mock openFile to avoid actual file operations
const openFileSpy = spyOn(client, "openFile")
openFileSpy.mockImplementation(async () => {})

try {
// #when
const startTime = Date.now()
const result = await client.diagnostics(filePath)
const elapsed = Date.now() - startTime

// #then
expect(result.items).toEqual(pullDiagnostics)
// Should return quickly without waiting for poll timeout
expect(elapsed).toBeLessThan(1000)
} finally {
sendRequestSpy.mockRestore()
openFileSpy.mockRestore()
rmSync(dir, { recursive: true, force: true })
}
})
})
})
12 changes: 12 additions & 0 deletions src/tools/lsp/lsp-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,18 @@ export class LSPClient extends LSPClientConnection {
}
} catch {}

const POLL_INTERVAL_MS = 200
const POLL_TIMEOUT_MS = 3000
const startTime = Date.now()

while (Date.now() - startTime < POLL_TIMEOUT_MS) {
const items = this.diagnosticsStore.get(uri)
if (items !== undefined) {
return { items }
}
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS))
}

return { items: this.diagnosticsStore.get(uri) ?? [] }
}

Expand Down