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/lsp | |
| parent | acc400768153a7bfda1413f15579c9455b877c87 (diff) | |
fix
Diffstat (limited to 'internal/lsp')
27 files changed, 270 insertions, 162 deletions
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) { // Preference order on each line: strict ;text; marker (no inner spaces), then // a line comment (//, #, --). Returns the instruction string and the selection // text cleaned of the matched instruction marker or comment. -func instructionFromSelection(sel string) (string, string) { +func (s *Server) instructionFromSelection(sel string) (string, string) { lines := splitLines(sel) for idx, line := range lines { - if instr, cleaned, ok := findFirstInstructionInLine(line); ok && strings.TrimSpace(instr) != "" { + if instr, cleaned, ok := s.findFirstInstructionInLine(line); ok && strings.TrimSpace(instr) != "" { lines[idx] = cleaned return instr, strings.Join(lines, "\n") } @@ -45,13 +45,13 @@ func instructionFromSelection(sel string) (string, string) { // - // text // - # text // - -- text -func findFirstInstructionInLine(line string) (instr string, cleaned string, ok bool) { +func (s *Server) findFirstInstructionInLine(line string) (instr string, cleaned string, ok bool) { type cand struct { start, end int text string } cands := []cand{} - if t, l, r, ok := findStrictInlineTag(line); ok { + if t, l, r, ok := findStrictInlineTag(line, s.inlineOpenChar, s.inlineCloseChar); ok { cands = append(cands, cand{start: l, end: r, text: t}) } if i := strings.Index(line, "/*"); i >= 0 { @@ -300,7 +300,7 @@ func (s *Server) isTriggerEvent(p CompletionParams, current string) bool { } // If configured and the line contains a bare double-open marker (e.g., '>>' with no '>>text>'), // do not treat as a trigger source. - if s.inlineOpen != "" && strings.Contains(current, s.inlineOpen+s.inlineOpen) && !hasDoubleOpenTrigger(current) { + if s.inlineOpen != "" && strings.Contains(current, s.inlineOpen+s.inlineOpen) && !hasDoubleOpenTrigger(current, s.inlineOpenChar, s.inlineCloseChar) { return false } // TriggerKind 1 = Invoked (manual). Always allow manual invoke. @@ -328,7 +328,7 @@ func (s *Server) isTriggerEvent(p CompletionParams, current string) bool { return false } // Bare double-open should not trigger via fallback char either (only when configured) - if s.inlineOpen != "" && strings.Contains(current, s.inlineOpen+s.inlineOpen) && !hasDoubleOpenTrigger(current) { + if s.inlineOpen != "" && strings.Contains(current, s.inlineOpen+s.inlineOpen) && !hasDoubleOpenTrigger(current, s.inlineOpenChar, s.inlineCloseChar) { return false } ch := string(current[idx-1]) diff --git a/internal/lsp/handlers_codeaction.go b/internal/lsp/handlers_codeaction.go index e5e61ef..8764525 100644 --- a/internal/lsp/handlers_codeaction.go +++ b/internal/lsp/handlers_codeaction.go @@ -122,7 +122,7 @@ func (s *Server) buildSimplifyCodeAction(p CodeActionParams, sel string) *CodeAc } func (s *Server) buildRewriteCodeAction(p CodeActionParams, sel string) *CodeAction { - if instr, cleaned := instructionFromSelection(sel); strings.TrimSpace(instr) != "" { + if instr, cleaned := s.instructionFromSelection(sel); strings.TrimSpace(instr) != "" { payload := struct { Type string `json:"type"` URI string `json:"uri"` diff --git a/internal/lsp/handlers_completion.go b/internal/lsp/handlers_completion.go index 6142a30..df541cc 100644 --- a/internal/lsp/handlers_completion.go +++ b/internal/lsp/handlers_completion.go @@ -13,6 +13,21 @@ import ( "codeberg.org/snonux/hexai/internal/stats" ) +type completionPlan struct { + params CompletionParams + above string + current string + below string + funcCtx string + docStr string + hasExtra bool + extraText string + inlinePrompt bool + inParams bool + manualInvoke bool + cacheKey string +} + func (s *Server) handleCompletion(req Request) { var p CompletionParams var docStr string @@ -75,44 +90,59 @@ func (s *Server) tryLLMCompletion(p CompletionParams, above, current, below, fun ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) defer cancel() - inlinePrompt := lineHasInlinePrompt(current) - if !inlinePrompt && !s.isTriggerEvent(p, current) { - logging.Logf("lsp ", "%scompletion skip=no-trigger line=%d char=%d current=%q%s", logging.AnsiYellow, p.Position.Line, p.Position.Character, trimLen(current), logging.AnsiBase) - return []CompletionItem{}, true + plan, items, handled := s.prepareCompletionPlan(p, above, current, below, funcCtx, docStr, hasExtra, extraText) + if handled { + return items, true } - if s.shouldSuppressForChatTriggerEOL(current, p) { - return []CompletionItem{}, true + + if items, ok := s.tryProviderNativeCompletion(current, p, above, below, funcCtx, docStr, hasExtra, extraText, plan.inParams); ok { + return items, true } - inParams := inParamList(current, p.Position.Character) - manualInvoke := parseManualInvoke(p.Context) + return s.executeChatCompletion(ctx, plan) +} - // Cache fast-path - key := s.completionCacheKey(p, above, current, below, funcCtx, inParams, hasExtra, extraText) - if cleaned, ok := s.completionCacheGet(key); ok && strings.TrimSpace(cleaned) != "" { +func (s *Server) prepareCompletionPlan(p CompletionParams, above, current, below, funcCtx, docStr string, hasExtra bool, extraText string) (completionPlan, []CompletionItem, bool) { + plan := completionPlan{ + params: p, + above: above, + current: current, + below: below, + funcCtx: funcCtx, + docStr: docStr, + hasExtra: hasExtra, + extraText: extraText, + } + plan.inlinePrompt = lineHasInlinePrompt(current, s.inlineOpenChar, s.inlineCloseChar) + if !plan.inlinePrompt && !s.isTriggerEvent(p, current) { + logging.Logf("lsp ", "%scompletion skip=no-trigger line=%d char=%d current=%q%s", logging.AnsiYellow, p.Position.Line, p.Position.Character, trimLen(current), logging.AnsiBase) + return plan, []CompletionItem{}, true + } + if s.shouldSuppressForChatTriggerEOL(current, p) { + return plan, []CompletionItem{}, true + } + plan.inParams = inParamList(current, p.Position.Character) + plan.manualInvoke = parseManualInvoke(p.Context) + plan.cacheKey = s.completionCacheKey(p, above, current, below, funcCtx, plan.inParams, hasExtra, extraText) + if cleaned, ok := s.completionCacheGet(plan.cacheKey); ok && strings.TrimSpace(cleaned) != "" { logging.Logf("lsp ", "completion cache hit uri=%s line=%d char=%d preview=%s%s%s", p.TextDocument.URI, p.Position.Line, p.Position.Character, logging.AnsiGreen, logging.PreviewForLog(cleaned), logging.AnsiBase) - return s.makeCompletionItems(cleaned, inParams, current, p, docStr), true + return plan, s.makeCompletionItems(cleaned, plan.inParams, current, p, docStr), true } - if isBareDoubleOpen(current) || isBareDoubleOpen(below) { + if isBareDoubleOpen(current, s.inlineOpenChar, s.inlineCloseChar) || isBareDoubleOpen(below, s.inlineOpenChar, s.inlineCloseChar) { logging.Logf("lsp ", "%scompletion skip=empty-double-semicolon line=%d char=%d current=%q%s", logging.AnsiYellow, p.Position.Line, p.Position.Character, trimLen(current), logging.AnsiBase) - return []CompletionItem{}, true + return plan, []CompletionItem{}, true } - - if !inParams && !s.prefixHeuristicAllows(inlinePrompt, current, p, manualInvoke) { + if !plan.inParams && !s.prefixHeuristicAllows(plan.inlinePrompt, current, p, plan.manualInvoke) { logging.Logf("lsp ", "%scompletion skip=short-prefix line=%d char=%d current=%q%s", logging.AnsiYellow, p.Position.Line, p.Position.Character, trimLen(current), logging.AnsiBase) - return []CompletionItem{}, true - } - - // Provider-native path - if items, ok := s.tryProviderNativeCompletion(current, p, above, below, funcCtx, docStr, hasExtra, extraText, inParams); ok { - return items, true + return plan, []CompletionItem{}, true } + return plan, nil, false +} - // Chat path - messages := s.buildCompletionMessages(inlinePrompt, hasExtra, extraText, inParams, p, above, current, below, funcCtx) - // Counters and options +func (s *Server) executeChatCompletion(ctx context.Context, plan completionPlan) ([]CompletionItem, bool) { + messages := s.buildCompletionMessages(plan.inlinePrompt, plan.hasExtra, plan.extraText, plan.inParams, plan.params, plan.above, plan.current, plan.below, plan.funcCtx) sentSize := 0 for _, m := range messages { sentSize += len(m.Content) @@ -122,13 +152,14 @@ func (s *Server) tryLLMCompletion(p CompletionParams, above, current, below, fun if s.codingTemperature != nil { opts = append(opts, llm.WithTemperature(*s.codingTemperature)) } - // Debounce and throttle before making the LLM call s.waitForDebounce(ctx) if !s.waitForThrottle(ctx) { return nil, false } + if s.llmClient == nil { + return nil, false + } logging.Logf("lsp ", "completion llm=requesting model=%s", s.llmClient.DefaultModel()) - text, err := s.llmClient.Chat(ctx, messages, opts...) if err != nil { logging.Logf("lsp ", "llm completion error: %v", err) @@ -137,13 +168,14 @@ func (s *Server) tryLLMCompletion(p CompletionParams, above, current, below, fun } s.incRecvCounters(len(text)) s.logLLMStats() - - cleaned := s.postProcessCompletion(strings.TrimSpace(text), current[:p.Position.Character], current) + trimmed := strings.TrimSpace(text) + cleaned := s.postProcessCompletion(trimmed, plan.current[:plan.params.Position.Character], plan.current) if cleaned == "" { return nil, false } - s.completionCachePut(key, cleaned) - return s.makeCompletionItems(cleaned, inParams, current, p, docStr), true + s.completionCachePut(plan.cacheKey, cleaned) + items := s.makeCompletionItems(cleaned, plan.inParams, plan.current, plan.params, plan.docStr) + return items, true } // parseManualInvoke inspects the LSP completion context and reports whether the user manually invoked completion. @@ -269,7 +301,7 @@ func (s *Server) tryProviderNativeCompletion(current string, p CompletionParams, if cleaned != "" { cleaned = stripDuplicateGeneralPrefix(current[:p.Position.Character], cleaned) } - if cleaned != "" && hasDoubleOpenTrigger(current) { + if cleaned != "" && hasDoubleOpenTrigger(current, s.inlineOpenChar, s.inlineCloseChar) { indent := leadingIndent(current) if indent != "" { cleaned = applyIndent(indent, cleaned) @@ -398,7 +430,7 @@ func (s *Server) postProcessCompletion(text string, leftOfCursor string, current if cleaned != "" { cleaned = stripDuplicateGeneralPrefix(leftOfCursor, cleaned) } - if cleaned != "" && hasDoubleOpenTrigger(currentLine) { + if cleaned != "" && hasDoubleOpenTrigger(currentLine, s.inlineOpenChar, s.inlineCloseChar) { if indent := leadingIndent(currentLine); indent != "" { cleaned = applyIndent(indent, cleaned) } diff --git a/internal/lsp/handlers_document.go b/internal/lsp/handlers_document.go index 3897885..ca0cb8d 100644 --- a/internal/lsp/handlers_document.go +++ b/internal/lsp/handlers_document.go @@ -11,13 +11,6 @@ import ( "codeberg.org/snonux/hexai/internal/logging" ) -// Package-level chat trigger vars for helpers without Server receiver. -// NewServer assigns these from configuration on startup. -var ( - chatSuffixChar byte = '>' - chatPrefixSingles = []string{"?", "!", ":", ";"} -) - func (s *Server) handleDidOpen(req Request) { var p DidOpenTextDocumentParams if err := json.Unmarshal(req.Params, &p); err == nil { @@ -236,7 +229,7 @@ func (s *Server) buildChatHistory(uri string, lineIdx int, currentPrompt string) break } q := strings.TrimSpace(d.lines[i]) - q = stripTrailingTrigger(q) + q = s.stripTrailingTrigger(q) pairs = append([]pair{{q: q, a: strings.Join(replyLines, "\n")}}, pairs...) i-- } @@ -254,25 +247,23 @@ func (s *Server) buildChatHistory(uri string, lineIdx int, currentPrompt string) } // stripTrailingTrigger removes the trailing chat trigger punctuation from a line if present. -func stripTrailingTrigger(sx string) string { - s := strings.TrimRight(sx, " \t") - if len(s) == 0 { +func (s *Server) stripTrailingTrigger(sx string) string { + trim := strings.TrimRight(sx, " \t") + if len(trim) == 0 { return sx } - // Configurable suffix removal when preceded by configured prefixes - if len(s) >= 2 && s[len(s)-1] == chatSuffixChar { - prev := string(s[len(s)-2]) - for _, pf := range chatPrefixSingles { + if len(trim) >= 2 && s.chatSuffixChar != 0 && trim[len(trim)-1] == s.chatSuffixChar { + prev := string(trim[len(trim)-2]) + for _, pf := range s.chatPrefixes { if prev == pf { - return strings.TrimRight(s[:len(s)-1], " \t") + return strings.TrimRight(trim[:len(trim)-1], " \t") } } } - // Legacy: remove one trailing punctuation (?, !, :) to build history nicely - last := s[len(s)-1] + last := trim[len(trim)-1] switch last { case '?', '!', ':': - return strings.TrimRight(s[:len(s)-1], " \t") + return strings.TrimRight(trim[:len(trim)-1], " \t") default: return sx } diff --git a/internal/lsp/handlers_end_to_end_test.go b/internal/lsp/handlers_end_to_end_test.go index 32cb488..5489b97 100644 --- a/internal/lsp/handlers_end_to_end_test.go +++ b/internal/lsp/handlers_end_to_end_test.go @@ -73,6 +73,7 @@ func TestHandleCodeAction_ListsHexaiActions(t *testing.T) { // Prepare server var out bytes.Buffer s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out} + initServerDefaults(s) s.chatSuffix = ">" s.chatPrefixes = []string{"?", "!", ":", ";"} s.llmClient = fakeLLM{resp: "// doc\nfunc add(a,b int) int { return a+b }"} @@ -121,6 +122,7 @@ func TestHandleCodeAction_ListsHexaiActions(t *testing.T) { func TestHandleCodeActionResolve_Document(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: "// doc\nfunc f(){}"} uri := "file:///x.go" s.setDocument(uri, "package p\nfunc f(){}\n") @@ -152,6 +154,7 @@ func TestHandleCodeActionResolve_Document(t *testing.T) { func TestHandleCodeAction_NoLLMOrEmptySelection_ReturnsEmpty(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" s.setDocument(uri, "package p\n\n") // Empty sele |
