xonecas.io
62159
Sy

symb / commit e3247e8

feat: basic git support

xonecas2026-02-13 e3247e8b0b94087c428a18fd629337dd8c3753d8 parent e6ec92f

11 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

cmd/symb/main.go+7−0
@@ -123,6 +123,13 @@ func main() {
123123 defer webCache.Close()
124124 }
125125
126+ // Register git tools
127+ gitStatusTool := mcp_tools.NewGitStatusTool()
128+ proxy.RegisterTool(gitStatusTool, mcp_tools.MakeGitStatusHandler())
129+
130+ gitDiffTool := mcp_tools.NewGitDiffTool()
131+ proxy.RegisterTool(gitDiffTool, mcp_tools.MakeGitDiffHandler())
132+
126133 // Register web tools
127134 webFetchTool := mcp_tools.NewWebFetchTool()
128135 webFetchHandler := mcp_tools.MakeWebFetchHandler(webCache)
docs/DESIGN.md+3−3
@@ -76,14 +76,14 @@ Retry-After parsing.
7676 matching, binary detection, 10MB size limit.
7777 - `internal/config` — TOML config, JSON credentials, env overrides.
7878
79-## Features waiting implementation for current version:
80-
8179 ### Git Integration
8280
8381 - git **read** tools for the LLM: diff, status
8482 - Editor displays diffs with syntax hl
8583 - git markers in the number column for editted files in the editor
8684
85+## Features waiting implementation for current version:
86+
8787 ### LSP Integration
8888
8989 - Start with diagnostics (show errors/warnings in the number line, a error line has a red color number, warnings yellow).
@@ -98,7 +98,7 @@ symbols/scope to LLM as auto-context instead of whole files.
9898
9999 Separate OpenForUser into Read and Show. Read sends the output to the llm, Show sends it to the editor after read. Update hover iteraction on tool responses for ux. Ui improvements.
100100
101-- Open (or as it's called internally open for user): Change to Read, shows the read output to the llm. User can click to see if he wants, no automatic loading it to the editor.
101+- Open (or as it's called internally open for user): Change to Read, shows the read output to the llm. User can click to see if he wants, no automatic loading it to the editor. Includes the current diff and lsp information for the file on read.
102102 - Show, new tool: Open and send to the editor.
103103 - All tools: don't auto update the editor (Show excluded).
104104 - mousing over a tool reply apllies a background to show it's clickable.
internal/mcp_tools/git.go+166−0
@@ -0,0 +1,166 @@
1+package mcp_tools
2+
3+import (
4+ "bytes"
5+ "context"
6+ "encoding/json"
7+ "fmt"
8+ "os/exec"
9+ "strings"
10+
11+ "github.com/xonecas/symb/internal/mcp"
12+)
13+
14+// GitStatusArgs represents arguments for the GitStatus tool.
15+type GitStatusArgs struct {
16+ Long bool `json:"long,omitempty"` // Use long format (default: false, short format)
17+}
18+
19+// GitDiffArgs represents arguments for the GitDiff tool.
20+type GitDiffArgs struct {
21+ File string `json:"file,omitempty"` // Optional: specific file to diff
22+ Staged bool `json:"staged,omitempty"` // Diff staged changes instead of unstaged
23+}
24+
25+// NewGitStatusTool creates the GitStatus tool definition.
26+func NewGitStatusTool() mcp.Tool {
27+ schema := map[string]interface{}{
28+ "type": "object",
29+ "properties": map[string]interface{}{
30+ "long": map[string]interface{}{
31+ "type": "boolean",
32+ "description": "Use long format output. Default: false (short format)",
33+ },
34+ },
35+ }
36+
37+ schemaJSON, _ := json.Marshal(schema)
38+
39+ return mcp.Tool{
40+ Name: "GitStatus",
41+ Description: "Show the working tree status. Returns modified, staged, and untracked files.",
42+ InputSchema: schemaJSON,
43+ }
44+}
45+
46+// NewGitDiffTool creates the GitDiff tool definition.
47+func NewGitDiffTool() mcp.Tool {
48+ schema := map[string]interface{}{
49+ "type": "object",
50+ "properties": map[string]interface{}{
51+ "file": map[string]interface{}{
52+ "type": "string",
53+ "description": "Optional: specific file path to diff. If omitted, diffs all changed files.",
54+ },
55+ "staged": map[string]interface{}{
56+ "type": "boolean",
57+ "description": "If true, show staged (cached) changes. Default: false (unstaged changes)",
58+ },
59+ },
60+ }
61+
62+ schemaJSON, _ := json.Marshal(schema)
63+
64+ return mcp.Tool{
65+ Name: "GitDiff",
66+ Description: "Show changes between working tree and index (unstaged), or between index and HEAD (staged). Returns unified diff output.",
67+ InputSchema: schemaJSON,
68+ }
69+}
70+
71+// runGit executes a git command and returns stdout, or a ToolResult error.
72+func runGit(ctx context.Context, args ...string) (string, *mcp.ToolResult) {
73+ cmd := exec.CommandContext(ctx, "git", args...)
74+ var stdout, stderr bytes.Buffer
75+ cmd.Stdout = &stdout
76+ cmd.Stderr = &stderr
77+
78+ if err := cmd.Run(); err != nil {
79+ // git diff returns exit code 1 when there are differences — that's not an error.
80+ if cmd.ProcessState != nil && cmd.ProcessState.ExitCode() == 1 && stderr.Len() == 0 {
81+ return stdout.String(), nil
82+ }
83+ msg := strings.TrimSpace(stderr.String())
84+ if msg == "" {
85+ msg = err.Error()
86+ }
87+ return "", &mcp.ToolResult{
88+ Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("git error: %s", msg)}},
89+ IsError: true,
90+ }
91+ }
92+ return stdout.String(), nil
93+}
94+
95+// MakeGitStatusHandler creates a handler for the GitStatus tool.
96+func MakeGitStatusHandler() mcp.ToolHandler {
97+ return func(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
98+ var args GitStatusArgs
99+ if len(arguments) > 0 {
100+ if err := json.Unmarshal(arguments, &args); err != nil {
101+ return &mcp.ToolResult{
102+ Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid arguments: %v", err)}},
103+ IsError: true,
104+ }, nil
105+ }
106+ }
107+
108+ gitArgs := []string{"status"}
109+ if !args.Long {
110+ gitArgs = append(gitArgs, "--short")
111+ }
112+
113+ out, errResult := runGit(ctx, gitArgs...)
114+ if errResult != nil {
115+ return errResult, nil
116+ }
117+
118+ if strings.TrimSpace(out) == "" {
119+ out = "nothing to commit, working tree clean"
120+ }
121+
122+ return &mcp.ToolResult{
123+ Content: []mcp.ContentBlock{{Type: "text", Text: out}},
124+ }, nil
125+ }
126+}
127+
128+// MakeGitDiffHandler creates a handler for the GitDiff tool.
129+func MakeGitDiffHandler() mcp.ToolHandler {
130+ return func(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
131+ var args GitDiffArgs
132+ if len(arguments) > 0 {
133+ if err := json.Unmarshal(arguments, &args); err != nil {
134+ return &mcp.ToolResult{
135+ Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid arguments: %v", err)}},
136+ IsError: true,
137+ }, nil
138+ }
139+ }
140+
141+ gitArgs := []string{"diff"}
142+ if args.Staged {
143+ gitArgs = append(gitArgs, "--cached")
144+ }
145+ if args.File != "" {
146+ gitArgs = append(gitArgs, "--", args.File)
147+ }
148+
149+ out, errResult := runGit(ctx, gitArgs...)
150+ if errResult != nil {
151+ return errResult, nil
152+ }
153+
154+ if strings.TrimSpace(out) == "" {
155+ label := "unstaged"
156+ if args.Staged {
157+ label = "staged"
158+ }
159+ out = fmt.Sprintf("no %s changes", label)
160+ }
161+
162+ return &mcp.ToolResult{
163+ Content: []mcp.ContentBlock{{Type: "text", Text: out}},
164+ }, nil
165+ }
166+}
internal/mcp_tools/git_test.go+394−0
@@ -0,0 +1,394 @@
1+package mcp_tools
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "os"
7+ "os/exec"
8+ "path/filepath"
9+ "strings"
10+ "testing"
11+
12+ "github.com/xonecas/symb/internal/mcp"
13+ "github.com/xonecas/symb/internal/tui/editor"
14+)
15+
16+// setupGitRepo creates a temp dir with an initialised git repo and returns
17+// the path along with a cleanup func that restores the original working dir.
18+func setupGitRepo(t *testing.T) (string, func()) {
19+ t.Helper()
20+
21+ dir := t.TempDir()
22+ origDir, _ := os.Getwd()
23+
24+ if err := os.Chdir(dir); err != nil {
25+ t.Fatalf("chdir: %v", err)
26+ }
27+
28+ // Initialise a git repo with a first commit so HEAD exists.
29+ for _, cmd := range [][]string{
30+ {"git", "init"},
31+ {"git", "config", "user.email", "test@test.com"},
32+ {"git", "config", "user.name", "Test"},
33+ } {
34+ c := exec.Command(cmd[0], cmd[1:]...)
35+ c.Dir = dir
36+ if out, err := c.CombinedOutput(); err != nil {
37+ t.Fatalf("setup %v: %s – %v", cmd, out, err)
38+ }
39+ }
40+
41+ // Create an initial commit so we have HEAD.
42+ initial := filepath.Join(dir, "init.txt")
43+ if err := os.WriteFile(initial, []byte("init\n"), 0644); err != nil {
44+ t.Fatal(err)
45+ }
46+ for _, cmd := range [][]string{
47+ {"git", "add", "."},
48+ {"git", "commit", "-m", "initial"},
49+ } {
50+ c := exec.Command(cmd[0], cmd[1:]...)
51+ c.Dir = dir
52+ if out, err := c.CombinedOutput(); err != nil {
53+ t.Fatalf("setup %v: %s – %v", cmd, out, err)
54+ }
55+ }
56+
57+ return dir, func() { os.Chdir(origDir) } //nolint:errcheck
58+}
59+
60+func callHandler(t *testing.T, handler func(context.Context, json.RawMessage) (*mcp.ToolResult, error), args interface{}) (string, bool) {
61+ t.Helper()
62+ raw, err := json.Marshal(args)
63+ if err != nil {
64+ t.Fatalf("marshal: %v", err)
65+ }
66+ result, err := handler(context.Background(), raw)
67+ if err != nil {
68+ t.Fatalf("handler error: %v", err)
69+ }
70+ text := ""
71+ if len(result.Content) > 0 {
72+ text = result.Content[0].Text
73+ }
74+ return text, result.IsError
75+}
76+
77+// ---------------------------------------------------------------------------
78+// GitStatus tests
79+// ---------------------------------------------------------------------------
80+
81+func TestGitStatusClean(t *testing.T) {
82+ _, cleanup := setupGitRepo(t)
83+ defer cleanup()
84+
85+ handler := MakeGitStatusHandler()
86+ text, isErr := callHandler(t, handler, GitStatusArgs{})
87+ if isErr {
88+ t.Fatalf("unexpected error: %s", text)
89+ }
90+ if !strings.Contains(text, "clean") {
91+ t.Errorf("expected clean status, got: %s", text)
92+ }
93+}
94+
95+func TestGitStatusWithChanges(t *testing.T) {
96+ dir, cleanup := setupGitRepo(t)
97+ defer cleanup()
98+
99+ // Create an untracked file.
100+ if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("hello\n"), 0644); err != nil {
101+ t.Fatal(err)
102+ }
103+
104+ handler := MakeGitStatusHandler()
105+ text, isErr := callHandler(t, handler, GitStatusArgs{})
106+ if isErr {
107+ t.Fatalf("unexpected error: %s", text)
108+ }
109+ if !strings.Contains(text, "new.txt") {
110+ t.Errorf("expected new.txt in status, got: %s", text)
111+ }
112+}
113+
114+func TestGitStatusLongFormat(t *testing.T) {
115+ _, cleanup := setupGitRepo(t)
116+ defer cleanup()
117+
118+ handler := MakeGitStatusHandler()
119+ // long=true → long format which contains "On branch"
120+ text, isErr := callHandler(t, handler, GitStatusArgs{Long: true})
121+ if isErr {
122+ t.Fatalf("unexpected error: %s", text)
123+ }
124+ // Long format includes "On branch" header.
125+ if !strings.Contains(text, "On branch") {
126+ t.Errorf("expected long format, got: %s", text)
127+ }
128+}
129+
130+// ---------------------------------------------------------------------------
131+// GitDiff tests
132+// ---------------------------------------------------------------------------
133+
134+func TestGitDiffNoChanges(t *testing.T) {
135+ _, cleanup := setupGitRepo(t)
136+ defer cleanup()
137+
138+ handler := MakeGitDiffHandler()
139+ text, isErr := callHandler(t, handler, GitDiffArgs{})
140+ if isErr {
141+ t.Fatalf("unexpected error: %s", text)
142+ }
143+ if !strings.Contains(text, "no unstaged changes") {
144+ t.Errorf("expected no changes message, got: %s", text)
145+ }
146+}
147+
148+func TestGitDiffUnstaged(t *testing.T) {
149+ dir, cleanup := setupGitRepo(t)
150+ defer cleanup()
151+
152+ // Modify the tracked file.
153+ if err := os.WriteFile(filepath.Join(dir, "init.txt"), []byte("modified\n"), 0644); err != nil {
154+ t.Fatal(err)
155+ }
156+
157+ handler := MakeGitDiffHandler()
158+ text, isErr := callHandler(t, handler, GitDiffArgs{})
159+ if isErr {
160+ t.Fatalf("unexpected error: %s", text)
161+ }
162+ if !strings.Contains(text, "diff") {
163+ t.Errorf("expected diff output, got: %s", text)
164+ }
165+ if !strings.Contains(text, "modified") {
166+ t.Errorf("expected 'modified' in diff, got: %s", text)
167+ }
168+}
169+
170+func TestGitDiffStaged(t *testing.T) {
171+ dir, cleanup := setupGitRepo(t)
172+ defer cleanup()
173+
174+ // Modify and stage.
175+ if err := os.WriteFile(filepath.Join(dir, "init.txt"), []byte("staged change\n"), 0644); err != nil {
176+ t.Fatal(err)
177+ }
178+ cmd := exec.Command("git", "add", "init.txt")
179+ cmd.Dir = dir
180+ if out, err := cmd.CombinedOutput(); err != nil {
181+ t.Fatalf("git add: %s – %v", out, err)
182+ }
183+
184+ handler := MakeGitDiffHandler()
185+ text, isErr := callHandler(t, handler, GitDiffArgs{Staged: true})
186+ if isErr {
187+ t.Fatalf("unexpected error: %s", text)
188+ }
189+ if !strings.Contains(text, "staged change") {
190+ t.Errorf("expected staged diff, got: %s", text)
191+ }
192+}
193+
194+func TestGitDiffSpecificFile(t *testing.T) {
195+ dir, cleanup := setupGitRepo(t)
196+ defer cleanup()
197+
198+ // Create and commit a second file, then modify both.
199+ second := filepath.Join(dir, "second.txt")
200+ if err := os.WriteFile(second, []byte("original\n"), 0644); err != nil {
201+ t.Fatal(err)
202+ }
203+ for _, c := range [][]string{
204+ {"git", "add", "second.txt"},
205+ {"git", "commit", "-m", "add second"},
206+ } {
207+ cmd := exec.Command(c[0], c[1:]...)
208+ cmd.Dir = dir
209+ if out, err := cmd.CombinedOutput(); err != nil {
210+ t.Fatalf("%v: %s – %v", c, out, err)
211+ }
212+ }
213+
214+ // Modify both files.
215+ os.WriteFile(filepath.Join(dir, "init.txt"), []byte("changed init\n"), 0644)
216+ os.WriteFile(second, []byte("changed second\n"), 0644)
217+
218+ handler := MakeGitDiffHandler()
219+
220+ // Diff only second.txt.
221+ text, isErr := callHandler(t, handler, GitDiffArgs{File: "second.txt"})
222+ if isErr {
223+ t.Fatalf("unexpected error: %s", text)
224+ }
225+ if !strings.Contains(text, "changed second") {
226+ t.Errorf("expected second.txt diff, got: %s", text)
227+ }
228+ if strings.Contains(text, "changed init") {
229+ t.Error("should not contain init.txt changes")
230+ }
231+}
232+
233+func TestGitDiffNoStagedChanges(t *testing.T) {
234+ _, cleanup := setupGitRepo(t)
235+ defer cleanup()
236+
237+ handler := MakeGitDiffHandler()
238+ text, isErr := callHandler(t, handler, GitDiffArgs{Staged: true})
239+ if isErr {
240+ t.Fatalf("unexpected error: %s", text)
241+ }
242+ if !strings.Contains(text, "no staged changes") {
243+ t.Errorf("expected no staged changes message, got: %s", text)
244+ }
245+}
246+
247+// ---------------------------------------------------------------------------
248+// runGit edge cases
249+// ---------------------------------------------------------------------------
250+
251+func TestRunGitNotARepo(t *testing.T) {
252+ dir := t.TempDir()
253+ origDir, _ := os.Getwd()
254+ defer os.Chdir(origDir) //nolint:errcheck
255+ os.Chdir(dir) //nolint:errcheck
256+
257+ handler := MakeGitStatusHandler()
258+ text, isErr := callHandler(t, handler, GitStatusArgs{})
259+ if !isErr {
260+ t.Errorf("expected error outside git repo, got: %s", text)
261+ }
262+ if !strings.Contains(text, "git error") {
263+ t.Errorf("expected git error message, got: %s", text)
264+ }
265+}
266+
267+// ---------------------------------------------------------------------------
268+// ParseDiffMarkers tests
269+// ---------------------------------------------------------------------------
270+
271+func TestParseDiffMarkersEmpty(t *testing.T) {
272+ m := ParseDiffMarkers("")
273+ if m != nil {
274+ t.Errorf("expected nil for empty diff, got %v", m)
275+ }
276+}
277+
278+func TestParseDiffMarkersAdd(t *testing.T) {
279+ // Pure addition: 3 new lines starting at line 5.
280+ diff := `diff --git a/file.go b/file.go
281+--- a/file.go
282++++ b/file.go
283+@@ -4,0 +5,3 @@ func foo() {
284++line1
285++line2
286++line3
287+`
288+ m := ParseDiffMarkers(diff)
289+ if len(m) != 3 {
290+ t.Fatalf("expected 3 markers, got %d: %v", len(m), m)
291+ }
292+ for _, row := range []int{4, 5, 6} { // 0-indexed
293+ if m[row] != editor.GutterAdd {
294+ t.Errorf("row %d: expected GutterAdd, got %v", row, m[row])
295+ }
296+ }
297+}
298+
299+func TestParseDiffMarkersDelete(t *testing.T) {
300+ // Pure deletion: 2 old lines removed, new file continues at line 10.
301+ diff := `diff --git a/file.go b/file.go
302+--- a/file.go
303++++ b/file.go
304+@@ -8,2 +10,0 @@ func bar() {
305+-old1
306+-old2
307+`
308+ m := ParseDiffMarkers(diff)
309+ if len(m) != 1 {
310+ t.Fatalf("expected 1 marker, got %d: %v", len(m), m)
311+ }
312+ // newStart=10, newCount=0 → mark row 10-1=9 (0-indexed)
313+ if m[9] != editor.GutterDelete {
314+ t.Errorf("row 9: expected GutterDelete, got %v", m[9])
315+ }
316+}
317+
318+func TestParseDiffMarkersChange(t *testing.T) {
319+ // Modification: 2 old lines replaced by 3 new lines starting at line 7.
320+ diff := `diff --git a/file.go b/file.go
321+--- a/file.go
322++++ b/file.go
323+@@ -7,2 +7,3 @@ func baz() {
324+-old
325+-old2
326++new1
327++new2
328++new3
329+`
330+ m := ParseDiffMarkers(diff)
331+ if len(m) != 3 {
332+ t.Fatalf("expected 3 markers, got %d: %v", len(m), m)
333+ }
334+ for _, row := range []int{6, 7, 8} { // 0-indexed
335+ if m[row] != editor.GutterChange {
336+ t.Errorf("row %d: expected GutterChange, got %v", row, m[row])
337+ }
338+ }
339+}
340+
341+func TestParseDiffMarkersMultipleHunks(t *testing.T) {
342+ diff := `diff --git a/file.go b/file.go
343+--- a/file.go
344++++ b/file.go
345+@@ -1,0 +2,1 @@
346++added
347+@@ -10,1 +12,1 @@
348+-old
349++changed
350+`
351+ m := ParseDiffMarkers(diff)
352+ if len(m) != 2 {
353+ t.Fatalf("expected 2 markers, got %d: %v", len(m), m)
354+ }
355+ if m[1] != editor.GutterAdd { // line 2, 0-indexed = 1
356+ t.Errorf("row 1: expected GutterAdd, got %v", m[1])
357+ }
358+ if m[11] != editor.GutterChange { // line 12, 0-indexed = 11
359+ t.Errorf("row 11: expected GutterChange, got %v", m[11])
360+ }
361+}
362+
363+func TestParseDiffMarkersSingleLineNoComma(t *testing.T) {
364+ // When count is 1, git omits the comma: @@ -5 +5 @@
365+ diff := `@@ -5 +5 @@
366+-old
367++new
368+`
369+ m := ParseDiffMarkers(diff)
370+ if len(m) != 1 {
371+ t.Fatalf("expected 1 marker, got %d: %v", len(m), m)
372+ }
373+ if m[4] != editor.GutterChange { // line 5, 0-indexed = 4
374+ t.Errorf("row 4: expected GutterChange, got %v", m[4])
375+ }
376+}
377+
378+func TestGitFileMarkersIntegration(t *testing.T) {
379+ dir, cleanup := setupGitRepo(t)
380+ defer cleanup()
381+
382+ // Modify the tracked file.
383+ if err := os.WriteFile(filepath.Join(dir, "init.txt"), []byte("changed\n"), 0644); err != nil {
384+ t.Fatal(err)
385+ }
386+
387+ m := GitFileMarkers(context.Background(), "init.txt")
388+ if m == nil {
389+ t.Fatal("expected markers for modified file, got nil")
390+ }
391+ if _, ok := m[0]; !ok {
392+ t.Errorf("expected marker on row 0, got %v", m)
393+ }
394+}
internal/mcp_tools/gitdiff.go+111−0
@@ -0,0 +1,111 @@
1+package mcp_tools
2+
3+import (
4+ "bytes"
5+ "context"
6+ "os/exec"
7+ "strconv"
8+ "strings"
9+
10+ "github.com/xonecas/symb/internal/tui/editor"
11+)
12+
13+// GitFileMarkers runs `git diff` for the given file path and returns
14+// gutter markers keyed by 0-indexed line number.
15+// Returns nil (not error) when outside a git repo or on a new/untracked file.
16+func GitFileMarkers(ctx context.Context, filePath string) map[int]editor.GutterMark {
17+ cmd := exec.CommandContext(ctx, "git", "diff", "--unified=0", "--", filePath)
18+ var stdout bytes.Buffer
19+ cmd.Stdout = &stdout
20+ // Ignore errors — not-a-repo or untracked files just return nil.
21+ _ = cmd.Run()
22+
23+ return ParseDiffMarkers(stdout.String())
24+}
25+
26+// ParseDiffMarkers parses unified diff output (--unified=0) and returns
27+// gutter markers keyed by 0-indexed line number in the new file.
28+func ParseDiffMarkers(diff string) map[int]editor.GutterMark {
29+ if strings.TrimSpace(diff) == "" {
30+ return nil
31+ }
32+
33+ markers := make(map[int]editor.GutterMark)
34+
35+ for _, line := range strings.Split(diff, "\n") {
36+ if !strings.HasPrefix(line, "@@ ") {
37+ continue
38+ }
39+
40+ // Parse hunk header: @@ -oldStart[,oldCount] +newStart[,newCount] @@
41+ newStart, newCount, oldCount, ok := parseHunkHeader(line)
42+ if !ok {
43+ continue
44+ }
45+
46+ if newCount == 0 {
47+ // Pure deletion: no new lines, mark the line before as delete.
48+ // newStart points to the line after the deletion.
49+ row := newStart - 1 // convert to 0-indexed
50+ if row < 0 {
51+ row = 0
52+ }
53+ markers[row] = editor.GutterDelete
54+ } else if oldCount == 0 {
55+ // Pure addition.
56+ for i := 0; i < newCount; i++ {
57+ markers[newStart-1+i] = editor.GutterAdd
58+ }
59+ } else {
60+ // Modification (some old lines replaced by some new lines).
61+ for i := 0; i < newCount; i++ {
62+ markers[newStart-1+i] = editor.GutterChange
63+ }
64+ }
65+ }
66+
67+ if len(markers) == 0 {
68+ return nil
69+ }
70+ return markers
71+}
72+
73+// parseHunkHeader extracts newStart, newCount, oldCount from a @@ line.
74+// Format: @@ -oldStart[,oldCount] +newStart[,newCount] @@
75+func parseHunkHeader(line string) (newStart, newCount, oldCount int, ok bool) {
76+ // Strip leading "@@ " and trailing " @@..."
77+ idx := strings.Index(line[3:], " @@")
78+ if idx < 0 {
79+ return 0, 0, 0, false
80+ }
81+ header := line[3 : 3+idx] // e.g. "-10,3 +12,5"
82+
83+ parts := strings.Fields(header)
84+ if len(parts) != 2 {
85+ return 0, 0, 0, false
86+ }
87+
88+ // Parse old range.
89+ old := strings.TrimPrefix(parts[0], "-")
90+ _, oldCount = parseRange(old)
91+
92+ // Parse new range.
93+ neu := strings.TrimPrefix(parts[1], "+")
94+ newStart, newCount = parseRange(neu)
95+
96+ if newStart == 0 {
97+ return 0, 0, 0, false
98+ }
99+ return newStart, newCount, oldCount, true
100+}
101+
102+// parseRange parses "start,count" or "start" (count defaults to 1).
103+func parseRange(s string) (start, count int) {
104+ if idx := strings.IndexByte(s, ','); idx >= 0 {
105+ start, _ = strconv.Atoi(s[:idx])
106+ count, _ = strconv.Atoi(s[idx+1:])
107+ return start, count
108+ }
109+ start, _ = strconv.Atoi(s)
110+ return start, 1
111+}
internal/tui/editor/editor.go+88−10
@@ -99,6 +99,15 @@ func hexNibble(c byte) int {
9999 return 0
100100 }
101101
102+// colorToBgSeq converts a color.Color to an ANSI 24-bit background escape.
103+func colorToBgSeq(c color.Color) string {
104+ if c == nil {
105+ return ""
106+ }
107+ r, g, b, _ := c.RGBA()
108+ return fmt.Sprintf("\x1b[48;2;%d;%d;%dm", r>>8, g>>8, b>>8)
109+}
110+
102111 // themeBg extracts the background hex color from a Chroma style.
103112 // Returns "" if no background is set.
104113 func themeBg(theme string) string {
@@ -117,6 +126,15 @@ func themeBg(theme string) string {
117126 // Model
118127 // ---------------------------------------------------------------------------
119128
129+// GutterMark identifies the type of change marker shown in the gutter.
130+type GutterMark int
131+
132+const (
133+ GutterAdd GutterMark = iota // Line was added
134+ GutterChange // Line was modified
135+ GutterDelete // Line(s) deleted after this line
136+)
137+
120138 // Model is a minimal text editor / viewer component.
121139 type Model struct {
122140 // Public configuration — set before first Update/View.
@@ -133,6 +151,15 @@ type Model struct {
133151 PlaceholderSty lipgloss.Style // Placeholder text
134152 BgColor color.Color // Fallback bg when no syntax theme
135153
154+ // Gutter markers (git diff indicators in line number column).
155+ GutterMarkers map[int]GutterMark // bufRow (0-indexed) -> mark type
156+ MarkAddStyle lipgloss.Style // Style for added-line marker
157+ MarkChgStyle lipgloss.Style // Style for changed-line marker
158+ MarkDelStyle lipgloss.Style // Style for deleted-line marker
159+
160+ // Per-line background overrides (e.g. diff line tinting).
161+ LineBg map[int]lipgloss.Style // bufRow (0-indexed) -> background style
162+
136163 // Internal state
137164 lines [][]rune // Backing store, one entry per line
138165 row int // Cursor row (0-indexed into lines)
@@ -462,7 +489,7 @@ func (m *Model) textWidth() int {
462489 if digits < 2 {
463490 digits = 2
464491 }
465- m.gutterWidth = digits + 1 // digits + 1 space
492+ m.gutterWidth = digits + 2 // digits + marker column + 1 space
466493 }
467494 w := m.width - m.gutterWidth
468495 if w < 1 {
@@ -471,6 +498,37 @@ func (m *Model) textWidth() int {
471498 return w
472499 }
473500
501+// SetGutterMarkers replaces the current gutter markers.
502+// Keys are 0-indexed buffer row numbers.
503+func (m *Model) SetGutterMarkers(markers map[int]GutterMark) {
504+ m.GutterMarkers = markers
505+}
506+
507+// renderGutterMark returns the styled single-character marker for a buffer row.
508+// Falls back to a space (in lineNumSty) if no marker exists.
509+func (m Model) renderGutterMark(bufRow int, lineNumSty lipgloss.Style) string {
510+ mark, ok := m.GutterMarkers[bufRow]
511+ if !ok {
512+ return lineNumSty.Render(" ")
513+ }
514+ switch mark {
515+ case GutterAdd:
516+ return m.MarkAddStyle.Render("+")
517+ case GutterChange:
518+ return m.MarkChgStyle.Render("~")
519+ case GutterDelete:
520+ return m.MarkDelStyle.Render("-")
521+ default:
522+ return lineNumSty.Render(" ")
523+ }
524+}
525+
526+// SetLineBg replaces the per-line background overrides.
527+// Keys are 0-indexed buffer row numbers.
528+func (m *Model) SetLineBg(bg map[int]lipgloss.Style) {
529+ m.LineBg = bg
530+}
531+
474532 // ---------------------------------------------------------------------------
475533 // Soft line wrapping helpers
476534 // ---------------------------------------------------------------------------
@@ -967,6 +1025,7 @@ func (m Model) View() string {
9671025 tw := m.textWidth()
9681026 bg := m.bgForRender()
9691027 lineNumSty := m.LineNumStyle.Background(bg.GetBackground())
1028+ themeBgSeq := hexToBgSeq(m.bgHexForHighlight()) // for LineBg replacement
9701029
9711030 // Build a flat list of visual rows from visible buffer lines.
9721031 type visualRow struct {
@@ -1055,15 +1114,28 @@ func (m Model) View() string {
10551114
10561115 vr := rows[vi]
10571116
1058- // -- Gutter (line numbers) -------------------------------------------
1117+ // Resolve per-line background override.
1118+ rowBg := bg
1119+ hasLineBg := false
1120+ if lbg, ok := m.LineBg[vr.bufRow]; ok {
1121+ rowBg = lbg
1122+ hasLineBg = true
1123+ }
1124+
1125+ // -- Gutter (line numbers + marker column) ---------------------------
10591126 if m.ShowLineNumbers {
1060- digits := m.gutterWidth - 1
1127+ gutSty := lineNumSty
1128+ if hasLineBg {
1129+ gutSty = gutSty.Background(rowBg.GetBackground())
1130+ }
1131+ digits := m.gutterWidth - 2 // gutter = digits + space + marker
10611132 if vr.subRow == 0 {
10621133 num := fmt.Sprintf("%*d ", digits, vr.bufRow+1)
1063- b.WriteString(lineNumSty.Render(num))
1134+ b.WriteString(gutSty.Render(num))
1135+ b.WriteString(m.renderGutterMark(vr.bufRow, gutSty))
10641136 } else {
10651137 // Continuation row — blank gutter
1066- b.WriteString(lineNumSty.Render(strings.Repeat(" ", m.gutterWidth)))
1138+ b.WriteString(gutSty.Render(strings.Repeat(" ", m.gutterWidth)))
10671139 }
10681140 }
10691141
@@ -1115,14 +1187,18 @@ func (m Model) View() string {
11151187 var rendered string
11161188 if rowHasSel {
11171189 rendered = m.renderSelectedSegment(segText, vr.fullHL, vr.segStart, segLen,
1118- selColStart, selColEnd, selSty, bg, isCursorHere, cursorExpandedCol-segRuneOff)
1190+ selColStart, selColEnd, selSty, rowBg, isCursorHere, cursorExpandedCol-segRuneOff)
11191191 } else if isCursorHere {
11201192 localCol := cursorExpandedCol - segRuneOff
11211193 rendered = m.renderCursorSegment(segText, vr.fullHL, vr.segStart, localCol)
11221194 } else if hasSyntax && vr.fullHL != "" {
11231195 rendered = ansi.Cut(vr.fullHL, vr.segStart, vr.segEnd)
1196+ if hasLineBg && themeBgSeq != "" {
1197+ overrideBgSeq := colorToBgSeq(rowBg.GetBackground())
1198+ rendered = strings.ReplaceAll(rendered, themeBgSeq, overrideBgSeq)
1199+ }
11241200 } else {
1125- rendered = bg.Render(segText)
1201+ rendered = rowBg.Render(segText)
11261202 }
11271203
11281204 // Pad to text width
@@ -1133,7 +1209,7 @@ func (m Model) View() string {
11331209 }
11341210 b.WriteString(rendered)
11351211 if rw < tw {
1136- b.WriteString(bg.Render(strings.Repeat(" ", tw-rw)))
1212+ b.WriteString(rowBg.Render(strings.Repeat(" ", tw-rw)))
11371213 }
11381214 }
11391215
@@ -1287,9 +1363,11 @@ func (m Model) placeholderView() string {
12871363 var b strings.Builder
12881364 // Gutter
12891365 if m.ShowLineNumbers {
1290- digits := m.gutterWidth - 1
1366+ lineNumSty := m.LineNumStyle.Background(bg.GetBackground())
1367+ digits := m.gutterWidth - 2 // gutter = digits + space + marker
12911368 num := fmt.Sprintf("%*d ", digits, 1)
1292- b.WriteString(m.LineNumStyle.Background(bg.GetBackground()).Render(num))
1369+ b.WriteString(lineNumSty.Render(num))
1370+ b.WriteString(m.renderGutterMark(0, lineNumSty))
12931371 }
12941372
12951373 // First line: cursor (if focused) then placeholder text
internal/tui/mouse.go+51−1
@@ -8,6 +8,7 @@ import (
88 "time"
99
1010 tea "charm.land/bubbletea/v2"
11+ "charm.land/lipgloss/v2"
1112 "github.com/charmbracelet/x/ansi"
1213 "github.com/xonecas/symb/internal/mcp_tools"
1314 )
@@ -209,6 +210,7 @@ func (m *Model) handleConvClick(wrappedLine int) tea.Cmd {
209210 if content, err := os.ReadFile(entry.filePath); err == nil {
210211 m.editor.SetValue(string(content))
211212 m.editor.Language = mcp_tools.DetectLanguage(entry.filePath)
213+ m.editor.SetLineBg(nil)
212214 m.setFocus(focusEditor)
213215 return nil
214216 }
@@ -216,7 +218,14 @@ func (m *Model) handleConvClick(wrappedLine int) tea.Cmd {
216218 // Fallback: show raw tool result text
217219 if entry.full != "" {
218220 m.editor.SetValue(entry.full)
219- m.editor.Language = "text"
221+ lang := detectToolResultLanguage(entry.full)
222+ m.editor.Language = lang
223+ if lang == "diff" {
224+ m.editor.SetLineBg(diffLineBg(entry.full))
225+ } else {
226+ m.editor.SetLineBg(nil)
227+ }
228+ m.editor.SetGutterMarkers(nil)
220229 m.setFocus(focusEditor)
221230 return nil
222231 }
@@ -266,9 +275,50 @@ func (m *Model) tryOpenFilePath(text string) tea.Cmd {
266275 language := mcp_tools.DetectLanguage(path)
267276 m.editor.SetValue(string(content))
268277 m.editor.Language = language
278+ m.editor.SetLineBg(nil)
269279 if lineNum > 0 {
270280 m.editor.GotoLine(lineNum)
271281 }
272282 m.setFocus(focusEditor)
273283 return nil
274284 }
285+
286+// detectToolResultLanguage guesses a Chroma lexer name from tool result content.
287+func detectToolResultLanguage(content string) string {
288+ if strings.Contains(content, "\n@@ ") ||
289+ strings.HasPrefix(content, "@@ ") ||
290+ strings.HasPrefix(content, "diff ") ||
291+ strings.HasPrefix(content, "--- ") {
292+ return "diff"
293+ }
294+ return "text"
295+}
296+
297+// diffLineBg builds per-line background styles for unified diff content.
298+// Added lines get a green tint, removed lines red, hunk headers a subtle accent.
299+func diffLineBg(content string) map[int]lipgloss.Style {
300+ lines := strings.Split(content, "\n")
301+ bg := make(map[int]lipgloss.Style)
302+
303+ addBg := lipgloss.NewStyle().Background(lipgloss.Color("#1a3a1a")).Foreground(ColorFg)
304+ delBg := lipgloss.NewStyle().Background(lipgloss.Color("#3a1a1a")).Foreground(ColorFg)
305+ hunkBg := lipgloss.NewStyle().Background(lipgloss.Color("#1a2a3a")).Foreground(ColorFg)
306+
307+ for i, line := range lines {
308+ switch {
309+ case strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "--- "):
310+ // File headers — skip, keep default bg
311+ case strings.HasPrefix(line, "+"):
312+ bg[i] = addBg
313+ case strings.HasPrefix(line, "-"):
314+ bg[i] = delBg
315+ case strings.HasPrefix(line, "@@"):
316+ bg[i] = hunkBg
317+ }
318+ }
319+
320+ if len(bg) == 0 {
321+ return nil
322+ }
323+ return bg
324+}
internal/tui/testdata/TestLayout/120x40/ANSI.golden+1−1
@@ -1,4 +1,4 @@
1- 1  │ 
1+ 1   │ 
22  │ 
33  │ 
44  │ 
internal/tui/testdata/TestLayout/80x24/ANSI.golden+1−1
@@ -1,4 +1,4 @@
1- 1  │ 
1+ 1   │ 
22  │ 
33  │ 
44  │ 
internal/tui/tui.go+3−0
@@ -216,6 +216,9 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
216216 ed.SelectionStyle = selStyle
217217 ed.LineNumStyle = lipgloss.NewStyle().Foreground(ColorBorder)
218218 ed.BgColor = ColorBg
219+ ed.MarkAddStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#4ec964")).Background(ColorBg)
220+ ed.MarkChgStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#e5c07b")).Background(ColorBg)
221+ ed.MarkDelStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#e06c75")).Background(ColorBg)
219222
220223 ai := editor.New()
221224 ai.Placeholder = "Type a message..."
internal/tui/update.go+3−0
@@ -233,6 +233,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
Cut short: this commit's diff is over 1000 lines.