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