v0.1.36 38717f5

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