v0.20.0 29be61c

interactive_host.go RawHistoryFolder

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.extNotes = nil
123	i.parkedTurn = 0
124	i.parkedTotal = 0
125	i.mu.Unlock()
126	i.invalidate()
127}
128func (i *Interactive) SetSubagentSessionScope(_ string) {
129	i.invalidate()
130}
131func (i *Interactive) ApplyChangedCWD(ag *core.Agent, provider, model, cwd string) {
132	i.applyChangedCWD(ag, provider, model, cwd, nil)
133}
134func (i *Interactive) ApplyChangedCWDWithStartupContext(ag *core.Agent, provider, model, cwd string, startupContextPaths []string) {
135	i.applyChangedCWD(ag, provider, model, cwd, startupContextPaths)
136}
137func (i *Interactive) applyChangedCWD(ag *core.Agent, provider, model, cwd string, startupContextPaths []string) {
138	home, _ := os.UserHomeDir()
139	profiles, _ := subagents.Discover(cwd, home)
140	subagentsAddendum := subagents.SystemPromptAddendum(profiles)
141
142	i.agentMu.Lock()
143	defer i.agentMu.Unlock()
144	i.mu.Lock()
145	i.prepareReplacementAgentLocked(ag)
146	i.resetCompactContinuationLocked()
147	i.agent = ag
148	i.cfg.CWD = cwd
149	i.cfg.SubagentsSystemAddendum = subagentsAddendum
150	i.managedAutoSubagentsAddenda = autoSubagentsAddenda(i.cfg, i.autoSubagentsEnabledLocked())
151	i.cfg.StartupContextPaths = append([]string(nil), startupContextPaths...)
152	i.view.StartupContextPaths = nil
153	i.view.InvalidateRenderCache()
154	if i.cfg.ShowInstructionsAtStartup != nil && *i.cfg.ShowInstructionsAtStartup {
155		i.view.StartupContextPaths = append(i.view.StartupContextPaths, startupContextPaths...)
156	}
157	// Re-report the working directory to the terminal so "new tab here"
158	// tracks the /cd change (OSC 7, see issue #38).
159	if i.cfg.Terminal != nil {
160		if seq := tui.ReportCWD(cwd); seq != "" {
161			_, _ = i.cfg.Terminal.Write([]byte(seq))
162		}
163	}
164	i.cfg.Provider = provider
165	i.cfg.Model = model
166	titleCancel := i.titleCancel
167	i.titleCancel = nil
168	i.titleVersion++
169	i.sessionTitle = ""
170	i.titleRealPromptSeen = false
171	i.titleGenerationStarted = false
172	i.writeTerminalTitleLocked("")
173	i.toolCalls = map[string]*tui.ToolCallView{}
174	i.toolOrder = nil
175	i.toolGate = map[string]int{}
176	i.helpBlock = nil
177	i.parkedTurn = 0
178	i.statusErr = ""
179	i.mu.Unlock()
180	if titleCancel != nil {
181		titleCancel()
182	}
183	i.fileSuggest.Reset()
184	i.fileSuggest.SetCWD(cwd)
185	i.invalidate()
186}
187func (i *Interactive) SubmitSlash(text string) {
188	i.mu.Lock()
189	i.doubleEscape.Reset()
190	i.mu.Unlock()
191	text = strings.TrimSpace(text)
192	if !strings.HasPrefix(text, "/") {
193		return
194	}
195	if slashCommandCancelsTurn(text) {
196		i.cancelAndWaitForIdle()
197	}
198	i.runSlash(i.runCtx, text)
199	i.invalidate()
200}
201func (i *Interactive) SubmitOrQueue(text string, images []provider.ImageBlock) {
202	i.submitOrQueue(text, images, true)
203}
204
205// SubmitFollowUp submits a scheduler-owned prompt without interpreting shell
206// escapes or steering an active agent loop. A busy interactive waits for its
207// current turn to end, then starts this prompt as a distinct follow-up turn.
208func (i *Interactive) SubmitFollowUp(ctx context.Context, text string) error {
209	text = strings.TrimSpace(text)
210	if text == "" {
211		return fmt.Errorf("scheduled prompt is empty")
212	}
213	i.mu.Lock()
214	if i.agent == nil {
215		i.mu.Unlock()
216		return fmt.Errorf("no agent running; log in first")
217	}
218	if i.busy {
219		accepted := make(chan error, 1)
220		i.scheduled = append(i.scheduled, scheduledFollowUp{text: text, accepted: accepted})
221		i.mu.Unlock()
222		i.invalidate()
223		select {
224		case err := <-accepted:
225			return err
226		case <-ctx.Done():
227			return ctx.Err()
228		}
229	}
230	i.mu.Unlock()
231	i.startTurn(i.runCtx, text)
232	return nil
233}
234func (i *Interactive) submitOrQueue(text string, images []provider.ImageBlock, userInput bool) {
235	if cmd, ok := shellEscapeCommand(text); ok {
236		i.startShellEscape(i.runCtx, cmd)
237		return
238	}
239	i.mu.Lock()
240	if i.agent == nil {
241		i.statusErr = "not logged in. type /login first."
242		i.mu.Unlock()
243		i.invalidate()
244		return
245	}
246	i.mu.Unlock()
247	if userInput && i.cfg.EnsureMission != nil {
248		if err := i.cfg.EnsureMission(text); err != nil {
249			i.ReportError(fmt.Errorf("persist mission: %w", err))
250			return
251		}
252	}
253	// User input is an orchestration event, not merely a queue append. When
254	// the manager is dormant behind a sealed worker wave, the coordinator makes
255	// this the next manager turn and carries any completed worker summary with it.
256	if userInput && i.coordinatorAcceptsUserInput() {
257		actions := i.applyCoordinator(orchestration.Event{Kind: orchestration.EventUserInput, Text: text})
258		i.executeCoordinatorActions(actions)
259		// The coordinator has accepted the input for its sealed worker wave.
260		// It may intentionally defer an action until pending workers finish;
261		// falling through would start a normal turn and discard that wave.
262		return
263	}
264	i.maybeStartSessionTitle(i.runCtx, text)
265	i.mu.Lock()
266	if i.busy {
267		// Queue text only; images are dropped for queued prompts. Keep the
268		// interactive mutex held through Agent.QueueMessage so turn teardown
269		// cannot inspect the agent queue between the busy check and enqueue.
270		// Compaction uses the host queue because it has no active agent loop
271		// to drain Agent.QueueMessage entries.
272		var handoff json.RawMessage
273		var persistHandoff bool
274		if i.agent != nil && !i.compacting {
275			handoff, persistHandoff = i.resetCompactContinuationLocked()
276			i.agent.QueueMessage(text)
277		} else {
278			handoff, persistHandoff = i.resetCompactContinuationLocked()
279			i.queued = append(i.queued, text)
280		}
281		i.mu.Unlock()
282		if persistHandoff {
283			i.persistCompactHandoff(handoff)
284		}
285		i.invalidate()
286		return
287	}
288	i.mu.Unlock()
289	i.startTurnWithImages(i.runCtx, text, images)
290}
291func (i *Interactive) ChangelogVersion() string {
292	if i.changelogDialog != nil {
293		return i.changelogDialog.version
294	}
295	return ""
296}
297func (i *Interactive) CancelTurn() {
298	i.mu.Lock()
299	cancel := i.cancelTurn
300	i.mu.Unlock()
301	if cancel != nil {
302		i.cancelCoordinator()
303
304		i.mu.Lock()
305		handoff, persistHandoff := i.resetCompactContinuationLocked()
306		i.mu.Unlock()
307		cancel()
308		i.confirmDialog.CancelAll("turn cancelled")
309		if persistHandoff {
310			i.persistCompactHandoff(handoff)
311		}
312	}
313}
314func (i *Interactive) Insert(text string) {
315	i.ed.Insert(text)
316	i.invalidate()
317}
318func (i *Interactive) Display(extName, text string) {
319	i.appendExtensionNote(extName, text, "info")
320	i.invalidate()
321}
322func (i *Interactive) ReportError(err error) {
323	if err == nil {
324		return
325	}
326	i.mu.Lock()
327	i.statusOK = ""
328	i.statusErr = err.Error()
329	i.mu.Unlock()
330	i.invalidate()
331}
332func (i *Interactive) SetStatus(extName, key, level, text string) {
333	if strings.TrimSpace(extName) == "" || strings.TrimSpace(key) == "" {
334		return
335	}
336	i.mu.Lock()
337	if i.extStatuses == nil {
338		i.extStatuses = map[string]map[string]extensionStatus{}
339	}
340	if strings.TrimSpace(text) == "" {
341		if items := i.extStatuses[extName]; items != nil {
342			delete(items, key)
343			if len(items) == 0 {
344				delete(i.extStatuses, extName)
345			}
346		}
347	} else {
348		if i.extStatuses[extName] == nil {
349			i.extStatuses[extName] = map[string]extensionStatus{}
350		}
351		i.extStatuses[extName][key] = extensionStatus{Level: level, Text: text}
352	}
353	i.mu.Unlock()
354	i.invalidate()
355}
356func (i *Interactive) SetWidget(extName, id, position, title string, lines []string) {
357	if strings.TrimSpace(extName) == "" || strings.TrimSpace(id) == "" {
358		return
359	}
360	position = extproto.NormalizeWidgetPosition(position)
361	i.mu.Lock()
362	if i.extWidgets == nil {
363		i.extWidgets = map[string]map[string]extensionWidget{}
364	}
365	if i.extWidgets[extName] == nil {
366		i.extWidgets[extName] = map[string]extensionWidget{}
367	}
368	i.extWidgets[extName][id] = extensionWidget{
369		Position: position,
370		Title:    title,
371		Lines:    append([]string(nil), lines...),
372	}
373	i.mu.Unlock()
374	i.invalidate()
375}
376func (i *Interactive) ClearWidget(extName, id string) {
377	i.mu.Lock()
378	if items := i.extWidgets[extName]; items != nil {
379		delete(items, id)
380		if len(items) == 0 {
381			delete(i.extWidgets, extName)
382		}
383	}
384	i.mu.Unlock()
385	i.invalidate()
386}
387func (i *Interactive) ClearExtensionChrome(extName string) {
388	if strings.TrimSpace(extName) == "" {
389		return
390	}
391	marker := "[" + extName + "] "
392	i.mu.Lock()
393	changed := false
394	if _, ok := i.extStatuses[extName]; ok {
395		delete(i.extStatuses, extName)
396		changed = true
397	}
398	if _, ok := i.extWidgets[extName]; ok {
399		delete(i.extWidgets, extName)
400		changed = true
401	}
402	if len(i.extNotes) > 0 {
403		kept := i.extNotes[:0:0]
404		for _, line := range i.extNotes {
405			if strings.Contains(line, marker) {
406				changed = true
407				continue
408			}
409			kept = append(kept, line)
410		}
411		i.extNotes = kept
412	}
413	if i.extPanel != nil && i.extPanel.Active() && i.extPanel.ext == extName {
414		i.extPanel.Close()
415		changed = true
416	}
417	i.mu.Unlock()
418	if changed {
419		i.invalidate()
420	}
421}
422func (i *Interactive) OpenPanel(extName string, spec extproto.PanelSpec) {
423	i.mu.Lock()
424	defer i.mu.Unlock()
425	i.extPanel.Open(extName, spec.ID, spec.Title, spec.Lines, spec.Footer)
426	i.confirmDialog.Blur()
427	if i.cfg.Extensions != nil {
428		cols, rows := i.cfg.Terminal.Size()
429		_ = cols
430		_ = rows
431	}
432	i.invalidate()
433}
434func (i *Interactive) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
435	i.mu.Lock()
436	defer i.mu.Unlock()
437	if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
438		i.extPanel.Update(title, lines, footer)
439		i.invalidate()
440	}
441}
442func (i *Interactive) ClosePanel(extName, panelID string) {
443	i.mu.Lock()
444	defer i.mu.Unlock()
445	if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
446		i.extPanel.Close()
447		i.invalidate()
448	}
449}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close