v0.39.0 33c980b

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