v0.3.92 6d56e22

slash_suggest.go RawHistoryFolder

1package modes
2
3import (
4	"sort"
5	"strings"
6
7	"github.com/mattn/go-runewidth"
8	"github.com/sahilm/fuzzy"
9
10	"github.com/patriceckhart/zot/packages/agent/skills"
11	"github.com/patriceckhart/zot/packages/tui"
12)
13
14// slashCommand is one entry in the autocomplete popup. Header rows
15// (group dividers like "── extensions ───") are real entries
16// flagged with header=true; they render but aren't navigable.
17type slashCommand struct {
18	Name           string // with leading "/"
19	Desc           string
20	Header         bool  // true = visual divider, not selectable
21	matchedIndexes []int // byte offsets in Name for fuzzy skill matches
22}
23
24// slashCancelsTurn reports whether the named slash command, when run
25// while a turn is in flight, requires the active turn to be cancelled
26// first. The destructive commands (those that mutate the transcript
27// or rebuild the agent) need a quiet state; the rest run alongside
28// the streaming response without trouble.
29func slashCancelsTurn(head string) bool {
30	switch strings.ToLower(head) {
31	case "/new", "/clear", "/compact", "/logout", "/login", "/model", "/llama", "/reload-ext", "/cd":
32		return true
33	}
34	return false
35}
36
37// slashCatalog lists every slash command the interactive mode handles.
38// Keep in sync with runSlash().
39var slashCatalog = []slashCommand{
40	{Name: "/help", Desc: "show key bindings and commands"},
41	{Name: "/login", Desc: "log in via api key or subscription"},
42	{Name: "/logout", Desc: "clear a provider's credentials"},
43	{Name: "/model", Desc: "pick a model (or /model <id>)"},
44	{Name: "/reasoning", Desc: "set the reasoning level"},
45	{Name: "/llama", Desc: "manage llama.cpp router models"},
46	{Name: "/sessions", Desc: "resume a previous session for this directory"},
47	{Name: "/new", Desc: "start a fresh session in this directory"},
48	{Name: "/session", Desc: "manage the current session"},
49	{Name: "/jump", Desc: "scroll the chat to a previous turn (or /jump <text>)"},
50	{Name: "/compact", Desc: "summarize and replace the transcript to free up context"},
51	{Name: "/study", Desc: "read every file in the cwd (or a passed file/dir) so the agent has full context"},
52	{Name: "/btw", Desc: "side-chat that doesn't add to the main thread (saves tokens)"},
53	{Name: "/jail", Desc: "confine tools to the current directory"},
54	{Name: "/unjail", Desc: "allow tools to touch paths outside this directory"},
55	{Name: "/skills", Desc: "list discovered skills (SKILL.md files)"},
56	{Name: "/swarm", Desc: "supervise background agents that share this working directory"},
57	{Name: "/reload-ext", Desc: "hot-reload all extensions (re-read manifests and respawn)"},
58	{Name: "/telegram", Desc: "connect, disconnect, or show status of the telegram bridge"},
59	{Name: "/settings", Desc: "open settings"},
60	{Name: "/clear", Desc: "clear the chat transcript"},
61	{Name: "/exit", Desc: "exit zot"},
62}
63
64var sessionSlashCommands = []slashCommand{
65	{Name: "/session timeline", Desc: "inspect context, messages, and tool calls"},
66	{Name: "/session export", Desc: "write the current session to a .zotsession file"},
67	{Name: "/session import", Desc: "load a .zotsession file into this directory"},
68	{Name: "/session fork", Desc: "branch from a past user message"},
69	{Name: "/session tree", Desc: "switch between session branches"},
70}
71
72// slashSuggester renders the popup that appears when the editor starts
73// with "/". It does not own any input state — the editor drives.
74const slashSuggestPageSize = 8
75
76type slashSuggester struct {
77	cursor int
78
79	// jailed and llamaConfigured drive state-dependent command visibility.
80	jailed          bool
81	llamaConfigured bool
82	sessionsEnabled bool
83
84	// extra are commands contributed by extensions, refreshed each
85	// frame from the extension manager. Empty when no extensions
86	// have registered any. Sorted by name in SetExtra so map
87	// iteration order doesn't reshuffle the popup between frames.
88	extra []slashCommand
89
90	// skills are dynamic /skill:<name> entries. skillInputActive tracks
91	// whether the editor is already in one autocomplete session so the
92	// interactive mode can refresh discovery once instead of every frame.
93	skills           []slashCommand
94	skillInputActive bool
95	fuzzySkills      bool
96
97	// lastMatches is the list shown in the most recent Render call.
98	// Up/Down read it so they know which indexes to skip across
99	// header rows.
100	lastMatches []slashCommand
101}
102
103// SetExtra updates the extension-contributed command list. Called
104// once per render with the live snapshot from the extension manager.
105// The list is sorted by name so the popup ordering stays stable
106// across redraws (Manager.Commands() iterates a map, which Go
107// randomises).
108func (s *slashSuggester) SetExtra(cmds []slashCommand) {
109	sorted := append([]slashCommand(nil), cmds...)
110	sortSlashCommands(sorted)
111	s.extra = sorted
112}
113
114// SetSkills updates the user-visible /skill:<name> completion entries.
115// Built-ins stay hidden, while skills that disable model invocation remain
116// available because explicit invocation is their intended entry point.
117func (s *slashSuggester) SetSkills(list []*skills.Skill) {
118	visible := skills.VisibleSkills(list)
119	commands := make([]slashCommand, 0, len(visible))
120	for _, skill := range visible {
121		commands = append(commands, slashCommand{
122			Name: skillCommandPrefix + skill.Name,
123			Desc: strings.TrimSpace(skill.Description),
124		})
125	}
126	sortSlashCommands(commands)
127	s.skills = commands
128	s.cursor = 0
129}
130
131func sortSlashCommands(commands []slashCommand) {
132	sort.Slice(commands, func(i, j int) bool {
133		left, right := strings.ToLower(commands[i].Name), strings.ToLower(commands[j].Name)
134		if left == right {
135			return commands[i].Name < commands[j].Name
136		}
137		return left < right
138	})
139}
140
141// SkillInputStarted reports the first frame of a /skill: autocomplete
142// session. Leaving the prefix resets it, so the next attempt refreshes skill
143// discovery while ordinary redraws reuse the existing list.
144func (s *slashSuggester) SkillInputStarted(input string) bool {
145	active := strings.HasPrefix(strings.ToLower(input), skillCommandPrefix)
146	started := active && !s.skillInputActive
147	s.skillInputActive = active
148	return started
149}
150
151// SetFuzzySkills changes skill matching without affecting other commands.
152func (s *slashSuggester) SetFuzzySkills(enabled bool) {
153	if s.fuzzySkills != enabled {
154		s.fuzzySkills = enabled
155		s.Reset()
156		s.lastMatches = nil
157	}
158}
159
160// fuzzySkillMatches ranks names only, breaking score ties by the index in
161// the alphabetically sorted catalog.
162func (s *slashSuggester) fuzzySkillMatches(query string) []slashCommand {
163	if query == "" {
164		return s.skills
165	}
166	names := make([]string, len(s.skills))
167	for i, c := range s.skills {
168		names[i] = strings.TrimPrefix(c.Name, skillCommandPrefix)
169	}
170	ranked := fuzzy.Find(query, names)
171	sort.Slice(ranked, func(i, j int) bool {
172		if ranked[i].Score == ranked[j].Score {
173			return ranked[i].Index < ranked[j].Index
174		}
175		return ranked[i].Score > ranked[j].Score
176	})
177	var out []slashCommand
178	for _, match := range ranked {
179		c := s.skills[match.Index]
180		c.matchedIndexes = make([]int, len(match.MatchedIndexes))
181		for i, index := range match.MatchedIndexes {
182			c.matchedIndexes[i] = len(skillCommandPrefix) + index
183		}
184		if strings.EqualFold(names[match.Index], query) {
185			return []slashCommand{c}
186		}
187		out = append(out, c)
188	}
189	return out
190}
191
192// SetJailed updates the current sandbox state. Called once per render
193// so state-dependent commands can appear/disappear immediately.
194func (s *slashSuggester) SetJailed(jailed bool) { s.jailed = jailed }
195
196// SetLlamaConfigured shows the management command only when a router login is
197// available.
198func (s *slashSuggester) SetLlamaConfigured(configured bool) { s.llamaConfigured = configured }
199
200// SetSessionsEnabled controls commands that require persisted sessions.
201func (s *slashSuggester) SetSessionsEnabled(enabled bool) { s.sessionsEnabled = enabled }
202
203// allCatalog returns slashCatalog plus the current extra commands
204// (extension-registered) with a header divider between the two
205// groups. Extra entries are only kept if they don't collide with
206// a built-in name; the built-in always wins.
207func (s *slashSuggester) allCatalog() []slashCommand {
208	base := s.baseCatalog()
209	if len(s.extra) == 0 {
210		return base
211	}
212	out := make([]slashCommand, 0, len(base)+len(s.extra)+1)
213	out = append(out, base...)
214	var kept []slashCommand
215	for _, c := range s.extra {
216		dup := false
217		for _, b := range base {
218			if strings.EqualFold(b.Name, c.Name) {
219				dup = true
220				break
221			}
222		}
223		if !dup {
224			kept = append(kept, c)
225		}
226	}
227	if len(kept) > 0 {
228		out = append(out, slashCommand{Header: true, Name: "extensions"})
229		out = append(out, kept...)
230	}
231	return out
232}
233
234// baseCatalog returns the built-in commands visible for the current
235// interactive state.
236func (s *slashSuggester) baseCatalog() []slashCommand {
237	hide := "/unjail"
238	if s.jailed {
239		hide = "/jail"
240	}
241	out := make([]slashCommand, 0, len(slashCatalog)-1)
242	for _, c := range slashCatalog {
243		if c.Name == hide || (c.Name == "/llama" && !s.llamaConfigured) || (c.Name == "/new" && !s.sessionsEnabled) {
244			continue
245		}
246		out = append(out, c)
247	}
248	return out
249}
250
251// looksLikeSlashCommand reports whether text is an attempt at a slash
252// command (valid or not). Returns true for things like "/foo" or
253// "/bar baz" but false for paths ("/Users/pat/...") and regexes
254// ("/foo.bar/") so those can be sent to the model as-is.
255//
256// The head after "/" must be a single simple word: only letters,
257// digits, hyphens, and underscores. The /skill:<name> form additionally
258// permits one colon. Paths, regexes, and URLs are still excluded.
259func looksLikeSlashCommand(text string) bool {
260	text = strings.TrimSpace(text)
261	if len(text) < 2 || text[0] != '/' {
262		return false
263	}
264	head := text[1:]
265	if i := strings.IndexAny(head, " \t\n"); i >= 0 {
266		head = head[:i]
267	}
268	if head == "" {
269		return false
270	}
271	if strings.HasPrefix(strings.ToLower(head), "skill:") {
272		head = head[len("skill:"):]
273		if head == "" {
274			return true
275		}
276	}
277	for _, r := range head {
278		if !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') &&
279			!(r >= '0' && r <= '9') && r != '-' && r != '_' {
280			return false
281		}
282	}
283	return true
284}
285
286// isKnownSlashCommand reports whether text's head matches a registered
287// slash command name in slashCatalog or hiddenSlashCommands. Built-in
288// only; extension commands are looked up separately by the dispatcher
289// (which consults the extension manager).
290func isKnownSlashCommand(text string) bool {
291	text = strings.TrimSpace(text)
292	if text == "" || text[0] != '/' {
293		return false
294	}
295	head := text
296	if i := strings.IndexAny(text, " \t\n"); i >= 0 {
297		head = text[:i]
298	}
299	if len(head) >= len(skillCommandPrefix) && strings.EqualFold(head[:len(skillCommandPrefix)], skillCommandPrefix) {
300		return true
301	}
302	for _, c := range slashCatalog {
303		if strings.EqualFold(c.Name, head) {
304			return true
305		}
306	}
307	for _, h := range hiddenSlashCommands {
308		if strings.EqualFold(h, head) {
309			return true
310		}
311	}
312	return false
313}
314
315// hiddenSlashCommands are dispatchable but intentionally absent from
316// the autocomplete popup, /help, and the README. Used for commands
317// driven by extensions or by other internal flows where surfacing
318// the verb to humans would be confusing or premature.
319var hiddenSlashCommands = []string{
320	"/cd",
321}
322
323func newSlashSuggester() *slashSuggester { return &slashSuggester{} }
324
325// matches uses name prefixes by default, or ranked name subsequences for
326// skills when explicitly enabled. If input is just "/", everything is shown.
327// The /session command exposes
328// its actions after the first space.
329func (s *slashSuggester) matches(input string) []slashCommand {
330	if input == "" || !strings.HasPrefix(input, "/") {
331		return nil
332	}
333	matchPrefix := strings.ToLower(input)
334	if strings.HasPrefix(matchPrefix, "/session ") {
335		var out []slashCommand
336		for _, c := range sessionSlashCommands {
337			if strings.HasPrefix(strings.ToLower(c.Name), matchPrefix) {
338				out = append(out, c)
339			}
340		}
341		return out
342	}
343	if strings.ContainsRune(input, ' ') {
344		return nil
345	}
346	catalog := s.allCatalog()
347	if strings.HasPrefix(matchPrefix, skillCommandPrefix) {
348		catalog = s.skills
349		if s.fuzzySkills {
350			return s.fuzzySkillMatches(input[len(skillCommandPrefix):])
351		}
352	}
353	var out []slashCommand
354	for _, c := range catalog {
355		if c.Header {
356			// Headers ride along whenever there's at least one
357			// matching command from their group; we drop trailing
358			// orphan headers below.
359			out = append(out, c)
360			continue
361		}
362		if strings.HasPrefix(strings.ToLower(c.Name), matchPrefix) {
363			out = append(out, c)
364		}
365	}
366	out = pruneOrphanHeaders(out)
367	// Prefer an exact command over longer commands sharing its prefix. This
368	// keeps /session selected instead of the earlier /sessions entry.
369	for _, c := range out {
370		if !c.Header && strings.EqualFold(c.Name, input) {
371			return []slashCommand{c}
372		}
373	}
374	return out
375}
376
377// pruneOrphanHeaders removes header rows that have no commands
378// after them (i.e. the next non-header is missing or another
379// header). Keeps the popup clean when the input filters out a whole
380// group.
381func pruneOrphanHeaders(in []slashCommand) []slashCommand {
382	out := make([]slashCommand, 0, len(in))
383	for i, c := range in {
384		if c.Header {
385			nextReal := false
386			for j := i + 1; j < len(in); j++ {
387				if !in[j].Header {
388					nextReal = true
389					break
390				}
391			}
392			if !nextReal {
393				continue
394			}
395		}
396		out = append(out, c)
397	}
398	return out
399}
400
401// clampCursor keeps the cursor inside the current match list and
402// nudges it past any header row so navigation never lands on one.
403func (s *slashSuggester) clampCursor(n int) {
404	if n <= 0 {
405		s.cursor = 0
406		return
407	}
408	if s.cursor < 0 {
409		s.cursor = 0
410	}
411	if s.cursor >= n {
412		s.cursor = n - 1
413	}
414}
415
416// Up / Down navigate the suggestion list, skipping header rows in
417// either direction so the cursor only ever lands on selectable
418// commands.
419func (s *slashSuggester) Up() {
420	s.skipHeader(-1)
421}
422func (s *slashSuggester) Down() {
423	s.skipHeader(+1)
424}
425
426func (s *slashSuggester) PageUp() {
427	if len(s.lastMatches) == 0 {
428		return
429	}
430	s.cursor -= slashSuggestPageSize
431	if s.cursor < 0 {
432		s.cursor = 0
433	}
434	if s.lastMatches[s.cursor].Header {
435		s.skipHeader(+1)
436	}
437}
438
439func (s *slashSuggester) PageDown() {
440	if len(s.lastMatches) == 0 {
441		return
442	}
443	s.cursor += slashSuggestPageSize
444	if s.cursor >= len(s.lastMatches) {
445		s.cursor = len(s.lastMatches) - 1
446	}
447	if s.lastMatches[s.cursor].Header {
448		s.skipHeader(-1)
449	}
450}
451
452// skipHeader moves the cursor by step, then keeps moving in the same
453// direction across header rows until it lands on a real command (or
454// hits the edge, in which case it bounces back to the nearest real
455// row).
456func (s *slashSuggester) skipHeader(step int) {
457	list := s.lastMatches
458	n := len(list)
459	if n == 0 {
460		return
461	}
462	s.cursor += step
463	for s.cursor >= 0 && s.cursor < n && list[s.cursor].Header {
464		s.cursor += step
465	}
466	if s.cursor < 0 {
467		// Bounce: find the first non-header from the top.
468		for i, c := range list {
469			if !c.Header {
470				s.cursor = i
471				return
472			}
473		}
474		s.cursor = 0
475	}
476	if s.cursor >= n {
477		// Bounce: find the last non-header.
478		for i := n - 1; i >= 0; i-- {
479			if !list[i].Header {
480				s.cursor = i
481				return
482			}
483		}
484		s.cursor = n - 1
485	}
486}
487
488// Active reports whether the popup is visible for the given input.
489func (s *slashSuggester) Active(input string) bool {
490	return len(s.matches(input)) > 0
491}
492
493// Selection returns the currently highlighted command for input, or "".
494// Headers are never returned even if the cursor index would point at
495// one; the cursor is moved forward to the next real command.
496func (s *slashSuggester) Selection(input string) string {
497	m := s.matches(input)
498	if len(m) == 0 {
499		return ""
500	}
501	s.clampCursor(len(m))
502	if m[s.cursor].Header {
503		for i := s.cursor + 1; i < len(m); i++ {
504			if !m[i].Header {
505				s.cursor = i
506				break
507			}
508		}
509	}
510	if m[s.cursor].Header {
511		return ""
512	}
513	return m[s.cursor].Name
514}
515
516// Render returns the popup lines or nil.
517func (s *slashSuggester) Render(input string, th tui.Theme, width int) []string {
518	m := s.matches(input)
519	if len(m) == 0 {
520		return nil
521	}
522	s.lastMatches = m
523	s.clampCursor(len(m))
524	// Snap cursor off any header (e.g. after a filter change put it on one).
525	if s.cursor >= 0 && s.cursor < len(m) && m[s.cursor].Header {
526		for i := s.cursor + 1; i < len(m); i++ {
527			if !m[i].Header {
528				s.cursor = i
529				break
530			}
531		}
532	}
533	// Compute the widest command name across the whole match list
534	// (built-ins + extension-contributed) so every row's description
535	// starts at the same x-position. A minimum keeps short lists
536	// from collapsing the descriptions into the name column.
537	nameWidth := 10
538	for _, c := range m {
539		if c.Header {
540			continue
541		}
542		if n := runewidth.StringWidth(c.Name); n > nameWidth {
543			nameWidth = n
544		}
545	}
546	var lines []string
547	for i := 0; i < len(m); i++ {
548		c := m[i]
549		if c.Header {
550			// Breathing room around group dividers — a blank row
551			// before AND after makes the boundary read at a glance.
552			lines = append(lines, "")
553			rule := strings.Repeat("─", width)
554			label := "── " + c.Name + " "
555			// runewidth, not len: the leading "── " glyphs are multi-byte,
556			// so byte-length padding leaves the rule short of the right edge.
557			if lw := runewidth.StringWidth(label); lw < width {
558				rule = label + strings.Repeat("─", width-lw)
559			}
560			lines = append(lines, th.FG256(th.Muted, rule))
561			lines = append(lines, "")
562			continue
563		}
564		name := highlightedSlashName(c)
565		if n := runewidth.StringWidth(c.Name); n < nameWidth {
566			name += strings.Repeat(" ", nameWidth-n)
567		}
568		plain := "  " + name + "  " + c.Desc
569		if i == s.cursor {
570			lines = append(lines, th.PadHighlight(plain, width))
571		} else {
572			lines = append(lines, th.FG256(th.Muted, plain))
573		}
574	}
575	// Blank row before the hint visually detaches it from the
576	// command list and groups it with its trailing blank.
577	lines = append(lines, "")
578	lines = append(lines, th.FG256(th.Muted, "  ↑/↓ navigate - tab complete - enter run"))
579	// Blank row after the hint separates the popup from the status
580	// bar / editor below it.
581	lines = append(lines, "")
582	return lines
583}
584
585// highlightedSlashName uses emphasis without resetting the row's foreground
586// or selection background. Match offsets are UTF-8 byte indexes.
587func highlightedSlashName(c slashCommand) string {
588	if len(c.matchedIndexes) == 0 {
589		return c.Name
590	}
591	var out strings.Builder
592	match := 0
593	for index, r := range c.Name {
594		text := string(r)
595		if match < len(c.matchedIndexes) && index == c.matchedIndexes[match] {
596			text = tui.Bold(text)
597			match++
598		}
599		out.WriteString(text)
600	}
601	return out.String()
602}
603
604// Reset puts the cursor back to the first match. Call this whenever the
605// input changes in a way that reshapes the match list.
606func (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