v0.9.2 49bea57

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