Repository navigation
Shut down on stdin EOF/close so host death can't orphan LSP children #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
carldaws
merged 9 commits into
carldaws:main
from
Bigzhangbig:fix/issue2-stdin-eof-shutdown
Sep 25, 2026
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
84c06a0
Shut down when stdin closes or hits EOF
Bigzhangbig 28a6a10
Add integration test for issue #2 shutdown wiring
Bigzhangbig e0268ad
Make the lightweight shutdown test discriminating: assert the
Bigzhangbig 6cb0dd3
Clean up timers and unify process.execPath in shutdown tests
Bigzhangbig a6f70f2
Escape YAML config paths with JSON.stringify in shutdown test
Bigzhangbig 67604b1
Register stdin shutdown listeners before MCP connect
Bigzhangbig 1c5ecff
Cover immediate stdin EOF race in shutdown integration test
Bigzhangbig 377e2c4
Remove comments from shutdown wiring
carldaws da45948
Simplify shutdown integration tests
carldaws File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { writeFileSync } from "node:fs"; | ||
|
|
||
| writeFileSync(process.argv[2], String(process.pid)); | ||
|
|
||
| function send(message) { | ||
| const json = JSON.stringify(message); | ||
| process.stdout.write(`Content-Length: ${Buffer.byteLength(json)}\r\n\r\n${json}`); | ||
| } | ||
|
|
||
| let buffer = Buffer.alloc(0); | ||
|
|
||
| process.stdin.on("data", (chunk) => { | ||
| buffer = Buffer.concat([buffer, chunk]); | ||
|
|
||
| for (;;) { | ||
| const separator = buffer.indexOf("\r\n\r\n"); | ||
| if (separator === -1) return; | ||
|
|
||
| const length = Number(/Content-Length: (\d+)/i.exec(buffer.subarray(0, separator).toString())?.[1]); | ||
| const bodyStart = separator + 4; | ||
| if (buffer.length < bodyStart + length) return; | ||
|
|
||
| const message = JSON.parse(buffer.subarray(bodyStart, bodyStart + length).toString()); | ||
| buffer = buffer.subarray(bodyStart + length); | ||
|
|
||
| if (message.method === "initialize") { | ||
| send({ jsonrpc: "2.0", id: message.id, result: { capabilities: { textDocumentSync: 1 } } }); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| setInterval(() => {}, 1000); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| import { describe, it, expect, beforeAll, beforeEach, afterEach } from "vitest"; | ||
| import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; | ||
| import { once } from "node:events"; | ||
| import * as fs from "node:fs"; | ||
| import * as path from "node:path"; | ||
| import { createInterface } from "node:readline"; | ||
| import { setTimeout as sleep } from "node:timers/promises"; | ||
|
|
||
| const ENTRY = path.resolve(import.meta.dirname, "../../dist/index.js"); | ||
| const FIXTURES = path.join(import.meta.dirname, "__shutdown_fixtures__"); | ||
| const DUMMY_LSP = path.join(FIXTURES, "dummy-lsp.mjs"); | ||
| const PROJECT = path.join(FIXTURES, "project"); | ||
| const EMPTY_PROJECT = path.join(FIXTURES, "empty-project"); | ||
| const PID_FILE = path.join(PROJECT, "dummy-lsp.pid"); | ||
|
|
||
| let running: ChildProcessWithoutNullStreams | undefined; | ||
|
|
||
| function startSquiggles(projectDir: string) { | ||
| const child = spawn(process.execPath, [ENTRY, projectDir]); | ||
| const answered = new Set<number>(); | ||
| let stderr = ""; | ||
|
|
||
| running = child; | ||
| child.stderr.setEncoding("utf8").on("data", (chunk: string) => { | ||
| stderr += chunk; | ||
| }); | ||
| createInterface({ input: child.stdout }).on("line", (line) => { | ||
| const message = JSON.parse(line); | ||
| if (typeof message.id === "number") answered.add(message.id); | ||
| }); | ||
|
|
||
| return { | ||
| child, | ||
| answered, | ||
| get stderr() { | ||
| return stderr; | ||
| }, | ||
| send(message: object) { | ||
| child.stdin.write(`${JSON.stringify(message)}\n`); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| async function exitCode(child: ChildProcessWithoutNullStreams, ms: number): Promise<number | null> { | ||
| const [code] = await once(child, "close", { signal: AbortSignal.timeout(ms) }); | ||
| return code; | ||
| } | ||
|
|
||
| async function waitFor(condition: () => boolean, ms: number, what: string): Promise<void> { | ||
| const deadline = Date.now() + ms; | ||
| while (!condition()) { | ||
| if (Date.now() > deadline) throw new Error(`Timed out waiting for ${what}`); | ||
| await sleep(50); | ||
| } | ||
| } | ||
|
|
||
| function lspPid(): number | undefined { | ||
| try { | ||
| return Number(fs.readFileSync(PID_FILE, "utf8")) || undefined; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| function alive(pid: number): boolean { | ||
| try { | ||
| process.kill(pid, 0); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| beforeAll(() => { | ||
| if (!fs.existsSync(ENTRY)) throw new Error(`${ENTRY} not found, run npm run build first`); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| fs.mkdirSync(PROJECT, { recursive: true }); | ||
| fs.mkdirSync(EMPTY_PROJECT, { recursive: true }); | ||
| fs.writeFileSync( | ||
| path.join(PROJECT, "squiggles.yaml"), | ||
| [ | ||
| "servers:", | ||
| " dummy:", | ||
| ` command: ${JSON.stringify([process.execPath, DUMMY_LSP, PID_FILE])}`, | ||
| ` filePatterns: ["*.txt"]`, | ||
| "", | ||
| ].join("\n"), | ||
| ); | ||
| fs.writeFileSync(path.join(PROJECT, "sample.txt"), "hello\n"); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| running?.kill("SIGKILL"); | ||
| const pid = lspPid(); | ||
| if (pid && alive(pid)) process.kill(pid, "SIGKILL"); | ||
| fs.rmSync(PROJECT, { recursive: true, force: true }); | ||
| fs.rmSync(EMPTY_PROJECT, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| describe("when stdin closes", () => { | ||
| it("exits and kills its LSP servers", async () => { | ||
| const squiggles = startSquiggles(PROJECT); | ||
|
|
||
| squiggles.send({ | ||
| jsonrpc: "2.0", | ||
| id: 1, | ||
| method: "initialize", | ||
| params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "test", version: "0" } }, | ||
| }); | ||
| await waitFor(() => squiggles.answered.has(1), 5000, "initialize response"); | ||
| squiggles.send({ jsonrpc: "2.0", method: "notifications/initialized" }); | ||
| squiggles.send({ | ||
| jsonrpc: "2.0", | ||
| id: 2, | ||
| method: "tools/call", | ||
| params: { name: "document_symbols", arguments: { file: "sample.txt" } }, | ||
| }); | ||
| await waitFor(() => lspPid() !== undefined, 10_000, "dummy LSP to start"); | ||
| const pid = lspPid()!; | ||
| expect(alive(pid)).toBe(true); | ||
|
|
||
| squiggles.child.stdin.end(); | ||
|
|
||
| expect(await exitCode(squiggles.child, 15_000)).toBe(0); | ||
| await waitFor(() => !alive(pid), 3000, "dummy LSP to exit"); | ||
| }, 30_000); | ||
|
|
||
| it("exits through shutdown before any requests", async () => { | ||
| const squiggles = startSquiggles(EMPTY_PROJECT); | ||
|
|
||
| squiggles.child.stdin.end(); | ||
|
|
||
| expect(await exitCode(squiggles.child, 5000)).toBe(0); | ||
| expect(squiggles.stderr).toContain("Shutting down..."); | ||
| }, 15_000); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.