xonecas.io
62159
Sy

symb / commit f86c804

feat: session management flags

xonecas2026-02-16 f86c804f787a20ab565c7c311930d5319e78f424 parent 87a7a0f

13 files changed

cmd/symb/main.go+132−7
@@ -4,9 +4,12 @@ import (
44 "context"
55 "crypto/rand"
66 "encoding/hex"
7+ "encoding/json"
8+ "flag"
79 "fmt"
810 "os"
911 "path/filepath"
12+ "strings"
1013 "time"
1114
1215 tea "charm.land/bubbletea/v2"
@@ -29,6 +32,15 @@ func main() {
2932 fmt.Fprintf(os.Stderr, "Warning: failed to setup logging: %v\n", err)
3033 }
3134
35+ // Parse CLI flags.
36+ flagSession := flag.String("s", "", "resume a session by ID")
37+ flagList := flag.Bool("l", false, "list sessions")
38+ flagContinue := flag.Bool("c", false, "continue most recent session")
39+ flag.StringVar(flagSession, "session", "", "resume a session by ID")
40+ flag.BoolVar(flagList, "list", false, "list sessions")
41+ flag.BoolVar(flagContinue, "continue", false, "continue most recent session")
42+ flag.Parse()
43+
3244 cfg, err := config.Load(filepath.Join(".", "config.toml"))
3345 if err != nil {
3446 fmt.Printf("Error loading config: %v\n", err)
@@ -59,18 +71,19 @@ func main() {
5971 defer svc.webCache.Close()
6072 }
6173
74+ // Handle --list: print sessions and exit.
75+ if *flagList {
76+ listSessions(svc.webCache)
77+ return
78+ }
79+
6280 tools, err := svc.proxy.ListTools(context.Background())
6381 if err != nil {
6482 fmt.Printf("Warning: Failed to list tools: %v\n", err)
6583 tools = []mcp.Tool{}
6684 }
6785
68- sessionID := newSessionID()
69- if svc.webCache != nil {
70- if err := svc.webCache.CreateSession(sessionID); err != nil {
71- fmt.Printf("Warning: failed to create session: %v\n", err)
72- }
73- }
86+ sessionID, resumeHistory := resolveSession(*flagSession, *flagContinue, svc.webCache)
7487
7588 // Build tree-sitter project symbol index.
7689 cwd, err := os.Getwd()
@@ -93,7 +106,7 @@ func main() {
93106 }
94107
95108 p := tea.NewProgram(
96- tui.New(prov, svc.proxy, tools, providerCfg.Model, svc.webCache, sessionID, tsIndex, svc.deltaTracker, svc.fileTracker, providerName, svc.scratchpad),
109+ tui.New(prov, svc.proxy, tools, providerCfg.Model, svc.webCache, sessionID, tsIndex, svc.deltaTracker, svc.fileTracker, providerName, svc.scratchpad, resumeHistory),
97110 tea.WithFilter(tui.MouseEventFilter),
98111 )
99112 svc.lspManager.SetCallback(func(absPath string, lines map[int]int) {
@@ -255,3 +268,115 @@ func setupFileLogging() error {
255268
256269 return nil
257270 }
271+
272+func listSessions(db *store.Cache) {
273+ if db == nil {
274+ fmt.Println("No cache available")
275+ return
276+ }
277+ sessions, err := db.ListSessions()
278+ if err != nil {
279+ fmt.Printf("Error listing sessions: %v\n", err)
280+ return
281+ }
282+ if len(sessions) == 0 {
283+ fmt.Println("No sessions found")
284+ return
285+ }
286+ for _, s := range sessions {
287+ ts := s.Timestamp.Format("2006-01-02 15:04")
288+ preview := s.Preview
289+ preview = strings.ReplaceAll(preview, "\n", " ")
290+ if len(preview) > 50 {
291+ preview = preview[:50]
292+ }
293+ fmt.Printf("%s %s %s\n", s.ID, ts, preview)
294+ }
295+}
296+
297+func storedToMessages(msgs []store.SessionMessage) []provider.Message {
298+ out := make([]provider.Message, 0, len(msgs))
299+ for _, m := range msgs {
300+ pm := provider.Message{
301+ Role: m.Role,
302+ Content: m.Content,
303+ Reasoning: m.Reasoning,
304+ ToolCallID: m.ToolCallID,
305+ CreatedAt: m.CreatedAt,
306+ }
307+ if len(m.ToolCalls) > 0 {
308+ var tcs []provider.ToolCall
309+ if err := json.Unmarshal(m.ToolCalls, &tcs); err == nil {
310+ pm.ToolCalls = tcs
311+ }
312+ }
313+ out = append(out, pm)
314+ }
315+ return out
316+}
317+
318+func resolveSession(flagSession string, flagContinue bool, db *store.Cache) (string, []provider.Message) {
319+ switch {
320+ case flagSession != "":
321+ if db != nil {
322+ ok, err := db.SessionExists(flagSession)
323+ if err != nil || !ok {
324+ fmt.Printf("Session %q not found\n", flagSession)
325+ os.Exit(1)
326+ }
327+ }
328+ msgs := loadHistory(flagSession, db)
329+ return flagSession, msgs
330+
331+ case flagContinue:
332+ if db == nil {
333+ fmt.Println("No cache available")
334+ os.Exit(1)
335+ }
336+ id, err := db.LatestSessionID()
337+ if err != nil {
338+ fmt.Printf("No sessions to continue: %v\n", err)
339+ os.Exit(1)
340+ }
341+ msgs := loadHistory(id, db)
342+ return id, msgs
343+
344+ default:
345+ sid := newSessionID()
346+ if db != nil {
347+ if err := db.CreateSession(sid); err != nil {
348+ fmt.Printf("Warning: failed to create session: %v\n", err)
349+ }
350+ }
351+ return sid, nil
352+ }
353+}
354+
355+func loadHistory(sessionID string, db *store.Cache) []provider.Message {
356+ if db == nil {
357+ return nil
358+ }
359+ stored, err := db.LoadMessages(sessionID)
360+ if err != nil {
361+ fmt.Printf("Warning: failed to load session history: %v\n", err)
362+ return nil
363+ }
364+ msgs := storedToMessages(stored)
365+ return trimIncomplete(msgs)
366+}
367+
368+// trimIncomplete removes trailing messages that form an incomplete turn.
369+// A valid history ends with an assistant message (finished response) or
370+// a system message (empty session). Trailing user/tool messages from a
371+// session killed mid-turn are dropped so the next user input doesn't
372+// create consecutive user messages which the API rejects.
373+func trimIncomplete(msgs []provider.Message) []provider.Message {
374+ for len(msgs) > 0 {
375+ last := msgs[len(msgs)-1]
376+ if last.Role == "assistant" || last.Role == "system" {
377+ break
378+ }
379+ msgs = msgs[:len(msgs)-1]
380+ }
381+ return msgs
382+}
internal/llm/loop.go+0−59
@@ -95,13 +95,6 @@ func ProcessTurn(ctx context.Context, opts ProcessTurnOptions) error {
9595 }
9696
9797 for round := 0; round < opts.MaxToolRounds; round++ {
98- // After round 0 the history contains tool results that the LLM
99- // has already responded to. Compact them so we don't resend
100- // large payloads on every subsequent call.
101- if round > 0 {
102- compactOldToolResults(opts.History)
103- }
104-
10598 // Inject a <system-reminder> into the last tool result to keep
10699 // the model focused. Two sources:
107100 // 1. Scratchpad (agent-written plan) — preferred when present.
@@ -291,64 +284,12 @@ func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provide
291284 return toolResults
292285 }
293286
294-// maxToolResultLen is the character threshold above which a tool result is
295-// compacted once the LLM has already processed it.
296-const maxToolResultLen = 200
297-
298287 // reminderInterval is the number of tool-calling rounds between synthetic
299288 // goal reminders. After this many rounds the loop injects a system message
300289 // reciting the user's original request so it stays in the model's recent
301290 // attention window.
302291 const reminderInterval = 10
303292
304-// compactOldToolResults replaces verbose tool-result messages that the LLM
305-// has already responded to with a short summary. A tool result is considered
306-// "processed" when an assistant message appears after it in the history.
307-//
308-// This reduces tokens sent to the provider during multi-round tool-calling
309-// turns. It operates on the local history copy inside ProcessTurn — the
310-// TUI's m.history is unaffected.
311-func compactOldToolResults(history []provider.Message) {
312- // Find the index of the last assistant message — everything before it
313- // has been seen by the LLM.
314- lastAssistant := -1
315- for i := len(history) - 1; i >= 0; i-- {
316- if history[i].Role == "assistant" {
317- lastAssistant = i
318- break
319- }
320- }
321- if lastAssistant < 0 {
322- return
323- }
324-
325- for i := 0; i < lastAssistant; i++ {
326- if history[i].Role != "tool" {
327- continue
328- }
329- if len(history[i].Content) <= maxToolResultLen {
330- continue
331- }
332- history[i].Content = trimToolResult(history[i].Content)
333- }
334-}
335-
336-// trimToolResult keeps the first line (usually a header like "Read file.go (200 lines):")
337-// plus a truncation notice. This preserves enough context for the LLM to know what
338-// tool was called and what it returned, without the full payload.
339-func trimToolResult(content string) string {
340- firstNL := strings.Index(content, "\n")
341- if firstNL < 0 || firstNL > maxToolResultLen {
342- // No newline or very long first line — hard truncate.
343- r := []rune(content)
344- if len(r) > maxToolResultLen {
345- return string(r[:maxToolResultLen]) + "\n[Truncated — already processed by assistant]"
346- }
347- return content
348- }
349- return content[:firstNL] + "\n[Truncated — already processed by assistant]"
350-}
351-
352293 // injectRecitation appends a <system-reminder> block to the last tool-result
353294 // message in history to keep the model focused during long tool-calling loops.
354295 // By appending to an existing message instead of creating a new one, we avoid
internal/mcptools/open.go+1−1
@@ -16,7 +16,7 @@ import (
1616
1717 const (
1818 maxReadLines = 500 // Max lines returned by Read before truncation.
19- maxReadChars = 20000 // Max characters returned by Read before truncation.
19+ maxReadChars = 30000 // Max characters returned by Read before truncation.
2020 )
2121
2222 // ReadArgs represents arguments for the Read tool.
internal/mcptools/shell.go+1−1
@@ -106,7 +106,7 @@ func (h *ShellHandler) Handle(ctx context.Context, arguments json.RawMessage) (*
106106 return toolText(output), nil
107107 }
108108
109-const maxOutputChars = 30000
109+const maxOutputChars = 15000
110110 const maxTimeoutSec = 600 // 10 minutes
111111
112112 // streamWriter wraps a bytes.Buffer and calls onChunk for each Write.
internal/store/session.go+84−0
@@ -2,6 +2,7 @@ package store
22
33 import (
44 "encoding/json"
5+ "fmt"
56 "time"
67
78 "github.com/rs/zerolog/log"
@@ -184,3 +185,86 @@ func (c *Cache) LoadMessages(sessionID string) ([]SessionMessage, error) {
184185 }
185186 return msgs, rows.Err()
186187 }
188+
189+// SessionSummary holds info for listing sessions.
190+type SessionSummary struct {
191+ ID string
192+ Timestamp time.Time
193+ Preview string // first 50 chars of last user message
194+}
195+
196+// ListSessions returns sessions ordered by most recent user message.
197+func (c *Cache) ListSessions() ([]SessionSummary, error) {
198+ if c == nil {
199+ return nil, nil
200+ }
201+ c.mu.Lock()
202+ defer c.mu.Unlock()
203+
204+ rows, err := c.db.Query(`
205+ SELECT s.id, m.created, m.content
206+ FROM sessions s
207+ JOIN messages m ON m.session_id = s.id
208+ WHERE m.role = 'user'
209+ AND m.id = (
210+ SELECT MAX(m2.id) FROM messages m2
211+ WHERE m2.session_id = s.id AND m2.role = 'user'
212+ )
213+ ORDER BY m.created DESC`)
214+ if err != nil {
215+ return nil, err
216+ }
217+ defer rows.Close()
218+
219+ var out []SessionSummary
220+ for rows.Next() {
221+ var s SessionSummary
222+ var ts int64
223+ if err := rows.Scan(&s.ID, &ts, &s.Preview); err != nil {
224+ continue
225+ }
226+ s.Timestamp = time.Unix(ts, 0)
227+ if len(s.Preview) > 50 {
228+ s.Preview = s.Preview[:50]
229+ }
230+ out = append(out, s)
231+ }
232+ return out, rows.Err()
233+}
234+
235+// LatestSessionID returns the session with the most recent user message.
236+func (c *Cache) LatestSessionID() (string, error) {
237+ if c == nil {
238+ return "", fmt.Errorf("no cache")
239+ }
240+ c.mu.Lock()
241+ defer c.mu.Unlock()
242+
243+ var id string
244+ err := c.db.QueryRow(`
245+ SELECT s.id FROM sessions s
246+ JOIN messages m ON m.session_id = s.id
247+ WHERE m.role = 'user'
248+ ORDER BY m.created DESC
249+ LIMIT 1`).Scan(&id)
250+ if err != nil {
251+ return "", fmt.Errorf("no sessions found")
252+ }
253+ return id, nil
254+}
255+
256+// SessionExists returns true if a session with the given ID exists.
257+func (c *Cache) SessionExists(id string) (bool, error) {
258+ if c == nil {
259+ return false, nil
260+ }
261+ c.mu.Lock()
262+ defer c.mu.Unlock()
263+
264+ var count int
265+ err := c.db.QueryRow("SELECT COUNT(*) FROM sessions WHERE id = ?", id).Scan(&count)
266+ if err != nil {
267+ return false, err
268+ }
269+ return count > 0, nil
270+}
internal/tui/conv.go+37−0
@@ -7,6 +7,7 @@ import (
77 "charm.land/lipgloss/v2"
88 "github.com/xonecas/symb/internal/constants"
99 "github.com/xonecas/symb/internal/highlight"
10+ "github.com/xonecas/symb/internal/provider"
1011 )
1112
1213 // ---------------------------------------------------------------------------
@@ -165,3 +166,39 @@ func (m *Model) visibleStartLine() int {
165166 }
166167 return start
167168 }
169+
170+// historyConvEntries rebuilds conversation display entries from loaded history.
171+func historyConvEntries(msgs []provider.Message) []convEntry {
172+ sty := DefaultStyles()
173+ var entries []convEntry
174+ for _, msg := range msgs {
175+ switch msg.Role {
176+ case "system":
177+ // not displayed
178+ case "user":
179+ if msg.Content == "" {
180+ continue
181+ }
182+ entries = append(entries, textEntries(highlightMarkdown(msg.Content, sty.Text)...)...)
183+ case "assistant":
184+ if msg.Content != "" {
185+ entries = append(entries, textEntries(highlightMarkdown(msg.Content, sty.Text)...)...)
186+ }
187+ for _, tc := range msg.ToolCalls {
188+ line := formatToolCall(tc)
189+ entries = append(entries, convEntry{display: line, kind: entryToolResult, full: line})
190+ }
191+ case "tool":
192+ // tool results stored as content; show abbreviated
193+ if msg.Content != "" {
194+ lines := strings.SplitN(msg.Content, "\n", 2)
195+ display := lines[0]
196+ if len(display) > 200 {
197+ display = display[:200] + "…"
198+ }
199+ entries = append(entries, convEntry{display: display, kind: entryToolResult, full: msg.Content})
200+ }
201+ }
202+ }
203+ return entries
204+}
internal/tui/golden_test.go+1−1
@@ -26,7 +26,7 @@ func TestLayout(t *testing.T) {
2626
2727 for _, tt := range tests {
2828 t.Run(tt.name, func(t *testing.T) {
29- m := New(nil, nil, nil, "test-model", nil, "test-session", nil, nil, nil, "test-provider", nil)
29+ m := New(nil, nil, nil, "test-model", nil, "test-session", nil, nil, nil, "test-provider", nil, nil)
3030 updated, _ := m.Update(tea.WindowSizeMsg{Width: tt.width, Height: tt.height})
3131 m = updated.(Model)
3232
internal/tui/testdata/TestLayout/120x40/ANSI.golden+40−40
@@ -1,40 +1,40 @@
1- 1   │ 
2- │ 
3- │ 
4- │ 
5- │ 
6- │ 
7- │ 
8- │ 
9- │ 
10- │ 
11- │ 
12- │ 
13- │ 
14- │ 
15- │ 
16- │ 
17- │ 
18- │ 
19- │ 
20- │ 
21- │ 
22- │ 
23- │ 
24- │ 
25- │ 
26- │ 
27- │ 
28- │ 
29- │ 
30- │ 
31- │ 
32- │ 
33- │ 
34- │ 
35- │───────────────────────────────────────────────────────────
36- │Type a message...  
37- │  
38- │  
39-────────────────────────────────────────────────────────────┴───────────────────────────────────────────────────────────
40- test-provider ⠋ 
1+ 1   │ 
2+ │ 
3+ │ 
4+ │ 
5+ │ 
6+ │ 
7+ │ 
8+ │ 
9+ │ 
10+ │ 
11+ │ 
12+ │ 
13+ │ 
14+ │ 
15+ │ 
16+ │ 
17+ │ 
18+ │ 
19+ │ 
20+ │ 
21+ │ 
22+ │ 
23+ │ 
24+ │ 
25+ │ 
26+ │ 
27+ │ 
28+ │ 
29+ │ 
30+ │ 
31+ │ 
32+ │ 
33+ │ 
34+ │ 
35+ │───────────────────────────────────────────────────────────
36+ │What's our task?  
37+ │  
38+ │  
39+────────────────────────────────────────────────────────────┴───────────────────────────────────────────────────────────
40+ test-provider ⠋ 
internal/tui/testdata/TestLayout/120x40/Stripped.golden+1−1
@@ -33,7 +33,7 @@
3333 │
3434 │
3535 │───────────────────────────────────────────────────────────
36- │Type a message...
36+ │What's our task?
3737 │
3838 │
3939 ────────────────────────────────────────────────────────────┴───────────────────────────────────────────────────────────
internal/tui/testdata/TestLayout/80x24/ANSI.golden+24−24
@@ -1,24 +1,24 @@
1- 1   │ 
2- │ 
3- │ 
4- │ 
5- │ 
6- │ 
7- │ 
8- │ 
9- │ 
10- │ 
11- │ 
12- │ 
13- │ 
14- │ 
15- │ 
16- │ 
17- │ 
18- │ 
19- │───────────────────────────────────────
20- │Type a message...  
21- │  
22- │  
23-────────────────────────────────────────┴───────────────────────────────────────
24- test-provider ⠋ 
1+ 1   │ 
2+ │ 
3+ │ 
4+ │ 
5+ │ 
6+ │ 
7+ │ 
8+ │ 
9+ │ 
10+ │ 
11+ │ 
12+ │ 
13+ │ 
14+ │ 
15+ │ 
16+ │ 
17+ │ 
18+ │ 
19+ │───────────────────────────────────────
20+ │What's our task?  
21+ │  
22+ │  
23+────────────────────────────────────────┴───────────────────────────────────────
24+ test-provider ⠋ 
internal/tui/testdata/TestLayout/80x24/Stripped.golden+1−1
@@ -17,7 +17,7 @@
1717 │
1818 │
1919 │───────────────────────────────────────
20- │Type a message...
20+ │What's our task?
2121 │
2222 │
2323 ────────────────────────────────────────┴───────────────────────────────────────
internal/tui/tui.go+17−8
@@ -274,7 +274,9 @@ type Model struct {
274274 }
275275
276276 // New creates a new TUI model.
277-func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID string, db *store.Cache, sessionID string, idx *treesitter.Index, dt *delta.Tracker, ft FileReadResetter, providerConfigName string, pad llm.ScratchpadReader) Model {
277+// If resumeHistory is non-nil, the session is being resumed and messages are
278+// loaded from the database instead of creating a fresh system prompt.
279+func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID string, db *store.Cache, sessionID string, idx *treesitter.Index, dt *delta.Tracker, ft FileReadResetter, providerConfigName string, pad llm.ScratchpadReader, resumeHistory []provider.Message) Model {
278280 sty := DefaultStyles()
279281 cursorStyle := lipgloss.NewStyle().Foreground(ColorHighlight)
280282
@@ -309,11 +311,18 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
309311 ch := make(chan tea.Msg, 500)
310312 ctx, cancel := context.WithCancel(context.Background())
311313
312- systemPrompt := llm.BuildSystemPrompt(modelID, idx)
313- systemMsg := provider.Message{Role: "system", Content: systemPrompt, CreatedAt: time.Now()}
314-
315- if db != nil {
316- db.SaveMessage(sessionID, messageToStore(systemMsg))
314+ var history []provider.Message
315+ var entries []convEntry
316+ if resumeHistory != nil {
317+ history = resumeHistory
318+ entries = historyConvEntries(resumeHistory)
319+ } else {
320+ systemPrompt := llm.BuildSystemPrompt(modelID, idx)
321+ systemMsg := provider.Message{Role: "system", Content: systemPrompt, CreatedAt: time.Now()}
322+ if db != nil {
323+ db.SaveMessage(sessionID, messageToStore(systemMsg))
324+ }
325+ history = []provider.Message{systemMsg}
317326 }
318327
319328 return Model{
@@ -325,8 +334,8 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
325334 provider: prov,
326335 mcpProxy: proxy,
327336 mcpTools: tools,
328- history: []provider.Message{systemMsg},
329- convEntries: []convEntry{},
337+ history: history,
338+ convEntries: entries,
330339 updateChan: ch,
331340 ctx: ctx,
332341 cancel: cancel,
internal/tui/update.go+23−1
@@ -271,10 +271,32 @@ func (m *Model) handleUserMsg(msg llmUserMsg) Model {
271271 func (m Model) handleLLMBatch(batch llmBatchMsg) (tea.Model, tea.Cmd) {
272272 // Turn was cancelled — drain remaining messages until the goroutine
273273 // sends its terminal message (llmDoneMsg or llmErrorMsg), then stop.
274+ // We still persist llmHistoryMsg so the DB stays consistent (an
275+ // assistant's tool_use blocks must be present for its tool results).
274276 if !m.llmInFlight {
275277 for _, raw := range batch {
276- switch raw.(type) {
278+ switch msg := raw.(type) {
279+ case llmHistoryMsg:
280+ m.history = append(m.history, msg.msg)
281+ m.saveMessage(msg.msg)
277282 case llmDoneMsg, llmErrorMsg:
283+ // If the interrupted turn left history in an invalid
284+ // API state (trailing tool_use without result, or
285+ // trailing tool result with no assistant follow-up),
286+ // close it with a synthetic assistant message so
287+ // resume won't trigger a 400.
288+ if n := len(m.history); n > 0 {
289+ last := m.history[n-1]
290+ if last.Role != "assistant" || len(last.ToolCalls) > 0 {
291+ interruptMsg := provider.Message{
292+ Role: "assistant",
293+ Content: "The user interrupted me.",
294+ CreatedAt: time.Now(),
295+ }
296+ m.history = append(m.history, interruptMsg)
297+ m.saveMessage(interruptMsg)
298+ }
299+ }
278300 m.turnCancel = nil
279301 m.turnCtx = nil
280302 return m, nil