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 if s.jailed {
125 return slashCatalog
126 }
127 out := make([]slashCommand, 0, len(slashCatalog)-1)
128 for _, c := range slashCatalog {
129 if c.Name == "/unjail" {
130 continue
131 }
132 out = append(out, c)
133 }
134 return out
135}
136
137// looksLikeSlashCommand reports whether text is an attempt at a slash
138// command (valid or not). Returns true for things like "/foo" or
139// "/bar baz" but false for paths ("/Users/pat/...") and regexes
140// ("/foo.bar/") so those can be sent to the model as-is.
141//
142// The head after "/" must be a single simple word: only letters,
143// digits, hyphens, and underscores. That excludes paths (contain "/"),
144// regexes (contain "."), and URLs.
145func looksLikeSlashCommand(text string) bool {
146 text = strings.TrimSpace(text)
147 if len(text) < 2 || text[0] != '/' {
148 return false
149 }
150 head := text[1:]
151 if i := strings.IndexAny(head, " \t\n"); i >= 0 {
152 head = head[:i]
153 }
154 if head == "" {
155 return false
156 }
157 for _, r := range head {
158 if !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') &&
159 !(r >= '0' && r <= '9') && r != '-' && r != '_' {
160 return false
161 }
162 }
163 return true
164}
165
166// isKnownSlashCommand reports whether text's head matches a registered
167// slash command name in slashCatalog. Built-in only; extension
168// commands are looked up separately by the dispatcher (which
169// consults the extension manager).
170func isKnownSlashCommand(text string) bool {
171 text = strings.TrimSpace(text)
172 if text == "" || text[0] != '/' {
173 return false
174 }
175 head := text
176 if i := strings.IndexAny(text, " \t\n"); i >= 0 {
177 head = text[:i]
178 }
179 for _, c := range slashCatalog {
180 if c.Name == head {
181 return true
182 }
183 }
184 return false
185}
186
187func newSlashSuggester() *slashSuggester { return &slashSuggester{} }
188
189// matches returns the commands whose name has input as a prefix.
190// If input is just "/", everything is shown.
191func (s *slashSuggester) matches(input string) []slashCommand {
192 input = strings.TrimRight(input, " ")
193 if input == "" || !strings.HasPrefix(input, "/") {
194 return nil
195 }
196 // If there is a space, the user has moved past the command name.
197 if idx := strings.IndexByte(input, ' '); idx >= 0 {
198 return nil
199 }
200 var out []slashCommand
201 for _, c := range s.allCatalog() {
202 if c.Header {
203 // Headers ride along whenever there's at least one
204 // matching command from their group; we drop trailing
205 // orphan headers below.
206 out = append(out, c)
207 continue
208 }
209 if strings.HasPrefix(c.Name, input) {
210 out = append(out, c)
211 }
212 }
213 return pruneOrphanHeaders(out)
214}
215
216// pruneOrphanHeaders removes header rows that have no commands
217// after them (i.e. the next non-header is missing or another
218// header). Keeps the popup clean when the input filters out a whole
219// group.
220func pruneOrphanHeaders(in []slashCommand) []slashCommand {
221 out := make([]slashCommand, 0, len(in))
222 for i, c := range in {
223 if c.Header {
224 nextReal := false
225 for j := i + 1; j < len(in); j++ {
226 if !in[j].Header {
227 nextReal = true
228 break
229 }
230 }
231 if !nextReal {
232 continue
233 }
234 }
235 out = append(out, c)
236 }
237 return out
238}
239
240// clampCursor keeps the cursor inside the current match list and
241// nudges it past any header row so navigation never lands on one.
242func (s *slashSuggester) clampCursor(n int) {
243 if n <= 0 {
244 s.cursor = 0
245 return
246 }
247 if s.cursor < 0 {
248 s.cursor = 0
249 }
250 if s.cursor >= n {
251 s.cursor = n - 1
252 }
253}
254
255// Up / Down navigate the suggestion list, skipping header rows in
256// either direction so the cursor only ever lands on selectable
257// commands.
258func (s *slashSuggester) Up() {
259 s.skipHeader(-1)
260}
261func (s *slashSuggester) Down() {
262 s.skipHeader(+1)
263}
264
265// skipHeader moves the cursor by step, then keeps moving in the same
266// direction across header rows until it lands on a real command (or
267// hits the edge, in which case it bounces back to the nearest real
268// row).
269func (s *slashSuggester) skipHeader(step int) {
270 list := s.lastMatches
271 n := len(list)
272 if n == 0 {
273 return
274 }
275 s.cursor += step
276 for s.cursor >= 0 && s.cursor < n && list[s.cursor].Header {
277 s.cursor += step
278 }
279 if s.cursor < 0 {
280 // Bounce: find the first non-header from the top.
281 for i, c := range list {
282 if !c.Header {
283 s.cursor = i
284 return
285 }
286 }
287 s.cursor = 0
288 }
289 if s.cursor >= n {
290 // Bounce: find the last non-header.
291 for i := n - 1; i >= 0; i-- {
292 if !list[i].Header {
293 s.cursor = i
294 return
295 }
296 }
297 s.cursor = n - 1
298 }
299}
300
301// Active reports whether the popup is visible for the given input.
302func (s *slashSuggester) Active(input string) bool {
303 return len(s.matches(input)) > 0
304}
305
306// Selection returns the currently highlighted command for input, or "".
307// Headers are never returned even if the cursor index would point at
308// one; the cursor is moved forward to the next real command.
309func (s *slashSuggester) Selection(input string) string {
310 m := s.matches(input)
311 if len(m) == 0 {
312 return ""
313 }
314 s.clampCursor(len(m))
315 if m[s.cursor].Header {
316 for i := s.cursor + 1; i < len(m); i++ {
317 if !m[i].Header {
318 s.cursor = i
319 break
320 }
321 }
322 }
323 if m[s.cursor].Header {
324 return ""
325 }
326 return m[s.cursor].Name
327}
328
329// Render returns the popup lines or nil.
330func (s *slashSuggester) Render(input string, th tui.Theme, width int) []string {
331 m := s.matches(input)
332 if len(m) == 0 {
333 return nil
334 }
335 s.lastMatches = m
336 s.clampCursor(len(m))
337 // Snap cursor off any header (e.g. after a filter change put it on one).
338 if s.cursor >= 0 && s.cursor < len(m) && m[s.cursor].Header {
339 for i := s.cursor + 1; i < len(m); i++ {
340 if !m[i].Header {
341 s.cursor = i
342 break
343 }
344 }
345 }
346 // Compute the widest command name across the whole match list
347 // (built-ins + extension-contributed) so every row's description
348 // starts at the same x-position. A minimum keeps short lists
349 // from collapsing the descriptions into the name column.
350 nameWidth := 10
351 for _, c := range m {
352 if c.Header {
353 continue
354 }
355 if n := len(c.Name); n > nameWidth {
356 nameWidth = n
357 }
358 }
359 var lines []string
360 for i, c := range m {
361 if c.Header {
362 // Breathing room around group dividers — a blank row
363 // before AND after makes the boundary read at a glance.
364 lines = append(lines, "")
365 rule := strings.Repeat("─", width)
366 label := "── " + c.Name + " "
367 if len(label) < width {
368 rule = label + strings.Repeat("─", width-len(label))
369 }
370 lines = append(lines, th.FG256(th.Muted, rule))
371 lines = append(lines, "")
372 continue
373 }
374 name := c.Name
375 if len(name) < nameWidth {
376 name = name + strings.Repeat(" ", nameWidth-len(name))
377 }
378 plain := " " + name + " " + c.Desc
379 if i == s.cursor {
380 lines = append(lines, th.PadHighlight(plain, width))
381 } else {
382 lines = append(lines, th.FG256(th.Muted, plain))
383 }
384 }
385 // Blank row before the hint visually detaches it from the
386 // command list and groups it with its trailing blank.
387 lines = append(lines, "")
388 lines = append(lines, th.FG256(th.Muted, " ↑/↓ navigate - tab complete - enter run"))
389 // Blank row after the hint separates the popup from the status
390 // bar / editor below it.
391 lines = append(lines, "")
392 return lines
393}
394
395// Reset puts the cursor back to the first match. Call this whenever the
396// input changes in a way that reshapes the match list.
397func (s *slashSuggester) Reset() { s.cursor = 0 }