v0.1.80 63e28ad

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: "/swarm", Desc: "supervise background agents working in their own worktrees"},
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. Built-in only; extension
170// commands are looked up separately by the dispatcher (which
171// 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	return false
187}
188
189func newSlashSuggester() *slashSuggester { return &slashSuggester{} }
190
191// matches returns the commands whose name has input as a prefix.
192// If input is just "/", everything is shown.
193func (s *slashSuggester) matches(input string) []slashCommand {
194	input = strings.TrimRight(input, " ")
195	if input == "" || !strings.HasPrefix(input, "/") {
196		return nil
197	}
198	// If there is a space, the user has moved past the command name.
199	if idx := strings.IndexByte(input, ' '); idx >= 0 {
200		return nil
201	}
202	var out []slashCommand
203	for _, c := range s.allCatalog() {
204		if c.Header {
205			// Headers ride along whenever there's at least one
206			// matching command from their group; we drop trailing
207			// orphan headers below.
208			out = append(out, c)
209			continue
210		}
211		if strings.HasPrefix(c.Name, input) {
212			out = append(out, c)
213		}
214	}
215	return pruneOrphanHeaders(out)
216}
217
218// pruneOrphanHeaders removes header rows that have no commands
219// after them (i.e. the next non-header is missing or another
220// header). Keeps the popup clean when the input filters out a whole
221// group.
222func pruneOrphanHeaders(in []slashCommand) []slashCommand {
223	out := make([]slashCommand, 0, len(in))
224	for i, c := range in {
225		if c.Header {
226			nextReal := false
227			for j := i + 1; j < len(in); j++ {
228				if !in[j].Header {
229					nextReal = true
230					break
231				}
232			}
233			if !nextReal {
234				continue
235			}
236		}
237		out = append(out, c)
238	}
239	return out
240}
241
242// clampCursor keeps the cursor inside the current match list and
243// nudges it past any header row so navigation never lands on one.
244func (s *slashSuggester) clampCursor(n int) {
245	if n <= 0 {
246		s.cursor = 0
247		return
248	}
249	if s.cursor < 0 {
250		s.cursor = 0
251	}
252	if s.cursor >= n {
253		s.cursor = n - 1
254	}
255}
256
257// Up / Down navigate the suggestion list, skipping header rows in
258// either direction so the cursor only ever lands on selectable
259// commands.
260func (s *slashSuggester) Up() {
261	s.skipHeader(-1)
262}
263func (s *slashSuggester) Down() {
264	s.skipHeader(+1)
265}
266
267// skipHeader moves the cursor by step, then keeps moving in the same
268// direction across header rows until it lands on a real command (or
269// hits the edge, in which case it bounces back to the nearest real
270// row).
271func (s *slashSuggester) skipHeader(step int) {
272	list := s.lastMatches
273	n := len(list)
274	if n == 0 {
275		return
276	}
277	s.cursor += step
278	for s.cursor >= 0 && s.cursor < n && list[s.cursor].Header {
279		s.cursor += step
280	}
281	if s.cursor < 0 {
282		// Bounce: find the first non-header from the top.
283		for i, c := range list {
284			if !c.Header {
285				s.cursor = i
286				return
287			}
288		}
289		s.cursor = 0
290	}
291	if s.cursor >= n {
292		// Bounce: find the last non-header.
293		for i := n - 1; i >= 0; i-- {
294			if !list[i].Header {
295				s.cursor = i
296				return
297			}
298		}
299		s.cursor = n - 1
300	}
301}
302
303// Active reports whether the popup is visible for the given input.
304func (s *slashSuggester) Active(input string) bool {
305	return len(s.matches(input)) > 0
306}
307
308// Selection returns the currently highlighted command for input, or "".
309// Headers are never returned even if the cursor index would point at
310// one; the cursor is moved forward to the next real command.
311func (s *slashSuggester) Selection(input string) string {
312	m := s.matches(input)
313	if len(m) == 0 {
314		return ""
315	}
316	s.clampCursor(len(m))
317	if m[s.cursor].Header {
318		for i := s.cursor + 1; i < len(m); i++ {
319			if !m[i].Header {
320				s.cursor = i
321				break
322			}
323		}
324	}
325	if m[s.cursor].Header {
326		return ""
327	}
328	return m[s.cursor].Name
329}
330
331// Render returns the popup lines or nil.
332func (s *slashSuggester) Render(input string, th tui.Theme, width int) []string {
333	m := s.matches(input)
334	if len(m) == 0 {
335		return nil
336	}
337	s.lastMatches = m
338	s.clampCursor(len(m))
339	// Snap cursor off any header (e.g. after a filter change put it on one).
340	if s.cursor >= 0 && s.cursor < len(m) && m[s.cursor].Header {
341		for i := s.cursor + 1; i < len(m); i++ {
342			if !m[i].Header {
343				s.cursor = i
344				break
345			}
346		}
347	}
348	// Compute the widest command name across the whole match list
349	// (built-ins + extension-contributed) so every row's description
350	// starts at the same x-position. A minimum keeps short lists
351	// from collapsing the descriptions into the name column.
352	nameWidth := 10
353	for _, c := range m {
354		if c.Header {
355			continue
356		}
357		if n := len(c.Name); n > nameWidth {
358			nameWidth = n
359		}
360	}
361	var lines []string
362	for i, c := range m {
363		if c.Header {
364			// Breathing room around group dividers — a blank row
365			// before AND after makes the boundary read at a glance.
366			lines = append(lines, "")
367			rule := strings.Repeat("─", width)
368			label := "── " + c.Name + " "
369			if len(label) < width {
370				rule = label + strings.Repeat("─", width-len(label))
371			}
372			lines = append(lines, th.FG256(th.Muted, rule))
373			lines = append(lines, "")
374			continue
375		}
376		name := c.Name
377		if len(name) < nameWidth {
378			name = name + strings.Repeat(" ", nameWidth-len(name))
379		}
380		plain := "  " + name + "  " + c.Desc
381		if i == s.cursor {
382			lines = append(lines, th.PadHighlight(plain, width))
383		} else {
384			lines = append(lines, th.FG256(th.Muted, plain))
385		}
386	}
387	// Blank row before the hint visually detaches it from the
388	// command list and groups it with its trailing blank.
389	lines = append(lines, "")
390	lines = append(lines, th.FG256(th.Muted, "  ↑/↓ navigate - tab complete - enter run"))
391	// Blank row after the hint separates the popup from the status
392	// bar / editor below it.
393	lines = append(lines, "")
394	return lines
395}
396
397// Reset puts the cursor back to the first match. Call this whenever the
398// input changes in a way that reshapes the match list.
399func (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