From e95f3fdf0a66ba05ba2c8fb7e755e107f9cf7991 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Thu, 11 Jun 2026 08:34:41 +0300 Subject: 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 --- internal/editor/editor.go | 23 +++++++++++-------- internal/editor/editor_test.go | 51 ++++++++++++++++++++++++++---------------- 2 files changed, 46 insertions(+), 28 deletions(-) (limited to 'internal/editor') diff --git a/internal/editor/editor.go b/internal/editor/editor.go index 722e336..9a9e737 100644 --- a/internal/editor/editor.go +++ b/internal/editor/editor.go @@ -1,6 +1,7 @@ package editor import ( + "context" "errors" "os" "os/exec" @@ -21,9 +22,11 @@ func Resolve() (string, error) { } // RunEditor is the seam that invokes the editor on the given file path. -// Override in tests to avoid launching a real editor. -var RunEditor = func(editor, path string) error { - cmd := exec.Command(editor, path) +// Override in tests to avoid launching a real editor. It uses +// exec.CommandContext so a cancelled ctx (e.g. process shutdown) kills the +// editor subprocess instead of leaving it blocking on terminal input. +var RunEditor = func(ctx context.Context, editor, path string) error { + cmd := exec.CommandContext(ctx, editor, path) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr @@ -32,8 +35,9 @@ var RunEditor = func(editor, path string) error { // OpenTempAndEdit creates a temporary .md file, writes initial content if provided, // opens it in the resolved editor, then reads the final content and removes the file. -// Returns the trimmed content. -func OpenTempAndEdit(initial []byte) (string, error) { +// Returns the trimmed content. ctx is forwarded to the editor subprocess so it +// can be cancelled along with the surrounding command. +func OpenTempAndEdit(ctx context.Context, initial []byte) (string, error) { ed, err := Resolve() if err != nil { return "", err @@ -59,7 +63,7 @@ func OpenTempAndEdit(initial []byte) (string, error) { if err := f.Close(); err != nil { return "", err } - if err := RunEditor(ed, path); err != nil { + if err := RunEditor(ctx, ed, path); err != nil { return "", err } b, err := os.ReadFile(filepath.Clean(path)) @@ -70,8 +74,9 @@ func OpenTempAndEdit(initial []byte) (string, error) { } // OpenFile ensures the parent directory exists, then opens path in the editor -// from Resolve() (HEXAI_EDITOR or EDITOR). -func OpenFile(path string) error { +// from Resolve() (HEXAI_EDITOR or EDITOR). ctx is forwarded to the editor +// subprocess so it can be cancelled with the surrounding command. +func OpenFile(ctx context.Context, path string) error { ed, err := Resolve() if err != nil { return err @@ -86,5 +91,5 @@ func OpenFile(path string) error { return mkErr } } - return RunEditor(ed, path) + return RunEditor(ctx, ed, path) } diff --git a/internal/editor/editor_test.go b/internal/editor/editor_test.go index 403d165..f2c1e22 100644 --- a/internal/editor/editor_test.go +++ b/internal/editor/editor_test.go @@ -1,6 +1,7 @@ package editor import ( + "context" "errors" "os" "path/filepath" @@ -14,19 +15,31 @@ func TestRunEditor_Default(t *testing.T) { if err := os.WriteFile(tmp, []byte("hello"), 0o600); err != nil { t.Fatal(err) } - if err := RunEditor("true", tmp); err != nil { + if err := RunEditor(context.Background(), "true", tmp); err != nil { t.Fatalf("RunEditor with 'true': %v", err) } } // TestRunEditor_Default_BadCommand verifies RunEditor returns an error for a nonexistent command. func TestRunEditor_Default_BadCommand(t *testing.T) { - err := RunEditor("nonexistent-editor-cmd-12345", "/dev/null") + err := RunEditor(context.Background(), "nonexistent-editor-cmd-12345", "/dev/null") if err == nil { t.Fatal("expected error for nonexistent editor command") } } +// TestRunEditor_CancelledContextKillsProcess verifies that a cancelled context +// terminates the editor subprocess (via exec.CommandContext) so RunEditor +// returns an error rather than blocking forever. +func TestRunEditor_CancelledContextKillsProcess(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() // already cancelled: CommandContext refuses to start the process + // "sleep 60" would otherwise block; the cancelled ctx kills it immediately. + if err := RunEditor(ctx, "sleep", "60"); err == nil { + t.Fatal("expected error when context is cancelled") + } +} + func TestResolve_EnvPriority(t *testing.T) { t.Setenv("HEXAI_EDITOR", "ed1") t.Setenv("EDITOR", "ed2") @@ -67,12 +80,12 @@ func TestOpenTempAndEdit_UsesRunEditor(t *testing.T) { // Ensure Resolve() succeeds t.Setenv("HEXAI_EDITOR", "dummy") var capturedPath string - RunEditor = func(editor, path string) error { + RunEditor = func(_ context.Context, editor, path string) error { capturedPath = path // simulate user writing content return os.WriteFile(path, []byte("Hello\nWorld\n"), 0o600) } - out, err := OpenTempAndEdit([]byte("# Start\n\n")) + out, err := OpenTempAndEdit(context.Background(), []byte("# Start\n\n")) if err != nil { t.Fatalf("OpenTempAndEdit: %v", err) } @@ -88,7 +101,7 @@ func TestOpenTempAndEdit_UsesRunEditor(t *testing.T) { func TestOpenTempAndEdit_NoEditor(t *testing.T) { t.Setenv("HEXAI_EDITOR", "") t.Setenv("EDITOR", "") - _, err := OpenTempAndEdit(nil) + _, err := OpenTempAndEdit(context.Background(), nil) if err == nil { t.Fatal("expected error when no editor is set") } @@ -99,11 +112,11 @@ func TestOpenTempAndEdit_NilInitial(t *testing.T) { old := RunEditor t.Cleanup(func() { RunEditor = old }) t.Setenv("HEXAI_EDITOR", "dummy") - RunEditor = func(editor, path string) error { + RunEditor = func(_ context.Context, editor, path string) error { // simulate user writing content into a file that started empty return os.WriteFile(path, []byte("result"), 0o600) } - out, err := OpenTempAndEdit(nil) + out, err := OpenTempAndEdit(context.Background(), nil) if err != nil { t.Fatalf("OpenTempAndEdit with nil initial: %v", err) } @@ -118,10 +131,10 @@ func TestOpenTempAndEdit_EmptyInitial(t *testing.T) { old := RunEditor t.Cleanup(func() { RunEditor = old }) t.Setenv("HEXAI_EDITOR", "dummy") - RunEditor = func(editor, path string) error { + RunEditor = func(_ context.Context, editor, path string) error { return os.WriteFile(path, []byte(" trimmed "), 0o600) } - out, err := OpenTempAndEdit([]byte{}) + out, err := OpenTempAndEdit(context.Background(), []byte{}) if err != nil { t.Fatalf("OpenTempAndEdit with empty initial: %v", err) } @@ -136,10 +149,10 @@ func TestOpenTempAndEdit_EditorError(t *testing.T) { t.Cleanup(func() { RunEditor = old }) t.Setenv("HEXAI_EDITOR", "dummy") editorErr := errors.New("editor crashed") - RunEditor = func(editor, path string) error { + RunEditor = func(_ context.Context, editor, path string) error { return editorErr } - _, err := OpenTempAndEdit([]byte("some content")) + _, err := OpenTempAndEdit(context.Background(), []byte("some content")) if err == nil { t.Fatal("expected error when editor fails") } @@ -153,11 +166,11 @@ func TestOpenTempAndEdit_EditorDeletesFile(t *testing.T) { old := RunEditor t.Cleanup(func() { RunEditor = old }) t.Setenv("HEXAI_EDITOR", "dummy") - RunEditor = func(editor, path string) error { + RunEditor = func(_ context.Context, editor, path string) error { // simulate the editor deleting the file return os.Remove(path) } - _, err := OpenTempAndEdit([]byte("content")) + _, err := OpenTempAndEdit(context.Background(), []byte("content")) if err == nil { t.Fatal("expected error when temp file is deleted by editor") } @@ -169,11 +182,11 @@ func TestOpenTempAndEdit_TempFileCleanup(t *testing.T) { t.Cleanup(func() { RunEditor = old }) t.Setenv("HEXAI_EDITOR", "dummy") var capturedPath string - RunEditor = func(editor, path string) error { + RunEditor = func(_ context.Context, editor, path string) error { capturedPath = path return os.WriteFile(path, []byte("done"), 0o600) } - _, err := OpenTempAndEdit(nil) + _, err := OpenTempAndEdit(context.Background(), nil) if err != nil { t.Fatalf("OpenTempAndEdit: %v", err) } @@ -189,12 +202,12 @@ func TestOpenFile_CreatesParentAndInvokesEditor(t *testing.T) { t.Setenv("HEXAI_EDITOR", "dummy") target := filepath.Join(t.TempDir(), "nested", "config.toml") var gotEditor, gotPath string - RunEditor = func(editorCmd, path string) error { + RunEditor = func(_ context.Context, editorCmd, path string) error { gotEditor = editorCmd gotPath = path return nil } - if err := OpenFile(target); err != nil { + if err := OpenFile(context.Background(), target); err != nil { t.Fatalf("OpenFile: %v", err) } if gotEditor != "dummy" { @@ -211,7 +224,7 @@ func TestOpenFile_CreatesParentAndInvokesEditor(t *testing.T) { func TestOpenFile_NoEditor(t *testing.T) { t.Setenv("HEXAI_EDITOR", "") t.Setenv("EDITOR", "") - err := OpenFile(filepath.Join(t.TempDir(), "x.toml")) + err := OpenFile(context.Background(), filepath.Join(t.TempDir(), "x.toml")) if err == nil { t.Fatal("expected error when no editor is set") } @@ -219,7 +232,7 @@ func TestOpenFile_NoEditor(t *testing.T) { func TestOpenFile_EmptyPath(t *testing.T) { t.Setenv("HEXAI_EDITOR", "true") - err := OpenFile(" ") + err := OpenFile(context.Background(), " ") if err == nil { t.Fatal("expected error for empty path") } -- cgit v1.2.3