v0.2.7 ea58887

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