v0.1.91 91c696d

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