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