@@ -6,6 +6,7 @@ import (
66 "time"
77
88 tea "charm.land/bubbletea/v2"
9+ "github.com/rs/zerolog/log"
910 "github.com/xonecas/symb/internal/provider"
1011 )
1112
@@ -55,6 +56,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
5556 case UpdateToolsMsg:
5657 m.mcpTools = msg.Tools
5758 return m, nil
59+
60+ case undoMsg:
61+ return m.handleUndo(), nil
5862 }
5963
6064 // Always tick spinner
@@ -139,8 +143,33 @@ func (m *Model) handleKeyPress(msg tea.KeyPressMsg) (Model, tea.Cmd, bool) {
139143 func (m *Model) handleUserMsg(msg llmUserMsg) Model {
140144 now := time.Now()
141145 userMsg := provider.Message{Role: "user", Content: msg.content, CreatedAt: now}
146+
147+ historyIdx := len(m.history)
148+ convIdx := len(m.convEntries)
142149 m.history = append(m.history, userMsg)
143- m.saveMessage(userMsg)
150+
151+ // Save synchronously to get DB row ID for undo tracking.
152+ var dbMsgID int64
153+ if m.store != nil {
154+ id, err := m.store.SaveMessageSync(m.sessionID, messageToStore(userMsg))
155+ if err != nil {
156+ log.Warn().Err(err).Msg("failed to save user message; undo disabled for this turn")
157+ } else {
158+ dbMsgID = id
159+ }
160+ }
161+
162+ // Set delta tracker turn so file edits are linked.
163+ if m.deltaTracker != nil && dbMsgID > 0 {
164+ m.deltaTracker.BeginTurn(dbMsgID)
165+ }
166+
167+ m.turnBoundaries = append(m.turnBoundaries, turnBoundary{
168+ historyIdx: historyIdx,
169+ convIdx: convIdx,
170+ dbMsgID: dbMsgID,
171+ })
172+
144173 m.appendText(styledLines(msg.content, m.styles.Text)...)
145174 m.appendText("")
146175 sep := m.makeSeparator("0s", now.Format("15:04:05"))
@@ -189,9 +218,13 @@ func (m Model) handleLLMBatch(batch llmBatchMsg) (tea.Model, tea.Cmd) {
189218
190219 case llmDoneMsg:
191220 m.flushRebuild(needRebuild)
221+ // Replace previous turn's undo entry with a normal separator.
222+ m.demoteOldUndo()
192223 m.appendText("")
224+ // Append undo control instead of a plain separator for the latest turn.
225+ // Store the separator text in full so it can be restored on demote.
193226 sep := m.makeSeparator(msg.duration.Round(time.Second).String(), msg.timestamp)
194- m.appendText(sep)
227+ m.appendConv(m.makeUndoEntry(sep))
195228 return m, nil
196229 }
197230 }
@@ -301,3 +334,91 @@ func (m *Model) updateComponentSizes() {
301334 m.agentInput.SetWidth(m.layout.input.Dx() - 2) // padding for border
302335 m.agentInput.SetHeight(inputRows)
303336 }
337+
338+// demoteOldUndo finds the existing entryUndo in convEntries and demotes it
339+// to an entrySeparator (preserving the original display for potential
340+// re-promotion). Called before appending a new undo entry so only the
341+// latest turn shows the undo control.
342+func (m *Model) demoteOldUndo() {
343+ for i := len(m.convEntries) - 1; i >= 0; i-- {
344+ if m.convEntries[i].kind == entryUndo {
345+ m.convEntries[i].kind = entrySeparator
346+ // full field carries the original separator display text.
347+ m.convEntries[i].display = m.convEntries[i].full
348+ m.convLines = nil // invalidate cache
349+ return
350+ }
351+ }
352+}
353+
354+// handleUndo reverts the most recent turn: restores files, truncates history
355+// and convEntries, and cleans up the database.
356+func (m *Model) handleUndo() Model {
357+ if m.streaming || len(m.turnBoundaries) == 0 {
358+ return *m
359+ }
360+
361+ tb := m.turnBoundaries[len(m.turnBoundaries)-1]
362+ m.turnBoundaries = m.turnBoundaries[:len(m.turnBoundaries)-1]
363+
364+ // 1. Reverse filesystem changes.
365+ var undoErr error
366+ var restoredFiles []string
367+ if m.deltaTracker != nil && tb.dbMsgID > 0 {
368+ restoredFiles, undoErr = m.deltaTracker.Undo(m.sessionID, tb.dbMsgID)
369+ m.deltaTracker.DeleteTurn(m.sessionID, tb.dbMsgID)
370+ }
371+
372+ // 2. Truncate in-memory history and display.
373+ m.history = m.history[:tb.historyIdx]
374+ m.convEntries = m.convEntries[:tb.convIdx]
375+ m.convLines = nil // invalidate cache
376+
377+ // 2b. Show error after truncation so it's visible.
378+ if undoErr != nil {
379+ m.appendText("", m.styles.Error.Render("undo file restore failed: "+undoErr.Error()), "")
380+ }
381+
382+ // 3. Flush async saves then delete messages from DB.
383+ if m.store != nil && tb.dbMsgID > 0 {
384+ m.store.Flush()
385+ if err := m.store.DeleteMessagesFrom(m.sessionID, tb.dbMsgID); err != nil {
386+ log.Warn().Err(err).Msg("undo: failed to delete messages")
387+ }
388+ }
389+
390+ // 4. Clear file-read tracker (LLM will re-Read as needed).
391+ if m.fileTracker != nil {
392+ m.fileTracker.Reset()
393+ }
394+
395+ // 5. Update tree-sitter index for restored files only.
396+ if m.tsIndex != nil {
397+ for _, f := range restoredFiles {
398+ m.tsIndex.UpdateFile(f)
399+ }
400+ }
401+
402+ // 6. Promote previous turn's demoted separator back to undo, if any.
403+ if len(m.turnBoundaries) > 0 {
404+ for i := len(m.convEntries) - 1; i >= 0; i-- {
405+ if m.convEntries[i].kind == entrySeparator {
406+ // full carries the original separator display text.
407+ m.convEntries[i] = m.makeUndoEntry(m.convEntries[i].full)
408+ m.convLines = nil
409+ break
410+ }
411+ }
412+ }
413+
414+ // 7. Reset streaming state.
415+ m.streaming = false
416+ m.streamEntryStart = -1
417+ m.streamingReasoning = ""
418+ m.streamingContent = ""
419+
420+ // 8. Scroll to bottom.
421+ m.scrollOffset = 0
422+
423+ return *m
424+}