xonecas.io
62159
Sy

symb / commit 7c18cf9

fix: agents finally got to the root of the issue with resume

xonecas2026-02-16 7c18cf90a485409517e5d8c4f224dbf82bf21182 parent 5dd96bb

6 files changed

cmd/symb/main.go+1−19
@@ -4,7 +4,6 @@ import (
44 "context"
55 "crypto/rand"
66 "encoding/hex"
7- "encoding/json"
87 "flag"
98 "fmt"
109 "os"
@@ -295,24 +294,7 @@ func listSessions(db *store.Cache) {
295294 }
296295
297296 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
297+ return store.ToProviderMessages(msgs)
316298 }
317299
318300 func resolveSession(flagSession string, flagContinue bool, db *store.Cache) (string, []provider.Message) {
internal/store/session.go+47−38
@@ -6,6 +6,7 @@ import (
66 "time"
77
88 "github.com/rs/zerolog/log"
9+ "github.com/xonecas/symb/internal/provider"
910 )
1011
1112 // Session represents a conversation session.
@@ -47,32 +48,11 @@ func (c *Cache) CreateSession(id string) error {
4748 return err
4849 }
4950
50-// SaveMessage queues a message for async persistence. Non-blocking.
51+// SaveMessage persists a message synchronously.
5152 func (c *Cache) SaveMessage(sessionID string, msg SessionMessage) {
5253 if c == nil {
5354 return
5455 }
55- select {
56- case c.saveCh <- saveReq{sessionID: sessionID, msg: msg}:
57- default:
58- log.Warn().Str("session", sessionID).Msg("save channel full, dropping message")
59- }
60-}
61-
62-// saveLoop drains saveCh and writes messages to the DB.
63-func (c *Cache) saveLoop() {
64- defer close(c.done)
65- for req := range c.saveCh {
66- if req.flush != nil {
67- close(req.flush)
68- continue
69- }
70- c.writeMessage(req.sessionID, req.msg)
71- }
72-}
73-
74-// writeMessage performs the actual DB insert for a message.
75-func (c *Cache) writeMessage(sessionID string, msg SessionMessage) {
7656 c.mu.Lock()
7757 defer c.mu.Unlock()
7858
@@ -91,7 +71,6 @@ func (c *Cache) writeMessage(sessionID string, msg SessionMessage) {
9171 log.Warn().Err(err).Str("session", sessionID).Msg("failed to save message")
9272 }
9373
94- // Touch session updated time.
9574 c.db.Exec("UPDATE sessions SET updated = ? WHERE id = ?", time.Now().Unix(), sessionID) //nolint:errcheck
9675 }
9776
@@ -124,21 +103,6 @@ func (c *Cache) SaveMessageSync(sessionID string, msg SessionMessage) (int64, er
124103 return res.LastInsertId()
125104 }
126105
127-// Flush blocks until all queued async saves have been written to the DB.
128-// Times out after 5 seconds to avoid deadlocking the caller.
129-func (c *Cache) Flush() {
130- if c == nil {
131- return
132- }
133- done := make(chan struct{})
134- select {
135- case c.saveCh <- saveReq{flush: done}:
136- <-done
137- case <-time.After(5 * time.Second):
138- log.Warn().Msg("flush timed out waiting to enqueue")
139- }
140-}
141-
142106 // DeleteMessagesFrom removes all messages with id >= minID for a session.
143107 func (c *Cache) DeleteMessagesFrom(sessionID string, minID int64) error {
144108 if c == nil {
@@ -154,6 +118,29 @@ func (c *Cache) DeleteMessagesFrom(sessionID string, minID int64) error {
154118 return err
155119 }
156120
121+// LoadLastMessage returns the most recent message for a session, or nil if none.
122+func (c *Cache) LoadLastMessage(sessionID string) (*SessionMessage, error) {
123+ if c == nil {
124+ return nil, nil
125+ }
126+ c.mu.Lock()
127+ defer c.mu.Unlock()
128+
129+ var m SessionMessage
130+ var tc string
131+ var created int64
132+ err := c.db.QueryRow(
133+ `SELECT role, content, reasoning, tool_calls, tool_call_id, created, input_tokens, output_tokens
134+ FROM messages WHERE session_id = ? ORDER BY id DESC LIMIT 1`, sessionID,
135+ ).Scan(&m.Role, &m.Content, &m.Reasoning, &tc, &m.ToolCallID, &created, &m.InputTokens, &m.OutputTokens)
136+ if err != nil {
137+ return nil, err
138+ }
139+ m.ToolCalls = json.RawMessage(tc)
140+ m.CreatedAt = time.Unix(created, 0)
141+ return &m, nil
142+}
143+
157144 // LoadMessages returns all messages for a session, ordered by ID.
158145 func (c *Cache) LoadMessages(sessionID string) ([]SessionMessage, error) {
159146 if c == nil {
@@ -253,6 +240,28 @@ func (c *Cache) LatestSessionID() (string, error) {
253240 return id, nil
254241 }
255242
243+// ToProviderMessages converts stored messages to provider messages.
244+func ToProviderMessages(msgs []SessionMessage) []provider.Message {
245+ out := make([]provider.Message, 0, len(msgs))
246+ for _, m := range msgs {
247+ pm := provider.Message{
248+ Role: m.Role,
249+ Content: m.Content,
250+ Reasoning: m.Reasoning,
251+ ToolCallID: m.ToolCallID,
252+ CreatedAt: m.CreatedAt,
253+ }
254+ if len(m.ToolCalls) > 0 {
255+ var tcs []provider.ToolCall
256+ if err := json.Unmarshal(m.ToolCalls, &tcs); err == nil {
257+ pm.ToolCalls = tcs
258+ }
259+ }
260+ out = append(out, pm)
261+ }
262+ return out
263+}
264+
256265 // SessionExists returns true if a session with the given ID exists.
257266 func (c *Cache) SessionExists(id string) (bool, error) {
258267 if c == nil {
internal/store/store.go+6−20
@@ -61,20 +61,11 @@ CREATE TABLE IF NOT EXISTS file_deltas (
6161 CREATE INDEX IF NOT EXISTS idx_deltas_turn ON file_deltas(session_id, turn_id);
6262 `
6363
64-// saveReq is an internal message sent to the background save goroutine.
65-type saveReq struct {
66- sessionID string
67- msg SessionMessage
68- flush chan struct{} // if non-nil, signal after processing (used by Flush)
69-}
70-
7164 // Cache is a SQLite-backed cache for web results and session storage.
7265 type Cache struct {
73- mu sync.Mutex
74- db *sql.DB
75- ttl time.Duration
76- saveCh chan saveReq // buffered channel for async message saves
77- done chan struct{} // closed when background goroutine exits
66+ mu sync.Mutex
67+ db *sql.DB
68+ ttl time.Duration
7869 }
7970
8071 // Open creates or opens a cache database at the given path.
@@ -116,12 +107,9 @@ func Open(dbPath string, ttl time.Duration) (*Cache, error) {
116107 }
117108
118109 c := &Cache{
119- db: db,
120- ttl: ttl,
121- saveCh: make(chan saveReq, 256),
122- done: make(chan struct{}),
110+ db: db,
111+ ttl: ttl,
123112 }
124- go c.saveLoop()
125113 c.purgeStale()
126114 return c, nil
127115 }
@@ -134,13 +122,11 @@ func (c *Cache) DB() *sql.DB {
134122 return c.db
135123 }
136124
137-// Close drains pending saves and closes the database.
125+// Close closes the database.
138126 func (c *Cache) Close() error {
139127 if c == nil {
140128 return nil
141129 }
142- close(c.saveCh)
143- <-c.done
144130 return c.db.Close()
145131 }
146132
internal/tui/messages.go+13−2
@@ -2,6 +2,7 @@ package tui
22
33 import (
44 "encoding/json"
5+ "fmt"
56 "os"
67 "os/exec"
78 "strings"
@@ -151,8 +152,8 @@ func (m Model) processLLM() tea.Cmd {
151152 proxy := m.mcpProxy
152153 tools := make([]mcp.Tool, len(m.mcpTools))
153154 copy(tools, m.mcpTools)
154- history := make([]provider.Message, len(m.history))
155- copy(history, m.history)
155+ db := m.store
156+ sid := m.sessionID
156157 ch := m.updateChan
157158 ctx := m.turnCtx
158159 dt := m.deltaTracker
@@ -160,6 +161,16 @@ func (m Model) processLLM() tea.Cmd {
160161
161162 return func() tea.Msg {
162163 go func() {
164+ // Load history from DB — the single source of truth.
165+ var history []provider.Message
166+ if db != nil {
167+ stored, err := db.LoadMessages(sid)
168+ if err != nil {
169+ ch <- llmErrorMsg{err: fmt.Errorf("load history: %w", err)}
170+ return
171+ }
172+ history = store.ToProviderMessages(stored)
173+ }
163174 // Snapshot the project directory before the turn for undo.
164175 // Capture cwd once so both pre/post snapshots use the same root.
165176 var preSnap map[string]delta.FileSnapshot
internal/tui/tui.go+1−7
@@ -168,9 +168,8 @@ type FileReadResetter interface {
168168 // Turn tracking (for undo)
169169 // ---------------------------------------------------------------------------
170170
171-// turnBoundary marks the start of a user turn in both history and convEntries.
171+// turnBoundary marks the start of a user turn in convEntries.
172172 type turnBoundary struct {
173- historyIdx int // index in m.history where the user message is
174173 convIdx int // index in m.convEntries where this turn's display starts
175174 dbMsgID int64 // messages.id of the user message (for DB cleanup)
176175 inputTokens int // total input tokens at start of this turn
@@ -200,7 +199,6 @@ type Model struct {
200199 provider provider.Provider
201200 mcpProxy *mcp.Proxy
202201 mcpTools []mcp.Tool
203- history []provider.Message
204202 updateChan chan tea.Msg
205203 ctx context.Context
206204 cancel context.CancelFunc
@@ -313,10 +311,8 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
313311 ch := make(chan tea.Msg, 500)
314312 ctx, cancel := context.WithCancel(context.Background())
315313
316- var history []provider.Message
317314 var entries []convEntry
318315 if resumeHistory != nil {
319- history = resumeHistory
320316 entries = historyConvEntries(resumeHistory)
321317 } else {
322318 systemPrompt := llm.BuildSystemPrompt(modelID, idx)
@@ -324,7 +320,6 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
324320 if db != nil {
325321 db.SaveMessage(sessionID, messageToStore(systemMsg))
326322 }
327- history = []provider.Message{systemMsg}
328323 }
329324
330325 return Model{
@@ -336,7 +331,6 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
336331 provider: prov,
337332 mcpProxy: proxy,
338333 mcpTools: tools,
339- history: history,
340334 convEntries: entries,
341335 updateChan: ch,
342336 ctx: ctx,
internal/tui/update.go+19−35
@@ -217,14 +217,12 @@ func (m *Model) handleKeyPress(msg tea.KeyPressMsg) (Model, tea.Cmd, bool) {
217217 return Model{}, nil, false
218218 }
219219
220-// handleUserMsg records a user message in history and conversation display.
220+// handleUserMsg records a user message in the DB and conversation display.
221221 func (m *Model) handleUserMsg(msg llmUserMsg) Model {
222222 now := time.Now()
223223 userMsg := provider.Message{Role: "user", Content: msg.content, CreatedAt: now}
224224
225- historyIdx := len(m.history)
226225 convIdx := len(m.convEntries)
227- m.history = append(m.history, userMsg)
228226
229227 // Save synchronously to get DB row ID for undo tracking.
230228 var dbMsgID int64
@@ -243,7 +241,6 @@ func (m *Model) handleUserMsg(msg llmUserMsg) Model {
243241 }
244242
245243 m.turnBoundaries = append(m.turnBoundaries, turnBoundary{
246- historyIdx: historyIdx,
247244 convIdx: convIdx,
248245 dbMsgID: dbMsgID,
249246 inputTokens: m.totalInputTokens,
@@ -285,7 +282,6 @@ func (m Model) handleLLMBatch(batch llmBatchMsg) (tea.Model, tea.Cmd) {
285282 m.streamDirty = true
286283
287284 case llmHistoryMsg:
288- m.history = append(m.history, msg.msg)
289285 m.saveMessage(msg.msg)
290286
291287 case llmAssistantMsg:
@@ -331,7 +327,6 @@ func (m Model) drainCancelled(batch llmBatchMsg) (tea.Model, tea.Cmd) {
331327 for _, raw := range batch {
332328 switch msg := raw.(type) {
333329 case llmHistoryMsg:
334- m.history = append(m.history, msg.msg)
335330 m.saveMessage(msg.msg)
336331 case llmDoneMsg, llmErrorMsg:
337332 m.patchInterruptedHistory()
@@ -357,17 +352,22 @@ func (m *Model) finishTurn() {
357352 // interrupted turn left history in an invalid API state (trailing tool_use
358353 // without result, or trailing tool result with no assistant follow-up).
359354 func (m *Model) patchInterruptedHistory() {
360- if n := len(m.history); n > 0 {
361- last := m.history[n-1]
362- if last.Role != roleAssistant || len(last.ToolCalls) > 0 {
363- interruptMsg := provider.Message{
364- Role: roleAssistant,
365- Content: "The user interrupted me.",
366- CreatedAt: time.Now(),
367- }
368- m.history = append(m.history, interruptMsg)
369- m.saveMessage(interruptMsg)
355+ if m.store == nil {
356+ return
357+ }
358+ last, err := m.store.LoadLastMessage(m.sessionID)
359+ if err != nil || last == nil {
360+ return
361+ }
362+ hasToolCalls := len(last.ToolCalls) > 0 && string(last.ToolCalls) != "[]"
363+ needsPatch := last.Role != roleAssistant || hasToolCalls
364+ if needsPatch {
365+ interruptMsg := provider.Message{
366+ Role: roleAssistant,
367+ Content: "The user interrupted me.",
368+ CreatedAt: time.Now(),
370369 }
370+ m.saveMessage(interruptMsg)
371371 }
372372 }
373373
@@ -643,31 +643,17 @@ func (m *Model) demoteOldUndo() {
643643 }
644644
645645 // trimOldTurns drops the oldest display turns when we exceed maxDisplayTurns.
646-// Messages are already persisted in the DB — this only trims in-memory state
647-// to bound rendering cost.
646+// Messages live in the DB — this only trims display entries to bound rendering cost.
648647 func (m *Model) trimOldTurns() {
649648 for len(m.turnBoundaries) > maxDisplayTurns {
650- // The second boundary marks where the oldest visible turn's display ends.
651649 cutConv := m.turnBoundaries[1].convIdx
652- cutHist := m.turnBoundaries[1].historyIdx
653650
654- // Shift convEntries and adjust all boundary indices.
655651 m.convEntries = m.convEntries[cutConv:]
656652 m.turnBoundaries = m.turnBoundaries[1:]
657653
658- // History: keep the system prompt (index 0) + trim old turn messages.
659- // After: history = [system] + history[cutHist:], so what was at
660- // cutHist is now at index 1 — offset is cutHist-1.
661- histOff := cutHist - 1
662- if cutHist > 1 && cutHist < len(m.history) {
663- m.history = append(m.history[:1], m.history[cutHist:]...)
664- }
665-
666654 for i := range m.turnBoundaries {
667655 m.turnBoundaries[i].convIdx -= cutConv
668- m.turnBoundaries[i].historyIdx -= histOff
669656 }
670-
671657 }
672658 }
673659
@@ -695,8 +681,7 @@ func (m *Model) handleUndo() Model {
695681 m.deltaTracker.DeleteTurn(m.sessionID, tb.dbMsgID)
696682 }
697683
698- // 2. Truncate in-memory history and display.
699- m.history = m.history[:tb.historyIdx]
684+ // 2. Truncate display entries.
700685 m.convEntries = m.convEntries[:tb.convIdx]
701686
702687 // 2b. Show error after truncation so it's visible.
@@ -704,9 +689,8 @@ func (m *Model) handleUndo() Model {
704689 m.appendText("", m.styles.Error.Render("undo file restore failed: "+undoErr.Error()), "")
705690 }
706691
707- // 3. Flush async saves then delete messages from DB.
692+ // 3. Delete messages from DB.
708693 if m.store != nil && tb.dbMsgID > 0 {
709- m.store.Flush()
710694 if err := m.store.DeleteMessagesFrom(m.sessionID, tb.dbMsgID); err != nil {
711695 log.Warn().Err(err).Msg("undo: failed to delete messages")
712696 }