v0.0.66 b29c6e7

slash_suggest.go RawHistoryFolder

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