1package modes
2
3import (
4 "context"
5 "fmt"
6 "strings"
7 "time"
8
9 "github.com/bnema/zut/packages/provider"
10 "github.com/bnema/zut/packages/tui"
11)
12
13const sessionTreeEscapeWindow = 500 * time.Millisecond
14
15type doubleEscapeTracker struct {
16 last time.Time
17 armed bool
18}
19
20func (d *doubleEscapeTracker) Arm(now time.Time) {
21 d.last = now
22 d.armed = true
23}
24
25// Consume reports whether now is the second tap of a valid gesture. A clock
26// that moves backwards is treated as a reset rather than as a valid tap.
27func (d *doubleEscapeTracker) Consume(now time.Time) bool {
28 last := d.last
29 armed := d.armed
30 d.last = time.Time{}
31 d.armed = false
32 if !armed {
33 return false
34 }
35 elapsed := now.Sub(last)
36 return elapsed >= 0 && elapsed <= sessionTreeEscapeWindow
37}
38
39func (d *doubleEscapeTracker) Reset() {
40 d.last = time.Time{}
41 d.armed = false
42}
43
44func isUnmodifiedEscape(k tui.Key) bool {
45 return k.Kind == tui.KeyEsc && !k.Ctrl && !k.Alt && !k.Shift && !k.Super
46}
47
48func (i *Interactive) sessionTreeEscapeNow() time.Time {
49 if i.clock != nil {
50 return i.clock()
51 }
52 return time.Now()
53}
54
55// currentSessionPath is the nil-safe session callback shared by slash
56// commands and tree operations. Running without persistence (for example
57// --no-session) is a supported mode, so callers must treat a missing
58// callback exactly like an empty path rather than invoking it blindly.
59func (i *Interactive) currentSessionPath() string {
60 if i == nil || i.cfg.CurrentSessionPath == nil {
61 return ""
62 }
63 return i.cfg.CurrentSessionPath()
64}
65
66// sessionTreeEscapeBlocked reports interactions that must retain precedence
67// over the gesture. It is intentionally broader than the overlay switch in
68// handleKey: notes and suggestions also own Escape even though they are not
69// all rendered as dialogs.
70func (i *Interactive) sessionTreeEscapeBlocked() bool {
71 if i == nil {
72 return true
73 }
74 if i.ed == nil {
75 return true
76 }
77 if i.dialog != nil && i.dialog.Active() ||
78 i.modelDialog != nil && i.modelDialog.Active() ||
79 i.llamaDialog != nil && i.llamaDialog.Active() ||
80 i.rescueDialog != nil && i.rescueDialog.Active() ||
81 i.sessionDialog != nil && i.sessionDialog.Active() ||
82 i.residentSubagentsDialog != nil && i.residentSubagentsDialog.Active() ||
83 i.residentChildSession != nil ||
84 i.jumpDialog != nil && i.jumpDialog.Active() ||
85 i.btwDialog != nil && i.btwDialog.Active() ||
86 i.skillsDialog != nil && i.skillsDialog.Active() ||
87 i.changelogDialog != nil && i.changelogDialog.Active() ||
88 i.logoutDialog != nil && i.logoutDialog.Active() ||
89 i.telegramDialog != nil && i.telegramDialog.Active() ||
90 i.settingsDialog != nil && i.settingsDialog.Active() ||
91 i.sessionOpsDialog != nil && i.sessionOpsDialog.Active() ||
92 i.sessionTreeDialog != nil && i.sessionTreeDialog.Active() ||
93 i.timeline != nil && i.timeline.Active() ||
94 i.extPanel != nil && i.extPanel.Active() ||
95 i.confirmDialog != nil && i.confirmDialog.Active() {
96 return true
97 }
98 if i.suggest != nil && i.suggest.Active(i.ed.Value()) ||
99 i.fileSuggest != nil && i.fileSuggest.Active(i.ed.Value()) {
100 return true
101 }
102 i.mu.Lock()
103 blocked := len(i.helpBlock) > 0 || len(i.extNotes) > 0
104 i.mu.Unlock()
105 return blocked
106}
107
108// canArmSessionTreeEscape checks only the cheap, local eligibility rules for
109// the first tap. The complete family read belongs to canOpenSessionTree on
110// the second tap; otherwise a malformed descendant would prevent arming and
111// the user would never receive the gate's status error.
112func (i *Interactive) canArmSessionTreeEscape() bool {
113 if i == nil || i.ed == nil || i.cfg.CWD == "" || i.sessionsRoot() == "" ||
114 i.cfg.CurrentSessionPath == nil || i.cfg.LoadSession == nil {
115 return false
116 }
117 if !i.ed.IsEmpty() || len(i.clipboardImages) != 0 || i.sessionTreeEscapeBlocked() {
118 return false
119 }
120 i.mu.Lock()
121 busy := i.busy || i.stream.Active() || i.shellRunning || i.compacting || i.autoCompacting || i.awaitingStartupPre || i.sessionLoading || i.modelRefreshing
122 queued := len(i.queued) != 0
123 ag := i.agent
124 pendingFork := i.pendingFork
125 i.mu.Unlock()
126 if busy || queued || pendingFork || ag == nil || ag.QueuedMessageCount() != 0 {
127 return false
128 }
129 return i.currentSessionPath() != ""
130}
131
132// canOpenSessionTree is the shared, fail-closed precondition for both the
133// /session tree command and the bare-Escape gesture. It intentionally avoids
134// filesystem work so a slow or large session family cannot stall input; the
135// asynchronous dialog loader validates the family after the overlay opens.
136func (i *Interactive) canOpenSessionTree() bool {
137 if i == nil || i.ed == nil || i.cfg.CWD == "" || i.sessionsRoot() == "" ||
138 i.cfg.CurrentSessionPath == nil || i.cfg.LoadSession == nil {
139 return false
140 }
141 if !i.ed.IsEmpty() || len(i.clipboardImages) != 0 || i.sessionTreeEscapeBlocked() {
142 return false
143 }
144
145 i.mu.Lock()
146 busy := i.busy || i.stream.Active() || i.shellRunning || i.compacting || i.autoCompacting || i.awaitingStartupPre || i.sessionLoading || i.modelRefreshing
147 queued := len(i.queued) != 0
148 ag := i.agent
149 pendingFork := i.pendingFork
150 i.mu.Unlock()
151 if busy || queued || pendingFork || ag == nil {
152 return false
153 }
154 if ag.QueuedMessageCount() != 0 {
155 return false
156 }
157
158 return i.currentSessionPath() != ""
159}
160
161// canCommitSessionTreeSelection is the open-gate subset used after the tree
162// already owns the keyboard. It deliberately permits the active tree dialog;
163// reusing canOpenSessionTree here would reject every Enter selection because
164// the dialog is itself an overlay.
165func (i *Interactive) canCommitSessionTreeSelection() bool {
166 if i == nil || i.cfg.CurrentSessionPath == nil || i.cfg.LoadSession == nil || i.sessionsRoot() == "" || i.cfg.CWD == "" {
167 return false
168 }
169 i.mu.Lock()
170 busy := i.busy || i.stream.Active() || i.shellRunning || i.compacting || i.autoCompacting || i.awaitingStartupPre || i.sessionLoading || i.modelRefreshing
171 queued := len(i.queued) != 0
172 ag := i.agent
173 i.mu.Unlock()
174 if busy || queued || ag == nil || ag.QueuedMessageCount() != 0 {
175 return false
176 }
177 return i.currentSessionPath() != ""
178}
179
180func (i *Interactive) setSessionTreeError(message string) {
181 if i.sessionTreeDialog != nil {
182 i.sessionTreeDialog.Close()
183 }
184 i.mu.Lock()
185 i.statusErr = message
186 i.statusOK = ""
187 i.mu.Unlock()
188 i.invalidate()
189}
190
191// openSessionTree is the only path that activates the session-tree overlay.
192// It queues the family read rather than performing it on the input goroutine;
193// a failed asynchronous read closes the overlay and reports the usual error.
194func (i *Interactive) openSessionTree() bool {
195 if !i.canOpenSessionTree() {
196 i.setSessionTreeError("tree: session tree is unavailable")
197 return false
198 }
199 current := i.currentSessionPath()
200 if current == "" {
201 i.setSessionTreeError("tree: no session is active")
202 return false
203 }
204 if i.sessionTreeDialog == nil {
205 i.setSessionTreeError("tree: session tree is unavailable")
206 return false
207 }
208 i.mu.Lock()
209 loadCtx := i.runCtx
210 i.mu.Unlock()
211 if loadCtx == nil {
212 loadCtx = context.Background()
213 }
214 i.sessionTreeLoads = i.sessionTreeDialog.OpenSessionFamilyAsync(loadCtx, i.sessionsRoot(), i.cfg.CWD, current, i.cfg.FlushSession)
215 i.mu.Lock()
216 i.statusErr = ""
217 i.statusOK = ""
218 i.mu.Unlock()
219 i.invalidate()
220 return true
221}
222
223type sessionTreeSelectionResult struct {
224 upTo int
225 restoreDraft bool
226 draftText string
227 images []clipboardImageAttachment
228}
229
230// sessionTreeSelection turns a structured dialog target into a branch
231// boundary. User rows are boundaries before that message and restore the
232// full editable draft; assistant/tool rows include the selected completed
233// exchange. Empty and detached rows are already safe message-count
234// boundaries. A tool call and its result rows are never split.
235func sessionTreeSelection(msgs []provider.Message, target sessionTreeTarget) (sessionTreeSelectionResult, error) {
236 if target.IsBoundary() {
237 upTo := target.SelectionBoundary
238 if upTo < 0 || upTo > len(msgs) || !safeSessionToolBoundary(msgs[:upTo]) {
239 return sessionTreeSelectionResult{}, fmt.Errorf("selection splits a tool exchange")
240 }
241 return sessionTreeSelectionResult{upTo: upTo}, nil
242 }
243 msgIdx := target.EffectiveIndex
244 if msgIdx < 0 || msgIdx >= len(msgs) {
245 return sessionTreeSelectionResult{}, fmt.Errorf("selection is outside the session")
246 }
247 selected := msgs[msgIdx]
248 if selected.Role == provider.RoleUser {
249 upTo := target.SelectionBoundary
250 if upTo < 0 || upTo > len(msgs) || !safeSessionToolBoundary(msgs[:upTo]) {
251 return sessionTreeSelectionResult{}, fmt.Errorf("selection splits a tool exchange")
252 }
253 text, images := sessionTreeDraft(selected, target.UserDraft)
254 return sessionTreeSelectionResult{
255 upTo: upTo,
256 restoreDraft: true,
257 draftText: text,
258 images: images,
259 }, nil
260 }
261
262 upTo := target.SelectionBoundary
263 if upTo < msgIdx+1 || upTo > len(msgs) {
264 return sessionTreeSelectionResult{}, fmt.Errorf("selection is outside the session")
265 }
266 if selected.Role == provider.RoleAssistant && messageHasToolCall(selected) || selected.Role == provider.RoleTool {
267 // A provider tool exchange may occupy one assistant row followed by
268 // one or more tool rows. Extend a selected row to the end of that
269 // contiguous exchange before checking the boundary.
270 for upTo < len(msgs) && msgs[upTo].Role == provider.RoleTool {
271 upTo++
272 }
273 }
274 if !safeSessionToolBoundary(msgs[:upTo]) {
275 return sessionTreeSelectionResult{}, fmt.Errorf("selection splits a tool exchange")
276 }
277 return sessionTreeSelectionResult{upTo: upTo}, nil
278}
279
280func messageHasToolCall(msg provider.Message) bool {
281 for _, content := range msg.Content {
282 if _, ok := content.(provider.ToolCallBlock); ok {
283 return true
284 }
285 }
286 return false
287}
288
289// safeSessionToolBoundary checks the provider's structural invariant at a
290// message cut: every tool call in the prefix has its matching result in the
291// immediately following tool row, and no result is orphaned.
292func safeSessionToolBoundary(msgs []provider.Message) bool {
293 pending := map[string]bool{}
294 for _, msg := range msgs {
295 if len(pending) > 0 && msg.Role != provider.RoleTool {
296 return false
297 }
298 switch msg.Role {
299 case provider.RoleAssistant:
300 if len(pending) != 0 {
301 return false
302 }
303 for _, content := range msg.Content {
304 if call, ok := content.(provider.ToolCallBlock); ok {
305 if call.ID == "" || pending[call.ID] {
306 return false
307 }
308 pending[call.ID] = true
309 }
310 }
311 case provider.RoleTool:
312 if len(pending) == 0 {
313 if len(msg.AddedToolNames) > 0 {
314 // Deferred-tool activation rows intentionally carry
315 // provider-local state without a preceding tool call.
316 continue
317 }
318 return false
319 }
320 for _, content := range msg.Content {
321 result, ok := content.(provider.ToolResultBlock)
322 if !ok || !pending[result.CallID] {
323 return false
324 }
325 delete(pending, result.CallID)
326 }
327 }
328 }
329 return len(pending) == 0
330}
331
332func sessionTreeDraft(msg provider.Message, fallback string) (string, []clipboardImageAttachment) {
333 // Agent.Prompt stores the text first and appends image blocks after it,
334 // even when an older transcript contains several text blocks. Rebuild
335 // that same editor representation: join every text block, then place
336 // image markers after the complete text so submitting the restored draft
337 // recreates the original text/images pair without losing any text.
338 var textBlocks []string
339 var imageBlocks []provider.ImageBlock
340 for _, content := range msg.Content {
341 switch block := content.(type) {
342 case provider.TextBlock:
343 textBlocks = append(textBlocks, block.Text)
344 case provider.ImageBlock:
345 imageBlocks = append(imageBlocks, block)
346 }
347 }
348 var text strings.Builder
349 if len(textBlocks) > 0 {
350 text.WriteString(strings.Join(textBlocks, "\n"))
351 } else {
352 text.WriteString(fallback)
353 }
354 images := make([]clipboardImageAttachment, 0, len(imageBlocks))
355 for _, block := range imageBlocks {
356 if text.Len() > 0 {
357 last := text.String()
358 if len(last) > 0 && last[len(last)-1] != ' ' && last[len(last)-1] != '\n' && last[len(last)-1] != '\t' {
359 text.WriteByte(' ')
360 }
361 }
362 marker := fmt.Sprintf("[clipboard image #%d]", len(images)+1)
363 text.WriteString(marker)
364 text.WriteByte(' ')
365 images = append(images, clipboardImageAttachment{
366 Marker: marker,
367 Image: provider.ImageBlock{
368 MimeType: block.MimeType,
369 Data: append([]byte(nil), block.Data...),
370 ThoughtSignature: block.ThoughtSignature,
371 },
372 })
373 }
374 return text.String(), images
375}