v0.51.0 a9d674e

slash_suggest.go RawHistoryFolder

1package modes
2
3import (
4	"sort"
5	"strings"
6
7	"github.com/mattn/go-runewidth"
8
9	"github.com/bnema/zut/packages/agent/skills"
10	"github.com/bnema/zut/packages/tui"
11)
12
13// slashCommand is one entry in the autocomplete popup. Header rows
14// (group dividers like "── extensions ───") are real entries
15// flagged with header=true; they render but aren't navigable.
16type slashCommand struct {
17	Name   string // with leading "/"
18	Desc   string
19	Header bool // true = visual divider, not selectable
20}
21
22// slashCancelsTurn reports whether the named slash command, when run
23// while a turn is in flight, requires the active turn to be cancelled
24// first. The destructive commands (those that mutate the transcript
25// or rebuild the agent) need a quiet state; the rest run alongside
26// the streaming response without trouble.
27func slashCancelsTurn(head string) bool {
28	switch strings.ToLower(head) {
29	case "/clear", "/compact", "/logout", "/login", "/model", "/llama", "/reload-ext", "/cd", "/fork":
30		return true
31	}
32	return false
33}
34
35func slashCommandCancelsTurn(cmd string) bool {
36	parts := strings.Fields(cmd)
37	if len(parts) == 0 {
38		return false
39	}
40	if slashCancelsTurn(parts[0]) {
41		return true
42	}
43	return strings.EqualFold(parts[0], "/session") && len(parts) > 1 && strings.EqualFold(parts[1], "fork")
44}
45
46// slashCatalog lists every slash command the interactive mode handles.
47// Keep in sync with runSlash().
48var slashCatalog = []slashCommand{
49	{Name: "/help", Desc: "show key bindings and commands"},
50	{Name: "/info", Desc: "show the current session's details and file path"},
51	{Name: "/mcp", Desc: "show MCP server status"},
52	{Name: "/login", Desc: "log in via api key or subscription"},
53	{Name: "/logout", Desc: "clear a provider's credentials"},
54	{Name: "/model", Desc: "pick a model (or /model <id>)"},
55	{Name: "/reasoning", Desc: "set the reasoning level"},
56	{Name: "/profile", Desc: "activate model + reasoning + fast-mode profile (/profile <1-9>)"},
57	{Name: "/fast", Desc: "toggle fast mode"},
58	{Name: "/orchestrator", Desc: "toggle automatic subagent orchestration"},
59	{Name: "/goal", Desc: "start or control an autonomous goal"},
60	{Name: "/llama", Desc: "manage llama.cpp router models"},
61	{Name: "/sessions", Desc: "resume a previous session for this directory"},
62	{Name: "/fork", Desc: "pick a user message and fork the current session"},
63	{Name: "/session", Desc: "inspect, export, import, fork, or browse the current session"},
64	{Name: "/jump", Desc: "scroll the chat to a previous turn (or /jump <text>)"},
65	{Name: "/compact", Desc: "summarize and replace the transcript to free up context"},
66	{Name: "/study", Desc: "read every file in the cwd (or a passed file/dir) so the agent has full context"},
67	{Name: "/btw", Desc: "side-chat that doesn't add to the main thread (saves tokens)"},
68	{Name: "/jail", Desc: "confine tools to the current directory"},
69	{Name: "/unjail", Desc: "allow tools to touch paths outside this directory"},
70	{Name: "/skills", Desc: "list discovered skills (SKILL.md files)"},
71	{Name: "/subagents", Desc: "supervise background subagents with lifecycle, results, and optional worktrees"},
72	{Name: "/reload-ext", Desc: "hot-reload all extensions (re-read manifests and respawn)"},
73	{Name: "/telegram", Desc: "connect, disconnect, or show status of the telegram bridge"},
74	{Name: "/settings", Desc: "open settings"},
75	{Name: "/clear", Desc: "clear the chat transcript"},
76	{Name: "/exit", Desc: "exit zut"},
77}
78
79var sessionSlashCommands = []slashCommand{
80	{Name: "/session timeline", Desc: "inspect context, messages, and tool calls"},
81	{Name: "/session export", Desc: "write the current session to a .zutsession file"},
82	{Name: "/session import", Desc: "load a .zutsession file into this directory"},
83	{Name: "/session fork", Desc: "branch from a past user message"},
84	{Name: "/session tree", Desc: "switch between session branches"},
85}
86
87// slashSuggester renders the popup that appears when the editor starts
88// with "/". It does not own any input state — the editor drives.
89const slashSuggestPageSize = 8
90
91type slashSuggester struct {
92	cursor int
93
94	// jailed and llamaConfigured drive state-dependent command visibility.
95	jailed          bool
96	llamaConfigured bool
97
98	// extra are commands contributed by extensions, refreshed each
99	// frame from the extension manager. Empty when no extensions
100	// have registered any. Sorted by name in SetExtra so map
101	// iteration order doesn't reshuffle the popup between frames.
102	extra []slashCommand
103
104	// skills are dynamic /skill:<name> entries. skillInputActive tracks
105	// whether the editor is already in one autocomplete session so the
106	// interactive mode can refresh discovery once instead of every frame.
107	skills           []slashCommand
108	skillInputActive bool
109
110	// lastMatches is the list shown in the most recent Render call.
111	// Up/Down read it so they know which indexes to skip across
112	// header rows.
113	lastMatches []slashCommand
114}
115
116// SetExtra updates the extension-contributed command list. Called
117// once per render with the live snapshot from the extension manager.
118// The list is sorted by name so the popup ordering stays stable
119// across redraws (Manager.Commands() iterates a map, which Go
120// randomises).
121func (s *slashSuggester) SetExtra(cmds []slashCommand) {
122	sorted := append([]slashCommand(nil), cmds...)
123	sortSlashCommands(sorted)
124	s.extra = sorted
125}
126
127// SetSkills updates the user-visible /skill:<name> completion entries.
128// Built-ins stay hidden, while skills that disable model invocation remain
129// available because explicit invocation is their intended entry point.
130func (s *slashSuggester) SetSkills(list []*skills.Skill) {
131	visible := skills.VisibleSkills(list)
132	commands := make([]slashCommand, 0, len(visible))
133	for _, skill := range visible {
134		commands = append(commands, slashCommand{
135			Name: skillCommandPrefix + skill.Name,
136			Desc: strings.TrimSpace(skill.Description),
137		})
138	}
139	sortSlashCommands(commands)
140	s.skills = commands
141	s.cursor = 0
142}
143
144func sortSlashCommands(commands []slashCommand) {
145	sort.Slice(commands, func(i, j int) bool {
146		left, right := strings.ToLower(commands[i].Name), strings.ToLower(commands[j].Name)
147		if left == right {
148			return commands[i].Name < commands[j].Name
149		}
150		return left < right
151	})
152}
153
154// SkillInputStarted reports the first frame of a /skill: autocomplete
155// session. Leaving the prefix resets it, so the next attempt refreshes skill
156// discovery while ordinary redraws reuse the existing list.
157func (s *slashSuggester) SkillInputStarted(input string) bool {
158	active := strings.HasPrefix(strings.ToLower(input), skillCommandPrefix)
159	started := active && !s.skillInputActive
160	s.skillInputActive = active
161	return started
162}
163
164// SetJailed updates the current sandbox state. Called once per render
165// so state-dependent commands can appear/disappear immediately.
166func (s *slashSuggester) SetJailed(jailed bool) { s.jailed = jailed }
167
168// SetLlamaConfigured shows the management command only when a router login is
169// available.
170func (s *slashSuggester) SetLlamaConfigured(configured bool) { s.llamaConfigured = configured }
171
172// allCatalog returns slashCatalog plus the current extra commands
173// (extension-registered) with a header divider between the two
174// groups. Extra entries are only kept if they don't collide with
175// a built-in name; the built-in always wins.
176func (s *slashSuggester) allCatalog() []slashCommand {
177	base := s.baseCatalog()
178	if len(s.extra) == 0 {
179		return base
180	}
181	out := make([]slashCommand, 0, len(base)+len(s.extra)+1)
182	out = append(out, base...)
183	var kept []slashCommand
184	for _, c := range s.extra {
185		dup := false
186		for _, b := range base {
187			if strings.EqualFold(b.Name, c.Name) {
188				dup = true
189				break
190			}
191		}
192		if !dup {
193			kept = append(kept, c)
194		}
195	}
196	if len(kept) > 0 {
197		out = append(out, slashCommand{Header: true, Name: "extensions"})
198		out = append(out, kept...)
199	}
200	return out
201}
202
203// baseCatalog returns the built-in commands visible for the current
204// interactive state.
205func (s *slashSuggester) baseCatalog() []slashCommand {
206	hide := "/unjail"
207	if s.jailed {
208		hide = "/jail"
209	}
210	out := make([]slashCommand, 0, len(slashCatalog)-1)
211	for _, c := range slashCatalog {
212		if c.Name == hide || (c.Name == "/llama" && !s.llamaConfigured) {
213			continue
214		}
215		out = append(out, c)
216	}
217	return out
218}
219
220// looksLikeSlashCommand reports whether text is an attempt at a slash
221// command (valid or not). Returns true for things like "/foo" or
222// "/bar baz" but false for paths ("/Users/example/...") and regexes
223// ("/foo.bar/") so those can be sent to the model as-is.
224//
225// The head after "/" must be a single simple word: only letters,
226// digits, hyphens, and underscores. The /skill:<name> form additionally
227// permits one colon. Paths, regexes, and URLs are still excluded.
228func looksLikeSlashCommand(text string) bool {
229	text = strings.TrimSpace(text)
230	if len(text) < 2 || text[0] != '/' {
231		return false
232	}
233	head := text[1:]
234	if i := strings.IndexAny(head, " \t\n"); i >= 0 {
235		head = head[:i]
236	}
237	if head == "" {
238		return false
239	}
240	if strings.HasPrefix(strings.ToLower(head), "skill:") {
241		head = head[len("skill:"):]
242		if head == "" {
243			return true
244		}
245	}
246	for _, r := range head {
247		if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') &&
248			(r < '0' || r > '9') && r != '-' && r != '_' {
249			return false
250		}
251	}
252	return true
253}
254
255// isKnownSlashCommand reports whether text's head matches a registered
256// slash command name in slashCatalog or hiddenSlashCommands. Built-in
257// only; extension commands are looked up separately by the dispatcher
258// (which consults the extension manager).
259func isKnownSlashCommand(text string) bool {
260	text = strings.TrimSpace(text)
261	if text == "" || text[0] != '/' {
262		return false
263	}
264	head := text
265	if i := strings.IndexAny(text, " \t\n"); i >= 0 {
266		head = text[:i]
267	}
268	if len(head) >= len(skillCommandPrefix) && strings.EqualFold(head[:len(skillCommandPrefix)], skillCommandPrefix) {
269		return true
270	}
271	for _, c := range slashCatalog {
272		if strings.EqualFold(c.Name, head) {
273			return true
274		}
275	}
276	for _, h := range hiddenSlashCommands {
277		if strings.EqualFold(h, head) {
278			return true
279		}
280	}
281	return false
282}
283
284// hiddenSlashCommands are dispatchable but intentionally absent from
285// the autocomplete popup, /help, and the README. Used for commands
286// driven by extensions or by other internal flows where surfacing
287// the verb to humans would be confusing or premature.
288var hiddenSlashCommands = []string{
289	"/cd",
290}
291
292func newSlashSuggester() *slashSuggester { return &slashSuggester{} }
293
294// matches returns the commands whose name has input as a prefix.
295// If input is just "/", everything is shown.
296func (s *slashSuggester) matches(input string) []slashCommand {
297	if input == "" || !strings.HasPrefix(input, "/") {
298		return nil
299	}
300	matchPrefix := strings.ToLower(input)
301	// /session exposes its actions after the first space.
302	if strings.HasPrefix(matchPrefix, "/session ") {
303		var out []slashCommand
304		for _, c := range sessionSlashCommands {
305			if strings.HasPrefix(strings.ToLower(c.Name), matchPrefix) {
306				out = append(out, c)
307			}
308		}
309		return out
310	}
311	// Any other command: a space means the user has moved on to its arguments.
312	input = strings.TrimRight(input, " ")
313	if strings.ContainsRune(input, ' ') {
314		return nil
315	}
316	matchPrefix = strings.ToLower(input)
317	catalog := s.allCatalog()
318	if strings.HasPrefix(matchPrefix, skillCommandPrefix) {
319		catalog = s.skills
320	}
321	var out []slashCommand
322	for _, c := range catalog {
323		if c.Header {
324			// Headers ride along whenever there's at least one
325			// matching command from their group; we drop trailing
326			// orphan headers below.
327			out = append(out, c)
328			continue
329		}
330		if strings.HasPrefix(strings.ToLower(c.Name), matchPrefix) {
331			out = append(out, c)
332		}
333	}
334	out = pruneOrphanHeaders(out)
335	// Prefer an exact command over longer commands sharing its prefix so
336	// /session stays selected instead of the earlier /sessions entry.
337	for _, c := range out {
338		if !c.Header && strings.EqualFold(c.Name, input) {
339			return []slashCommand{c}
340		}
341	}
342	return out
343}
344
345// pruneOrphanHeaders removes header rows that have no commands
346// after them (i.e. the next non-header is missing or another
347// header). Keeps the popup clean when the input filters out a whole
348// group.
349func pruneOrphanHeaders(in []slashCommand) []slashCommand {
350	out := make([]slashCommand, 0, len(in))
351	for i, c := range in {
352		if c.Header {
353			nextReal := false
354			for j := i + 1; j < len(in); j++ {
355				if !in[j].Header {
356					nextReal = true
357					break
358				}
359			}
360			if !nextReal {
361				continue
362			}
363		}
364		out = append(out, c)
365	}
366	return out
367}
368
369// clampCursor keeps the cursor inside the current match list and
370// nudges it past any header row so navigation never lands on one.
371func (s *slashSuggester) clampCursor(n int) {
372	if n <= 0 {
373		s.cursor = 0
374		return
375	}
376	if s.cursor < 0 {
377		s.cursor = 0
378	}
379	if s.cursor >= n {
380		s.cursor = n - 1
381	}
382}
383
384// Up / Down navigate the suggestion list, skipping header rows in
385// either direction so the cursor only ever lands on selectable
386// commands.
387func (s *slashSuggester) Up() {
388	s.skipHeader(-1)
389}
390func (s *slashSuggester) Down() {
391	s.skipHeader(+1)
392}
393
394func (s *slashSuggester) PageUp() {
395	if len(s.lastMatches) == 0 {
396		return
397	}
398	s.cursor -= slashSuggestPageSize
399	if s.cursor < 0 {
400		s.cursor = 0
401	}
402	if s.lastMatches[s.cursor].Header {
403		s.skipHeader(+1)
404	}
405}
406
407func (s *slashSuggester) PageDown() {
408	if len(s.lastMatches) == 0 {
409		return
410	}
411	s.cursor += slashSuggestPageSize
412	if s.cursor >= len(s.lastMatches) {
413		s.cursor = len(s.lastMatches) - 1
414	}
415	if s.lastMatches[s.cursor].Header {
416		s.skipHeader(-1)
417	}
418}
419
420// skipHeader moves the cursor by step, then keeps moving in the same
421// direction across header rows until it lands on a real command (or
422// hits the edge, in which case it bounces back to the nearest real
423// row).
424func (s *slashSuggester) skipHeader(step int) {
425	list := s.lastMatches
426	n := len(list)
427	if n == 0 {
428		return
429	}
430	s.cursor += step
431	for s.cursor >= 0 && s.cursor < n && list[s.cursor].Header {
432		s.cursor += step
433	}
434	if s.cursor < 0 {
435		// Bounce: find the first non-header from the top.
436		for i, c := range list {
437			if !c.Header {
438				s.cursor = i
439				return
440			}
441		}
442		s.cursor = 0
443	}
444	if s.cursor >= n {
445		// Bounce: find the last non-header.
446		for i := n - 1; i >= 0; i-- {
447			if !list[i].Header {
448				s.cursor = i
449				return
450			}
451		}
452		s.cursor = n - 1
453	}
454}
455
456// Active reports whether the popup is visible for the given input.
457func (s *slashSuggester) Active(input string) bool {
458	return len(s.matches(input)) > 0
459}
460
461// Selection returns the currently highlighted command for input, or "".
462// Headers are never returned even if the cursor index would point at
463// one; the cursor is moved forward to the next real command.
464func (s *slashSuggester) Selection(input string) string {
465	m := s.matches(input)
466	if len(m) == 0 {
467		return ""
468	}
469	s.clampCursor(len(m))
470	if m[s.cursor].Header {
471		for i := s.cursor + 1; i < len(m); i++ {
472			if !m[i].Header {
473				s.cursor = i
474				break
475			}
476		}
477	}
478	if m[s.cursor].Header {
479		return ""
480	}
481	return m[s.cursor].Name
482}
483
484// Render returns the popup lines or nil.
485func (s *slashSuggester) Render(input string, th tui.Theme, width int) []string {
486	m := s.matches(input)
487	if len(m) == 0 {
488		return nil
489	}
490	s.lastMatches = m
491	s.clampCursor(len(m))
492	// Snap cursor off any header (e.g. after a filter change put it on one).
493	if s.cursor >= 0 && s.cursor < len(m) && m[s.cursor].Header {
494		for i := s.cursor + 1; i < len(m); i++ {
495			if !m[i].Header {
496				s.cursor = i
497				break
498			}
499		}
500	}
501	// Compute the widest command name across the whole match list
502	// (built-ins + extension-contributed) so every row's description
503	// starts at the same x-position. A minimum keeps short lists
504	// from collapsing the descriptions into the name column.
505	nameWidth := 10
506	for _, c := range m {
507		if c.Header {
508			continue
509		}
510		if n := len(c.Name); n > nameWidth {
511			nameWidth = n
512		}
513	}
514	var lines []string
515	for i := 0; i < len(m); i++ {
516		c := m[i]
517		if c.Header {
518			// Breathing room around group dividers — a blank row
519			// before AND after makes the boundary read at a glance.
520			lines = append(lines, "")
521			rule := strings.Repeat("─", width)
522			label := "── " + c.Name + " "
523			// runewidth, not len: the leading "── " glyphs are multi-byte,
524			// so byte-length padding leaves the rule short of the right edge.
525			if lw := runewidth.StringWidth(label); lw < width {
526				rule = label + strings.Repeat("─", width-lw)
527			}
528			lines = append(lines, th.FGColor(th.Muted, rule))
529			lines = append(lines, "")
530			continue
531		}
532		name := c.Name
533		if len(name) < nameWidth {
534			name = name + strings.Repeat(" ", nameWidth-len(name))
535		}
536		plain := "  " + name + "  " + c.Desc
537		if i == s.cursor {
538			lines = append(lines, th.PadHighlight(plain, width))
539		} else {
540			lines = append(lines, th.FGColor(th.Muted, plain))
541		}
542	}
543	// Blank row before the hint visually detaches it from the
544	// command list and groups it with its trailing blank.
545	lines = append(lines, "")
546	lines = append(lines, th.FGColor(th.Muted, "  ↑/↓ navigate - tab complete - enter run"))
547	// Blank row after the hint separates the popup from the status
548	// bar / editor below it.
549	lines = append(lines, "")
550	return lines
551}
552
553// Reset puts the cursor back to the first match. Call this whenever the
554// input changes in a way that reshapes the match list.
555func (s *slashSuggester) Reset() { s.cursor = 0 }

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 477

↑↓ moveenter openesc close