v0.3.30 2501d48

slash_suggest.go RawHistoryFolder

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