Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: list commands with what they do when typing /

leepokai7864de91f744
diff --git a/apps/desktop/src/renderer/components/overlay.css b/apps/desktop/src/renderer/components/overlay.css
index c6262ca7..542f677e 100644
--- a/apps/desktop/src/renderer/components/overlay.css
+++ b/apps/desktop/src/renderer/components/overlay.css
@@ -53,7 +53,8 @@
.dialog-card::after,
.anchored-panel::after,
.account-panel::after,
-.action-menu::after {
+.action-menu::after,
+.command-menu::after {
content: '';
position: absolute;
inset: 0;
diff --git a/apps/desktop/src/renderer/views/marketplace/SkillSheet.tsx b/apps/desktop/src/renderer/views/marketplace/SkillSheet.tsx
index 4e1e1325..3af5c9af 100644
--- a/apps/desktop/src/renderer/views/marketplace/SkillSheet.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/SkillSheet.tsx
@@ -6,7 +6,7 @@ import { ModalHeader } from '../../components/Overlay'
import { font } from '../../lib/fonts'
import { useStore } from '../../store/context'
import { MarkdownText } from '../thread/Markdown'
-import { SKILLS_HOST } from '../thread/skill-command'
+import { SKILLS_HOST } from '../thread/slash-commands'
import { errorText, market } from './market-models'
import { ErrorText } from './pieces'
import { usePlugins } from './plugins'
diff --git a/apps/desktop/src/renderer/views/thread/CommandMenu.tsx b/apps/desktop/src/renderer/views/thread/CommandMenu.tsx
new file mode 100644
index 00000000..09656d74
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/CommandMenu.tsx
@@ -0,0 +1,76 @@
+import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
+import { Icon } from '../../components/Icon'
+import { usePresence } from '../../components/Overlay'
+import { returnRuns, type SlashCommand } from './slash-commands'
+
+/**
+ * The `/` list's highlight and keys: ↑/↓ move, Tab or Return picks, Escape hides the list until
+ * the draft changes.
+ */
+export function useCommandMenu(draft: string, commands: SlashCommand[], run: (command: SlashCommand) => void) {
+ const [pick, setPick] = useState({ draft: '', index: 0 })
+ const [dismissed, setDismissed] = useState<string | null>(null)
+ const shown = dismissed === draft ? [] : commands
+ const index = pick.draft === draft ? Math.min(pick.index, shown.length - 1) : 0
+
+ /** Handles a key in the field while the list is up; returns whether it did. */
+ const onKey = (e: KeyboardEvent, composing: boolean): boolean => {
+ const picked = shown[index]
+ if (!picked || composing || e.altKey || e.metaKey || e.ctrlKey) return false
+ const step = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : 0
+ const runs = (e.key === 'Tab' && !e.shiftKey) || (e.key === 'Enter' && !e.shiftKey && returnRuns(picked, draft))
+ if (!step && !runs && e.key !== 'Escape') return false
+ e.preventDefault()
+ e.stopPropagation()
+ if (step) setPick({ draft, index: (index + step + shown.length) % shown.length })
+ else if (runs) run(picked)
+ else setDismissed(draft)
+ return true
+ }
+
+ return { shown, index, hover: (i: number) => setPick({ draft, index: i }), onKey }
+}
+
+/** The `/` list over the transcript, above the box: each command's icon, name and what it does. */
+export function CommandMenu({ commands, index, hover, pick }: {
+ commands: SlashCommand[]
+ index: number
+ hover: (index: number) => void
+ pick: (command: SlashCommand) => void
+}) {
+ const open = commands.length > 0
+ const { mounted, shown } = usePresence(open)
+ const last = useRef(commands)
+ if (open) last.current = commands
+ const list = open ? commands : last.current
+ const rows = useRef<(HTMLButtonElement | null)[]>([])
+ // Braces: newer Chromium returns a promise from `scrollIntoView`, which an effect mustn't return.
+ useEffect(() => {
+ void rows.current[index]?.scrollIntoView({ block: 'nearest' })
+ }, [index, list])
+ if (!mounted) return null
+ return (
+ <div className={`command-menu ${shown ? 'shown' : ''}`} inert={!open}>
+ <div className="menu-panel" role="listbox" aria-label="Commands">
+ {list.map((c, i) => (
+ <button
+ key={`${c.action.kind}:${c.name}`}
+ ref={(el) => { rows.current[i] = el }}
+ role="option"
+ aria-selected={i === index}
+ className={`menu-row ${i === index ? 'highlight' : ''}`}
+ title={c.detail || c.title}
+ onMouseEnter={() => hover(i)}
+ // Keep the caret in the field.
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => pick(c)}
+ >
+ <span className="menu-icon"><Icon name={c.icon} size={12} color="var(--secondary)" /></span>
+ <span className="command-title">{c.title}</span>
+ <span className={`command-detail ${c.warning ? 'warning' : ''}`}>{c.detail}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/thread/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsx
index 32fb42de..ae6650a5 100644
--- a/apps/desktop/src/renderer/views/thread/Composer.tsx
+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx
@@ -1,6 +1,5 @@
import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'
import { isBelow } from '@shared/compat'
-import { fastCommandOffered, fastModeState, fastModeTitle, isFastCommand } from '@shared/fast-mode'
import { isGroup, isWorkingIn, type Bot } from '@shared/models'
import { BotAvatar } from '../../components/Avatar'
import { Icon } from '../../components/Icon'
@@ -11,14 +10,15 @@ import { useStore } from '../../store/context'
import { MAX_FILE_SIZE, type OutgoingFile } from '../../store/bot-store'
import { pluginsFor } from '../marketplace/plugins'
import { composerEnter } from './composer-keyboard'
+import { CommandMenu, useCommandMenu } from './CommandMenu'
import { ComposerAttachment } from './ComposerAttachment'
-import { matchingSkills, SKILLS_HOST, skillQuery } from './skill-command'
+import { builtInCommand, SKILLS_HOST, slashCommands, slashQuery, type SlashCommand } from './slash-commands'
type Trailing = 'interrupt' | 'stop' | 'call' | 'send'
/**
* The message box under a chat or a thread: send, or stop while the bot (or the group) is
- * working there. In a group, typing `@` suggests its bots; with one bot, a leading `/` offers Fast mode and its skills.
+ * working there. In a group, typing `@` suggests its bots; with one bot, a leading `/` lists its commands.
*/
export function Composer({ botId, thread = null, onCall, onInterrupt }: {
botId: string
@@ -104,14 +104,27 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
// Not in a group: each member has its own skills.
const skillsShown = !!bot && !isGroup(bot) && !isBelow(store.hello?.version ?? '', SKILLS_HOST)
- const slash = skillQuery(draft)
- const skills = !skillsShown || slash === null || !bot ? [] : matchingSkills(plugins.installedSkills, bot.skills, slash)
- const fastOffered = slash !== null && fastCommandOffered(bot, slash)
+ const slash = slashQuery(draft)
+ const commands = slash === null ? [] : slashCommands(bot, slash, skillsShown ? plugins.installedSkills : [])
- const pickSkill = (id: string) => {
- setDraft(`/${id} `)
+ const run = (command: SlashCommand) => {
+ if (!bot) return
+ switch (command.action.kind) {
+ case 'fast':
+ store.setFastMode(bot, !bot.fastMode)
+ setDraft('')
+ break
+ case 'newSession':
+ store.newSession(bot.id)
+ setDraft('')
+ break
+ case 'skill':
+ setDraft(`/${command.action.id} `)
+ break
+ }
field.current?.focus()
}
+ const menu = useCommandMenu(draft, commands, run)
const append = (incoming: { name: string; data: Uint8Array }[]) => {
if (!canAttach) return
@@ -126,15 +139,9 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
setFiles((list) => [...list, ...accepted])
}
- const toggleFast = () => {
- if (!bot) return
- store.setFastMode(bot, !bot.fastMode)
- setDraft('')
- field.current?.focus()
- }
-
const submit = () => {
- if (!files.length && isFastCommand(bot, draft)) return toggleFast()
+ const command = files.length ? null : builtInCommand(bot, draft)
+ if (command) return run(command)
if (!canSend) return
store.send(draft, botId, thread, files)
setDraft('')
@@ -155,7 +162,7 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
- <ComposerReveal open={suggestions.length > 0 || skills.length > 0 || fastOffered}>
+ <ComposerReveal open={suggestions.length > 0}>
<div className="mentions">
{suggestions.map((m) => (
<button key={m.id} className="press mention" onClick={() => mention(m)}>
@@ -163,21 +170,6 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
<span style={{ ...font('subheadline'), color: 'var(--text)' }}>{m.name}</span>
</button>
))}
- {fastOffered && bot ? (
- <button className="press mention" title={fastModeTitle(bot)} aria-label={fastModeTitle(bot)} aria-pressed={bot.fastMode} onClick={toggleFast}>
- <Icon name="bolt" size={12} color="var(--secondary)" />
- <span style={{ ...font('subheadline'), color: 'var(--text)' }}>Fast mode</span>
- <span style={{ ...font('subheadline'), color: fastModeState(bot) === 'refused' ? 'var(--warning)' : 'var(--secondary)' }}>
- {{ on: 'On', off: 'Off', refused: 'Refused' }[fastModeState(bot)]}
- </span>
- </button>
- ) : null}
- {skills.map((s) => (
- <button key={s.id} className="press mention" title={s.description || s.name} onClick={() => pickSkill(s.id)}>
- <Icon name="book.pages" size={12} color="var(--secondary)" />
- <span style={{ ...font('subheadline'), color: 'var(--text)' }}>{s.name}</span>
- </button>
- ))}
</div>
</ComposerReveal>
<div
@@ -192,6 +184,7 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
}}
>
<div className="composer-surface">
+ <CommandMenu commands={menu.shown} index={menu.index} hover={menu.hover} pick={run} />
<ComposerReveal open={files.length > 0}>
<div className="file-chips">
{files.map((f) => (
@@ -220,10 +213,11 @@ function DestinationComposer({ botId, thread, onCall, onInterrupt }: {
onCompositionEnd={() => { composing.current = false }}
onChange={(e) => {
setDraft(e.target.value)
- // Starting a skill name: list the computer's skills again.
+ // Starting a command: list the computer's skills again.
if (skillsShown && e.target.value === '/') void plugins.refresh()
}}
onKeyDown={(e) => {
+ if (menu.onKey(e, composing.current || e.nativeEvent.isComposing || e.keyCode === 229)) return
// Return sends, Shift-Return adds a line; an input method's Return picks its candidate.
const action = composerEnter({ key: e.key, shiftKey: e.shiftKey, altKey: e.altKey, repeat: e.repeat, isComposing: composing.current || e.nativeEvent.isComposing, keyCode: e.keyCode })
if (e.key === 'Enter' && e.repeat && !e.shiftKey && !e.altKey) e.preventDefault()
diff --git a/apps/desktop/src/renderer/views/thread/composer.css b/apps/desktop/src/renderer/views/thread/composer.css
index 34ed8a1a..ad67972d 100644
--- a/apps/desktop/src/renderer/views/thread/composer.css
+++ b/apps/desktop/src/renderer/views/thread/composer.css
@@ -11,6 +11,7 @@
margin-bottom: calc(max(0px, (round(up, calc(var(--conversation) * 1.25), 1px) + 10px - 25px) / 2));
}
.composer-surface {
+ position: relative;
flex: 1;
min-width: 0;
background: var(--composer-fill);
@@ -83,3 +84,41 @@
margin-bottom: calc(max(0px, (round(up, calc(var(--conversation) * 1.25), 1px) + 10px - 25px) / 2));
transition: background-color var(--morph), color var(--morph), transform var(--press);
}
+
+/* The `/` command list, floating over the transcript above the box. */
+.command-menu {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: calc(100% + 8px);
+ z-index: 20;
+ background: var(--bubble-agent);
+ border-radius: 14px;
+ box-shadow: 0 8px 40px rgba(0, 0, 0, 0.12);
+ overflow: hidden;
+ opacity: 0;
+ transform: translateY(4px);
+ transition: opacity var(--fade), transform var(--layout);
+}
+.command-menu.shown {
+ opacity: 1;
+ transform: none;
+}
+.command-menu .menu-panel {
+ max-height: 300px;
+}
+.command-title {
+ flex: none;
+}
+.command-detail {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ text-align: left;
+ color: var(--secondary);
+}
+.command-detail.warning {
+ color: var(--warning);
+}
diff --git a/apps/desktop/src/renderer/views/thread/skill-command.test.ts b/apps/desktop/src/renderer/views/thread/skill-command.test.ts
deleted file mode 100644
index 7938ab17..00000000
--- a/apps/desktop/src/renderer/views/thread/skill-command.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import assert from 'node:assert/strict'
-import { test } from 'node:test'
-import { matchingSkills, skillQuery } from './skill-command.ts'
-
-test('a leading slash opens the skill menu until the name ends', () => {
- assert.equal(skillQuery('/'), '')
- assert.equal(skillQuery('/pd'), 'pd')
- assert.equal(skillQuery('/pdf merge'), null)
- assert.equal(skillQuery('hi /pdf'), null)
-})
-
-test('only the bot\'s own skills match, by id or name', () => {
- const installed = [{ id: 'pdf', name: 'PDF' }, { id: 'code-review', name: 'Code Review' }, { id: 'xlsx', name: 'xlsx' }]
- assert.deepEqual(matchingSkills(installed, ['pdf', 'code-review'], '').map((s) => s.id), ['pdf', 'code-review'])
- assert.deepEqual(matchingSkills(installed, ['pdf', 'code-review'], 'review').map((s) => s.id), ['code-review'])
- assert.deepEqual(matchingSkills(installed, ['pdf'], 'xl'), [])
-})
diff --git a/apps/desktop/src/renderer/views/thread/skill-command.ts b/apps/desktop/src/renderer/views/thread/skill-command.ts
deleted file mode 100644
index e19e1ccc..00000000
--- a/apps/desktop/src/renderer/views/thread/skill-command.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-// `/skill` in the composer: while the draft is just `/partial`, the bot's skills are offered
-// (after Fast mode's `/fast`, `@shared/fast-mode`).
-// The host turns a message starting with `/<skill id>` into "read this skill first"
-// (host/src/market/skills.rs `expand_command`).
-
-/** The first host with `/skill` messages and skill details; older ones get the text as typed. */
-export const SKILLS_HOST = '2.14.1'
-
-/** The skill name being typed after a leading `/`, before any space; otherwise null. */
-export function skillQuery(draft: string): string | null {
- return /^\/\S*$/.test(draft) ? draft.slice(1) : null
-}
-
-/** The bot's skills (ids in `enabled`) whose id or name holds `query`. */
-export function matchingSkills<T extends { id: string; name: string }>(installed: T[], enabled: string[], query: string): T[] {
- const q = query.toLowerCase()
- return installed.filter((s) => enabled.includes(s.id) && (s.id.includes(q) || s.name.toLowerCase().includes(q)))
-}
diff --git a/apps/desktop/src/renderer/views/thread/slash-commands.test.ts b/apps/desktop/src/renderer/views/thread/slash-commands.test.ts
new file mode 100644
index 00000000..c730df7c
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/slash-commands.test.ts
@@ -0,0 +1,43 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { normalizeBot } from '../../../shared/models.ts'
+import { builtInCommand, returnRuns, slashCommands, slashQuery } from './slash-commands.ts'
+
+const installed = [
+ { id: 'pdf', name: 'PDF', description: 'PDFs' },
+ { id: 'code-review', name: 'Code Review', description: '' },
+ { id: 'xlsx', name: 'xlsx', description: '' },
+]
+
+test('a leading slash opens the list until the name ends', () => {
+ assert.equal(slashQuery('/'), '')
+ assert.equal(slashQuery('/pd'), 'pd')
+ assert.equal(slashQuery('/pdf merge'), null)
+ assert.equal(slashQuery('hi /pdf'), null)
+})
+
+test('built-in commands come first, then only the bot\'s own skills, by name or title', () => {
+ const bot = normalizeBot({ id: 'b', skills: ['pdf', 'code-review'], fastModeSupport: 'offered' })
+ assert.deepEqual(slashCommands(bot, '', installed).map((c) => c.name), ['fast', 'new', 'pdf', 'code-review'])
+ assert.deepEqual(slashCommands(bot, 'review', installed).map((c) => c.name), ['code-review'])
+ assert.deepEqual(slashCommands(bot, 'session', installed).map((c) => c.name), ['new'])
+ assert.deepEqual(slashCommands(normalizeBot({ id: 'b', skills: ['pdf'] }), 'xl', installed), [])
+ assert.deepEqual(slashCommands(normalizeBot({ id: 'b' }), '', []).map((c) => c.name), ['new'], 'no Fast mode on offer')
+ assert.deepEqual(slashCommands(normalizeBot({ id: 'g', kind: 'group', fastModeSupport: 'offered' }), '', installed), [])
+})
+
+test('sending just a built-in command runs it; anything else is a message', () => {
+ const bot = normalizeBot({ id: 'b', fastModeSupport: 'offered' })
+ assert.equal(builtInCommand(bot, '/fast ')?.action.kind, 'fast')
+ assert.equal(builtInCommand(bot, '/new')?.action.kind, 'newSession')
+ assert.equal(builtInCommand(bot, '/fast please'), null)
+ assert.equal(builtInCommand(normalizeBot({ id: 'b' }), '/fast'), null, 'without Fast mode it reaches the agent')
+})
+
+test('Return runs the highlighted command, but sends a skill already typed out', () => {
+ const bot = normalizeBot({ id: 'b', skills: ['pdf'] })
+ const [newSession, pdf] = slashCommands(bot, '', installed)
+ assert.equal(returnRuns(newSession!, '/'), true)
+ assert.equal(returnRuns(pdf!, '/pd'), true)
+ assert.equal(returnRuns(pdf!, '/pdf'), false)
+})
diff --git a/apps/desktop/src/renderer/views/thread/slash-commands.ts b/apps/desktop/src/renderer/views/thread/slash-commands.ts
new file mode 100644
index 00000000..a59ca966
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/slash-commands.ts
@@ -0,0 +1,62 @@
+// The composer's `/` commands, listed while the draft is just `/partial`: Fast mode and New
+// session run here through host methods (`updateBot`, `newSession`); a skill fills in
+// `/<id> `, and the host turns that message into "read this skill first"
+// (host/src/market/skills.rs `expand_command`). docs/features/marketplace.md, "Commands".
+import { fastModeDetail, fastModeShown, fastModeState } from '../../../shared/fast-mode.ts'
+import type { Bot } from '../../../shared/models.ts'
+
+/** The first host with `/skill` messages and skill details; older ones get the text as typed. */
+export const SKILLS_HOST = '2.14.1'
+
+export type SlashAction = { kind: 'fast' } | { kind: 'newSession' } | { kind: 'skill'; id: string }
+
+export interface SlashCommand {
+ /** What follows the `/`. */
+ name: string
+ icon: string
+ title: string
+ detail: string
+ warning: boolean
+ action: SlashAction
+}
+
+/** The command name being typed after a leading `/`, before any space; otherwise null. */
+export function slashQuery(draft: string): string | null {
+ return /^\/\S*$/.test(draft) ? draft.slice(1) : null
+}
+
+/** The bot's built-in commands; a group has none (each member has its own agent). */
+function builtIn(bot: Bot): SlashCommand[] {
+ if (bot.kind === 'group') return []
+ const fast: SlashCommand[] = fastModeShown(bot)
+ ? [{ name: 'fast', icon: 'bolt', title: 'Fast mode', detail: fastModeDetail(bot), warning: fastModeState(bot) === 'refused', action: { kind: 'fast' } }]
+ : []
+ return [
+ ...fast,
+ { name: 'new', icon: 'arrow.counterclockwise', title: 'New session', detail: 'Start over with a fresh context; the transcript stays', warning: false, action: { kind: 'newSession' } },
+ ]
+}
+
+/** Built-in commands, then the bot's skills (ids in `bot.skills`), whose name or title holds `query`. */
+export function slashCommands(bot: Bot | null, query: string, installedSkills: { id: string; name: string; description: string }[]): SlashCommand[] {
+ if (!bot || bot.kind === 'group') return []
+ const skills = installedSkills
+ .filter((s) => bot.skills.includes(s.id))
+ .map((s): SlashCommand => ({ name: s.id, icon: 'book.pages', title: s.name, detail: s.description, warning: false, action: { kind: 'skill', id: s.id } }))
+ const q = query.toLowerCase()
+ return [...builtIn(bot), ...skills].filter((c) => c.name.includes(q) || c.title.toLowerCase().includes(q))
+}
+
+/** A draft that is just a built-in command (`/fast`, `/new`): sending it runs the command. */
+export function builtInCommand(bot: Bot | null, draft: string): SlashCommand | null {
+ const name = slashQuery(draft.trim())
+ return bot && name !== null ? (builtIn(bot).find((c) => c.name === name) ?? null) : null
+}
+
+/**
+ * What Return does with `picked` highlighted: run it, except a skill whose name is already
+ * typed out, which sends.
+ */
+export function returnRuns(picked: SlashCommand, draft: string): boolean {
+ return picked.action.kind !== 'skill' || draft !== `/${picked.name}`
+}
diff --git a/apps/desktop/src/shared/fast-mode.ts b/apps/desktop/src/shared/fast-mode.ts
index ca31688a..677cb444 100644
--- a/apps/desktop/src/shared/fast-mode.ts
+++ b/apps/desktop/src/shared/fast-mode.ts
@@ -21,27 +21,14 @@ export function fastModeRefusal(bot: Bot): string | null {
return `The agent turned it off: ${bot.fastModeIssue ?? 'not available'}. Switch it off and on to try again.`
}
-/** `/fast` in the composer turns Fast mode on or off instead of going to the agent. */
-export const FAST_COMMAND = '/fast'
-
-/** The `/` menu offers Fast mode while `query` (what follows the `/`) could still name it. */
-export function fastCommandOffered(bot: Bot | null, query: string): boolean {
- return fastModeShown(bot) && 'fast mode'.includes(query.toLowerCase())
-}
-
-/** A draft that is just `/fast`: sending it switches Fast mode. */
-export function isFastCommand(bot: Bot | null, draft: string): boolean {
- return fastModeShown(bot) && draft.trim() === FAST_COMMAND
-}
-
-/** The `/` menu entry's tooltip and accessibility label. */
-export function fastModeTitle(bot: Bot): string {
+/** What picking `/fast` in the composer's command list does, or why it isn't in effect. */
+export function fastModeDetail(bot: Bot): string {
switch (fastModeState(bot)) {
case 'off':
- return 'Turn on Fast mode: faster replies, more usage'
+ return 'Turn on for faster replies and more usage'
case 'on':
- return 'Turn off Fast mode'
+ return 'Turn off and return to standard speed'
case 'refused':
- return `Fast mode is off. ${fastModeRefusal(bot)}`
+ return fastModeRefusal(bot) ?? ''
}
}
diff --git a/apps/desktop/src/shared/models.test.ts b/apps/desktop/src/shared/models.test.ts
index 872dc05e..56dad919 100644
--- a/apps/desktop/src/shared/models.test.ts
+++ b/apps/desktop/src/shared/models.test.ts
@@ -13,24 +13,13 @@ test('a host without Fast mode reads as off', () => {
})
test('the composer offers Fast mode once the agent does, and while it is on', async () => {
- const { fastModeShown, fastModeState, fastModeTitle } = await import('./fast-mode.ts')
+ const { fastModeShown, fastModeState, fastModeDetail } = await import('./fast-mode.ts')
assert.equal(fastModeShown(normalizeBot({ id: 'b' })), false)
assert.equal(fastModeShown(normalizeBot({ id: 'b', fastModeSupport: 'offered' })), true)
assert.equal(fastModeShown(normalizeBot({ id: 'b', fastMode: true, fastModeSupport: 'unsupported' })), true)
assert.equal(fastModeShown(normalizeBot({ id: 'g', kind: 'group', fastModeSupport: 'offered' })), false)
const refused = normalizeBot({ id: 'b', fastMode: true, fastModeSupport: 'refused', fastModeIssue: 'requires extra usage' })
assert.equal(fastModeState(refused), 'refused')
- assert.match(fastModeTitle(refused), /requires extra usage/)
+ assert.match(fastModeDetail(refused), /requires extra usage/)
})
-test('/fast is offered while typed and switches Fast mode instead of sending', async () => {
- const { fastCommandOffered, isFastCommand } = await import('./fast-mode.ts')
- const offered = normalizeBot({ id: 'b', fastModeSupport: 'offered' })
- assert.equal(fastCommandOffered(offered, ''), true)
- assert.equal(fastCommandOffered(offered, 'fa'), true)
- assert.equal(fastCommandOffered(offered, 'pdf'), false)
- assert.equal(fastCommandOffered(normalizeBot({ id: 'b' }), ''), false)
- assert.equal(isFastCommand(offered, '/fast '), true)
- assert.equal(isFastCommand(offered, '/fast please'), false)
- assert.equal(isFastCommand(normalizeBot({ id: 'b' }), '/fast'), false, 'without Fast mode it reaches the agent')
-})
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift
index 3ed74d3a..a64fdd15 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot+FastMode.swift
@@ -21,16 +21,12 @@ public extension Bot {
return "The agent turned it off: \(fastModeIssue ?? "not available"). Switch it off and on to try again."
}
- /// `/fast` in the composer turns Fast mode on or off instead of going to the agent.
- static let fastCommand = "/fast"
-
- /// The `/` menu offers Fast mode while `query` (what follows the `/`) could still name it.
- func offersFastCommand(_ query: String) -> Bool {
- fastModeShown && (query.isEmpty || "fast mode".localizedCaseInsensitiveContains(query))
- }
-
- /// A draft that is just `/fast`: sending it switches Fast mode.
- func isFastCommand(_ draft: String) -> Bool {
- fastModeShown && draft.trimmingCharacters(in: .whitespacesAndNewlines) == Self.fastCommand
+ /// What picking `/fast` in the composer's command list does, or why it isn't in effect.
+ var fastModeDetail: String {
+ switch fastModeState {
+ case .off: "Turn on for faster replies and more usage"
+ case .on: "Turn off and return to standard speed"
+ case .refused: fastModeRefusal ?? ""
+ }
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/SkillSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/SkillSheet.swift
index b8e08b93..e723ca58 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/SkillSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/SkillSheet.swift
@@ -37,7 +37,7 @@ struct SkillSheet: View {
}
/// Older hosts list skills but can't show what's in them.
- private var readable: Bool { !AppVersion.isBelow(model.hello?.version ?? "", SkillCommand.minHost) }
+ private var readable: Bool { !AppVersion.isBelow(model.hello?.version ?? "", SlashCommands.minSkillsHost) }
var body: some View {
VStack(spacing: 0) {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/CommandList.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/CommandList.swift
new file mode 100644
index 00000000..9f334171
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/CommandList.swift
@@ -0,0 +1,46 @@
+import CodyncKit
+import SwiftUI
+
+/// The `/` list above the box: each command's icon, name and what it does; tapping one runs it.
+struct CommandList: View {
+ let commands: [SlashCommand]
+ let pick: (SlashCommand) -> Void
+
+ var body: some View {
+ // Scrolls only once it's taller than the room it gets.
+ ViewThatFits(in: .vertical) {
+ rows
+ ScrollView { rows }.scrollIndicators(.hidden)
+ }
+ .frame(maxHeight: 280, alignment: .bottom)
+ .glass(in: RoundedRectangle(cornerRadius: 20, style: .continuous))
+ }
+
+ private var rows: some View {
+ VStack(spacing: 0) {
+ ForEach(commands) { command in
+ Button { pick(command) } label: {
+ HStack(spacing: 10) {
+ Image(systemName: command.icon)
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .frame(width: 20)
+ Text(command.title).font(.subheadline).foregroundStyle(Palette.text)
+ Text(command.detail)
+ .font(.subheadline)
+ .foregroundStyle(command.warning ? Palette.warning : Palette.secondary)
+ .lineLimit(1)
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(PressScale())
+ .accessibilityLabel(command.title)
+ .accessibilityHint(command.detail)
+ }
+ }
+ .padding(.vertical, 6)
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
index b2912f50..90efcb3a 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
@@ -5,7 +5,7 @@ import UniformTypeIdentifiers
/// The message box under a chat or a thread: send, or stop while the bot (or the
/// group) is working there. In a group, typing `@` suggests its bots; with one bot, a
-/// leading `/` offers Fast mode and its skills.
+/// leading `/` lists its commands.
struct Composer: View {
let botId: String
/// Replies go to the thread on this message.
@@ -62,25 +62,23 @@ struct Composer: View {
}
}
- /// The bot's skills while the draft is `/partial`; not in a group, where each member has its own.
- private var skillSuggestions: [InstalledSkill] {
- guard let bot, !bot.isGroup, !AppVersion.isBelow(model.hello?.version ?? "", SkillCommand.minHost),
- let query = SkillCommand.query(draft) else { return [] }
- return SkillCommand.matches(model.installedSkills, enabled: bot.skills, query: query)
- }
-
- /// The bot whose Fast mode the `/` menu offers while the draft could still be `/fast`.
- private var fastOffer: Bot? {
- guard let bot, let query = SkillCommand.query(draft), bot.offersFastCommand(query) else { return nil }
- return bot
+ /// The bot's `/` commands while the draft is `/partial`; skills only from hosts that run them.
+ private var commands: [SlashCommand] {
+ guard let query = SlashCommands.query(draft) else { return [] }
+ let skillsShown = !AppVersion.isBelow(model.hello?.version ?? "", SlashCommands.minSkillsHost)
+ return SlashCommands.list(for: bot, query: query, skills: skillsShown ? model.installedSkills : [])
}
var body: some View {
VStack(alignment: .leading, spacing: 6) {
- if !suggestions.isEmpty || !skillSuggestions.isEmpty || fastOffer != nil {
+ if !commands.isEmpty {
+ CommandList(commands: commands, pick: run)
+ .padding(.horizontal, 16)
+ .transition(.move(edge: .bottom).combined(with: .opacity))
+ }
+ if !suggestions.isEmpty {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 6) {
- if let bot = fastOffer { fastChip(bot) }
ForEach(suggestions) { member in
SuggestionChip(title: member.name) {
CharacterAvatar(bot: member, size: 18, animated: false)
@@ -88,16 +86,6 @@ struct Composer: View {
mention(member)
}
}
- ForEach(skillSuggestions) { skill in
- SuggestionChip(title: skill.name) {
- Image(systemName: "book.pages").font(.caption).foregroundStyle(Palette.secondary)
- } action: {
- draft = "/\(skill.id) "
- focused = true
- }
- .help(skill.description)
- .accessibilityHint(skill.description)
- }
}
.padding(.horizontal, 16)
}
@@ -106,26 +94,7 @@ struct Composer: View {
field
}
.animation(Motion.layout, value: suggestions.map(\.id))
- .animation(Motion.layout, value: skillSuggestions.map(\.id))
- .animation(Motion.layout, value: fastOffer != nil)
- }
-
- /// `/fast`: Fast mode and whether it's on; tapping switches it.
- private func fastChip(_ bot: Bot) -> some View {
- let (value, tint): (String, Color) = switch bot.fastModeState {
- case .on: ("On", Palette.secondary)
- case .off: ("Off", Palette.secondary)
- case .refused: ("Refused", Palette.warning)
- }
- let about = bot.fastModeRefusal ?? "Faster replies for more usage."
- return SuggestionChip(title: "Fast mode", detail: (value, tint)) {
- Image(systemName: "bolt").font(.caption).foregroundStyle(Palette.secondary)
- } action: {
- toggleFast(bot)
- }
- .accessibilityValue(value)
- .accessibilityHint(about)
- .help(about)
+ .animation(Motion.layout, value: commands.map(\.id))
}
private var fieldPadding: CGFloat { 10 }
@@ -246,7 +215,7 @@ struct Composer: View {
}
.onChange(of: draft) { _, value in
model.setComposerDraft(value, for: botId, thread: thread)
- // Starting a skill name: list the computer's skills again.
+ // Starting a command: list the computer's skills again.
if value == "/", bot?.isGroup == false { Task { await model.refreshPlugins() } }
}
.onChange(of: model.routineDrafts[botId]) { _, value in
@@ -338,14 +307,23 @@ struct Composer: View {
focused = true
}
- private func toggleFast(_ bot: Bot) {
- model.setFastMode(bot, !bot.fastMode)
- draft = ""
+ private func run(_ command: SlashCommand) {
+ guard let bot else { return }
+ switch command.action {
+ case .fast:
+ model.setFastMode(bot, !bot.fastMode)
+ draft = ""
+ case .newSession:
+ model.newSession(bot.id)
+ draft = ""
+ case .skill(let id):
+ draft = "/\(id) "
+ }
focused = true
}
private func submit() {
- if files.isEmpty, let bot, bot.isFastCommand(draft) { return toggleFast(bot) }
+ if files.isEmpty, let command = SlashCommands.builtIn(for: bot, draft: draft) { return run(command) }
guard canSend else { return }
withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {
guard model.sendComposerDraft(to: botId, thread: thread, files: files) else { return }
@@ -355,11 +333,9 @@ struct Composer: View {
}
}
-/// One suggestion above the box: a bot to @mention, Fast mode, or a skill to start with.
+/// One suggestion above the box: a bot to @mention.
private struct SuggestionChip<Icon: View>: View {
let title: String
- /// A value after the title, such as Fast mode's On / Off.
- var detail: (text: String, tint: Color)?
@ViewBuilder let icon: Icon
let action: () -> Void
@@ -368,7 +344,6 @@ private struct SuggestionChip<Icon: View>: View {
HStack(spacing: 6) {
icon
Text(title).font(.subheadline).foregroundStyle(Palette.text)
- if let detail { Text(detail.text).font(.subheadline).foregroundStyle(detail.tint) }
}
.padding(.horizontal, 10)
.padding(.vertical, 6)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/SkillCommand.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/SkillCommand.swift
deleted file mode 100644
index 75da4cd1..00000000
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/SkillCommand.swift
+++ /dev/null
@@ -1,23 +0,0 @@
-import CodyncKit
-
-/// `/skill` in the composer: while the draft is just `/partial`, the bot's skills are offered.
-/// The host turns a message starting with `/<skill id>` into "read this skill first"
-/// (`host/src/market/skills.rs` `expand_command`).
-enum SkillCommand {
- /// The first host that understands `/skill` messages; older ones get the text as typed.
- static let minHost = "2.14.1"
-
- /// The skill name being typed after a leading `/`, before any space.
- static func query(_ draft: String) -> String? {
- guard draft.hasPrefix("/"), !draft.contains(where: \.isWhitespace) else { return nil }
- return String(draft.dropFirst())
- }
-
- /// The bot's skills (ids in `enabled`) whose id or name holds `query`.
- static func matches(_ installed: [InstalledSkill], enabled: [String], query: String) -> [InstalledSkill] {
- installed.filter {
- enabled.contains($0.id)
- && (query.isEmpty || $0.id.localizedCaseInsensitiveContains(query) || $0.name.localizedCaseInsensitiveContains(query))
- }
- }
-}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/SlashCommands.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/SlashCommands.swift
new file mode 100644
index 00000000..33ef3f49
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/SlashCommands.swift
@@ -0,0 +1,60 @@
+import CodyncKit
+
+/// A command in the composer's `/` list.
+struct SlashCommand: Identifiable, Equatable {
+ enum Action: Hashable { case fast, newSession, skill(String) }
+
+ /// What follows the `/`.
+ let name: String
+ let icon: String
+ let title: String
+ let detail: String
+ let warning: Bool
+ let action: Action
+
+ var id: Action { action }
+}
+
+/// The composer's `/` commands, listed while the draft is just `/partial`: Fast mode and New
+/// session run here through host methods (`updateBot`, `newSession`); a skill fills in
+/// `/<id> `, and the host turns that message into "read this skill first"
+/// (`host/src/market/skills.rs` `expand_command`). docs/features/marketplace.md, "Commands".
+enum SlashCommands {
+ /// The first host that understands `/skill` messages; older ones get the text as typed.
+ static let minSkillsHost = "2.14.1"
+
+ /// The command name being typed after a leading `/`, before any space.
+ static func query(_ draft: String) -> String? {
+ guard draft.hasPrefix("/"), !draft.contains(where: \.isWhitespace) else { return nil }
+ return String(draft.dropFirst())
+ }
+
+ /// Built-in commands, then the bot's skills, whose name or title holds `query` (none in a group).
+ static func list(for bot: Bot?, query: String, skills: [InstalledSkill]) -> [SlashCommand] {
+ guard let bot, !bot.isGroup else { return [] }
+ let own = skills.filter { bot.skills.contains($0.id) }.map {
+ SlashCommand(name: $0.id, icon: "book.pages", title: $0.name, detail: $0.description, warning: false, action: .skill($0.id))
+ }
+ return (builtIn(bot) + own).filter {
+ query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) || $0.title.localizedCaseInsensitiveContains(query)
+ }
+ }
+
+ /// A draft that is just a built-in command (`/fast`, `/new`): sending it runs the command.
+ static func builtIn(for bot: Bot?, draft: String) -> SlashCommand? {
+ guard let bot, let name = query(draft.trimmingCharacters(in: .whitespacesAndNewlines)) else { return nil }
+ return builtIn(bot).first { $0.name == name }
+ }
+
+ private static func builtIn(_ bot: Bot) -> [SlashCommand] {
+ guard !bot.isGroup else { return [] }
+ var commands: [SlashCommand] = []
+ if bot.fastModeShown {
+ commands.append(SlashCommand(name: "fast", icon: "bolt", title: "Fast mode", detail: bot.fastModeDetail,
+ warning: bot.fastModeState == .refused, action: .fast))
+ }
+ commands.append(SlashCommand(name: "new", icon: "arrow.counterclockwise", title: "New session",
+ detail: "Start over with a fresh context; the transcript stays", warning: false, action: .newSession))
+ return commands
+ }
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index b79a903b..f28b281f 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -9,8 +9,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
-- 快速模式改成在輸入框輸入 /fast 開關:打 / 就會在選單最前面看到快速模式和它目前的狀態,點一下或送出 /fast 即可切換。
+- 在輸入框打 / 就會列出所有指令:快速模式、開新工作階段,以及 bot 的 skills,每一項都附上說明。快速模式改從這裡開關,不再放在 + 選單。
### en-US
-- Fast mode now lives in the composer's / menu: type / to see it first, with whether it's on, and tap it or send /fast to switch it.
+- Type / in the composer to see every command with what it does: Fast mode, New session and the bot's skills. Fast mode now switches from here instead of the + menu.
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index 555aceea..7fd68eac 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -25,10 +25,20 @@ Skills follow the same rule: an installed or hand-written skill is turned on for
Clicking a skill (an Extensions row, an installed skill, or the info button beside a skill's switch in bot settings; in the terminal, ↵ on a skill, or `i` on the bot form's Skills field) opens its details: the description and its instructions, with Add while it isn't installed. `skillDetails {id}` (installed) or `{source}` (catalog) returns `{markdown}`: the `SKILL.md` body without its front matter, at most 256 KB. The host looks names up in the installed list or the catalog cache, never as a path; the catalog fetch already downloads every `SKILL.md`, so the bodies stay in that cache. An Extensions row opens its details, or does what its button does when it has none (connectors open their install sheet).
-Typing `/` at the start of a message to a bot (desktop, iPhone, terminal; not in a group, where each member has its own skills) lists that bot's skills, after the built-in `/fast` when the bot offers [Fast mode](#fast-mode); picking a skill fills in `/<skill id> `. The host sees a message starting with `/<id of a skill the bot has on>` and hands the agent `[Codync: the user picked the "<name>" skill for this message. Read <path> first and follow it.]` followed by the rest of the message; the chat keeps the text as typed. Any other `/command` reaches the agent unchanged, so its own commands keep working. Clients show the menu and load skill instructions only from hosts 2.14.1 and newer.
-
Registry-backed package connectors follow their upstream release. The host checks the Registry periodically after credentials are unlocked and checks again immediately before a package process starts. If a newer pinned npm, PyPI, OCI or NuGet reference is available, only that package/image argument is replaced; the running process is not interrupted, and the new version applies on its next launch. Network failures, missing packages and attempted downgrades leave the installed reference unchanged. Custom command connectors are never updated automatically.
+## Commands
+
+Typing `/` at the start of a message to a bot (desktop, iPhone, terminal; not in a group, where each member has its own agent and skills) lists that bot's commands, filtered by what follows the `/` (a command's name or title): the built-in ones first, then the skills the bot has on. Each row shows an icon, the title and what it does. The list floats above the box on the desktop (↑/↓ move the highlight, Tab or Return picks it, Escape hides the list until the draft changes, hover and click work too), sits inline above the box on the iPhone (a tap picks; it isn't a menu, so the system-menu rule doesn't apply), and is the highlighted list over the transcript in the terminal (↑/↓, Tab or ↵).
+
+| Command | Title | Does |
+| --- | --- | --- |
+| `/fast` | Fast mode | Switches [Fast mode](#fast-mode) with `updateBot`; listed only while the bot offers it. Its detail says what picking it does, or why the agent refused it (warning color). |
+| `/new` | New session | `newSession`: the agent starts over with a fresh context and the transcript stays. No confirmation, unlike the bot menu's New session, because typing the command is the confirmation. |
+| `/<skill id>` | the skill's name | Fills in `/<skill id> ` for the rest of the message. |
+
+Picking a built-in command, or sending a message that is just one (`/fast`, `/new`), runs it in the client and clears the box; nothing reaches the agent. Return on a skill whose name is already typed out sends the message. The host sees a message starting with `/<id of a skill the bot has on>` and hands the agent `[Codync: the user picked the "<name>" skill for this message. Read <path> first and follow it.]` followed by the rest of the message; the chat keeps the text as typed. Any other `/command`, including `/fast` for a bot without Fast mode on offer, reaches the agent unchanged, so its own commands keep working. Clients list skills and load skill instructions only from hosts 2.14.1 and newer.
+
## Sign-in for remote connectors (`host/src/market/oauth.rs`)
Installing a remote connector probes it: a 401 to `initialize`, or (with no headers given) protected-resource metadata naming an authorization server, for servers like Call2Me that only refuse tool calls, marks it `signedOut`, and bots don't get it until someone signs in. Sign-in follows the MCP authorization spec: protected-resource metadata → authorization-server metadata → dynamic client registration (both redirect URIs at once) → PKCE. Tokens stay on the computer and are refreshed on use (or after a 401).
@@ -77,7 +87,7 @@ The bot's runtime carries what the agent says (`fastModeSupport`, `fastModeIssue
Clients show Fast mode for an agent bot whose runtime says `offered` or `refused`, or while it's on (so it can be turned off); never for a group:
-- Composer: `/fast`, a client command rather than a button. Typing `/` (or a start of "fast mode") puts a Fast mode entry first in the `/` menu, with its state (On, Off, or Refused in the warning color, the reason in its tooltip / accessibility hint; the terminal shows it as the row's description). Picking it, or sending a message that is just `/fast`, switches Fast mode with `updateBot` and clears the box; nothing reaches the agent. Without Fast mode on offer, `/fast` is an ordinary message. The terminal UI also shows `⚡ fast` or `⚡ refused` in the chat header.
+- Composer: the `/fast` [command](#commands), not a button. The terminal UI also shows `⚡ fast` or `⚡ refused` in the chat header.
- Bot settings: a Fast mode switch row under Model when the agent's model list offers it (never for a custom command), when the bot's own sessions do, or while it's on. While refused, its detail gives the reason. The terminal UI form always lists the field and notes when the agent doesn't offer it.
## Secure connection setup
diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rs
index 7413d17b..3eb5a9dd 100644
--- a/host/src/tui/app/input.rs
+++ b/host/src/tui/app/input.rs
@@ -89,7 +89,7 @@ impl App {
self.typing = false;
return;
};
- if self.complete_skill(k) {
+ if self.slash_key(k) {
return;
}
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
@@ -106,7 +106,7 @@ impl App {
if text.is_empty() && files.is_empty() {
return;
}
- if files.is_empty() && self.fast_command(&text) {
+ if files.is_empty() && self.built_in_command(&text) {
return;
}
if let Some(m) = &self.mismatch {
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index e62983ea..0373c51a 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -15,6 +15,7 @@ mod ui;
pub use editor::Editor;
pub use exchange::{ConversationRow, Exchange, Item, Outcome, conversation, group, rows};
pub use model::{After, AgentModel, Bot, Entry, Kind, Mark, ModelOption, Msg, Status};
+pub use slash::SlashAction;
pub use ui::{
ACTIONS, Action, AgentPicker, COLORS, Click, Confirm, ConfirmAct, Dir, FIELDS, FILTERS, Field, Focus, FolderPicker,
Form, Goto, GotoItem, GroupField, GroupForm, Hits, NEW_GROUP, Overlay, SHAPES, Toast, Toggle, TraceMode, Width,
@@ -59,6 +60,8 @@ pub struct App {
/// Narrow layout: showing the chat page (else the roster page).
pub chat_page: bool,
pub drafts: HashMap<String, Editor>,
+ /// The `/` list's highlighted row and the draft it was picked for.
+ pub slash_pick: (String, usize),
/// Files dropped on the composer (pasted paths), per draft like the text.
pub files: HashMap<String, Vec<std::path::PathBuf>>,
pub download: Option<super::net::files::Download>,
@@ -133,6 +136,7 @@ impl App {
typing: false,
chat_page: false,
drafts: HashMap::new(),
+ slash_pick: (String::new(), 0),
files: HashMap::new(),
sends: HashMap::new(),
chat_scroll: 0,
diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rs
index 60a4de10..2128f7ef 100644
--- a/host/src/tui/app/model.rs
+++ b/host/src/tui/app/model.rs
@@ -173,6 +173,15 @@ impl Bot {
})
}
+ /// What picking `/fast` does, or why Fast mode isn't in effect.
+ pub fn fast_detail(&self) -> String {
+ match self.fast_refusal() {
+ Some(why) => why,
+ None if self.fast_mode => "Turn off and return to standard speed".to_owned(),
+ None => "Turn on for faster replies and more usage".to_owned(),
+ }
+ }
+
/// Where it works, as the header shows it.
pub fn folder(&self, home: &str) -> String {
if self.managed_workspace { "personal workspace".to_owned() } else { tilde(&self.cwd, home) }
diff --git a/host/src/tui/app/slash.rs b/host/src/tui/app/slash.rs
index 90033350..9681e585 100644
--- a/host/src/tui/app/slash.rs
+++ b/host/src/tui/app/slash.rs
@@ -1,79 +1,142 @@
-//! The composer's `/` menu: Fast mode and the bot's skills, offered while the draft is just `/partial`.
+//! The composer's `/` commands, listed while the draft is just `/partial`: Fast mode and New
+//! session run here (`updateBot`, `newSession`); a skill fills in `/<id> `, which the host turns
+//! into "read this skill first" (`market::expand_command`).
use crossterm::event::{KeyCode, KeyEvent};
use serde_json::json;
use super::{After, App, Editor};
-/// `/fast` switches the bot's Fast mode instead of going to the agent.
-const FAST: &str = "/fast";
+/// What picking a command does.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SlashAction {
+ Fast,
+ NewSession,
+ Skill,
+}
-/// What the menu offers: Fast mode or one of the bot's skills.
-pub struct SlashMatch {
- pub id: String,
+/// A command the list offers.
+pub struct SlashCommand {
+ /// What follows the `/`.
pub name: String,
- pub description: String,
+ pub title: String,
+ pub detail: String,
+ pub action: SlashAction,
+}
+
+impl SlashCommand {
+ /// The row's text after `/name`.
+ pub fn about(&self) -> String {
+ match self.action {
+ SlashAction::Skill if self.detail.is_empty() => self.title.clone(),
+ SlashAction::Skill => self.detail.replace('\n', " "),
+ _ => format!("{} · {}", self.title, self.detail),
+ }
+ }
}
impl App {
- /// Fast mode, then the selected bot's skills, whose id or name holds the `/partial` being
- /// typed (none in a group).
- pub fn slash_matches(&self) -> Vec<SlashMatch> {
+ /// The selected bot's built-in commands; a group has none.
+ fn built_in(&self) -> Vec<SlashCommand> {
+ let Some(bot) = self.bot().filter(|b| !b.group) else { return vec![] };
+ let fast = bot.fast_shown().then(|| SlashCommand {
+ name: "fast".into(),
+ title: "Fast mode".into(),
+ detail: bot.fast_detail(),
+ action: SlashAction::Fast,
+ });
+ let new = SlashCommand {
+ name: "new".into(),
+ title: "New session".into(),
+ detail: "Start over with a fresh context; the transcript stays".into(),
+ action: SlashAction::NewSession,
+ };
+ fast.into_iter().chain([new]).collect()
+ }
+
+ /// Built-in commands, then the selected bot's skills, whose name or title holds the
+ /// `/partial` being typed (none in a group).
+ pub fn slash_commands(&self) -> Vec<SlashCommand> {
let Some(bot) = self.bot().filter(|b| !b.group) else { return vec![] };
let draft = self.draft();
let Some((query, None)) = crate::market::slash_command(&draft.text) else { return vec![] };
let query = query.to_lowercase();
- let fast = (bot.fast_shown() && "fast mode".contains(&query)).then(|| SlashMatch {
- id: FAST[1..].to_owned(),
- name: "Fast mode".to_owned(),
- description: match bot.fast_refusal() {
- Some(why) => format!("Fast mode refused · {why}"),
- None if bot.fast_mode => "Fast mode on".to_owned(),
- None => "Fast mode off · faster replies, more usage".to_owned(),
- },
- });
let skills = self.plugins.1.iter().filter_map(|s| {
let id = s["id"].as_str()?;
- let name = s["name"].as_str().unwrap_or(id);
- let hit = id.contains(&query) || name.to_lowercase().contains(&query);
- (hit && bot.skills.iter().any(|on| on == id)).then(|| SlashMatch {
- id: id.to_owned(),
- name: name.to_owned(),
- description: s["description"].as_str().unwrap_or_default().to_owned(),
+ bot.skills.iter().any(|on| on == id).then(|| SlashCommand {
+ name: id.to_owned(),
+ title: s["name"].as_str().unwrap_or(id).to_owned(),
+ detail: s["description"].as_str().unwrap_or_default().to_owned(),
+ action: SlashAction::Skill,
})
});
- fast.into_iter().chain(skills).collect()
+ self.built_in()
+ .into_iter()
+ .chain(skills)
+ .filter(|c| c.name.contains(&query) || c.title.to_lowercase().contains(&query))
+ .collect()
}
- /// A draft that is just `/fast` switches Fast mode instead of being sent. Returns whether it did.
- pub(super) fn fast_command(&mut self, text: &str) -> bool {
- let Some(b) = self.bot().filter(|b| b.fast_shown() && text == FAST) else { return false };
- let (id, on) = (b.id.clone(), !b.fast_mode);
- self.call("updateBot", json!({"id": id, "fastMode": on}), After::Nothing);
- self.flash(if on { "Fast mode on" } else { "Fast mode off" });
- if let Some(key) = self.draft_key() {
- self.drafts.remove(&key);
- }
- true
+ /// The highlighted row of `count`: kept while the draft stays the same, else the first.
+ pub fn slash_selected(&self, count: usize) -> usize {
+ let (draft, index) = &self.slash_pick;
+ if *draft == self.draft().text { (*index).min(count.saturating_sub(1)) } else { 0 }
}
- /// Tab, or Return before the name is complete, fills in the first match. Returns whether it did.
- pub(super) fn complete_skill(&mut self, k: KeyEvent) -> bool {
- if !k.modifiers.is_empty() || !matches!(k.code, KeyCode::Tab | KeyCode::Enter) {
+ /// Keys while the list is up: ↑/↓ move, Tab or Return runs the highlighted command (Return
+ /// sends a skill whose name is already typed out). Returns whether it took the key.
+ pub(super) fn slash_key(&mut self, k: KeyEvent) -> bool {
+ if !k.modifiers.is_empty() {
return false;
}
- let matches = self.slash_matches();
- let Some(first) = matches.first() else { return false };
+ let commands = self.slash_commands();
+ let Some(n) = std::num::NonZeroUsize::new(commands.len()).map(usize::from) else { return false };
let typed = self.draft().text;
- // `/pdf` already names a skill (or `/fast` the command): Return sends it.
- if k.code == KeyCode::Enter && matches.iter().any(|m| typed[1..] == m.id) {
- return false;
+ let sel = self.slash_selected(n);
+ match k.code {
+ KeyCode::Down => self.slash_pick = (typed, (sel + 1) % n),
+ KeyCode::Up => self.slash_pick = (typed, (sel + n - 1) % n),
+ KeyCode::Tab | KeyCode::Enter => {
+ let picked = &commands[sel];
+ if k.code == KeyCode::Enter && picked.action == SlashAction::Skill && typed[1..] == picked.name {
+ return false;
+ }
+ self.run_slash(picked);
+ }
+ _ => return false,
}
- let Some(key) = self.draft_key() else { return false };
- self.drafts.insert(key, Editor::with(&format!("/{} ", first.id)));
true
}
+ /// A draft that is just a built-in command (`/fast`, `/new`) runs it instead of being sent.
+ /// Returns whether it did.
+ pub(super) fn built_in_command(&mut self, text: &str) -> bool {
+ let Some(name) = text.strip_prefix('/') else { return false };
+ let Some(command) = self.built_in().into_iter().find(|c| c.name == name) else { return false };
+ self.run_slash(&command);
+ true
+ }
+
+ fn run_slash(&mut self, command: &SlashCommand) {
+ let Some((id, fast)) = self.bot().map(|b| (b.id.clone(), b.fast_mode)) else { return };
+ let fill = match command.action {
+ SlashAction::Fast => {
+ self.call("updateBot", json!({"id": id, "fastMode": !fast}), After::Nothing);
+ self.flash(if fast { "Fast mode off" } else { "Fast mode on" });
+ String::new()
+ }
+ SlashAction::NewSession => {
+ self.call("newSession", json!({"botId": id}), After::Nothing);
+ self.flash("New session");
+ String::new()
+ }
+ SlashAction::Skill => format!("/{} ", command.name),
+ };
+ if let Some(key) = self.draft_key() {
+ self.drafts.insert(key, Editor::with(&fill));
+ }
+ }
+
/// Starting a draft with `/` loads the computer's skills again, so the menu is current.
pub(super) fn slash_typed(&self) {
if self.bot().is_some_and(|b| !b.group) && self.draft().text == "/" {
@@ -88,46 +151,62 @@ mod tests {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::json;
- #[tokio::test]
- async fn the_menu_offers_and_fills_in_the_bots_skills() {
+ fn app_with(bot: &serde_json::Value) -> super::App {
let mut app = test_app();
- let bot = Bot::parse(&json!({"id": "b", "name": "Bot", "skills": ["pdf", "docx"]})).expect("a bot parses");
- app.bots.insert("b".into(), bot);
+ app.bots.insert("b".into(), Bot::parse(bot).expect("a bot parses"));
app.selected = Some("b".into());
app.plugins.1 = vec![
json!({"id": "pdf", "name": "pdf", "description": "PDFs"}),
json!({"id": "docx", "name": "docx"}),
json!({"id": "xlsx", "name": "xlsx"}),
];
- let ids = |app: &super::App| app.slash_matches().into_iter().map(|m| m.id).collect::<Vec<_>>();
- let key = |code| KeyEvent::new(code, KeyModifiers::NONE);
+ app
+ }
+
+ fn names(app: &super::App) -> Vec<String> {
+ app.slash_commands().into_iter().map(|c| c.name).collect()
+ }
+
+ fn key(code: KeyCode) -> KeyEvent {
+ KeyEvent::new(code, KeyModifiers::NONE)
+ }
+
+ #[tokio::test]
+ async fn the_list_offers_built_in_commands_then_the_bots_skills() {
+ let mut app =
+ app_with(&json!({"id": "b", "name": "Bot", "skills": ["pdf", "docx"], "fastModeSupport": "offered"}));
app.drafts.insert("b".into(), super::Editor::with("/"));
- assert_eq!(ids(&app), ["pdf", "docx"], "only skills the bot has on");
- app.drafts.insert("b".into(), super::Editor::with("/pd"));
- assert_eq!(ids(&app), ["pdf"]);
- assert!(app.complete_skill(key(KeyCode::Enter)), "Return fills in an unfinished name");
+ assert_eq!(names(&app), ["fast", "new", "pdf", "docx"], "only skills the bot has on");
+ app.drafts.insert("b".into(), super::Editor::with("/session"));
+ assert_eq!(names(&app), ["new"], "titles match too");
+ app.bots.get_mut("b").expect("the bot").fast_support = "unsupported".into();
+ app.drafts.insert("b".into(), super::Editor::with("/"));
+ assert_eq!(names(&app), ["new", "pdf", "docx"], "no Fast mode on offer");
+ }
+
+ #[tokio::test]
+ async fn arrows_pick_a_row_and_return_runs_it() {
+ let mut app = app_with(&json!({"id": "b", "name": "Bot", "skills": ["pdf"], "fastModeSupport": "offered"}));
+ app.drafts.insert("b".into(), super::Editor::with("/"));
+ assert!(app.slash_key(key(KeyCode::Up)), "up wraps to the last row");
+ assert_eq!(app.slash_selected(3), 2);
+ assert!(app.slash_key(key(KeyCode::Enter)), "Return on a skill fills it in");
assert_eq!(app.draft().text, "/pdf ");
- assert!(ids(&app).is_empty(), "the menu closes once the name is done");
+ assert!(names(&app).is_empty(), "the list closes once the name is done");
app.drafts.insert("b".into(), super::Editor::with("/pdf"));
- assert!(!app.complete_skill(key(KeyCode::Enter)), "a full name sends");
- assert!(app.complete_skill(key(KeyCode::Tab)));
+ assert!(!app.slash_key(key(KeyCode::Enter)), "a skill already typed out sends");
+ app.drafts.insert("b".into(), super::Editor::with("/fa"));
+ assert!(app.slash_key(key(KeyCode::Tab)), "a built-in command runs");
+ assert_eq!(app.draft().text, "", "and the draft clears");
}
#[tokio::test]
- async fn fast_comes_first_and_switches_instead_of_sending() {
- let mut app = test_app();
- let bot = Bot::parse(&json!({"id": "b", "name": "Bot", "skills": ["fastlane"], "fastModeSupport": "offered"}))
- .expect("a bot parses");
- app.bots.insert("b".into(), bot);
- app.selected = Some("b".into());
- app.plugins.1 = vec![json!({"id": "fastlane", "name": "fastlane"})];
- let ids = |app: &super::App| app.slash_matches().into_iter().map(|m| m.id).collect::<Vec<_>>();
- app.drafts.insert("b".into(), super::Editor::with("/fa"));
- assert_eq!(ids(&app), ["fast", "fastlane"]);
- assert!(!app.fast_command("/fast please"), "only the bare command");
- assert!(app.fast_command("/fast"));
- assert_eq!(app.draft().text, "", "the draft clears");
+ async fn sending_just_a_built_in_command_runs_it() {
+ let mut app = app_with(&json!({"id": "b", "name": "Bot", "fastModeSupport": "offered"}));
+ assert!(!app.built_in_command("/fast please"), "only the bare command");
+ assert!(app.built_in_command("/new"));
+ assert!(app.built_in_command("/fast"));
app.bots.get_mut("b").expect("the bot").fast_support = "unsupported".into();
- assert!(!app.fast_command("/fast"), "without Fast mode it reaches the agent");
+ assert!(!app.built_in_command("/fast"), "without Fast mode it reaches the agent");
}
}
diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rs
index 8faebf4a..1fa5df33 100644
--- a/host/src/tui/view/chat.rs
+++ b/host/src/tui/view/chat.rs
@@ -5,7 +5,7 @@ use ratatui::layout::{Position, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
-use super::super::app::{App, Click, Editor, Mark, Status};
+use super::super::app::{App, Click, Editor, Mark, SlashAction, Status};
use super::super::md::{truncate, width as w};
use super::buffer::{fill, hline, put, put_line, rput, u};
use super::set_cursor;
@@ -193,25 +193,32 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
rput(buf, r.right() - 1, box_top.saturating_sub(1), &s, t.btn);
}
if typing {
- skill_menu(buf, body, app);
+ command_menu(buf, body, app);
}
}
-/// The `/` menu over the bottom of the transcript: Fast mode and the bot's skills matching what's typed.
-fn skill_menu(buf: &mut Buffer, body: Rect, app: &App) {
+/// The `/` list over the bottom of the transcript: the commands matching what's typed, the
+/// highlighted one kept in view.
+fn command_menu(buf: &mut Buffer, body: Rect, app: &App) {
let t = theme();
- let matches = app.slash_matches();
- let n = u(matches.len().min(5)).min(body.height);
- for (i, m) in matches.iter().take(usize::from(n)).enumerate() {
- let y = body.bottom() - n + u(i);
- fill(buf, Rect::new(body.x, y, body.width, 1), t.panel);
- let name = if i == 0 { t.bold } else { t.text };
- let x = put(buf, body.x + 3, y, 26, &truncate(&format!("/{}", m.id), 26), name.patch(t.panel)) + 2;
- let hint = if i == 0 { "tab fills in" } else { "" };
- let rx = rput(buf, body.right() - 1, y, hint, t.dim.patch(t.panel));
- let about = if m.description.is_empty() { &m.name } else { &m.description };
+ let commands = app.slash_commands();
+ let sel = app.slash_selected(commands.len());
+ let n = u(commands.len().min(5)).min(body.height);
+ let start = sel.saturating_sub(usize::from(n).saturating_sub(1));
+ for (row, (i, c)) in commands.iter().enumerate().skip(start).take(usize::from(n)).enumerate() {
+ let y = body.bottom() - n + u(row);
+ let bg = if i == sel { t.sel } else { t.panel };
+ fill(buf, Rect::new(body.x, y, body.width, 1), bg);
+ let name = if i == sel { t.bold } else { t.text };
+ let x = put(buf, body.x + 3, y, 26, &truncate(&format!("/{}", c.name), 26), name.patch(bg)) + 2;
+ let hint = match (i == sel, c.action) {
+ (false, _) => "",
+ (true, SlashAction::Skill) => "tab fills in",
+ (true, _) => "↵ runs",
+ };
+ let rx = rput(buf, body.right() - 1, y, hint, t.dim.patch(bg));
let room = usize::from(rx.saturating_sub(x + 1));
- put(buf, x, y, u(room), &truncate(&about.replace('\n', " "), room), t.secondary.patch(t.panel));
+ put(buf, x, y, u(room), &truncate(&c.about(), room), t.secondary.patch(bg));
}
}
diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rs
index c8075ca1..c3c495bd 100644
--- a/host/src/tui/view/help.rs
+++ b/host/src/tui/view/help.rs
@@ -44,7 +44,7 @@ const HELP: [(&str, &str, &str); 57] = [
("TYPE", "alt b / f", "word left / right"),
("TYPE", "^w ^u", "delete word / line"),
("TYPE", "@name", "group: ask just that bot"),
- ("TYPE", "/fast", "Fast mode on / off"),
+ ("TYPE", "/", "commands: /fast, /new, skills"),
("BOTS", "n", "new bot"),
("BOTS", "m", "new group chat"),
("BOTS", "e", "edit bot or group"),