v0.3.32 6bae491

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