summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2026-06-11 08:34:41 +0300
committerPaul Buetow <paul@buetow.org>2026-06-11 08:34:41 +0300
commite95f3fdf0a66ba05ba2c8fb7e755e107f9cf7991 (patch)
tree412c7e21ec9c317beb99ed7fe0d4d93a7dacbe50
parent73dadb573f92dca310036e8793932e94277abd62 (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>
-rw-r--r--cmd/hexai-lsp-server/main.go10
-rw-r--r--cmd/hexai-mcp-server/main.go16
-rw-r--r--cmd/hexai-mcp-server/main_test.go27
-rw-r--r--cmd/hexai/app_runner.go4
-rw-r--r--internal/appconfig/config_alias_test.go3
-rw-r--r--internal/appconfig/config_env_model_test.go9
-rw-r--r--internal/appconfig/config_features_test.go15
-rw-r--r--internal/appconfig/config_load.go18
-rw-r--r--internal/appconfig/config_test.go47
-rw-r--r--internal/appconfig/custom_validation_more_test.go5
-rw-r--r--internal/askcli/command_edit.go11
-rw-r--r--internal/askcli/command_edit_test.go4
-rw-r--r--internal/editor/editor.go23
-rw-r--r--internal/editor/editor_test.go51
-rw-r--r--internal/hexaiaction/custom_action_test.go2
-rw-r--r--internal/hexaiaction/custom_exec_more_test.go4
-rw-r--r--internal/hexaiaction/custom_exec_test.go4
-rw-r--r--internal/hexaiaction/prompts_simplify_test.go2
-rw-r--r--internal/hexaiaction/run.go4
-rw-r--r--internal/hexaiaction/run_more_test.go8
-rw-r--r--internal/hexaiaction/run_seam_test.go2
-rw-r--r--internal/hexaiaction/run_test.go2
-rw-r--r--internal/hexaicli/editor_integration_test.go6
-rw-r--r--internal/hexaicli/run_editor_behavior_test.go2
-rw-r--r--internal/hexaicli/runner.go8
-rw-r--r--internal/hexaicli/runner_test.go6
-rw-r--r--internal/hexailsp/dependencies.go3
-rw-r--r--internal/hexailsp/run.go31
-rw-r--r--internal/hexailsp/run_more_test.go16
-rw-r--r--internal/hexailsp/run_test.go19
-rw-r--r--internal/hexaimcp/run.go33
-rw-r--r--internal/hexaimcp/run_test.go29
-rw-r--r--internal/lsp/chat_commands.go4
-rw-r--r--internal/lsp/chat_commands_test.go5
-rw-r--r--internal/lsp/server.go30
-rw-r--r--internal/lsp/server_test.go58
-rw-r--r--internal/mcp/handlers_prompt_test.go5
-rw-r--r--internal/mcp/server.go16
-rw-r--r--internal/mcp/server_test.go21
-rw-r--r--internal/runtimeconfig/store.go9
-rw-r--r--internal/runtimeconfig/store_test.go11
-rw-r--r--internal/tmuxedit/run.go5
42 files changed, 404 insertions, 184 deletions
diff --git a/cmd/hexai-lsp-server/main.go b/cmd/hexai-lsp-server/main.go
index 03e2546..ed3af42 100644
--- a/cmd/hexai-lsp-server/main.go
+++ b/cmd/hexai-lsp-server/main.go
@@ -2,12 +2,15 @@
package main
import (
+ "context"
"flag"
"fmt"
"log"
"os"
+ "os/signal"
"path/filepath"
"strings"
+ "syscall"
"codeberg.org/snonux/hexai/internal"
"codeberg.org/snonux/hexai/internal/appconfig"
@@ -26,8 +29,13 @@ func main() {
return
}
+ // Cancel the run when the process receives an interrupt/terminate signal so
+ // the LSP serve loop and any in-flight LLM requests are torn down cleanly.
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+
path := strings.TrimSpace(*configPath)
- if err := hexailsp.RunWithConfig(*logPath, path, os.Stdin, os.Stdout, os.Stderr); err != nil {
+ if err := hexailsp.RunWithConfig(ctx, *logPath, path, os.Stdin, os.Stdout, os.Stderr); err != nil {
log.Fatalf("server error: %v", err)
}
}
diff --git a/cmd/hexai-mcp-server/main.go b/cmd/hexai-mcp-server/main.go
index ac88178..03150bb 100644
--- a/cmd/hexai-mcp-server/main.go
+++ b/cmd/hexai-mcp-server/main.go
@@ -2,11 +2,14 @@
package main
import (
+ "context"
"flag"
"fmt"
"io"
"os"
+ "os/signal"
"path/filepath"
+ "syscall"
"codeberg.org/snonux/hexai/internal"
"codeberg.org/snonux/hexai/internal/appconfig"
@@ -100,7 +103,11 @@ func runMain(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
syncAll: *syncAll,
showVersion: *showVersion,
}
- if err := run(opts, stdin, stdout, stderr); err != nil {
+ // Cancel the run on interrupt/terminate so the serve loop exits cleanly.
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+
+ if err := run(ctx, opts, stdin, stdout, stderr); err != nil {
fmt.Fprintf(stderr, "error: %v\n", err)
return 1
}
@@ -109,7 +116,8 @@ func runMain(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
// run executes the MCP server logic with the given options and I/O streams.
// CLI flag values are passed via MCPOverrides instead of environment variables.
-func run(opts mcpOptions, stdin io.Reader, stdout, stderr io.Writer) error {
+// ctx is threaded into the server/backfill so they stop on shutdown signals.
+func run(ctx context.Context, opts mcpOptions, stdin io.Reader, stdout, stderr io.Writer) error {
if opts.showVersion {
fmt.Fprintln(stdout, internal.Version)
return nil
@@ -119,10 +127,10 @@ func run(opts mcpOptions, stdin io.Reader, stdout, stderr io.Writer) error {
// Handle backfill operation
if opts.syncAll {
- return runBackfill(opts.logPath, opts.configPath, overrides)
+ return runBackfill(ctx, opts.logPath, opts.configPath, overrides)
}
- return runMCP(opts.logPath, opts.configPath, overrides, stdin, stdout, stderr)
+ return runMCP(ctx, opts.logPath, opts.configPath, overrides, stdin, stdout, stderr)
}
// defaultLogPath returns the default MCP log file path in the state directory.
diff --git a/cmd/hexai-mcp-server/main_test.go b/cmd/hexai-mcp-server/main_test.go
index 33f662d..b2a3895 100644
--- a/cmd/hexai-mcp-server/main_test.go
+++ b/cmd/hexai-mcp-server/main_test.go
@@ -2,6 +2,7 @@ package main
import (
"bytes"
+ "context"
"errors"
"io"
"strings"
@@ -37,7 +38,7 @@ func TestDefaultLogPath(t *testing.T) {
func TestRun_ShowVersion(t *testing.T) {
var stdout bytes.Buffer
opts := mcpOptions{showVersion: true}
- if err := run(opts, nil, &stdout, nil); err != nil {
+ if err := run(context.Background(), opts, nil, &stdout, nil); err != nil {
t.Fatalf("run --version: %v", err)
}
got := strings.TrimSpace(stdout.String())
@@ -70,7 +71,7 @@ func TestRun_SyncAll(t *testing.T) {
var gotLog, gotConfig string
var gotOverrides hexaimcp.MCPOverrides
- runBackfill = func(logPath, configPath string, overrides hexaimcp.MCPOverrides) error {
+ runBackfill = func(_ context.Context, logPath, configPath string, overrides hexaimcp.MCPOverrides) error {
gotLog = logPath
gotConfig = configPath
gotOverrides = overrides
@@ -85,7 +86,7 @@ func TestRun_SyncAll(t *testing.T) {
slashCommandSync: true,
slashCommandDir: "/tmp/cmds",
}
- if err := run(opts, nil, nil, nil); err != nil {
+ if err := run(context.Background(), opts, nil, nil, nil); err != nil {
t.Fatalf("run syncAll: %v", err)
}
if gotLog != "/tmp/test.log" {
@@ -110,10 +111,10 @@ func TestRun_SyncAllError(t *testing.T) {
t.Cleanup(func() { runBackfill = old })
wantErr := errors.New("backfill failed")
- runBackfill = func(_, _ string, _ hexaimcp.MCPOverrides) error { return wantErr }
+ runBackfill = func(_ context.Context, _, _ string, _ hexaimcp.MCPOverrides) error { return wantErr }
opts := mcpOptions{syncAll: true}
- if err := run(opts, nil, nil, nil); !errors.Is(err, wantErr) {
+ if err := run(context.Background(), opts, nil, nil, nil); !errors.Is(err, wantErr) {
t.Fatalf("expected backfill error, got: %v", err)
}
}
@@ -123,13 +124,13 @@ func TestRun_MCPServer(t *testing.T) {
t.Cleanup(func() { runMCP = old })
called := false
- runMCP = func(logPath, configPath string, overrides hexaimcp.MCPOverrides, stdin io.Reader, stdout, stderr io.Writer) error {
+ runMCP = func(_ context.Context, logPath, configPath string, overrides hexaimcp.MCPOverrides, stdin io.Reader, stdout, stderr io.Writer) error {
called = true
return nil
}
opts := mcpOptions{logPath: "/tmp/mcp.log"}
- if err := run(opts, nil, nil, nil); err != nil {
+ if err := run(context.Background(), opts, nil, nil, nil); err != nil {
t.Fatalf("run MCP: %v", err)
}
if !called {
@@ -142,9 +143,11 @@ func TestRun_MCPServerError(t *testing.T) {
t.Cleanup(func() { runMCP = old })
wantErr := errors.New("server failed")
- runMCP = func(_, _ string, _ hexaimcp.MCPOverrides, _ io.Reader, _, _ io.Writer) error { return wantErr }
+ runMCP = func(_ context.Context, _, _ string, _ hexaimcp.MCPOverrides, _ io.Reader, _, _ io.Writer) error {
+ return wantErr
+ }
- if err := run(mcpOptions{}, nil, nil, nil); !errors.Is(err, wantErr) {
+ if err := run(context.Background(), mcpOptions{}, nil, nil, nil); !errors.Is(err, wantErr) {
t.Fatalf("expected server error, got: %v", err)
}
}
@@ -173,7 +176,7 @@ func TestRunMain_SyncAllSuccess(t *testing.T) {
t.Cleanup(func() { runBackfill = old })
var gotLog string
- runBackfill = func(logPath string, _ string, _ hexaimcp.MCPOverrides) error {
+ runBackfill = func(_ context.Context, logPath string, _ string, _ hexaimcp.MCPOverrides) error {
gotLog = logPath
return nil
}
@@ -193,7 +196,7 @@ func TestRunMain_SyncAllSuccess(t *testing.T) {
func TestRunMain_ServerErrorReturnsOne(t *testing.T) {
old := runMCP
t.Cleanup(func() { runMCP = old })
- runMCP = func(string, string, hexaimcp.MCPOverrides, io.Reader, io.Writer, io.Writer) error {
+ runMCP = func(context.Context, string, string, hexaimcp.MCPOverrides, io.Reader, io.Writer, io.Writer) error {
return errors.New("mcp boom")
}
@@ -212,7 +215,7 @@ func TestRunMain_BadFlagReturnsTwo(t *testing.T) {
old := runMCP
t.Cleanup(func() { runMCP = old })
called := false
- runMCP = func(string, string, hexaimcp.MCPOverrides, io.Reader, io.Writer, io.Writer) error {
+ runMCP = func(context.Context, string, string, hexaimcp.MCPOverrides, io.Reader, io.Writer, io.Writer) error {
called = true
return nil
}
diff --git a/cmd/hexai/app_runner.go b/cmd/hexai/app_runner.go
index ab1766b..e9b7e44 100644
--- a/cmd/hexai/app_runner.go
+++ b/cmd/hexai/app_runner.go
@@ -69,7 +69,9 @@ func normalizeAppRunner(r appRunner) appRunner {
func loadAppConfig(configPath string) appconfig.App {
logger := log.New(io.Discard, "", 0)
- return appconfig.LoadWithOptions(logger, appconfig.LoadOptions{ConfigPath: configPath})
+ // Config is loaded before the signal-aware CLI context exists, so use a
+ // background context here; the load is a quick local file read.
+ return appconfig.LoadWithOptions(context.Background(), logger, appconfig.LoadOptions{ConfigPath: configPath})
}
func parseAppArgs(cfg appconfig.App, configPath string, args []string, stderr io.Writer) (parsedAppArgs, error) {
diff --git a/internal/appconfig/config_alias_test.go b/internal/appconfig/config_alias_test.go
index da7909e..764611b 100644
--- a/internal/appconfig/config_alias_test.go
+++ b/internal/appconfig/config_alias_test.go
@@ -1,6 +1,7 @@
package appconfig
import (
+ "context"
"log"
"os"
"path/filepath"
@@ -28,7 +29,7 @@ codex = "gpt-5-codex"
if err := os.WriteFile(path, []byte(toml), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
- cfg := Load(log.New(os.Stderr, "test ", 0))
+ cfg := Load(context.Background(), log.New(os.Stderr, "test ", 0))
if cfg.OpenAIModel != "gpt-5-codex" {
t.Fatalf("expected alias to resolve to gpt-5-codex, got %q", cfg.OpenAIModel)
}
diff --git a/internal/appconfig/config_env_model_test.go b/internal/appconfig/config_env_model_test.go
index e10fa5d..9856a4e 100644
--- a/internal/appconfig/config_env_model_test.go
+++ b/internal/appconfig/config_env_model_test.go
@@ -1,6 +1,7 @@
package appconfig
import (
+ "context"
"log"
"os"
"testing"
@@ -12,14 +13,14 @@ func TestEnv_GenericModelOverrideAndPrecedence(t *testing.T) {
t.Setenv("HEXAI_MODEL", "gpt-5-codex")
t.Setenv("HEXAI_PROVIDER", "openai")
// No provider-specific env set yet: HEXAI_MODEL should flow into OpenAIModel
- cfg := Load(log.New(os.Stderr, "test ", 0))
+ cfg := Load(context.Background(), log.New(os.Stderr, "test ", 0))
if cfg.OpenAIModel != "gpt-5-codex" {
t.Fatalf("expected OpenAIModel=gpt-5-codex via HEXAI_MODEL, got %q", cfg.OpenAIModel)
}
// Now set a provider-specific model; it should win over HEXAI_MODEL
t.Setenv("HEXAI_OPENAI_MODEL", "gpt-5-thinking")
- cfg2 := Load(log.New(os.Stderr, "test ", 0))
+ cfg2 := Load(context.Background(), log.New(os.Stderr, "test ", 0))
if cfg2.OpenAIModel != "gpt-5-thinking" {
t.Fatalf("expected OpenAIModel from HEXAI_OPENAI_MODEL to win, got %q", cfg2.OpenAIModel)
}
@@ -30,7 +31,7 @@ func TestEnv_ModelForce_OverridesProviderSpecific(t *testing.T) {
t.Setenv("HEXAI_OPENAI_MODEL", "gpt-5-main")
t.Setenv("HEXAI_MODEL_FORCE", "gpt-5-codex")
t.Setenv("HEXAI_PROVIDER", "openai")
- cfg := Load(log.New(os.Stderr, "test ", 0))
+ cfg := Load(context.Background(), log.New(os.Stderr, "test ", 0))
if cfg.OpenAIModel != "gpt-5-codex" {
t.Fatalf("expected OpenAIModel forced to gpt-5-codex, got %q", cfg.OpenAIModel)
}
@@ -43,7 +44,7 @@ func TestEnv_SurfaceModelOverrides(t *testing.T) {
t.Setenv("HEXAI_MODEL_CLI", "gpt-cli")
t.Setenv("HEXAI_TEMPERATURE_CLI", "0.22")
t.Setenv("HEXAI_PROVIDER_CLI", "ollama")
- cfg := Load(log.New(os.Stderr, "test ", 0))
+ cfg := Load(context.Background(), log.New(os.Stderr, "test ", 0))
if len(cfg.CompletionConfigs) != 1 {
t.Fatalf("expected single completion entry, got %+v", cfg.CompletionConfigs)
}
diff --git a/internal/appconfig/config_features_test.go b/internal/appconfig/config_features_test.go
index 123283a..77beb07 100644
--- a/internal/appconfig/config_features_test.go
+++ b/internal/appconfig/config_features_test.go
@@ -3,6 +3,7 @@
package appconfig
import (
+ "context"
"os"
"path/filepath"
"reflect"
@@ -11,7 +12,7 @@ import (
func TestIgnoreConfig_Defaults(t *testing.T) {
clearHexaiEnv(t)
- cfg := Load(nil)
+ cfg := Load(context.Background(), nil)
if cfg.IgnoreGitignore == nil || !*cfg.IgnoreGitignore {
t.Error("expected IgnoreGitignore default true")
}
@@ -33,7 +34,7 @@ gitignore = false
extra_patterns = ["*.min.js", "dist/**"]
lsp_notify_ignored = false
`)
- cfg := LoadWithOptions(newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
if cfg.IgnoreGitignore == nil || *cfg.IgnoreGitignore {
t.Error("expected IgnoreGitignore false from file")
}
@@ -58,7 +59,7 @@ lsp_notify_ignored = true
withEnv(t, "HEXAI_IGNORE_GITIGNORE", "false")
withEnv(t, "HEXAI_IGNORE_LSP_NOTIFY", "0")
withEnv(t, "HEXAI_IGNORE_EXTRA_PATTERNS", "*.bak,*.tmp")
- cfg := LoadWithOptions(newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
if cfg.IgnoreGitignore == nil || *cfg.IgnoreGitignore {
t.Error("expected IgnoreGitignore false from env override")
}
@@ -90,7 +91,7 @@ gitignore = true
gitignore = false
extra_patterns = ["build/**"]
`)
- cfg := LoadWithOptions(newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: projectDir})
+ cfg := LoadWithOptions(context.Background(), newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: projectDir})
if cfg.IgnoreGitignore == nil || *cfg.IgnoreGitignore {
t.Error("expected project override to set IgnoreGitignore false")
}
@@ -108,7 +109,7 @@ func TestIgnoreConfig_DisableGitignore(t *testing.T) {
[ignore]
gitignore = false
`)
- cfg := LoadWithOptions(newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
if cfg.IgnoreGitignore == nil || *cfg.IgnoreGitignore {
t.Error("expected IgnoreGitignore false")
}
@@ -149,7 +150,7 @@ clear_keys = "C-u"
newline_keys = "S-Enter"
submit_keys = "Enter"
`)
- cfg := LoadWithOptions(newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
if cfg.TmuxEditPopupWidth != "90%" {
t.Errorf("PopupWidth = %q, want 90%%", cfg.TmuxEditPopupWidth)
}
@@ -212,7 +213,7 @@ func TestTmuxEditConfig_SkipsEmptyName(t *testing.T) {
name = ""
display_name = "Empty"
`)
- cfg := LoadWithOptions(newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), newLogger(), LoadOptions{ConfigPath: cfgPath, ProjectRoot: dir})
if len(cfg.TmuxEditAgents) != 0 {
t.Errorf("got %d agents, want 0 (empty name should be skipped)", len(cfg.TmuxEditAgents))
}
diff --git a/internal/appconfig/config_load.go b/internal/appconfig/config_load.go
index 3ed1654..1e4c6b7 100644
--- a/internal/appconfig/config_load.go
+++ b/internal/appconfig/config_load.go
@@ -1,6 +1,7 @@
package appconfig
import (
+ "context"
"fmt"
"log"
"os"
@@ -15,15 +16,26 @@ import (
const ProjectConfigFilename = ".hexaiconfig.toml"
// Load reads configuration from a file and merges with defaults.
-// It respects the XDG Base Directory Specification.
-func Load(logger *log.Logger) App { return LoadWithOptions(logger, LoadOptions{}) }
+// It respects the XDG Base Directory Specification. The context lets callers
+// abort the (blocking) file reads on shutdown/cancellation.
+func Load(ctx context.Context, logger *log.Logger) App {
+ return LoadWithOptions(ctx, logger, LoadOptions{})
+}
// LoadWithOptions reads configuration and applies the requested loading options.
-func LoadWithOptions(logger *log.Logger, opts LoadOptions) App {
+// ctx is honored before performing the blocking file I/O so a cancelled caller
+// gets a clean default config back instead of stalling on disk access.
+func LoadWithOptions(ctx context.Context, logger *log.Logger, opts LoadOptions) App {
cfg := newDefaultConfig()
if logger == nil {
return cfg // Return defaults if no logger is provided (e.g. in tests)
}
+ // Respect cancellation up front: config loading touches several files and
+ // there is no value in starting that work once the caller has given up.
+ if ctx != nil && ctx.Err() != nil {
+ logger.Printf("config load cancelled: %v", ctx.Err())
+ return cfg
+ }
// Step 1: Load global config file
configPath := strings.TrimSpace(opts.ConfigPath)
diff --git a/internal/appconfig/config_test.go b/internal/appconfig/config_test.go
index d4e7739..06e73a1 100644
--- a/internal/appconfig/config_test.go
+++ b/internal/appconfig/config_test.go
@@ -2,6 +2,7 @@ package appconfig
import (
"bytes"
+ "context"
"errors"
"io"
"log"
@@ -14,6 +15,24 @@ import (
func newLogger() *log.Logger { return log.New(io.Discard, "", 0) }
+// TestLoadWithOptions_CancelledContextReturnsDefaults verifies that a
+// pre-cancelled context short-circuits config loading (skipping the blocking
+// file reads) and returns the default config instead.
+func TestLoadWithOptions_CancelledContextReturnsDefaults(t *testing.T) {
+ dir := t.TempDir()
+ cfgPath := filepath.Join(dir, "config.toml")
+ writeFile(t, cfgPath, "[core]\nmax_tokens = 9999\n")
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ cfg := LoadWithOptions(ctx, newLogger(), LoadOptions{ConfigPath: cfgPath})
+ def := newDefaultConfig()
+ if cfg.MaxTokens != def.MaxTokens {
+ t.Fatalf("expected default config on cancelled ctx, got MaxTokens=%d", cfg.MaxTokens)
+ }
+}
+
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
@@ -46,7 +65,7 @@ func withEnv(t *testing.T, k, v string) {
}
func TestLoad_Defaults_NoLogger(t *testing.T) {
- cfg := Load(nil)
+ cfg := Load(context.Background(), nil)
if cfg.MaxTokens == 0 || cfg.ContextMode == "" || cfg.ContextWindowLines == 0 || cfg.MaxContextTokens == 0 {
t.Fatalf("expected defaults populated, got %+v", cfg)
}
@@ -60,7 +79,7 @@ func TestLoad_Defaults_WithLogger_NoFile_NoEnv(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
logger := newLogger()
- cfg := LoadWithOptions(logger, LoadOptions{ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), logger, LoadOptions{ProjectRoot: dir})
def := newDefaultConfig()
if cfg.MaxTokens != def.MaxTokens || cfg.ContextMode != def.ContextMode || cfg.ContextWindowLines != def.ContextWindowLines {
t.Fatalf("expected defaults; got %+v want %+v", cfg, def)
@@ -186,7 +205,7 @@ temperature = 0.0
withEnv(t, "HEXAI_PROVIDER_CLI", "ollama")
logger := newLogger()
- cfg := LoadWithOptions(logger, LoadOptions{ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), logger, LoadOptions{ProjectRoot: dir})
// Check overrides
if cfg.MaxTokens != 321 || cfg.ContextMode != "always-full" || cfg.ContextWindowLines != 77 || cfg.MaxContextTokens != 888 {
@@ -255,7 +274,7 @@ temperature = 0.0
} {
t.Setenv(k, "")
}
- cfg2 := LoadWithOptions(logger, LoadOptions{ProjectRoot: dir})
+ cfg2 := LoadWithOptions(context.Background(), logger, LoadOptions{ProjectRoot: dir})
if cfg2.MaxTokens != 123 || cfg2.ContextMode != "file-on-new-func" || cfg2.ContextWindowLines != 50 || cfg2.MaxContextTokens != 999 || cfg2.LogPreviewLimit != 0 {
t.Fatalf("file merge not applied: %+v", cfg2)
}
@@ -434,7 +453,7 @@ temperature = 0.0
// Ensure no env override interferes with manual_invoke_min_prefix in this test
t.Setenv("HEXAI_MANUAL_INVOKE_MIN_PREFIX", "")
logger := newLogger()
- cfg := LoadWithOptions(logger, LoadOptions{ProjectRoot: dir})
+ cfg := LoadWithOptions(context.Background(), logger, LoadOptions{ProjectRoot: dir})
if cfg.MaxTokens != 111 || cfg.ContextMode != "window" || cfg.ContextWindowLines != 42 || cfg.MaxContextTokens != 777 {
t.Fatalf("sectioned basics wrong: %+v", cfg)
@@ -495,7 +514,7 @@ explain_system = "CLI-EXPLAIN"
`
writeFile(t, cfgPath, content)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
// completion
if cfg.PromptCompletionSystemGeneral != "SYS-GENERAL" || cfg.PromptCompletionSystemParams != "SYS-PARAMS" || cfg.PromptCompletionSystemInline != "SYS-INLINE" {
@@ -557,7 +576,7 @@ user = "Diagnostics to resolve (selection only):\n{{diagnostics}}\n\nSelected co
custom_menu_hotkey = "a"
`
writeFile(t, cfgPath, content)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
if err := cfg.Validate(); err != nil {
t.Fatalf("validate: %v", err)
}
@@ -592,7 +611,7 @@ id = "DUP"
title = "B"
instruction = "y"
`)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "duplicate custom action id") {
t.Fatalf("expected duplicate id error, got %v", err)
}
@@ -616,7 +635,7 @@ title = "B"
instruction = "y"
hotkey = "E"
`)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "duplicate custom action hotkey") {
t.Fatalf("expected duplicate hotkey error, got %v", err)
}
@@ -635,7 +654,7 @@ title = "A"
instruction = "x"
scope = "bad"
`)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "invalid scope") {
t.Fatalf("expected invalid scope error, got %v", err)
}
@@ -650,7 +669,7 @@ func TestTmuxMenuHotkey_Clash_Error(t *testing.T) {
[tmux]
custom_menu_hotkey = "r"
`)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "clashes with built-in") {
t.Fatalf("expected clash error, got %v", err)
}
@@ -727,7 +746,7 @@ name = "anthropic"
// Load using explicit ProjectRoot (avoids needing to chdir)
logger := newLogger()
- cfg := LoadWithOptions(logger, LoadOptions{ProjectRoot: projectDir})
+ cfg := LoadWithOptions(context.Background(), logger, LoadOptions{ProjectRoot: projectDir})
// Project config should override global values
if cfg.MaxTokens != 8000 {
@@ -768,7 +787,7 @@ max_tokens = 8000
withEnv(t, "HEXAI_MAX_TOKENS", "9999")
logger := newLogger()
- cfg := LoadWithOptions(logger, LoadOptions{ProjectRoot: projectDir})
+ cfg := LoadWithOptions(context.Background(), logger, LoadOptions{ProjectRoot: projectDir})
if cfg.MaxTokens != 9999 {
t.Fatalf("expected env max_tokens=9999 to override project, got %d", cfg.MaxTokens)
@@ -799,7 +818,7 @@ max_tokens = 2000
}
logger := newLogger()
- cfg := LoadWithOptions(logger, LoadOptions{})
+ cfg := LoadWithOptions(context.Background(), logger, LoadOptions{})
// Should get global config values, not defaults
if cfg.MaxTokens != 2000 {
diff --git a/internal/appconfig/custom_validation_more_test.go b/internal/appconfig/custom_validation_more_test.go
index 36212aa..255963b 100644
--- a/internal/appconfig/custom_validation_more_test.go
+++ b/internal/appconfig/custom_validation_more_test.go
@@ -1,6 +1,7 @@
package appconfig
import (
+ "context"
"path/filepath"
"strings"
"testing"
@@ -19,7 +20,7 @@ instruction = "x"
id = "no-title"
instruction = "x"
`)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
if err := cfg.Validate(); err == nil || (!strings.Contains(err.Error(), "missing required field id") && !strings.Contains(err.Error(), "missing required field title")) {
t.Fatalf("expected missing field error, got %v", err)
}
@@ -40,7 +41,7 @@ hotkey = "too"
[tmux]
custom_menu_hotkey = "ab"
`)
- cfg := Load(newLogger())
+ cfg := Load(context.Background(), newLogger())
if err := cfg.Validate(); err == nil || (!strings.Contains(err.Error(), "hotkey must be a single character") && !strings.Contains(err.Error(), "invalid tmux.custom_menu_hotkey")) {
t.Fatalf("expected invalid hotkey error, got %v", err)
}
diff --git a/internal/askcli/command_edit.go b/internal/askcli/command_edit.go
index 27c9106..a82d575 100644
--- a/internal/askcli/command_edit.go
+++ b/internal/askcli/command_edit.go
@@ -10,9 +10,10 @@ import (
// captureFromEditor opens the user's editor on a temporary file pre-filled with
// the given initial content and returns its trimmed contents after the editor
-// exits. It is a variable so tests can stub it.
-var captureFromEditor = func(initial []byte) (string, error) {
- return editor.OpenTempAndEdit(initial)
+// exits. ctx is forwarded to the editor subprocess so it can be cancelled with
+// the surrounding command. It is a variable so tests can stub it.
+var captureFromEditor = func(ctx context.Context, initial []byte) (string, error) {
+ return editor.OpenTempAndEdit(ctx, initial)
}
// handleEdit opens the configured editor on a temporary file. With no selector
@@ -22,7 +23,7 @@ func (d *Dispatcher) handleEdit(ctx context.Context, args []string, stdout, stde
if len(args) >= 2 {
return d.editTaskDescription(ctx, args[1], stdout, stderr)
}
- description, err := captureFromEditor(nil)
+ description, err := captureFromEditor(ctx, nil)
if err != nil {
writeInfoError(stderr, err)
return 1, nil