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