v0.0.3 c0f685f

interactive.go RawHistoryFolder

1package modes
2
3import (
4	"context"
5	"encoding/json"
6	"fmt"
7	"strings"
8	"sync"
9	"time"
10
11	"github.com/patriceckhart/zot/internal/agent/tools"
12	"github.com/patriceckhart/zot/internal/auth"
13	"github.com/patriceckhart/zot/internal/core"
14	"github.com/patriceckhart/zot/internal/provider"
15	"github.com/patriceckhart/zot/internal/tui"
16)
17
18// InteractiveConfig configures the interactive loop.
19type InteractiveConfig struct {
20	Terminal     tui.Terminal
21	Theme        tui.Theme
22	Model        string
23	Provider     string
24	AuthMethod   string // "apikey" | "oauth" — used to tag cost as (sub) in status bar
25	BaseURL      string
26	Reasoning    string
27	SystemPrompt string
28	Tools        core.Registry
29	MaxSteps     int
30	CWD          string
31
32	// Agent is optional. If nil, zot opens without credentials; the
33	// user must /login before they can prompt.
34	Agent *core.Agent
35
36	InitialInput string
37
38	// Auth is required. When the user runs /login, Interactive talks to
39	// AuthManager to open a browser and wait for the callback.
40	AuthManager *auth.Manager
41	// BuildAgent is called after a successful login to (re)construct the
42	// agent with the fresh credential. It returns the new agent and
43	// the concrete provider/model in use.
44	BuildAgent func() (*core.Agent, string, string, error)
45
46	// BuildAgentFor rebuilds the agent with an explicit provider/model
47	// override (used by the /model picker when switching providers).
48	// If providerOverride is empty, the current provider is kept.
49	BuildAgentFor func(providerOverride, modelOverride string) (*core.Agent, string, string, error)
50
51	// ZotHome is the root directory for sessions/, used by /sessions.
52	ZotHome string
53
54	// Sandbox is the shared sandbox pointer. Toggled by /lock and /unlock.
55	Sandbox *tools.Sandbox
56
57	// LoadSession swaps the current session for the one at path. The
58	// callback returns the new agent message slice so the TUI can invalidate.
59	LoadSession func(path string) error
60
61	// PersistModel is called whenever the user switches model or provider.
62	// It should update config.json and (if there's an active session)
63	// write a new meta row so resume picks up the same model.
64	PersistModel func(providerName, model string)
65
66	OnAssistant  func(m provider.Message)
67	OnToolResult func(id string, r core.ToolResult)
68}
69
70// Interactive is the TUI chat loop.
71type Interactive struct {
72	cfg  InteractiveConfig
73	view *tui.View
74	ed   *tui.Editor
75	rend *tui.Renderer
76
77	mu           sync.Mutex
78	agent        *core.Agent
79	streaming    strings.Builder
80	streamOn     bool
81	toolCalls    map[string]*tui.ToolCallView
82	toolOrder    []string
83	statusErr    string
84	statusOK     string
85	helpBlock    []string // rendered above the chat when /help was typed
86	cumUsage     provider.Usage
87	lastCtxInput int // input_tokens of the most recent turn — approximates current context size
88	busy         bool
89	dirty        chan struct{}
90	cancelTurn   context.CancelFunc
91	scrollOffset int // rows from the bottom; 0 = pinned to latest
92
93	// Messages typed while a turn is in flight. Each is delivered as
94	// its own follow-up turn once the current one finishes. Rendered
95	// above the status bar as "sliding in: ..." chips.
96	queued []string
97
98	// runCtx is the top-level context passed to Run(). Follow-up turns
99	// drained from `queued` are started against this context so they
100	// survive past the ctx of the key event that enqueued them.
101	runCtx context.Context
102
103	// autoCompacting is true while a model-triggered compaction is in
104	// flight. Surfaced in the status bar so the user can tell a
105	// condense pass from a regular assistant turn.
106	autoCompacting bool
107
108	dialog        *loginDialog
109	modelDialog   *modelDialog
110	sessionDialog *sessionDialog
111	suggest       *slashSuggester
112	spin          *spinner
113}
114
115// NewInteractive constructs an Interactive from cfg.
116func NewInteractive(cfg InteractiveConfig) *Interactive {
117	i := &Interactive{
118		cfg: cfg,
119		view: &tui.View{
120			Theme:      cfg.Theme,
121			ImageProto: tui.DetectImageProtocol(),
122		},
123		ed:            tui.NewEditor(cfg.Theme.FG256(cfg.Theme.Accent, "▌ ")),
124		rend:          tui.NewRenderer(cfg.Terminal),
125		toolCalls:     map[string]*tui.ToolCallView{},
126		dirty:         make(chan struct{}, 8),
127		dialog:        newLoginDialog(),
128		modelDialog:   newModelDialog(),
129		sessionDialog: newSessionDialog(),
130		suggest:       newSlashSuggester(),
131		spin:          newSpinner(),
132	}
133	if cfg.Agent != nil {
134		i.agent = cfg.Agent
135		i.view.Messages = cfg.Agent.Messages()
136	}
137	return i
138}
139
140// Run blocks until the user quits.
141func (i *Interactive) Run(ctx context.Context) error {
142	i.runCtx = ctx
143	term := i.cfg.Terminal
144	restore, err := term.EnterRaw()
145	if err != nil {
146		return err
147	}
148	defer restore()
149
150	_, _ = term.Write([]byte(tui.SeqBracketedPasteOn))
151	_, _ = term.Write([]byte(tui.SeqAltScreenOn))
152	defer term.Write([]byte(tui.SeqAltScreenOff + tui.SeqBracketedPasteOff + tui.SeqShowCursor))
153
154	cols, rows := term.Size()
155	i.rend.Resize(cols, rows)
156	term.OnResize(func() {
157		c, r := term.Size()
158		i.rend.Resize(c, r)
159		i.invalidate()
160	})
161
162	if i.cfg.InitialInput != "" {
163		i.ed.SetValue(i.cfg.InitialInput)
164	}
165
166	// No credential at startup? Auto-open the login dialog, and mark
167	// the status line. The user can Esc out of the dialog if they
168	// want to dismiss it (e.g. to check /help or /exit first).
169	if i.agent == nil {
170		i.statusErr = "not logged in. pick a login method below or press esc to dismiss."
171		i.dialog.Open()
172	}
173
174	// Input goroutine.
175	keys := make(chan tui.Key, 8)
176	go func() {
177		reader := tui.NewReaderWithPeek(term.ReadByte, term.PeekByteTimeout)
178		for {
179			k, err := reader.Read()
180			if err != nil {
181				return
182			}
183			keys <- k
184		}
185	}()
186
187	// Subscribe to auth events.
188	var authEvents <-chan auth.Event
189	if i.cfg.AuthManager != nil {
190		authEvents = i.cfg.AuthManager.Events()
191	}
192
193	// Animation ticker: drives spinner and dialog-related redraws when
194	// nothing else changed. 120ms is slow enough that highlighting a huge
195	// transcript doesn't spin the cpu.
196	tick := time.NewTicker(120 * time.Millisecond)
197	defer tick.Stop()
198
199	// Redraw throttle: coalesce bursts of invalidate() calls so we paint
200	// at most once every redrawMinInterval. Huge tool-result dumps can
201	// fire hundreds of invalidations while the user is typing; without
202	// this, the input goroutine never gets CPU and keystrokes lag.
203	const redrawMinInterval = 16 * time.Millisecond
204	var lastRedraw time.Time
205	var pendingRedraw bool
206	var pendingTimer *time.Timer
207
208	drainPending := func() {
209		if pendingTimer != nil {
210			pendingTimer.Stop()
211			pendingTimer = nil
212		}
213		if pendingRedraw {
214			pendingRedraw = false
215			lastRedraw = time.Now()
216			i.redraw()
217		}
218	}
219
220	requestRedraw := func() {
221		since := time.Since(lastRedraw)
222		if since >= redrawMinInterval {
223			lastRedraw = time.Now()
224			i.redraw()
225			return
226		}
227		if pendingRedraw {
228			return // already scheduled
229		}
230		pendingRedraw = true
231		wait := redrawMinInterval - since
232		if pendingTimer == nil {
233			pendingTimer = time.AfterFunc(wait, func() {
234				// Poke the dirty channel; the main loop will call drainPending().
235				i.invalidate()
236			})
237		} else {
238			pendingTimer.Reset(wait)
239		}
240	}
241
242	i.invalidate()
243
244	for {
245		select {
246		case <-ctx.Done():
247			return ctx.Err()
248		case k := <-keys:
249			if done := i.handleKey(ctx, k); done {
250				return nil
251			}
252			i.invalidate()
253		case ev := <-authEvents:
254			i.handleAuthEvent(ev)
255			i.invalidate()
256		case <-i.dirty:
257			requestRedraw()
258		case <-tick.C:
259			if i.busy || i.dialog.Active() || i.modelDialog.Active() || i.sessionDialog.Active() {
260				drainPending()
261				requestRedraw()
262			}
263		}
264	}
265}
266
267func (i *Interactive) invalidate() {
268	select {
269	case i.dirty <- struct{}{}:
270	default:
271	}
272}
273
274// lastCols returns the current terminal width in columns.
275func (i *Interactive) lastCols() int {
276	cols, _ := i.cfg.Terminal.Size()
277	return cols
278}
279
280// chatPage returns the number of chat rows currently visible, used
281// as the page size for PageUp/PageDown.
282func (i *Interactive) chatPage() int {
283	_, rows := i.cfg.Terminal.Size()
284	p := rows - 6 // rough reservation for status + editor + a dialog line
285	if p < 4 {
286		p = 4
287	}
288	return p
289}
290
291// scrollBy adjusts the scroll offset. Positive = up (into history).
292func (i *Interactive) scrollBy(delta int) {
293	i.mu.Lock()
294	i.scrollOffset += delta
295	if i.scrollOffset < 0 {
296		i.scrollOffset = 0
297	}
298	i.mu.Unlock()
299	i.invalidate()
300}
301
302// scrollToBottom pins the view to the latest content.
303func (i *Interactive) scrollToBottom() {
304	i.mu.Lock()
305	i.scrollOffset = 0
306	i.mu.Unlock()
307	i.invalidate()
308}
309
310func (i *Interactive) redraw() {
311	i.mu.Lock()
312	defer i.mu.Unlock()
313
314	cols, _ := i.cfg.Terminal.Size()
315	if i.agent != nil {
316		i.view.Messages = i.agent.Messages()
317	} else {
318		i.view.Messages = nil
319	}
320	i.view.Streaming = i.streaming.String()
321	i.view.StreamingActive = i.streamOn
322	// Belt and suspenders: if the transcript's last message is already an
323	// assistant message, the streaming view is stale (EvAssistantMessage may
324	// not have fired yet) — suppress it to avoid double-rendering the reply.
325	if n := len(i.view.Messages); n > 0 && i.view.Messages[n-1].Role == provider.RoleAssistant {
326		i.view.StreamingActive = false
327	}
328	// Live tool-call view: only shown while a turn is in flight. Once
329	// the agent is idle, every tool call has already been folded into
330	// the transcript (as assistant.ToolCallBlock + a tool-role message),
331	// so showing v.ToolCalls a second time would duplicate them below
332	// the final assistant text — which looks like the summary came
333	// "before" the tools.
334	i.view.ToolCalls = i.view.ToolCalls[:0]
335	if i.busy {
336		for _, id := range i.toolOrder {
337			if tc, ok := i.toolCalls[id]; ok {
338				i.view.ToolCalls = append(i.view.ToolCalls, *tc)
339			}
340		}
341	}
342	i.view.Err = i.statusErr
343
344	chat := i.view.Build(cols)
345
346	// Welcome banner: shown at the top of the chat area when there is
347	// no transcript yet. Disappears after the first message is sent.
348	if len(i.view.Messages) == 0 && !i.streamOn && len(i.toolOrder) == 0 {
349		chat = append(welcomeBanner(i.cfg.Theme), chat...)
350	}
351
352	// /help block: appended to the transcript so it appears at the
353	// bottom of the chat area (right above the status bar / editor).
354	// Prepending it would push long conversations off the top of the
355	// viewport, which users would miss entirely.
356	if len(i.helpBlock) > 0 {
357		chat = append(chat, i.helpBlock...)
358	}
359
360	if i.statusOK != "" {
361		chat = append(chat, i.cfg.Theme.FG256(i.cfg.Theme.Tool, "✓ "+i.statusOK), "")
362	}
363
364	// Dialogs (login or model picker) render between chat and the editor.
365	var dialog []string
366	switch {
367	case i.dialog.Active():
368		dialog = i.dialog.Render(i.cfg.Theme, cols)
369	case i.modelDialog.Active():
370		dialog = i.modelDialog.Render(i.cfg.Theme, cols)
371	case i.sessionDialog.Active():
372		dialog = i.sessionDialog.Render(i.cfg.Theme, cols)
373	}
374
375	// Slash-command autocomplete: popup above the status line, only
376	// when the editor starts with "/" and no dialog is already open.
377	var suggest []string
378	currentInput := i.ed.Value()
379	if len(dialog) == 0 && i.suggest.Active(currentInput) && !i.busy {
380		suggest = i.suggest.Render(currentInput, i.cfg.Theme, cols)
381	}
382
383	// Busy prefix shown at the far left of the status bar.
384	var busyPrefix string
385	if i.busy {
386		busyPrefix = fmt.Sprintf("%s %s · %s",
387			i.cfg.Theme.FG256(i.cfg.Theme.Spinner, i.spin.Frame()),
388			i.cfg.Theme.FG256(i.cfg.Theme.Spinner, i.spin.Message()),
389			i.cfg.Theme.FG256(i.cfg.Theme.Muted, i.spin.Elapsed().String()),
390		)
391	}
392
393	ctxMax := 0
394	if m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model); err == nil {
395		ctxMax = m.ContextWindow
396	}
397	status := tui.StatusBar(tui.StatusBarParams{
398		Theme:          i.cfg.Theme,
399		Provider:       i.cfg.Provider,
400		Model:          i.cfg.Model,
401		Busy:           i.busy,
402		BusyPrefix:     busyPrefix,
403		CWD:            i.cfg.CWD,
404		Locked:         i.cfg.Sandbox.Locked(),
405		Usage:          i.cumUsage,
406		Subscription:   i.cfg.AuthMethod == "oauth",
407		ContextUsed:    i.lastCtxInput,
408		ContextMax:     ctxMax,
409		AutoCompacting: i.autoCompacting,
410		Cols:           cols,
411	})
412	edLines, curR, curC := i.ed.Render(cols)
413
414	// "Sliding in" chips for messages the user typed while a turn is
415	// in flight. Shown directly above the status bar so they're close
416	// to the editor but don't push the chat around.
417	var queue []string
418	if len(i.queued) > 0 {
419		for _, q := range i.queued {
420			label := i.cfg.Theme.FG256(i.cfg.Theme.Accent, "▸ sliding in: ")
421			text := truncateLine(q, cols-15)
422			queue = append(queue, label+i.cfg.Theme.FG256(i.cfg.Theme.Muted, text))
423		}
424	}
425
426	// Bottom-sticky sections (always visible, never scroll).
427	bottom := make([]string, 0, len(dialog)+len(suggest)+len(queue)+len(edLines)+1)
428	bottom = append(bottom, dialog...)
429	bottom = append(bottom, suggest...)
430	bottom = append(bottom, queue...)
431	bottom = append(bottom, status)
432	bottom = append(bottom, edLines...)
433
434	_, rows := i.cfg.Terminal.Size()
435	chatRows := rows - len(bottom)
436	if chatRows < 1 {
437		chatRows = 1
438	}
439
440	// Apply scroll offset to the chat slice.
441	maxOffset := len(chat) - chatRows
442	if maxOffset < 0 {
443		maxOffset = 0
444	}
445	if i.scrollOffset > maxOffset {
446		i.scrollOffset = maxOffset
447	}
448	if i.scrollOffset < 0 {
449		i.scrollOffset = 0
450	}
451
452	var visibleChat []string
453	if len(chat) <= chatRows {
454		visibleChat = chat
455	} else {
456		end := len(chat) - i.scrollOffset
457		start := end - chatRows
458		if start < 0 {
459			start = 0
460		}
461		visibleChat = chat[start:end]
462	}
463
464	// A tiny "scrolled up" indicator in the top-right of the chat pane
465	// so you know you're not at the bottom.
466	if i.scrollOffset > 0 && len(visibleChat) > 0 {
467		note := i.cfg.Theme.FG256(i.cfg.Theme.Muted,
468			fmt.Sprintf("  ↑ %d lines more below (end to jump)", i.scrollOffset))
469		visibleChat = append([]string{note}, visibleChat...)
470		if len(visibleChat) > chatRows {
471			visibleChat = visibleChat[:chatRows]
472		}
473	}
474
475	frame := make([]string, 0, len(visibleChat)+len(bottom))
476	frame = append(frame, visibleChat...)
477	frame = append(frame, bottom...)
478
479	cursorRow := len(visibleChat) + len(dialog) + len(suggest) + len(queue) + 1 + curR
480	cursorCol := curC
481	i.rend.Draw(frame, cursorRow, cursorCol)
482}
483
484// truncateLine shortens s so it fits within n display cells, with an
485// ellipsis if trimmed. Used by the "sliding in" chips so a pasted
486// novel doesn't blow past the status line.
487func truncateLine(s string, n int) string {
488	if n <= 0 {
489		return ""
490	}
491	// Collapse newlines — chips are single line.
492	s = strings.ReplaceAll(s, "\n", " ↩ ")
493	runes := []rune(s)
494	if len(runes) <= n {
495		return s
496	}
497	if n <= 1 {
498		return "…"
499	}
500	return string(runes[:n-1]) + "…"
501}
502
503func (i *Interactive) handleKey(ctx context.Context, k tui.Key) (done bool) {
504	// Dialogs consume keys while open (except ctrl+c, which always closes them).
505	if i.dialog.Active() {
506		if k.Kind == tui.KeyCtrlC {
507			i.dialog.Close()
508			if i.cfg.AuthManager != nil {
509				i.cfg.AuthManager.CancelOAuth()
510			}
511			return false
512		}
513		act := i.dialog.HandleKey(k)
514		if act.StartAPIKey {
515			i.startAPIKeyFlow(act.Provider)
516		}
517		if act.StartOAuth {
518			i.startOAuthFlow(act.Provider)
519		}
520		return false
521	}
522	if i.modelDialog.Active() {
523		if k.Kind == tui.KeyCtrlC {
524			i.modelDialog.Close()
525			return false
526		}
527		act := i.modelDialog.HandleKey(k)
528		if act.Select {
529			i.applyModelSelection(act.Provider, act.Model)
530		}
531		return false
532	}
533	if i.sessionDialog.Active() {
534		if k.Kind == tui.KeyCtrlC {
535			i.sessionDialog.Close()
536			return false
537		}
538		act := i.sessionDialog.HandleKey(k)
539		if act.Select {
540			i.applySessionSelection(act.Path)
541		}
542		return false
543	}
544
545	// Global keys.
546	switch k.Kind {
547	case tui.KeyCtrlC:
548		if i.busy && i.cancelTurn != nil {
549			i.cancelTurn()
550			return false
551		}
552		return true
553	case tui.KeyEsc:
554		// Esc interrupts a running turn. When idle, fall through so the
555		// editor can clear itself.
556		if i.busy && i.cancelTurn != nil {
557			i.cancelTurn()
558			return false
559		}
560	case tui.KeyCtrlD:
561		if i.ed.IsEmpty() && !i.busy {
562			return true
563		}
564	case tui.KeyCtrlL:
565		i.rend.Clear()
566		i.invalidate()
567		return false
568	case tui.KeyCtrlO:
569		// Toggle expansion of collapsed tool results. Affects every tool
570		// call in the transcript — press again to re-collapse.
571		i.mu.Lock()
572		i.view.ExpandAll = !i.view.ExpandAll
573		i.mu.Unlock()
574		i.invalidate()
575		return false
576	case tui.KeyPageUp:
577		i.scrollBy(+i.chatPage())
578		return false
579	case tui.KeyPageDown:
580		i.scrollBy(-i.chatPage())
581		return false
582	case tui.KeyUp:
583		// Wheel-up in alt screen sends Up arrows on most terminals. When the
584		// editor is empty and we're not busy, use that for chat scroll-up.
585		if i.ed.IsEmpty() && !i.busy {
586			i.scrollBy(+3)
587			return false
588		}
589	case tui.KeyDown:
590		if i.ed.IsEmpty() && !i.busy {
591			if i.scrollOffset > 0 {
592				i.scrollBy(-3)
593			}
594			return false
595		}
596	}
597
598	// Note: we intentionally do NOT gate the editor on i.busy here.
599	// Typing while the agent is working is supported — submitted
600	// messages are queued and delivered as follow-up turns when the
601	// current turn ends. See the submit handler below.
602
603	if k.Kind == tui.KeyEnter && k.Alt {
604		i.ed.HandleKey(tui.Key{Kind: tui.KeyRune, Rune: '\n', Alt: true})
605		return false
606	}
607
608	// Slash suggestions: intercept up/down/tab/enter when the popup is visible.
609	if i.suggest.Active(i.ed.Value()) {
610		switch k.Kind {
611		case tui.KeyUp:
612			i.suggest.Up()
613			return false
614		case tui.KeyDown:
615			i.suggest.Down()
616			return false
617		case tui.KeyTab:
618			if name := i.suggest.Selection(i.ed.Value()); name != "" {
619				i.ed.SetValue(name)
620				i.suggest.Reset()
621			}
622			return false
623		case tui.KeyEnter:
624			// Enter on an ambiguous or partial slash prefix: complete to the
625			// currently highlighted command and run it. That way typing
626			// "/lo" + enter picks whichever of /login or /logout is selected
627			// in the popup instead of submitting "/lo" as unknown. Also
628			// clear the editor so the command doesn't linger after the
629			// dialog opens/closes.
630			if name := i.suggest.Selection(i.ed.Value()); name != "" {
631				i.ed.PushHistory(name)
632				i.ed.Clear()
633				i.suggest.Reset()
634				return i.runSlash(ctx, name)
635			}
636		case tui.KeyEsc:
637			i.ed.Clear()
638			i.suggest.Reset()
639			return false
640		}
641	}
642
643	if submit := i.ed.HandleKey(k); submit {
644		text := strings.TrimRight(i.ed.Value(), "\n")
645		if text == "" {
646			return false
647		}
648		i.ed.PushHistory(text)
649		i.ed.Clear()
650		i.suggest.Reset()
651
652		if looksLikeSlashCommand(text) {
653			if !isKnownSlashCommand(text) {
654				head := text
655				if idx := strings.IndexAny(text, " \t"); idx >= 0 {
656					head = text[:idx]
657				}
658				i.mu.Lock()
659				i.statusErr = "unknown command " + head + " — type /help to see the list"
660				i.statusOK = ""
661				i.mu.Unlock()
662				return false
663			}
664			// Slash commands need a quiet state (they may swap models,
665			// compact the transcript, open dialogs, etc). Refuse while
666			// a turn is in flight — esc / ctrl+c cancels first.
667			i.mu.Lock()
668			busy := i.busy
669			i.mu.Unlock()
670			if busy {
671				i.mu.Lock()
672				i.statusErr = "cancel the current turn (esc) before running a slash command"
673				i.mu.Unlock()
674				return false
675			}
676			return i.runSlash(ctx, text)
677		}
678
679		if i.agent == nil {
680			i.mu.Lock()
681			i.statusErr = "not logged in. type /login first."
682			i.mu.Unlock()
683			return false
684		}
685		// If a turn is already in flight, queue this prompt instead of
686		// starting a second one. The drain loop at the end of startTurn
687		// will pick it up when the current turn finishes.
688		i.mu.Lock()
689		if i.busy {
690			i.queued = append(i.queued, text)
691			i.mu.Unlock()
692			i.invalidate()
693			return false
694		}
695		i.mu.Unlock()
696		i.startTurn(ctx, text)
697	}
698	return false
699}
700
701func (i *Interactive) runSlash(ctx context.Context, cmd string) (done bool) {
702	parts := strings.Fields(cmd)
703	switch parts[0] {
704	case "/exit":
705		return true
706	case "/clear":
707		if i.agent != nil {
708			i.agent.SetMessages(nil)
709		}
710		i.mu.Lock()
711		i.toolCalls = map[string]*tui.ToolCallView{}
712		i.toolOrder = nil
713		i.statusErr = ""
714		i.statusOK = ""
715		i.helpBlock = nil
716		i.mu.Unlock()
717	case "/help":
718		i.mu.Lock()
719		i.helpBlock = renderHelpBlock(i.cfg.Theme, i.lastCols())
720		i.statusErr = ""
721		i.statusOK = ""
722		// Pin the viewport to the newest content so the help block,
723		// which we just appended to the end of the transcript, is
724		// what the user actually sees.
725		i.scrollOffset = 0
726		i.mu.Unlock()
727	case "/login":
728		i.dialog.Open()
729	case "/logout":
730		target := "all"
731		if len(parts) >= 2 {
732			target = parts[1]
733		}
734		i.doLogout(target)
735	case "/model":
736		if len(parts) >= 2 {
737			i.applyModelSelection("", parts[1])
738		} else {
739			i.modelDialog.Open(i.cfg.Model)
740		}
741	case "/sessions":
742		i.sessionDialog.Open(i.cfg.ZotHome, i.cfg.CWD)
743	case "/compact":
744		i.runCompact(ctx, false)
745	case "/lock":
746		if i.cfg.Sandbox == nil {
747			i.mu.Lock()
748			i.statusErr = "sandbox not available in this build"
749			i.mu.Unlock()
750			break
751		}
752		i.cfg.Sandbox.Lock()
753		i.mu.Lock()
754		i.statusOK = "locked to " + i.cfg.CWD + " (tools cannot touch paths outside this directory)"
755		i.statusErr = ""
756		i.mu.Unlock()
757	case "/unlock":
758		if i.cfg.Sandbox == nil {
759			i.mu.Lock()
760			i.statusErr = "sandbox not available in this build"
761			i.mu.Unlock()
762			break
763		}
764		i.cfg.Sandbox.Unlock()
765		i.mu.Lock()
766		i.statusOK = "unlocked"
767		i.statusErr = ""
768		i.mu.Unlock()
769	default:
770		i.mu.Lock()
771		i.statusErr = "unknown command: " + parts[0]
772		i.mu.Unlock()
773	}
774	return false
775}
776
777// doLogout clears credentials for the given provider (or all providers)
778// from auth.json. If the active agent was using those credentials, it
779// is torn down so the user is forced through /login before their next
780// prompt.
781//
782// target: "anthropic" | "openai" | "all"
783func (i *Interactive) doLogout(target string) {
784	if i.cfg.AuthManager == nil {
785		i.mu.Lock()
786		i.statusErr = "no auth manager configured"
787		i.mu.Unlock()
788		return
789	}
790	store := i.cfg.AuthManager.Store()
791	if store == nil {
792		i.mu.Lock()
793		i.statusErr = "auth store is not available"
794		i.mu.Unlock()
795		return
796	}
797
798	var providers []string
799	switch target {
800	case "", "all":
801		providers = []string{"anthropic", "openai"}
802	case "anthropic", "openai":
803		providers = []string{target}
804	default:
805		i.mu.Lock()
806		i.statusErr = "unknown provider: " + target + " (use anthropic, openai, or all)"
807		i.mu.Unlock()
808		return
809	}
810
811	var errs []string
812	clearedCurrent := false
813	for _, p := range providers {
814		if err := store.Clear(p); err != nil {
815			errs = append(errs, p+": "+err.Error())
816			continue
817		}
818		if p == i.cfg.Provider {
819			clearedCurrent = true
820		}
821	}
822
823	i.mu.Lock()
824	defer i.mu.Unlock()
825	if len(errs) > 0 {
826		i.statusErr = "logout errors: " + strings.Join(errs, "; ")
827		return
828	}
829	i.statusErr = ""
830	if clearedCurrent {
831		// The running agent was using a credential we just wiped. Drop
832		// it so prompts can't go out with the stale client, and hint at
833		// /login.
834		i.agent = nil
835		i.statusOK = "logged out of " + strings.Join(providers, ", ") + ". type /login to sign back in."
836	} else {
837		i.statusOK = "logged out of " + strings.Join(providers, ", ")
838	}
839}
840
841func (i *Interactive) startAPIKeyFlow(provider string) {
842	url, err := i.cfg.AuthManager.StartAPIKey(provider)
843	if err != nil {
844		i.dialog.ShowResult(false, err.Error())
845		return
846	}
847	i.dialog.ShowWaiting(url)
848}
849
850func (i *Interactive) startOAuthFlow(provider string) {
851	url, err := i.cfg.AuthManager.StartOAuth(provider)
852	if err != nil {
853		i.dialog.ShowResult(false, err.Error())
854		return
855	}
856	i.dialog.ShowWaiting(url)
857}
858
859// applyModelSelection switches the active model (and provider, if the
860// new model belongs to a different one). It rebuilds the underlying
861// client when needed so the provider wire-protocol matches.
862// applySessionSelection loads the given session via the cli-provided callback.
863func (i *Interactive) applySessionSelection(path string) {
864	if i.cfg.LoadSession == nil {
865		i.mu.Lock()
866		i.statusErr = "session loading is not wired in this build"
867		i.mu.Unlock()
868		return
869	}
870	if err := i.cfg.LoadSession(path); err != nil {
871		i.mu.Lock()
872		i.statusErr = err.Error()
873		i.mu.Unlock()
874		return
875	}
876	i.mu.Lock()
877	i.statusOK = "resumed session: " + path
878	i.statusErr = ""
879	i.scrollOffset = 0
880	i.mu.Unlock()
881}
882
883func (i *Interactive) applyModelSelection(prov, model string) {
884	if model == "" {
885		return
886	}
887	m, err := provider.FindModel(prov, model)
888	if err != nil {
889		i.mu.Lock()
890		i.statusErr = err.Error()
891		i.mu.Unlock()
892		return
893	}
894	// Same provider? Just swap the model on the existing agent.
895	if i.agent != nil && m.Provider == i.cfg.Provider {
896		i.mu.Lock()
897		i.cfg.Model = m.ID
898		i.agent.Model = m.ID
899		i.statusOK = "model: " + m.ID
900		i.statusErr = ""
901		i.mu.Unlock()
902		if i.cfg.PersistModel != nil {
903			i.cfg.PersistModel(i.cfg.Provider, m.ID)
904		}
905		return
906	}
907	// Different provider: rebuild agent (needs credentials for target provider).
908	if i.cfg.BuildAgentFor == nil {
909		i.mu.Lock()
910		i.statusErr = "cannot switch provider: no builder configured"
911		i.mu.Unlock()
912		return
913	}
914	ag, p, md, err := i.cfg.BuildAgentFor(m.Provider, m.ID)
915	if err != nil {
916		i.mu.Lock()
917		i.statusErr = err.Error()
918		i.mu.Unlock()
919		return
920	}
921	i.mu.Lock()
922	i.agent = ag
923	i.cfg.Provider = p
924	i.cfg.Model = md
925	i.statusOK = "switched to " + p + " / " + md
926	i.statusErr = ""
927	i.mu.Unlock()
928	if i.cfg.PersistModel != nil {
929		i.cfg.PersistModel(p, md)
930	}
931}
932
933func (i *Interactive) handleAuthEvent(ev auth.Event) {
934	switch ev.Kind {
935	case "started":
936		i.dialog.ShowWaiting(ev.URL)
937	case "browser_open":
938		// no-op
939	case "error":
940		i.dialog.ShowResult(false, ev.Message)
941	case "success":
942		// Rebuild the agent with the fresh credential.
943		ag, prov, model, err := i.cfg.BuildAgent()
944		if err != nil {
945			i.dialog.ShowResult(false, err.Error())
946			return
947		}
948		i.mu.Lock()
949		i.agent = ag
950		i.cfg.Provider = prov
951		i.cfg.Model = model
952		i.statusErr = ""
953		i.statusOK = "logged in to " + ev.Provider + " via " + ev.Method
954		i.mu.Unlock()
955		i.dialog.ShowResult(true, "")
956	}
957}
958
959// runCompact invokes core.Agent.Compact and reflects the progress in
960// the tui. It runs in a goroutine so the ui stays responsive; esc/ctrl+c
961// cancel via the same cancelTurn channel used for normal turns.
962//
963// When auto is true the spinner message is pinned to "condensing
964// history" and the status bar surfaces "(auto)" next to the context
965// percentage so it's obvious the system triggered this, not the user.
966func (i *Interactive) runCompact(parent context.Context, auto bool) {
967	if i.agent == nil {
968		i.mu.Lock()
969		i.statusErr = "not logged in. type /login first."
970		i.mu.Unlock()
971		return
972	}
973	ctx, cancel := context.WithCancel(parent)
974	i.mu.Lock()
975	i.busy = true
976	if auto {
977		i.spin.StartFixed("condensing history")
978		i.autoCompacting = true
979		i.statusOK = "condensing history… (esc to cancel)"
980	} else {
981		i.spin.Start()
982		i.statusOK = "compacting..."
983	}
984	i.cancelTurn = cancel
985	i.statusErr = ""
986	i.streaming.Reset()
987	i.streamOn = true
988	i.scrollOffset = 0
989	i.helpBlock = nil
990	i.mu.Unlock()
991	i.invalidate()
992
993	go func() {
994		sink := func(delta string) {
995			i.mu.Lock()
996			i.streaming.WriteString(delta)
997			i.mu.Unlock()
998			i.invalidate()
999		}
1000		summary, err := i.agent.Compact(ctx, 4, sink)
1001		i.mu.Lock()
1002		i.busy = false
1003		i.streamOn = false
1004		i.streaming.Reset()
1005		i.cancelTurn = nil
1006		i.autoCompacting = false
1007		switch {
1008		case err != nil && ctx.Err() != nil:
1009			i.statusErr = ""
1010			if auto {
1011				i.statusOK = "auto-condense cancelled"
1012			} else {
1013				i.statusOK = "compaction cancelled"
1014			}
1015		case err != nil:
1016			i.statusErr = "compaction failed: " + err.Error()
1017			i.statusOK = ""
1018		default:
1019			i.statusErr = ""
1020			i.statusOK = fmt.Sprintf("compacted transcript (%d chars of summary)", len(summary))
1021			i.lastCtxInput = 0 // reset; next turn will get a fresh measurement
1022			i.toolCalls = map[string]*tui.ToolCallView{}
1023			i.toolOrder = nil
1024		}
1025		i.mu.Unlock()
1026		i.invalidate()
1027	}()
1028}
1029
1030func (i *Interactive) startTurn(parent context.Context, prompt string) {
1031	if i.agent == nil {
1032		return
1033	}
1034	ctx, cancel := context.WithCancel(parent)
1035	i.mu.Lock()
1036	i.busy = true
1037	i.spin.Start()
1038	i.cancelTurn = cancel
1039	i.statusErr = ""
1040	i.statusOK = ""
1041	i.streaming.Reset()
1042	i.streamOn = true
1043	i.toolCalls = map[string]*tui.ToolCallView{}
1044	i.toolOrder = nil
1045	i.scrollOffset = 0 // jump back to the bottom on new turn
1046	i.helpBlock = nil  // hide the help block once the user asks something
1047	i.mu.Unlock()
1048	i.invalidate()
1049
1050	sink := func(ev core.AgentEvent) {
1051		i.handleEvent(ev)
1052		i.invalidate()
1053	}
1054
1055	go func() {
1056		err := i.agent.Prompt(ctx, prompt, nil, sink)
1057		i.mu.Lock()
1058		i.busy = false
1059		i.streamOn = false
1060		i.cancelTurn = nil
1061		if err != nil && ctx.Err() == nil {
1062			i.statusErr = err.Error()
1063		}
1064		// Pop the next queued message, if any, and relaunch.
1065		var next string
1066		var hasNext bool
1067		if len(i.queued) > 0 && ctx.Err() == nil && err == nil {
1068			next, i.queued = i.queued[0], i.queued[1:]
1069			hasNext = true
1070		}
1071		// If the turn was cancelled or errored, drop the queue so the
1072		// user isn't bombarded with stale messages after an interrupt.
1073		if ctx.Err() != nil || err != nil {
1074			i.queued = nil
1075		}
1076		// Decide whether the next thing to do is an auto-compaction.
1077		// Only fires when the turn completed cleanly AND the queue is
1078		// empty (otherwise a queued message would race the condense).
1079		shouldAutoCompact := !hasNext && err == nil && ctx.Err() == nil && i.shouldAutoCompactLocked()
1080		i.mu.Unlock()
1081		i.invalidate()
1082		parent := i.runCtx
1083		if parent == nil {
1084			parent = context.Background()
1085		}
1086		switch {
1087		case hasNext:
1088			i.startTurn(parent, next)
1089		case shouldAutoCompact:
1090			i.runCompact(parent, true)
1091		}
1092	}()
1093}
1094
1095// autoCompactThreshold is the context-window fraction at which the
1096// agent will auto-compact after a turn ends. 0.85 leaves enough
1097// headroom for one more user prompt + response before we bump the
1098// hard limit.
1099const autoCompactThreshold = 0.85
1100
1101// shouldAutoCompactLocked reports whether the last turn pushed context
1102// usage past the auto-compact threshold. Must be called with i.mu
1103// held; it reads lastCtxInput and the current model's context window.
1104func (i *Interactive) shouldAutoCompactLocked() bool {
1105	if i.agent == nil {
1106		return false
1107	}
1108	if i.autoCompacting {
1109		return false
1110	}
1111	m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
1112	if err != nil || m.ContextWindow <= 0 {
1113		return false
1114	}
1115	if i.lastCtxInput <= 0 {
1116		return false
1117	}
1118	return float64(i.lastCtxInput)/float64(m.ContextWindow) >= autoCompactThreshold
1119}
1120
1121func (i *Interactive) handleEvent(ev core.AgentEvent) {
1122	i.mu.Lock()
1123	defer i.mu.Unlock()
1124	switch e := ev.(type) {
1125	case core.EvTextDelta:
1126		i.streaming.WriteString(e.Delta)
1127	case core.EvAssistantMessage:
1128		i.streaming.Reset()
1129		i.streamOn = false
1130		if i.cfg.OnAssistant != nil {
1131			i.cfg.OnAssistant(e.Message)
1132		}
1133	case core.EvToolCall:
1134		tcv := &tui.ToolCallView{
1135			ID:   e.ID,
1136			Name: e.Name,
1137			Args: shortArgs(e.Args),
1138		}
1139		i.toolCalls[e.ID] = tcv
1140		i.toolOrder = append(i.toolOrder, e.ID)
1141	case core.EvToolResult:
1142		if tc, ok := i.toolCalls[e.ID]; ok {
1143			tc.Done = true
1144			tc.Error = e.Result.IsError
1145			var text strings.Builder
1146			for _, c := range e.Result.Content {
1147				if tb, ok := c.(provider.TextBlock); ok {
1148					if text.Len() > 0 {
1149						text.WriteString("\n")
1150					}
1151					text.WriteString(tb.Text)
1152				}
1153			}
1154			tc.Result = text.String()
1155		}
1156		if i.cfg.OnToolResult != nil {
1157			i.cfg.OnToolResult(e.ID, e.Result)
1158		}
1159	case core.EvUsage:
1160		i.cumUsage = e.Cumulative
1161		if e.Usage.InputTokens > 0 {
1162			i.lastCtxInput = e.Usage.InputTokens + e.Usage.CacheReadTokens + e.Usage.CacheWriteTokens
1163		}
1164	case core.EvTurnEnd:
1165		if e.Stop == provider.StopAborted {
1166			// Aborted turn: discard the partial streaming text (it is not
1167			// persisted in the transcript) and clear any transient error.
1168			i.streaming.Reset()
1169			i.streamOn = false
1170			i.statusErr = ""
1171			i.statusOK = "cancelled"
1172			return
1173		}
1174		if e.Err != nil && !strings.Contains(e.Err.Error(), "context canceled") {
1175			i.statusErr = e.Err.Error()
1176		}
1177	}
1178}
1179
1180// Agent returns the current agent, if any. Used by cli.go to flush the
1181// final transcript to the session file.
1182func (i *Interactive) Agent() *core.Agent {
1183	i.mu.Lock()
1184	defer i.mu.Unlock()
1185	return i.agent
1186}
1187
1188func shortArgs(raw json.RawMessage) string {
1189	var v any
1190	if err := json.Unmarshal(raw, &v); err != nil {
1191		return ""
1192	}
1193	if m, ok := v.(map[string]any); ok {
1194		for _, k := range []string{"path", "file_path", "command"} {
1195			if s, ok := m[k].(string); ok {
1196				if len(s) > 60 {
1197					s = s[:57] + "..."
1198				}
1199				return s
1200			}
1201		}
1202	}
1203	b, _ := json.Marshal(v)
1204	s := string(b)
1205	if len(s) > 60 {
1206		s = s[:57] + "..."
1207	}
1208	return s
1209}
1210
1211// silence unused import in some build configs
1212var _ = fmt.Sprintf

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