diff options
| author | Paul Buetow <paul@buetow.org> | 2026-06-11 08:34:41 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2026-06-11 08:34:41 +0300 |
| commit | e95f3fdf0a66ba05ba2c8fb7e755e107f9cf7991 (patch) | |
| tree | 412c7e21ec9c317beb99ed7fe0d4d93a7dacbe50 /internal/lsp | |
| parent | 73dadb573f92dca310036e8793932e94277abd62 (diff) | |
Thread context.Context through blocking I/O entry points
Accept ctx as the first parameter on the blocking I/O entry points and
propagate it to downstream blocking calls so the work is cancellable from
the process entry point:
- appconfig.Load / LoadWithOptions: honor ctx before the blocking file
reads, returning defaults on a cancelled context.
- LSP: lsp.Server.Run(ctx) ties the serve loop to the caller context via a
new watchParentContext bridge (cancels the server context, aborting
in-flight LLM work). Threaded through hexailsp.Run/RunWithConfig/
RunWithFactory and runtimeconfig.Store.Reload.
- MCP: mcp.Server.Run(ctx) stops accepting requests once ctx is cancelled;
threaded through hexaimcp.Run/RunWithFactory/RunBackfill.
- editor: RunEditor/OpenTempAndEdit/OpenFile take ctx and use
exec.CommandContext so a cancelled context kills the editor subprocess;
threaded through hexaicli, hexaiaction and askcli call sites.
Top-level callers (cmd/hexai-lsp-server, cmd/hexai-mcp-server) now build a
signal-cancelled context (SIGINT/SIGTERM) so shutdown tears the run down
cleanly. Updated comments to explain the cancellation flow and added
cancellation tests for the LSP/MCP loops, editor, and config load.
All tests pass with -race; cross-package coverage 86.2%.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Diffstat (limited to 'internal/lsp')
| -rw-r--r-- | internal/lsp/chat_commands.go | 4 | ||||
| -rw-r--r-- | internal/lsp/chat_commands_test.go | 5 | ||||
| -rw-r--r-- | internal/lsp/server.go | 30 | ||||
| -rw-r--r-- | internal/lsp/server_test.go | 58 |
4 files changed, 93 insertions, 4 deletions
diff --git a/internal/lsp/chat_commands.go b/internal/lsp/chat_commands.go index 480643a..eb38ba0 100644 --- a/internal/lsp/chat_commands.go +++ b/internal/lsp/chat_commands.go @@ -48,7 +48,9 @@ func (c *chatService) handleReloadCommand() chatCommandResult { } loadOpts := s.configLoadOpts loadOpts.IgnoreEnv = true - changes, err := s.configStore.Reload(s.logger, loadOpts) + // Tie the reload's blocking file reads to the server context so an + // in-progress reload is abandoned if the server is shutting down. + changes, err := s.configStore.Reload(s.serverCtx, s.logger, loadOpts) if err != nil { s.logger.Printf("config reload failed: %v", err) return chatCommandResult{message: fmt.Sprintf("Reload failed: %v", err)} diff --git a/internal/lsp/chat_commands_test.go b/internal/lsp/chat_commands_test.go index 15a3acf..d1836df 100644 --- a/internal/lsp/chat_commands_test.go +++ b/internal/lsp/chat_commands_test.go @@ -2,6 +2,7 @@ package lsp import ( "bytes" + "context" "log" "os" "path/filepath" @@ -55,7 +56,7 @@ func TestHandleReloadCommandReloadsStore(t *testing.T) { var logBuf bytes.Buffer logger := log.New(&logBuf, "", 0) - initial := appconfig.Load(logger) + initial := appconfig.Load(context.Background(), logger) if initial.MaxTokens != 321 { t.Fatalf("expected env override to win initial load, got %d", initial.MaxTokens) } @@ -102,7 +103,7 @@ func TestDetectAndHandleChatExecutesSlashCommand(t *testing.T) { var logBuf bytes.Buffer logger := log.New(&logBuf, "", 0) - initial := appconfig.Load(logger) + initial := appconfig.Load(context.Background(), logger) store := runtimeconfig.New(initial) s := newTestServer() diff --git a/internal/lsp/server.go b/internal/lsp/server.go index e42179d..966ec90 100644 --- a/internal/lsp/server.go +++ b/internal/lsp/server.go @@ -345,6 +345,27 @@ func (s *Server) cancelRequests() { } } +// watchParentContext propagates cancellation from the caller-provided ctx into +// the server's own context. When ctx is cancelled we call cancelRequests so any +// in-flight LLM/network work tied to s.serverCtx is aborted; the main loop then +// returns once the current blocking read unblocks. It returns a stop function +// that tears down the watcher goroutine when Run exits normally (EOF), so the +// goroutine never leaks. A nil ctx (or context.Background) yields a no-op. +func (s *Server) watchParentContext(ctx context.Context) func() { + if ctx == nil || ctx.Done() == nil { + return func() {} + } + done := make(chan struct{}) + go func() { + select { + case <-ctx.Done(): + s.cancelRequests() + case <-done: + } + }() + return func() { close(done) } +} + func (s *Server) emitLLMStartStatus(provider, model string) { if s.statusSink != nil { if err := s.statusSink.SetLLMStart(provider, model); err != nil { @@ -363,7 +384,14 @@ func (s *Server) emitGlobalStatus(gs GlobalStatus) { // Run starts the server's main loop, reading and dispatching LSP messages until EOF or exit. // On shutdown it cancels the server context and waits for in-flight goroutines. -func (s *Server) Run() error { +// +// The supplied ctx ties the serve loop to the process lifecycle: when the +// caller's context is cancelled (e.g. SIGINT/SIGTERM at main), we cancel the +// internal server context so in-flight LLM/network requests are aborted and the +// blocking stdin read is unblocked, letting Run return promptly. +func (s *Server) Run(ctx context.Context) error { + stopWatch := s.watchParentContext(ctx) + defer stopWatch() defer func() { s.cancelRequests() s.inflight.Wait() diff --git a/internal/lsp/server_test.go b/internal/lsp/server_test.go index 1f33a46..40e8f76 100644 --- a/internal/lsp/server_test.go +++ b/internal/lsp/server_test.go @@ -1,8 +1,12 @@ package lsp import ( + "bytes" "context" + "io" + "log" "testing" + "time" "codeberg.org/snonux/hexai/internal/appconfig" "codeberg.org/snonux/hexai/internal/llm" @@ -86,6 +90,60 @@ func TestServerApplyOptions(t *testing.T) { } } +// TestRunReturnsOnEOF verifies the serve loop exits cleanly when the input +// stream reaches EOF, regardless of the parent context being active. +func TestRunReturnsOnEOF(t *testing.T) { + srv := NewServer(bytes.NewReader(nil), &bytes.Buffer{}, log.New(io.Discard, "", 0), ServerOptions{}) + if err := srv.Run(context.Background()); err != nil { + t.Fatalf("Run on EOF returned error: %v", err) + } +} + +// TestRunCancelsServerContextOnParentCancel verifies that cancelling the +// caller-provided context propagates into the server's own context (so +// in-flight LLM/network work is aborted) via watchParentContext. +func TestRunCancelsServerContextOnParentCancel(t *testing.T) { + // A pipe whose write end is never written blocks the serve loop's read, + // so Run only returns once the parent context cancellation unblocks it by + // the input being closed. + pr, pw := io.Pipe() + srv := NewServer(pr, &bytes.Buffer{}, log.New(io.Discard, "", 0), ServerOptions{}) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- srv.Run(ctx) }() + + // Cancel the parent: watchParentContext should cancel the server context. + cancel() + // Allow the watcher goroutine to observe cancellation. + deadline := time.After(2 * time.Second) + for srv.serverCtx.Err() == nil { + select { + case <-deadline: + t.Fatal("server context was not cancelled after parent cancel") + default: + } + } + // Unblock the read so Run can return. + _ = pw.Close() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("Run did not return after input closed") + } +} + +// TestWatchParentContextNilIsNoOp verifies a nil/background context yields a +// no-op stop function and never cancels the server. +func TestWatchParentContextNilIsNoOp(t *testing.T) { + srv := NewServer(bytes.NewReader(nil), &bytes.Buffer{}, log.New(io.Discard, "", 0), ServerOptions{}) + stop := srv.watchParentContext(nil) + stop() + if srv.serverCtx.Err() != nil { + t.Fatalf("server context should remain active for nil parent ctx") + } +} + func TestServerStoreAndTakePendingCompletion(t *testing.T) { s := newTestServer() items := []CompletionItem{{Label: "foo"}} |
