diff options
| author | Paul Buetow <paul@buetow.org> | 2025-09-19 22:52:48 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2025-09-19 22:52:48 +0300 |
| commit | eb72b06fe8e62cb77af73f6dc558d384a5a5fe80 (patch) | |
| tree | efeb1165b9fbcb69a4ee675dba7bdc8c28fee3aa /internal | |
| parent | acc400768153a7bfda1413f15579c9455b877c87 (diff) | |
fix
Diffstat (limited to 'internal')
33 files changed, 455 insertions, 229 deletions
diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index 2274aee..9119688 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -247,9 +247,36 @@ type sectionStats struct { } type sectionOpenAI struct { - Model string `toml:"model"` - BaseURL string `toml:"base_url"` - Temperature *float64 `toml:"temperature"` + Model string `toml:"model"` + BaseURL string `toml:"base_url"` + Temperature *float64 `toml:"temperature"` + Presets map[string]string `toml:"presets"` +} + +func (s sectionOpenAI) isZero() bool { + return strings.TrimSpace(s.Model) == "" && strings.TrimSpace(s.BaseURL) == "" && s.Temperature == nil && len(s.Presets) == 0 +} + +func (s sectionOpenAI) resolvedModel() string { + model := strings.TrimSpace(s.Model) + if model == "" { + return "" + } + if len(s.Presets) == 0 { + return model + } + if mapped := strings.TrimSpace(s.Presets[model]); mapped != "" { + return mapped + } + lower := strings.ToLower(model) + for k, v := range s.Presets { + if strings.ToLower(strings.TrimSpace(k)) == lower { + if mapped := strings.TrimSpace(v); mapped != "" { + return mapped + } + } + } + return model } type sectionCopilot struct { @@ -380,10 +407,10 @@ func (fc *fileConfig) toApp() App { } // openai - if (fc.OpenAI != sectionOpenAI{}) || fc.OpenAI.Temperature != nil { + if !fc.OpenAI.isZero() || fc.OpenAI.Temperature != nil { tmp := App{ OpenAIBaseURL: fc.OpenAI.BaseURL, - OpenAIModel: fc.OpenAI.Model, + OpenAIModel: fc.OpenAI.resolvedModel(), OpenAITemperature: fc.OpenAI.Temperature, } out.mergeProviderFields(&tmp) @@ -939,13 +966,46 @@ func loadFromEnv(logger *log.Logger) *App { any = true } + modelForce := strings.TrimSpace(getenv("HEXAI_MODEL_FORCE")) + modelGeneric := strings.TrimSpace(getenv("HEXAI_MODEL")) + providerLower := strings.ToLower(strings.TrimSpace(out.Provider)) + forceUsed := false + genericUsed := false + pickModel := func(providerName, specific string) (string, bool) { + specific = strings.TrimSpace(specific) + nameLower := strings.ToLower(strings.TrimSpace(providerName)) + if modelForce != "" { + if providerLower == nameLower { + forceUsed = true + return modelForce, true + } + if providerLower == "" && !forceUsed { + forceUsed = true + return modelForce, true + } + } + if specific != "" { + return specific, true + } + if modelGeneric != "" { + if providerLower == nameLower { + return modelGeneric, true + } + if providerLower == "" && !genericUsed { + genericUsed = true + return modelGeneric, true + } + } + return "", false + } + // Provider-specific if s := getenv("HEXAI_OPENAI_BASE_URL"); s != "" { out.OpenAIBaseURL = s any = true } - if s := getenv("HEXAI_OPENAI_MODEL"); s != "" { - out.OpenAIModel = s + if model, ok := pickModel("openai", getenv("HEXAI_OPENAI_MODEL")); ok { + out.OpenAIModel = model any = true } if f, ok := parseFloatPtr("HEXAI_OPENAI_TEMPERATURE"); ok { @@ -957,8 +1017,8 @@ func loadFromEnv(logger *log.Logger) *App { out.OllamaBaseURL = s any = true } - if s := getenv("HEXAI_OLLAMA_MODEL"); s != "" { - out.OllamaModel = s + if model, ok := pickModel("ollama", getenv("HEXAI_OLLAMA_MODEL")); ok { + out.OllamaModel = model any = true } if f, ok := parseFloatPtr("HEXAI_OLLAMA_TEMPERATURE"); ok { @@ -970,8 +1030,8 @@ func loadFromEnv(logger *log.Logger) *App { out.CopilotBaseURL = s any = true } - if s := getenv("HEXAI_COPILOT_MODEL"); s != "" { - out.CopilotModel = s + if model, ok := pickModel("copilot", getenv("HEXAI_COPILOT_MODEL")); ok { + out.CopilotModel = model any = true } if f, ok := parseFloatPtr("HEXAI_COPILOT_TEMPERATURE"); ok { diff --git a/internal/hexaiaction/run.go b/internal/hexaiaction/run.go index 45eacc2..a48bf94 100644 --- a/internal/hexaiaction/run.go +++ b/internal/hexaiaction/run.go @@ -73,54 +73,85 @@ func executeAction(ctx context.Context, kind ActionKind, parts InputParts, cfg a case ActionSkip: return parts.Selection, nil case ActionRewrite: - instr, cleaned := ExtractInstruction(parts.Selection) - if strings.TrimSpace(instr) == "" { - fmt.Fprintln(stderr, logging.AnsiBase+"hexai-tmux-action: no inline instruction found; echoing input"+logging.AnsiReset) - return parts.Selection, nil - } - cctx, cancel := timeout10s(ctx) - defer cancel() - return runRewrite(cctx, cfg, client, instr, cleaned) + return handleRewriteAction(ctx, parts, cfg, client, stderr) case ActionDiagnostics: - cctx, cancel := timeout10s(ctx) - defer cancel() - return runDiagnostics(cctx, cfg, client, parts.Diagnostics, parts.Selection) + return handleDiagnosticsAction(ctx, parts, cfg, client) case ActionDocument: - cctx, cancel := timeout10s(ctx) - defer cancel() - return runDocument(cctx, cfg, client, parts.Selection) + return handleDocumentAction(ctx, parts, cfg, client) case ActionGoTest: - cctx, cancel := timeout8s(ctx) - defer cancel() - return runGoTest(cctx, cfg, client, parts.Selection) + return handleGoTestAction(ctx, parts, cfg, client) case ActionSimplify: - cctx, cancel := timeout10s(ctx) - defer cancel() - return runSimplify(cctx, cfg, client, parts.Selection) + return handleSimplifyAction(ctx, parts, cfg, client) case ActionCustom: - cctx, cancel := timeout10s(ctx) - defer cancel() - if selectedCustom != nil { - // Run configured custom action - out, err := runCustom(cctx, cfg, client, *selectedCustom, parts) - selectedCustom = nil // clear after use - return out, err - } - // No selected custom; treat as no-op - return parts.Selection, nil + return handleCustomAction(ctx, parts, cfg, client) case ActionCustomPrompt: - cctx, cancel := timeout10s(ctx) - defer cancel() - // Open editor for free-form instruction - prompt, err := editor.OpenTempAndEdit(nil) - if err != nil || strings.TrimSpace(prompt) == "" { - fmt.Fprintln(stderr, logging.AnsiBase+"hexai-tmux-action: custom prompt canceled or empty; echoing input"+logging.AnsiReset) - return parts.Selection, nil - } - return runRewrite(cctx, cfg, client, prompt, parts.Selection) + return handleCustomPromptAction(ctx, parts, cfg, client, stderr) default: return parts.Selection, nil } } +func handleRewriteAction(ctx context.Context, parts InputParts, cfg appconfig.App, client chatDoer, stderr io.Writer) (string, error) { + instr, cleaned := ExtractInstruction(parts.Selection) + if strings.TrimSpace(instr) == "" { + fmt.Fprintln(stderr, logging.AnsiBase+"hexai-tmux-action: no inline instruction found; echoing input"+logging.AnsiReset) + return parts.Selection, nil + } + return runWithTimeout(ctx, timeout10s, func(cctx context.Context) (string, error) { + return runRewrite(cctx, cfg, client, instr, cleaned) + }) +} + +func handleDiagnosticsAction(ctx context.Context, parts InputParts, cfg appconfig.App, client chatDoer) (string, error) { + return runWithTimeout(ctx, timeout10s, func(cctx context.Context) (string, error) { + return runDiagnostics(cctx, cfg, client, parts.Diagnostics, parts.Selection) + }) +} + +func handleDocumentAction(ctx context.Context, parts InputParts, cfg appconfig.App, client chatDoer) (string, error) { + return runWithTimeout(ctx, timeout10s, func(cctx context.Context) (string, error) { + return runDocument(cctx, cfg, client, parts.Selection) + }) +} + +func handleGoTestAction(ctx context.Context, parts InputParts, cfg appconfig.App, client chatDoer) (string, error) { + return runWithTimeout(ctx, timeout8s, func(cctx context.Context) (string, error) { + return runGoTest(cctx, cfg, client, parts.Selection) + }) +} + +func handleSimplifyAction(ctx context.Context, parts InputParts, cfg appconfig.App, client chatDoer) (string, error) { + return runWithTimeout(ctx, timeout10s, func(cctx context.Context) (string, error) { + return runSimplify(cctx, cfg, client, parts.Selection) + }) +} + +func handleCustomAction(ctx context.Context, parts InputParts, cfg appconfig.App, client chatDoer) (string, error) { + if selectedCustom == nil { + return parts.Selection, nil + } + return runWithTimeout(ctx, timeout10s, func(cctx context.Context) (string, error) { + out, err := runCustom(cctx, cfg, client, *selectedCustom, parts) + selectedCustom = nil + return out, err + }) +} + +func handleCustomPromptAction(ctx context.Context, parts InputParts, cfg appconfig.App, client chatDoer, stderr io.Writer) (string, error) { + prompt, err := editor.OpenTempAndEdit(nil) + if err != nil || strings.TrimSpace(prompt) == "" { + fmt.Fprintln(stderr, logging.AnsiBase+"hexai-tmux-action: custom prompt canceled or empty; echoing input"+logging.AnsiReset) + return parts.Selection, nil + } + return runWithTimeout(ctx, timeout10s, func(cctx context.Context) (string, error) { + return runRewrite(cctx, cfg, client, prompt, parts.Selection) + }) +} + +func runWithTimeout(ctx context.Context, timeout func(context.Context) (context.Context, context.CancelFunc), fn func(context.Context) (string, error)) (string, error) { + innerCtx, cancel := timeout(ctx) + defer cancel() + return fn(innerCtx) +} + // client construction is shared via internal/llmutils diff --git a/internal/hexaicli/run.go b/internal/hexaicli/run.go index 823dcaa..11e8938 100644 --- a/internal/hexaicli/run.go +++ b/internal/hexaicli/run.go @@ -3,7 +3,6 @@ package hexaicli import ( - "bufio" "context" "fmt" "io" @@ -78,8 +77,11 @@ func RunWithClient(ctx context.Context, args []string, stdin io.Reader, stdout, func readInput(stdin io.Reader, args []string) (string, error) { var stdinData string if fi, err := os.Stdin.Stat(); err == nil && (fi.Mode()&os.ModeCharDevice) == 0 { - b, _ := io.ReadAll(bufio.NewReader(stdin)) - stdinData = strings.TrimSpace(string(b)) + data, readErr := io.ReadAll(stdin) + if readErr != nil { + return "", fmt.Errorf("hexai: failed to read stdin: %w", readErr) + } + stdinData = strings.TrimSpace(string(data)) } argData := strings.TrimSpace(strings.Join(args, " ")) switch { diff --git a/internal/hexaicli/run_test.go b/internal/hexaicli/run_test.go index d192850..a4184f6 100644 --- a/internal/hexaicli/run_test.go +++ b/internal/hexaicli/run_test.go @@ -12,6 +12,10 @@ import ( "codeberg.org/snonux/hexai/internal/llm" ) +type failingReader struct{ err error } + +func (f failingReader) Read([]byte) (int, error) { return 0, f.err } + func TestReadInput_Combinations(t *testing.T) { // stdin + arg restore, f := setStdin(t, "from-stdin") @@ -41,6 +45,15 @@ func TestReadInput_Combinations(t *testing.T) { } } +func TestReadInput_PropagatesStdinError(t *testing.T) { + restore, _ := setStdin(t, "ignored") + defer restore() + bad := failingReader{err: io.ErrUnexpectedEOF} + if _, err := readInput(bad, nil); err == nil || !strings.Contains(err.Error(), "failed to read stdin") { + t.Fatalf("expected stdin read error, got %v", err) + } +} + func TestBuildMessages_Explain(t *testing.T) { msgs := buildMessages("please explain this") if len(msgs) != 2 || msgs[0].Role != "system" || !strings.Contains(strings.ToLower(msgs[0].Content), "explanation") { diff --git a/internal/llm/ollama.go b/internal/llm/ollama.go index ce607a7..374a771 100644 --- a/internal/llm/ollama.go +++ b/internal/llm/ollama.go @@ -46,7 +46,7 @@ func newOllama(baseURL, model string, defaultTemp *float64) Client { baseURL = "http://localhost:11434" } if strings.TrimSpace(model) == "" { - model = "qwen3-coder:30b-a3b-q4_K_M`" + model = "qwen3-coder:30b-a3b-q4_K_M" } return ollamaClient{ httpClient: &http.Client{Timeout: 30 * time.Second}, diff --git a/internal/lsp/chat_history_test.go b/internal/lsp/chat_history_test.go index b1cae80..70080f3 100644 --- a/internal/lsp/chat_history_test.go +++ b/internal/lsp/chat_history_test.go @@ -3,19 +3,20 @@ package lsp import "testing" func TestStripTrailingTrigger(t *testing.T) { - if got := stripTrailingTrigger("what?"); got != "what" { + s := newTestServer() + if got := s.stripTrailingTrigger("what?"); got != "what" { t.Fatalf("should remove trailing ?") } - if got := stripTrailingTrigger("what?>"); got != "what?" { + if got := s.stripTrailingTrigger("what?>"); got != "what?" { t.Fatalf("should drop trailing > when preceded by ?") } - if got := stripTrailingTrigger("ok!>"); got != "ok!" { + if got := s.stripTrailingTrigger("ok!>"); got != "ok!" { t.Fatalf("should drop > after !") } - if got := stripTrailingTrigger("note:>"); got != "note:" { + if got := s.stripTrailingTrigger("note:>"); got != "note:" { t.Fatalf("should drop > after :") } - if got := stripTrailingTrigger("go;>"); got != "go;" { + if got := s.stripTrailingTrigger("go;>"); got != "go;" { t.Fatalf("should drop > after ;") } } diff --git a/internal/lsp/chat_no_double_answer_test.go b/internal/lsp/chat_no_double_answer_test.go index 8821cd0..04196f8 100644 --- a/internal/lsp/chat_no_double_answer_test.go +++ b/internal/lsp/chat_no_double_answer_test.go @@ -10,6 +10,7 @@ import ( func TestDetectAndHandleChat_NoDoubleAnswer(t *testing.T) { var out bytes.Buffer s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out} + initServerDefaults(s) s.llmClient = fakeLLM{resp: "IGNORED"} uri := "file:///x.go" // Question line with trigger, followed by an existing answer line starting with '>' diff --git a/internal/lsp/chat_trigger_suppression_test.go b/internal/lsp/chat_trigger_suppression_test.go index 55a5245..8d016d1 100644 --- a/internal/lsp/chat_trigger_suppression_test.go +++ b/internal/lsp/chat_trigger_suppression_test.go @@ -5,6 +5,7 @@ import "testing" // Ensure completion is suppressed when a chat trigger is at EOL (?>,!>,:>,;>) func TestCompletionSuppressedOnChatTriggerEOL(t *testing.T) { s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)} + initServerDefaults(s) s.llmClient = &countingLLM{} tests := []string{"What now?>", "Explain!>", "Refactor:>", "note ;>"} for i, line := range tests { diff --git a/internal/lsp/codeaction_custom_test.go b/internal/lsp/codeaction_custom_test.go index 7baf993..1ea4c3c 100644 --- a/internal/lsp/codeaction_custom_test.go +++ b/internal/lsp/codeaction_custom_test.go @@ -27,7 +27,18 @@ func capResp(t *testing.T, buf *bytes.Buffer) Response { func TestHandleCodeAction_ListsCustomActions(t *testing.T) { var out bytes.Buffer - s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out} + s := &Server{ + logger: log.New(io.Discard, "", 0), + docs: make(map[string]*document), + out: &out, + inlineOpen: ">", + inlineClose: ">", + inlineOpenChar: '>', + inlineCloseChar: '>', + chatSuffix: ">", + chatSuffixChar: '>', + chatPrefixes: []string{"?", "!", ":", ";"}, + } s.llmClient = fakeLLM{resp: "IGN"} // Inject two custom actions s.customActions = []CustomAction{ diff --git a/internal/lsp/codeaction_gotest_int_test.go b/internal/lsp/codeaction_gotest_int_test.go index 04a73e0..384f3d5 100644 --- a/internal/lsp/codeaction_gotest_int_test.go +++ b/internal/lsp/codeaction_gotest_int_test.go @@ -13,6 +13,7 @@ func TestResolveGoTest_CreatesTestFile(t *testing.T) { t.Fatalf("write: %v", err) } s := &Server{} // minimal server with nil llmClient to trigger stub + initServerDefaults(s) uri := "file://" + src we, jumpURI, jumpRange, ok := s.resolveGoTest(uri, Position{Line: 2}) if !ok || jumpURI == "" || jumpRange.Start.Line < 0 { diff --git a/internal/lsp/completion_codex_path_test.go b/internal/lsp/completion_codex_path_test.go index bd3b3f4..6c0a60f 100644 --- a/internal/lsp/completion_codex_path_test.go +++ b/internal/lsp/completion_codex_path_test.go @@ -40,6 +40,7 @@ func (f *fakeCodeLLM) DefaultModel() string { return "m" } func TestTryLLMCompletion_PrefersCodeCompleterOverChat(t *testing.T) { s := &Server{maxTokens: 32, triggerChars: []string{"."}, compCache: make(map[string]string)} + initServerDefaults(s) fake := &fakeCodeLLM{result: "DoThing()"} s.llmClient = fake line := "obj." @@ -58,6 +59,7 @@ func TestTryLLMCompletion_PrefersCodeCompleterOverChat(t *testing.T) { func TestTryLLMCompletion_FallsBackToChatOnCodeCompleterError(t *testing.T) { s := &Server{maxTokens: 32, triggerChars: []string{"."}, compCache: make(map[string]string)} + initServerDefaults(s) fake := &fakeCodeLLM{result: "DoThing()", codeErr: errors.New("boom")} s.llmClient = fake line := "obj." diff --git a/internal/lsp/completion_prefix_strip_test.go b/internal/lsp/completion_prefix_strip_test.go index 6af87a0..acc7921 100644 --- a/internal/lsp/completion_prefix_strip_test.go +++ b/internal/lsp/completion_prefix_strip_test.go @@ -42,6 +42,7 @@ func TestStripDuplicateAssignmentPrefix_AssignAndWalrus(t *testing.T) { func TestTryLLMCompletion_ManualInvokeAfterWhitespace_Allows(t *testing.T) { s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)} + initServerDefaults(s) s.llmClient = fakeLLM{resp: tut.MultilineFunctionSuggestion()} line := "func fib(i int) " // cursor after space p := CompletionParams{Position: Position{Line: 0, Character: len(line)}, TextDocument: TextDocumentIdentifier{URI: "file://x.go"}} @@ -58,6 +59,7 @@ func TestTryLLMCompletion_ManualInvokeAfterWhitespace_Allows(t *testing.T) { func TestTryLLMCompletion_InlinePromptAlwaysTriggers(t *testing.T) { s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)} + initServerDefaults(s) s.llmClient = fakeLLM{resp: "replacement"} line := "prefix >do something> suffix" // No trigger char immediately before cursor; place cursor at end @@ -69,7 +71,17 @@ func TestTryLLMCompletion_InlinePromptAlwaysTriggers(t *testing.T) { } func TestTryLLMCompletion_DoubleOpenEmpty_DoesNotAutoTrigger(t *testing.T) { - s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)} + s := &Server{ + maxTokens: 32, + triggerChars: []string{".", ":", "/", "_"}, + compCache: make(map[string]string), + inlineOpen: ">", + inlineClose: ">", + inlineOpenChar: '>', + inlineCloseChar: '>', + } + initServerDefaults(s) + initServerDefaults(s) fake := &countingLLM{} s.llmClient = fake line := ">> " // empty content after double-open should not force-trigger @@ -87,22 +99,30 @@ func TestTryLLMCompletion_DoubleOpenEmpty_DoesNotAutoTrigger(t *testing.T) { } func TestHasDoubleSemicolonTrigger_Variants(t *testing.T) { - if hasDoubleOpenTrigger(">>") { + if hasDoubleOpenTrigger(">>", '>', '>') { t.Fatalf("bare double-open should not trigger") } - if hasDoubleOpenTrigger(">> ") { + if hasDoubleOpenTrigger(">> ", '>', '>') { t.Fatalf("double-open followed by space should not trigger") } - if hasDoubleOpenTrigger(">>>") { + if hasDoubleOpenTrigger(">>>", '>', '>') { t.Fatalf("';;;' should not trigger (no content)") } - if !hasDoubleOpenTrigger(">>x>") { + if !hasDoubleOpenTrigger(">>x>", '>', '>') { t.Fatalf("expected trigger for ';;x;' pattern") } } func TestBareDoubleOpenPreventsAutoTriggerEvenWithOtherTriggers(t *testing.T) { - s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)} + s := &Server{ + maxTokens: 32, + triggerChars: []string{".", ":", "/", "_"}, + compCache: make(map[string]string), + inlineOpen: ">", + inlineClose: ">", + inlineOpenChar: '>', + inlineCloseChar: '>', + } fake := &countingLLM{} s.llmClient = fake // Place a '.' earlier but also include bare double-open at end; should not auto-trigger @@ -122,6 +142,7 @@ func TestBareDoubleOpenPreventsAutoTriggerEvenWithOtherTriggers(t *testing.T) { func TestBareDoubleOpenOnNextLine_PreventsAutoTrigger(t *testing.T) { s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)} + initServerDefaults(s) fake := &countingLLM{} s.llmClient = fake current := "expression := flag.String(\"expression\", \"\", \"Expression to evaluate\")" @@ -141,6 +162,7 @@ func TestBareDoubleOpenOnNextLine_PreventsAutoTrigger(t *testing.T) { func TestBareDoubleOpenPreventsManualInvoke(t *testing.T) { s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)} + initServerDefaults(s) fake := &countingLLM{} s.llmClient = fake line := ">>" diff --git a/internal/lsp/coverage_add_test.go b/internal/lsp/coverage_add_test.go index 7701a5e..b3b7322 100644 --- a/internal/lsp/coverage_add_test.go +++ b/internal/lsp/coverage_add_test.go @@ -56,13 +56,14 @@ func TestFindGoFunctionAtLine_NoBody(t *testing.T) { } func TestLineHasInlinePrompt(t *testing.T) { - if !lineHasInlinePrompt(">do>") { + if !lineHasInlinePrompt(">do>", '>', '>') { t.Fatalf("expected inline prompt") } } func TestDiagnosticsInRange_Overlap(t *testing.T) { s := &Server{} + initServerDefaults(s) ctx := CodeActionContext{Diagnostics: []Diagnostic{{ Range: Range{Start: Position{Line: 10, Character: 0}, End: Position{Line: 12, Character: 0}}, Message: "x", @@ -88,15 +89,12 @@ func TestIndentHelpersAndPromptRemoval(t *testing.T) { t.Fatalf("applyIndent: %q", out) } // double-open trigger removes whole line - edits := promptRemovalEditsForLine(">>ask>", 3) + edits := promptRemovalEditsForLine(">>ask>", 3, '>', '>') if len(edits) != 1 || edits[0].Range.Start.Line != 3 { t.Fatalf("unexpected edits: %#v", edits) } - // temporarily switch to semicolon tags and test collection - oldOpen, oldClose := inlineOpenChar, inlineCloseChar - inlineOpenChar, inlineCloseChar = ';', ';' - t.Cleanup(func() { inlineOpenChar, inlineCloseChar = oldOpen, oldClose }) - edits2 := collectSemicolonMarkers("pre;do;post", 1) + // semicolon tags collect correctly when provided explicitly + edits2 := collectSemicolonMarkers("pre;do;post", 1, ';', ';') if len(edits2) != 1 { t.Fatalf("expected one semicolon edit, got %#v", edits2) } diff --git a/internal/lsp/diagnostics_action_test.go b/internal/lsp/diagnostics_action_test.go index a607b86..761062d 100644 --- a/internal/lsp/diagnostics_action_test.go +++ b/internal/lsp/diagnostics_action_test.go @@ -9,6 +9,7 @@ import ( func TestHandleCodeAction_ListsDiagnosticsActionWhenOverlap(t *testing.T) { s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document)} + initServerDefaults(s) s.llmClient = fakeLLM{resp: "fixed"} uri := "file:///x.go" s.setDocument(uri, "package p\nvar a=1\n") diff --git a/internal/lsp/document_handlers_test.go b/internal/lsp/document_handlers_test.go index eae5020..1fdd0da 100644 --- a/internal/lsp/document_handlers_test.go +++ b/internal/lsp/document_handlers_test.go @@ -34,6 +34,7 @@ func TestDidOpenChangeClose_UpdateDocs(t *testing.T) { func TestClientShowDocument_WritesRequest(t *testing.T) { var out bytes.Buffer s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out} + initServerDefaults(s) uri := "file:///x.go" sel := Range{Start: Position{Line: 1}, End: Position{Line: 2}} out.Reset() @@ -47,6 +48,7 @@ func TestClientShowDocument_WritesRequest(t *testing.T) { func TestHandleExecuteCommand_ShowDocument(t *testing.T) { var out bytes.Buffer s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out} + initServerDefaults(s) uri := "file:///x.go" r := Range{Start: Position{Line: 0}, End: Position{Line: 0}} args := []any{uri, r} @@ -61,6 +63,7 @@ func TestHandleExecuteCommand_ShowDocument(t *testing.T) { func TestDeferShowDocument_WritesLater(t *testing.T) { var out bytes.Buffer s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out} + initServerDefaults(s) uri := "file:///x.go" out.Reset() s.deferShowDocument(uri, Range{Start: Position{Line: 0}, End: Position{Line: 0}}) diff --git a/internal/lsp/document_test.go b/internal/lsp/document_test.go index 652d867..cbea62a 100644 --- a/internal/lsp/document_test.go +++ b/internal/lsp/document_test.go @@ -10,12 +10,15 @@ import ( func newTestServer() *Server { s := &Server{ - logger: log.New(io.Discard, "", 0), - docs: make(map[string]*document), - inlineOpen: ">", - inlineClose: ">", - chatSuffix: ">", - chatPrefixes: []string{"?", "!", ":", ";"}, + logger: log.New(io.Discard, "", 0), + docs: make(map[string]*document), + inlineOpen: ">", + inlineClose: ">", + chatSuffix: ">", + chatPrefixes: []string{"?", "!", ":", ";"}, + inlineOpenChar: '>', + inlineCloseChar: '>', + chatSuffixChar: '>', } // Default prompt templates (mirror app defaults) s.promptCompSysParams = "You are a code completion engine for function signatures. Return only the parameter list contents (without parentheses), no braces, no prose. Prefer idiomatic names and types." @@ -34,14 +37,33 @@ func newTestServer() *Server { s.promptDocumentUser = "Add documentation comments to this code:\n{{selection}}" s.promptGoTestSystem = "You are a precise Go unit test generator. Given a Go function, write one or more Test* functions using the testing package. Do NOT include package or imports, only the test function(s). Prefer table-driven tests. Keep it minimal and idiomatic." s.promptGoTestUser = "Function under test:\n{{function}}" - // Keep package-level helpers in sync for tests using free functions - inlineOpenChar = '>' - inlineCloseChar = '>' - chatSuffixChar = '>' - chatPrefixSingles = []string{"?", "!", ":", ";"} return s } +func initServerDefaults(s *Server) { + if s.inlineOpen == "" { + s.inlineOpen = ">" + } + if s.inlineClose == "" { + s.inlineClose = ">" + } + if s.inlineOpenChar == 0 && s.inlineOpen != "" { + s.inlineOpenChar = s.inlineOpen[0] + } + if s.inlineCloseChar == 0 && s.inlineClose != "" { + s.inlineCloseChar = s.inlineClose[0] + } + if s.chatSuffix == "" { + s.chatSuffix = ">" + } + if s.chatSuffixChar == 0 && s.chatSuffix != "" { + s.chatSuffixChar = s.chatSuffix[0] + } + if len(s.chatPrefixes) == 0 { + s.chatPrefixes = []string{"?", "!", ":", ";"} + } +} + func TestSplitLines(t *testing.T) { in := "a\r\nb\nc" got := splitLines(in) diff --git a/internal/lsp/handlers.go b/internal/lsp/handlers.go index e85065b..9452551 100644 --- a/internal/lsp/handlers.go +++ b/internal/lsp/handlers.go @@ -25,10 +25,10 @@ func (s *Server) handle(req Request) { // Prefer |
