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.subagentsDialog != nil && i.subagentsDialog.Active() ||
83 i.jumpDialog != nil && i.jumpDialog.Active() ||
84 i.btwDialog != nil && i.btwDialog.Active() ||
85 i.skillsDialog != nil && i.skillsDialog.Active() ||
86 i.changelogDialog != nil && i.changelogDialog.Active() ||
87 i.logoutDialog != nil && i.logoutDialog.Active() ||
88 i.telegramDialog != nil && i.telegramDialog.Active() ||
89 i.settingsDialog != nil && i.settingsDialog.Active() ||
90 i.sessionOpsDialog != nil && i.sessionOpsDialog.Active() ||
91 i.sessionTreeDialog != nil && i.sessionTreeDialog.Active() ||
92 i.extPanel != nil && i.extPanel.Active() ||
93 i.confirmDialog != nil && i.confirmDialog.Active() {
94 return true
95 }
96 if i.suggest != nil && i.suggest.Active(i.ed.Value()) ||
97 i.fileSuggest != nil && i.fileSuggest.Active(i.ed.Value()) {
98 return true
99 }
100 i.mu.Lock()
101 blocked := len(i.helpBlock) > 0 || len(i.extNotes) > 0
102 i.mu.Unlock()
103 return blocked
104}
105
106// canArmSessionTreeEscape checks only the cheap, local eligibility rules for
107// the first tap. The complete family read belongs to canOpenSessionTree on
108// the second tap; otherwise a malformed descendant would prevent arming and
109// the user would never receive the gate's status error.
110func (i *Interactive) canArmSessionTreeEscape() bool {
111 if i == nil || i.ed == nil || i.cfg.CWD == "" || i.sessionsRoot() == "" ||
112 i.cfg.CurrentSessionPath == nil || i.cfg.LoadSession == nil {
113 return false
114 }
115 if !i.ed.IsEmpty() || len(i.clipboardImages) != 0 || i.sessionTreeEscapeBlocked() {
116 return false
117 }
118 i.mu.Lock()
119 busy := i.busy || i.streamOn || i.streamFlushPending || len(i.streamPending) != 0 ||
120 i.shellRunning || i.compacting || i.autoCompacting || i.awaitingStartupPre || i.sessionLoading || i.modelRefreshing
121 queued := len(i.queued) != 0
122 ag := i.agent
123 pendingFork := i.pendingFork
124 i.mu.Unlock()
125 if busy || queued || pendingFork || ag == nil || ag.QueuedMessageCount() != 0 {
126 return false
127 }
128 return i.currentSessionPath() != ""
129}
130
131// canOpenSessionTree is the shared, fail-closed precondition for both the
132// /session tree command and the bare-Escape gesture. It intentionally avoids
133// filesystem work so a slow or large session family cannot stall input; the
134// asynchronous dialog loader validates the family after the overlay opens.
135func (i *Interactive) canOpenSessionTree() bool {
136 if i == nil || i.ed == nil || i.cfg.CWD == "" || i.sessionsRoot() == "" ||
137 i.cfg.CurrentSessionPath == nil || i.cfg.LoadSession == nil {
138 return false
139 }
140 if !i.ed.IsEmpty() || len(i.clipboardImages) != 0 || i.sessionTreeEscapeBlocked() {
141 return false
142 }
143
144 i.mu.Lock()
145 busy := i.busy || i.streamOn || i.streamFlushPending || len(i.streamPending) != 0 ||
146 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.streamOn || i.streamFlushPending || len(i.streamPending) != 0 ||
171 i.shellRunning || i.compacting || i.autoCompacting || i.awaitingStartupPre || i.sessionLoading || i.modelRefreshing
172 queued := len(i.queued) != 0
173 ag := i.agent
174 i.mu.Unlock()
175 if busy || queued || ag == nil || ag.QueuedMessageCount() != 0 {
176 return false
177 }
178 return i.currentSessionPath() != ""
179}
180
181func (i *Interactive) setSessionTreeError(message string) {
182 if i.sessionTreeDialog != nil {
183 i.sessionTreeDialog.Close()
184 }
185 i.mu.Lock()
186 i.statusErr = message
187 i.statusOK = ""
188 i.mu.Unlock()
189 i.invalidate()
190}
191
192// openSessionTree is the only path that activates the session-tree overlay.
193// It queues the family read rather than performing it on the input goroutine;
194// a failed asynchronous read closes the overlay and reports the usual error.
195func (i *Interactive) openSessionTree() bool {
196 if !i.canOpenSessionTree() {
197 i.setSessionTreeError("tree: session tree is unavailable")
198 return false
199 }
200 current := i.currentSessionPath()
201 if current == "" {
202 i.setSessionTreeError("tree: no session is active")
203 return false
204 }
205 if i.sessionTreeDialog == nil {
206 i.setSessionTreeError("tree: session tree is unavailable")
207 return false
208 }
209 i.mu.Lock()
210 loadCtx := i.runCtx
211 i.mu.Unlock()
212 if loadCtx == nil {
213 loadCtx = context.Background()
214 }
215 i.sessionTreeLoads = i.sessionTreeDialog.OpenSessionFamilyAsync(loadCtx, i.sessionsRoot(), i.cfg.CWD, current, i.cfg.FlushSession)
216 i.mu.Lock()
217 i.statusErr = ""
218 i.statusOK = ""
219 i.mu.Unlock()
220 i.invalidate()
221 return true
222}
223
224type sessionTreeSelectionResult struct {
225 upTo int
226 restoreDraft bool
227 draftText string
228 images []clipboardImageAttachment
229}
230
231// sessionTreeSelection turns a structured dialog target into a branch
232// boundary. User rows are boundaries before that message and restore the
233// full editable draft; assistant/tool rows include the selected completed
234// exchange. Empty and detached rows are already safe message-count
235// boundaries. A tool call and its result rows are never split.
236func sessionTreeSelection(msgs []provider.Message, target sessionTreeTarget) (sessionTreeSelectionResult, error) {
237 if target.IsBoundary() {
238 upTo := target.SelectionBoundary
239 if upTo < 0 || upTo > len(msgs) || !safeSessionToolBoundary(msgs[:upTo]) {
240 return sessionTreeSelectionResult{}, fmt.Errorf("selection splits a tool exchange")
241 }
242 return sessionTreeSelectionResult{upTo: upTo}, nil
243 }
244 msgIdx := target.EffectiveIndex
245 if msgIdx < 0 || msgIdx >= len(msgs) {
246 return sessionTreeSelectionResult{}, fmt.Errorf("selection is outside the session")
247 }
248 selected := msgs[msgIdx]
249 if selected.Role == provider.RoleUser {
250 upTo := target.SelectionBoundary
251 if upTo < 0 || upTo > len(msgs) || !safeSessionToolBoundary(msgs[:upTo]) {
252 return sessionTreeSelectionResult{}, fmt.Errorf("selection splits a tool exchange")
253 }
254 text, images := sessionTreeDraft(selected, target.UserDraft)
255 return sessionTreeSelectionResult{
256 upTo: upTo,
257 restoreDraft: true,
258 draftText: text,
259 images: images,
260 }, nil
261 }
262
263 upTo := target.SelectionBoundary
264 if upTo < msgIdx+1 || upTo > len(msgs) {
265 return sessionTreeSelectionResult{}, fmt.Errorf("selection is outside the session")
266 }
267 if selected.Role == provider.RoleAssistant && messageHasToolCall(selected) || selected.Role == provider.RoleTool {
268 // A provider tool exchange may occupy one assistant row followed by
269 // one or more tool rows. Extend a selected row to the end of that
270 // contiguous exchange before checking the boundary.
271 for upTo < len(msgs) && msgs[upTo].Role == provider.RoleTool {
272 upTo++
273 }
274 }
275 if !safeSessionToolBoundary(msgs[:upTo]) {
276 return sessionTreeSelectionResult{}, fmt.Errorf("selection splits a tool exchange")
277 }
278 return sessionTreeSelectionResult{upTo: upTo}, nil
279}
280
281func messageHasToolCall(msg provider.Message) bool {
282 for _, content := range msg.Content {
283 if _, ok := content.(provider.ToolCallBlock); ok {
284 return true
285 }
286 }
287 return false
288}
289
290// safeSessionToolBoundary checks the provider's structural invariant at a
291// message cut: every tool call in the prefix has its matching result in the
292// immediately following tool row, and no result is orphaned.
293func safeSessionToolBoundary(msgs []provider.Message) bool {
294 pending := map[string]bool{}
295 for _, msg := range msgs {
296 if len(pending) > 0 && msg.Role != provider.RoleTool {
297 return false
298 }
299 switch msg.Role {
300 case provider.RoleAssistant:
301 if len(pending) != 0 {
302 return false
303 }
304 for _, content := range msg.Content {
305 if call, ok := content.(provider.ToolCallBlock); ok {
306 if call.ID == "" || pending[call.ID] {
307 return false
308 }
309 pending[call.ID] = true
310 }
311 }
312 case provider.RoleTool:
313 if len(pending) == 0 {
314 if len(msg.AddedToolNames) > 0 {
315 // Deferred-tool activation rows intentionally carry
316 // provider-local state without a preceding tool call.
317 continue
318 }
319 return false
320 }
321 for _, content := range msg.Content {
322 result, ok := content.(provider.ToolResultBlock)
323 if !ok || !pending[result.CallID] {
324 return false
325 }
326 delete(pending, result.CallID)
327 }
328 }
329 }
330 return len(pending) == 0
331}
332
333func sessionTreeDraft(msg provider.Message, fallback string) (string, []clipboardImageAttachment) {
334 // Agent.Prompt stores the text first and appends image blocks after it,
335 // even when an older transcript contains several text blocks. Rebuild
336 // that same editor representation: join every text block, then place
337 // image markers after the complete text so submitting the restored draft
338 // recreates the original text/images pair without losing any text.
339 var textBlocks []string
340 var imageBlocks []provider.ImageBlock
341 for _, content := range msg.Content {
342 switch block := content.(type) {
343 case provider.TextBlock:
344 textBlocks = append(textBlocks, block.Text)
345 case provider.ImageBlock:
346 imageBlocks = append(imageBlocks, block)
347 }
348 }
349 var text strings.Builder
350 if len(textBlocks) > 0 {
351 text.WriteString(strings.Join(textBlocks, "\n"))
352 } else {
353 text.WriteString(fallback)
354 }
355 images := make([]clipboardImageAttachment, 0, len(imageBlocks))
356 for _, block := range imageBlocks {
357 if text.Len() > 0 {
358 last := text.String()
359 if len(last) > 0 && last[len(last)-1] != ' ' && last[len(last)-1] != '\n' && last[len(last)-1] != '\t' {
360 text.WriteByte(' ')
361 }
362 }
363 marker := fmt.Sprintf("[clipboard image #%d]", len(images)+1)
364 text.WriteString(marker)
365 text.WriteByte(' ')
366 images = append(images, clipboardImageAttachment{
367 Marker: marker,
368 Image: provider.ImageBlock{
369 MimeType: block.MimeType,
370 Data: append([]byte(nil), block.Data...),
371 ThoughtSignature: block.ThoughtSignature,
372 },
373 })
374 }
375 return text.String(), images
376}