1package modes
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "strings"
9 "time"
10
11 "github.com/bnema/zut/packages/agent/extproto"
12 "github.com/bnema/zut/packages/agent/internal/orchestration"
13 "github.com/bnema/zut/packages/agent/subagents"
14 "github.com/bnema/zut/packages/core"
15 "github.com/bnema/zut/packages/provider"
16 "github.com/bnema/zut/packages/tui"
17)
18
19func (i *Interactive) invokeExtensionCommand(ctx context.Context, name, args string) {
20 resp, err := i.cfg.Extensions.Invoke(ctx, name, args, 30*time.Second)
21 if err != nil {
22 i.mu.Lock()
23 i.statusErr = "extension /" + name + ": " + err.Error()
24 i.statusOK = ""
25 i.mu.Unlock()
26 i.invalidate()
27 return
28 }
29 if resp.Error != "" {
30 i.mu.Lock()
31 i.statusErr = "extension /" + name + ": " + resp.Error
32 i.statusOK = ""
33 i.mu.Unlock()
34 i.invalidate()
35 return
36 }
37 switch resp.Action {
38 case "open_panel":
39 if resp.OpenPanel != nil {
40 extName := name
41 if i.cfg.Extensions != nil {
42 if owner := i.cfg.Extensions.CommandOwner(name); owner != "" {
43 extName = owner
44 }
45 }
46 i.OpenPanel(extName, *resp.OpenPanel)
47 }
48 case "prompt":
49 if strings.TrimSpace(resp.Prompt) == "" {
50 return
51 }
52 i.startTurn(i.runCtx, resp.Prompt)
53 case "insert":
54 i.ed.Insert(resp.Insert)
55 i.invalidate()
56 case "display":
57 i.appendExtensionNote(name, resp.Display, "info")
58 case "noop", "":
59 // nothing
60 default:
61 i.mu.Lock()
62 i.statusErr = "extension /" + name + ": unknown action " + resp.Action
63 i.mu.Unlock()
64 i.invalidate()
65 }
66}
67func (i *Interactive) appendExtensionNote(extName, msg, level string) {
68 if msg == "" {
69 return
70 }
71 i.mu.Lock()
72 defer i.mu.Unlock()
73 color := i.cfg.Theme.Muted
74 switch level {
75 case "warn":
76 color = i.cfg.Theme.Warning
77 case "error":
78 color = i.cfg.Theme.Error
79 case "success":
80 color = i.cfg.Theme.Tool
81 }
82 prefix := i.cfg.Theme.FGColor(i.cfg.Theme.Accent, "["+extName+"] ")
83 for _, line := range strings.Split(msg, "\n") {
84 i.statusOK = "" // clear any stale ok
85 i.statusErr = ""
86 i.extNotes = append(i.extNotes, prefix+i.cfg.Theme.FGColor(color, line))
87 }
88 // Extension slash commands complete asynchronously. If their result is
89 // displayed while confirmation is waiting, keep Esc assigned to the note
90 // until it is dismissed rather than letting it answer the tool call.
91 i.confirmDialog.Blur()
92}
93func (i *Interactive) ApplySessionAgent(ag *core.Agent, providerName, model string) {
94 i.ApplySessionAgentWithCompactHandoff(ag, providerName, model, nil)
95}
96func (i *Interactive) ApplySessionAgentWithCompactHandoff(ag *core.Agent, providerName, model string, compactHandoff json.RawMessage) {
97 if ag == nil {
98 return
99 }
100 i.agentMu.Lock()
101 defer i.agentMu.Unlock()
102 i.mu.Lock()
103 i.prepareReplacementAgentLocked(ag)
104 i.compactContinuation = decodeCompactHandoff(compactHandoff)
105 i.agent = ag
106 i.cfg.Provider = providerName
107 i.cfg.Model = model
108 i.view.Messages = filterHiddenTranscriptMessages(ag.Messages())
109 i.cumUsage = ag.Cost()
110 last := ag.LastTurnUsage()
111 i.lastCtxInput = last.InputTokens + last.CacheReadTokens + last.CacheWriteTokens
112 if len(i.view.Messages) > initialResumeTailLimit {
113 i.view.TailLimit = initialResumeTailLimit
114 } else {
115 i.view.TailLimit = 0
116 }
117 i.view.InvalidateRenderCache()
118 i.toolCalls = map[string]*tui.ToolCallView{}
119 i.toolOrder = nil
120 i.toolGate = map[string]int{}
121 i.helpBlock = nil
122 i.sessionInfoBlocks = nil
123 i.extNotes = nil
124 i.parkedTurn = 0
125 i.parkedTotal = 0
126 i.mu.Unlock()
127 i.invalidate()
128}
129func (i *Interactive) SetSubagentSessionScope(_ string) {
130 i.invalidate()
131}
132func (i *Interactive) ApplyChangedCWD(ag *core.Agent, provider, model, cwd string) {
133 i.applyChangedCWD(ag, provider, model, cwd, nil)
134}
135func (i *Interactive) ApplyChangedCWDWithStartupContext(ag *core.Agent, provider, model, cwd string, startupContextPaths []string) {
136 i.applyChangedCWD(ag, provider, model, cwd, startupContextPaths)
137}
138func (i *Interactive) applyChangedCWD(ag *core.Agent, provider, model, cwd string, startupContextPaths []string) {
139 home, _ := os.UserHomeDir()
140 profiles, _ := subagents.Discover(cwd, home)
141 subagentsAddendum := subagents.SystemPromptAddendum(profiles)
142
143 i.agentMu.Lock()
144 defer i.agentMu.Unlock()
145 i.mu.Lock()
146 i.prepareReplacementAgentLocked(ag)
147 i.resetCompactContinuationLocked()
148 i.agent = ag
149 i.cfg.CWD = cwd
150 i.cfg.SubagentsSystemAddendum = subagentsAddendum
151 i.managedAutoSubagentsAddenda = autoSubagentsAddenda(i.cfg, i.autoSubagentsEnabledLocked())
152 i.cfg.StartupContextPaths = append([]string(nil), startupContextPaths...)
153 i.view.StartupContextPaths = nil
154 i.view.InvalidateRenderCache()
155 if i.cfg.ShowInstructionsAtStartup != nil && *i.cfg.ShowInstructionsAtStartup {
156 i.view.StartupContextPaths = append(i.view.StartupContextPaths, startupContextPaths...)
157 }
158 // Re-report the working directory to the terminal so "new tab here"
159 // tracks the /cd change (OSC 7, see issue #38).
160 if i.cfg.Terminal != nil {
161 if seq := tui.ReportCWD(cwd); seq != "" {
162 _, _ = i.cfg.Terminal.Write([]byte(seq))
163 }
164 }
165 i.cfg.Provider = provider
166 i.cfg.Model = model
167 titleCancel := i.titleCancel
168 i.titleCancel = nil
169 i.titleVersion++
170 i.sessionTitle = ""
171 i.titleRealPromptSeen = false
172 i.titleGenerationStarted = false
173 i.writeTerminalTitleLocked("")
174 i.toolCalls = map[string]*tui.ToolCallView{}
175 i.toolOrder = nil
176 i.toolGate = map[string]int{}
177 i.helpBlock = nil
178 i.sessionInfoBlocks = nil
179 i.parkedTurn = 0
180 i.statusErr = ""
181 i.mu.Unlock()
182 if titleCancel != nil {
183 titleCancel()
184 }
185 i.fileSuggest.Reset()
186 i.fileSuggest.SetCWD(cwd)
187 i.invalidate()
188}
189func (i *Interactive) SubmitSlash(text string) {
190 i.mu.Lock()
191 i.doubleEscape.Reset()
192 i.mu.Unlock()
193 text = strings.TrimSpace(text)
194 if !strings.HasPrefix(text, "/") {
195 return
196 }
197 if slashCommandCancelsTurn(text) {
198 i.cancelAndWaitForIdle()
199 }
200 i.runSlash(i.runCtx, text)
201 i.invalidate()
202}
203func (i *Interactive) SubmitOrQueue(text string, images []provider.ImageBlock) {
204 i.submitOrQueue(text, images, true)
205}
206
207// SubmitFollowUp submits a scheduler-owned prompt without interpreting shell
208// escapes or steering an active agent loop. A busy interactive waits for its
209// current turn to end, then starts this prompt as a distinct follow-up turn.
210func (i *Interactive) SubmitFollowUp(ctx context.Context, text string) error {
211 text = strings.TrimSpace(text)
212 if text == "" {
213 return fmt.Errorf("scheduled prompt is empty")
214 }
215 i.mu.Lock()
216 if i.agent == nil {
217 i.mu.Unlock()
218 return fmt.Errorf("no agent running; log in first")
219 }
220 if i.busy {
221 accepted := make(chan error, 1)
222 i.scheduled = append(i.scheduled, scheduledFollowUp{text: text, accepted: accepted})
223 i.mu.Unlock()
224 i.invalidate()
225 select {
226 case err := <-accepted:
227 return err
228 case <-ctx.Done():
229 return ctx.Err()
230 }
231 }
232 i.mu.Unlock()
233 i.startTurn(i.runCtx, text)
234 return nil
235}
236func (i *Interactive) submitOrQueue(text string, images []provider.ImageBlock, userInput bool) {
237 if cmd, ok := shellEscapeCommand(text); ok {
238 i.startShellEscape(i.runCtx, cmd)
239 return
240 }
241 i.mu.Lock()
242 if i.agent == nil {
243 i.statusErr = "not logged in. type /login first."
244 i.mu.Unlock()
245 i.invalidate()
246 return
247 }
248 i.mu.Unlock()
249 if userInput && i.cfg.EnsureMission != nil {
250 if err := i.cfg.EnsureMission(text); err != nil {
251 i.ReportError(fmt.Errorf("persist mission: %w", err))
252 return
253 }
254 }
255 // User input is an orchestration event, not merely a queue append. When
256 // the manager is dormant behind a sealed worker wave, the coordinator makes
257 // this the next manager turn and carries any completed worker summary with it.
258 if userInput && i.coordinatorAcceptsUserInput() {
259 actions := i.applyCoordinator(orchestration.Event{Kind: orchestration.EventUserInput, Text: text, Images: images})
260 i.executeCoordinatorActions(actions)
261 // The coordinator has accepted the input for its sealed worker wave.
262 // It may intentionally defer an action until pending workers finish;
263 // falling through would start a normal turn and discard that wave.
264 return
265 }
266 i.maybeStartSessionTitle(i.runCtx, text)
267 i.mu.Lock()
268 if i.busy {
269 // Keep the interactive mutex held through Agent.QueueMessage so turn teardown
270 // cannot inspect the agent queue between the busy check and enqueue.
271 // Compaction uses the host queue because it has no active agent loop
272 // to drain Agent.QueueMessage entries.
273 var handoff json.RawMessage
274 var persistHandoff bool
275 if i.agent != nil && !i.compacting {
276 handoff, persistHandoff = i.resetCompactContinuationLocked()
277 i.agent.QueueMessage(text, images)
278 } else {
279 handoff, persistHandoff = i.resetCompactContinuationLocked()
280 i.queued = append(i.queued, core.QueuedMessage{Text: text, Images: images})
281 }
282 i.mu.Unlock()
283 if persistHandoff {
284 i.persistCompactHandoff(handoff)
285 }
286 i.invalidate()
287 return
288 }
289 i.mu.Unlock()
290 i.startTurnWithImages(i.runCtx, text, images)
291}
292func (i *Interactive) ChangelogVersion() string {
293 if i.changelogDialog != nil {
294 return i.changelogDialog.version
295 }
296 return ""
297}
298func (i *Interactive) CancelTurn() {
299 i.mu.Lock()
300 cancel := i.cancelTurn
301 i.mu.Unlock()
302 if cancel != nil {
303 i.cancelCoordinator()
304
305 i.mu.Lock()
306 handoff, persistHandoff := i.resetCompactContinuationLocked()
307 i.mu.Unlock()
308 cancel()
309 i.confirmDialog.CancelAll("turn cancelled")
310 if persistHandoff {
311 i.persistCompactHandoff(handoff)
312 }
313 }
314}
315func (i *Interactive) Insert(text string) {
316 i.ed.Insert(text)
317 i.invalidate()
318}
319func (i *Interactive) Display(extName, text string) {
320 i.appendExtensionNote(extName, text, "info")
321 i.invalidate()
322}
323func (i *Interactive) ReportError(err error) {
324 if err == nil {
325 return
326 }
327 i.mu.Lock()
328 i.statusOK = ""
329 i.statusErr = err.Error()
330 i.mu.Unlock()
331 i.invalidate()
332}
333func (i *Interactive) SetStatus(extName, key, level, text string) {
334 if strings.TrimSpace(extName) == "" || strings.TrimSpace(key) == "" {
335 return
336 }
337 i.mu.Lock()
338 if i.extStatuses == nil {
339 i.extStatuses = map[string]map[string]extensionStatus{}
340 }
341 if strings.TrimSpace(text) == "" {
342 if items := i.extStatuses[extName]; items != nil {
343 delete(items, key)
344 if len(items) == 0 {
345 delete(i.extStatuses, extName)
346 }
347 }
348 } else {
349 if i.extStatuses[extName] == nil {
350 i.extStatuses[extName] = map[string]extensionStatus{}
351 }
352 i.extStatuses[extName][key] = extensionStatus{Level: level, Text: text}
353 }
354 i.mu.Unlock()
355 i.invalidate()
356}
357func (i *Interactive) SetWidget(extName, id, position, title string, lines []string) {
358 if strings.TrimSpace(extName) == "" || strings.TrimSpace(id) == "" {
359 return
360 }
361 position = extproto.NormalizeWidgetPosition(position)
362 i.mu.Lock()
363 if i.extWidgets == nil {
364 i.extWidgets = map[string]map[string]extensionWidget{}
365 }
366 if i.extWidgets[extName] == nil {
367 i.extWidgets[extName] = map[string]extensionWidget{}
368 }
369 i.extWidgets[extName][id] = extensionWidget{
370 Position: position,
371 Title: title,
372 Lines: append([]string(nil), lines...),
373 }
374 i.mu.Unlock()
375 i.invalidate()
376}
377func (i *Interactive) ClearWidget(extName, id string) {
378 i.mu.Lock()
379 if items := i.extWidgets[extName]; items != nil {
380 delete(items, id)
381 if len(items) == 0 {
382 delete(i.extWidgets, extName)
383 }
384 }
385 i.mu.Unlock()
386 i.invalidate()
387}
388func (i *Interactive) ClearExtensionChrome(extName string) {
389 if strings.TrimSpace(extName) == "" {
390 return
391 }
392 marker := "[" + extName + "] "
393 i.mu.Lock()
394 changed := false
395 if _, ok := i.extStatuses[extName]; ok {
396 delete(i.extStatuses, extName)
397 changed = true
398 }
399 if _, ok := i.extWidgets[extName]; ok {
400 delete(i.extWidgets, extName)
401 changed = true
402 }
403 if len(i.extNotes) > 0 {
404 kept := i.extNotes[:0:0]
405 for _, line := range i.extNotes {
406 if strings.Contains(line, marker) {
407 changed = true
408 continue
409 }
410 kept = append(kept, line)
411 }
412 i.extNotes = kept
413 }
414 if i.extPanel != nil && i.extPanel.Active() && i.extPanel.ext == extName {
415 i.extPanel.Close()
416 changed = true
417 }
418 i.mu.Unlock()
419 if changed {
420 i.invalidate()
421 }
422}
423func (i *Interactive) OpenPanel(extName string, spec extproto.PanelSpec) {
424 i.mu.Lock()
425 defer i.mu.Unlock()
426 i.extPanel.Open(extName, spec.ID, spec.Title, spec.Lines, spec.Footer)
427 i.confirmDialog.Blur()
428 if i.cfg.Extensions != nil {
429 cols, rows := i.cfg.Terminal.Size()
430 _ = cols
431 _ = rows
432 }
433 i.invalidate()
434}
435func (i *Interactive) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
436 i.mu.Lock()
437 defer i.mu.Unlock()
438 if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
439 i.extPanel.Update(title, lines, footer)
440 i.invalidate()
441 }
442}
443func (i *Interactive) ClosePanel(extName, panelID string) {
444 i.mu.Lock()
445 defer i.mu.Unlock()
446 if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
447 i.extPanel.Close()
448 i.invalidate()
449 }
450}