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