v0.1.96 6684724

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