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