The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): run /rollback, /agents, /config, /history on the owner's verbs
Teknium80d2db927c05
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-desktop-commands.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-desktop-commands.test.tsxnew file mode 100644index 00000000000..70a03901d38--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-desktop-commands.test.tsx@@ -0,0 +1,233 @@+import { cleanup } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { resolveDesktopCommand } from '@/lib/desktop-slash-commands'+import { $connection } from '@/store/session'+import { dropSessionState } from '@/store/session-states'++import { actRender, Harness, type HarnessHandle, RUNTIME_SESSION_ID } from './index-test-utils'+import { clearSingleFlightSessionResumeState } from './single-flight-resume'++// T11 (#134889): Desktop commands the shared gateway refused as `slash.exec`, or that Desktop never+// offered, run on the owner's existing verbs instead.++vi.mock('@/hermes', () => ({+ getLatestSessionMessages: vi.fn(async () => ({ messages: [], session_id: 'session' })),+ getProfiles: vi.fn(async () => ({ profiles: [] })),+ getSession: vi.fn(),+ PROMPT_SUBMIT_REQUEST_TIMEOUT_MS: 1_800_000,+ setApiRequestProfile: vi.fn(),+ transcribeAudio: vi.fn()+}))++vi.mock('@/store/gateway', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ requestGatewayForAgent: vi.fn()+}))++type Responder = (method: string, params?: Record<string, unknown>) => unknown++function gateway(respond: Responder) {+ return vi.fn(async (method: string, params?: Record<string, unknown>) => (respond(method, params) ?? {}) as never)+}++async function mount(requestGateway: ReturnType<typeof gateway>) {+ let handle: HarnessHandle | null = null+ await actRender(+ <Harness onReady={h => (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} />+ )++ return handle!+}++const callsOf = (requestGateway: ReturnType<typeof gateway>, method: string) =>+ requestGateway.mock.calls.filter(([name]) => name === method).map(([, params]) => params)++const renderedText = (handle: HarnessHandle) =>+ handle+ .state()+ .messages.flatMap(message => message.parts.map(part => ('text' in part ? String(part.text) : '')))+ .join('\n')++beforeEach(() => {+ clearSingleFlightSessionResumeState()+ $connection.set({ mode: 'local', wsUrl: 'ws://localhost/api/ws?native_dial=unminted' } as never)+})++afterEach(() => {+ cleanup()+ $connection.set(null)+ dropSessionState(RUNTIME_SESSION_ID)+ vi.restoreAllMocks()+})++describe('desktop surfaces for /rollback /agents /config /history', () => {+ it('routes each to a local action (never slash.exec, never "terminal only")', () => {+ for (const [name, action] of Object.entries({+ '/rollback': 'rollback',+ '/agents': 'agents',+ '/tasks': 'agents',+ '/config': 'config',+ '/history': 'history'+ })) {+ expect(resolveDesktopCommand(name)?.surface).toEqual({ kind: 'action', action })+ }+ })+})++const CHECKPOINTS = {+ enabled: true,+ checkpoints: [+ { hash: 'aaaa1111', timestamp: '2026-10-18T10:00:00', message: 'before write_file' },+ { hash: 'bbbb2222', timestamp: '2026-10-18T09:00:00', message: 'before patch' }+ ]+}++describe('/rollback', () => {+ it('lists checkpoints through rollback.list', async () => {+ const requestGateway = gateway(method => (method === 'rollback.list' ? CHECKPOINTS : undefined))+ const handle = await mount(requestGateway)++ await handle.submitText('/rollback')++ expect(callsOf(requestGateway, 'rollback.list')).toEqual([{ session_id: RUNTIME_SESSION_ID }])+ expect(callsOf(requestGateway, 'slash.exec')).toEqual([])+ const text = renderedText(handle)+ expect(text).toContain('1. aaaa1111')+ expect(text).toContain('before patch')+ })++ it('says checkpoints are off when the owner reports them disabled', async () => {+ const requestGateway = gateway(method =>+ method === 'rollback.list' ? { enabled: false, checkpoints: [] } : undefined+ )++ const handle = await mount(requestGateway)++ await handle.submitText('/rollback list')++ expect(renderedText(handle)).toMatch(/checkpoints are not enabled/i)+ })++ it('restores checkpoint N (with --all and a file) through rollback.restore', async () => {+ const requestGateway = gateway(method =>+ method === 'rollback.restore' ? { success: true, restored_to: 'aaaa1111', history_removed: 2 } : undefined+ )++ const handle = await mount(requestGateway)++ await handle.submitText('/rollback 1 --all')+ await handle.submitText('/rollback 2 src/app.py')++ expect(callsOf(requestGateway, 'rollback.restore')).toEqual([+ { session_id: RUNTIME_SESSION_ID, hash: '1', all: true },+ { session_id: RUNTIME_SESSION_ID, hash: '2', file_path: 'src/app.py' }+ ])+ expect(renderedText(handle)).toContain('aaaa1111')+ })++ it('shows a failed restore as an error, and diffs through rollback.diff', async () => {+ const requestGateway = gateway(method => {+ if (method === 'rollback.restore') {+ return { success: false, error: 'Invalid checkpoint number. Use 1-2.' }+ }++ if (method === 'rollback.diff') {+ return { stat: ' a.py | 2 +-', diff: '-old\n+new' }+ }+ })++ const handle = await mount(requestGateway)++ await handle.submitText('/rollback 9')+ await handle.submitText('/rollback diff 1')++ expect(callsOf(requestGateway, 'rollback.diff')).toEqual([{ session_id: RUNTIME_SESSION_ID, hash: '1' }])+ const text = renderedText(handle)+ expect(text).toContain('Invalid checkpoint number')+ expect(text).toContain('+new')+ })+})++describe('/agents', () => {+ it("reads this session's subagents and background processes from the owner", async () => {+ const requestGateway = gateway(method => {+ if (method === 'subagent.list') {+ return {+ subagents: [{ subagent_id: 'sa-1', depth: 1, goal: 'research the API', status: 'running', tool_count: 3 }]+ }+ }++ if (method === 'process.list') {+ return { processes: [{ session_id: 'proc_1', command: 'npm run dev', status: 'running' }] }+ }+ })++ const handle = await mount(requestGateway)++ await handle.submitText('/tasks')++ expect(callsOf(requestGateway, 'subagent.list')).toEqual([{ session_id: RUNTIME_SESSION_ID }])+ expect(callsOf(requestGateway, 'process.list')).toEqual([{ session_id: RUNTIME_SESSION_ID }])+ expect(callsOf(requestGateway, 'slash.exec')).toEqual([])+ const text = renderedText(handle)+ expect(text).toContain('research the API')+ expect(text).toContain('npm run dev')+ })++ it('says nothing is running when both lists are empty', async () => {+ const requestGateway = gateway(method =>+ method === 'subagent.list' ? { subagents: [] } : method === 'process.list' ? { processes: [] } : undefined+ )++ const handle = await mount(requestGateway)++ await handle.submitText('/agents')++ expect(renderedText(handle)).toMatch(/no active subagents or background processes/i)+ })+})++describe('/config', () => {+ it("shows the profile's client config projection from config.get", async () => {+ const requestGateway = gateway(method =>+ method === 'config.get' ? { config: { display: { skin: 'mono', timestamps: true } } } : undefined+ )++ const handle = await mount(requestGateway)++ await handle.submitText('/config')++ expect(callsOf(requestGateway, 'config.get')).toEqual([{ session_id: RUNTIME_SESSION_ID, key: 'full' }])+ const text = renderedText(handle)+ expect(text).toContain('skin: mono')+ expect(text).toContain('Settings')+ })+})++describe('/history', () => {+ it("renders the owner's transcript snapshot", async () => {+ const requestGateway = gateway(method =>+ method === 'session.resume'+ ? {+ messages: [+ { role: 'user', content: 'first question', row_id: 1 },+ { role: 'assistant', content: [{ type: 'text', text: 'first answer' }], row_id: 2 },+ { role: 'tool', content: 'tool noise', row_id: 3 }+ ]+ }+ : undefined+ )++ const handle = await mount(requestGateway)++ await handle.submitText('/history')++ expect(callsOf(requestGateway, 'session.resume')).toEqual([{ session_id: RUNTIME_SESSION_ID }])+ expect(callsOf(requestGateway, 'slash.exec')).toEqual([])+ const text = renderedText(handle)+ expect(text).toContain('You: first question')+ expect(text).toContain('Hermes: first answer')+ expect(text).not.toContain('tool noise')+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-desktop-commands.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-desktop-commands.tsnew file mode 100644index 00000000000..8d0241ec131--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash-desktop-commands.ts@@ -0,0 +1,310 @@+import type { GatewayRequest } from './utils'++// T11 (#134889): /rollback, /agents (/tasks), /config and /history on the session owner's existing+// verbs. The shared gateway refuses these as `slash.exec` (`gateway/session_commands.py`), and+// `/config` / `/history` were marked terminal-only, so Desktop either dead-ended or never offered them.+// Each verb here is the one Ink and the owner already serve: rollback.list|diff|restore,+// subagent.list + process.list, config.get key=full (the presentation-only projection) and the+// session.resume transcript snapshot.++interface SlashOutput {+ render: (text: string) => void+ sessionId: string+}++export interface DesktopReadCommandEnv<C extends { arg: string }> {+ requestGateway: GatewayRequest+ withSlashOutput: (ctx: C) => Promise<null | SlashOutput>+}++interface CheckpointRow {+ hash?: string+ message?: string+ timestamp?: string+}++interface RestoreResult {+ error?: string+ history_removed?: number+ reason?: string+ restored_to?: string+ success?: boolean+}++const errorText = (err: unknown) => `error: ${err instanceof Error ? err.message : String(err)}`++const ROLLBACK_USAGE = 'usage: /rollback [list] | diff <n|hash> | <n|hash> [file] [--all]'+const HISTORY_PREVIEW = 400++function formatCheckpoints(result: { checkpoints?: CheckpointRow[]; enabled?: boolean } | null): string {+ if (result?.enabled === false) {+ return 'Checkpoints are not enabled for this session (set checkpoints.enabled in config.yaml).'+ }++ const rows = Array.isArray(result?.checkpoints) ? result.checkpoints : []++ if (!rows.length) {+ return 'No checkpoints yet for this working directory.'+ }++ return [+ 'Checkpoints (newest first):',+ ...rows.map((row, index) =>+ `${index + 1}. ${String(row.hash ?? '').slice(0, 8)} ${row.timestamp ?? ''} ${row.message ?? ''}`.trimEnd()+ ),+ '',+ 'Restore with /rollback <n> [file] (add --all to also overwrite your own edits); preview with /rollback diff <n>.'+ ].join('\n')+}++/** `/rollback` argument words → the owner verb and its params; null for a usage error. */+export function rollbackRequest(+ arg: string+): { method: 'rollback.diff' | 'rollback.list' | 'rollback.restore'; params: Record<string, unknown> } | null {+ const words = arg.trim().split(/\s+/).filter(Boolean)+ const all = words.includes('--all')+ const rest = words.filter(word => word !== '--all')+ const first = rest[0]?.toLowerCase() ?? ''++ if (!first || first === 'list' || first === 'ls') {+ return rest.length <= 1 && !all ? { method: 'rollback.list', params: {} } : null+ }++ if (first === 'diff') {+ return rest.length === 2 && !all ? { method: 'rollback.diff', params: { hash: rest[1] } } : null+ }++ const filePath = rest.slice(1).join(' ')++ return {+ method: 'rollback.restore',+ params: { hash: rest[0], ...(filePath ? { file_path: filePath } : {}), ...(all ? { all: true } : {}) }+ }+}++function formatRestore(result: RestoreResult | null): string {+ if (!result?.success) {+ return `Rollback failed: ${result?.error || 'unknown error'}`+ }++ const lines = [`Restored checkpoint ${result.restored_to ?? ''}.`.replace(' .', '.')]++ if (result.reason) {+ lines.push(result.reason)+ }++ if (result.history_removed) {+ lines.push(`Rewound ${result.history_removed} message(s) from this conversation.`)+ }++ return lines.join('\n')+}++interface SubagentRow {+ depth?: number+ goal?: string+ model?: string+ status?: string+ subagent_id?: string+ tool_count?: number+}++interface ProcessRow {+ command?: string+ session_id?: string+ status?: string+}++function formatAgents(subagents: SubagentRow[], processes: ProcessRow[]): string {+ const running = processes.filter(row => !row.status || row.status === 'running')++ if (!subagents.length && !running.length) {+ return 'No active subagents or background processes in this chat.'+ }++ const lines: string[] = []++ if (subagents.length) {+ lines.push(`Subagents (${subagents.length}):`)++ for (const row of subagents) {+ const indent = ' '.repeat(Math.max(0, Number(row.depth ?? 1) - 1))+ const tools = row.tool_count ? ` · ${row.tool_count} tool calls` : ''+ lines.push(`${indent}- [${row.status ?? 'running'}] ${row.goal || row.subagent_id || 'subagent'}${tools}`)+ }+ }++ if (running.length) {+ lines.push(`Background processes (${running.length}):`)++ for (const row of running) {+ lines.push(`- ${row.session_id ?? ''} ${row.command ?? ''}`.trimEnd())+ }+ }++ return lines.join('\n')+}++function yamlLines(value: unknown, indent = ''): string[] {+ if (value === null || typeof value !== 'object') {+ return [`${indent}${String(value)}`]+ }++ return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) =>+ child !== null && typeof child === 'object' && !Array.isArray(child)+ ? [`${indent}${key}:`, ...yamlLines(child, `${indent} `)]+ : [`${indent}${key}: ${Array.isArray(child) ? JSON.stringify(child) : String(child)}`]+ )+}++function contentText(content: unknown): string {+ if (typeof content === 'string') {+ return content+ }++ if (Array.isArray(content)) {+ return content+ .map(part =>+ part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string'+ ? (part as { text: string }).text+ : ''+ )+ .filter(Boolean)+ .join(' ')+ }++ return ''+}++interface HistoryRow {+ archived?: unknown+ content?: unknown+ display_kind?: unknown+ role?: unknown+ text?: unknown+}++export function formatHistory(rows: HistoryRow[]): string {+ const turns = rows.flatMap(row => {+ if (row.archived || (row.role !== 'user' && row.role !== 'assistant')) {+ return []+ }++ const text = (contentText(row.content) || (typeof row.text === 'string' ? row.text : '')).trim()++ if (!text) {+ return []+ }++ const clipped = text.length > HISTORY_PREVIEW ? `${text.slice(0, HISTORY_PREVIEW)}…` : text++ return [`${row.role === 'user' ? 'You' : 'Hermes'}: ${clipped}`]+ })++ return turns.length ? [`Conversation history (${turns.length} messages):`, ...turns].join('\n') : 'No messages yet.'+}++export function desktopReadCommandHandlers<C extends { arg: string }>(env: DesktopReadCommandEnv<C>) {+ const { requestGateway } = env++ return {+ rollback: async (ctx: C) => {+ const out = await env.withSlashOutput(ctx)++ if (!out) {+ return+ }++ const request = rollbackRequest(ctx.arg)++ if (!request) {+ return out.render(ROLLBACK_USAGE)+ }++ try {+ const result = await requestGateway<unknown>(request.method, { session_id: out.sessionId, ...request.params })++ if (request.method === 'rollback.list') {+ return out.render(formatCheckpoints(result as Parameters<typeof formatCheckpoints>[0]))+ }++ if (request.method === 'rollback.diff') {+ const diff = result as { diff?: string; stat?: string } | null++ return out.render([diff?.stat, diff?.diff].filter(Boolean).join('\n') || 'No changes since that checkpoint.')+ }++ out.render(formatRestore(result as RestoreResult | null))+ } catch (err) {+ out.render(errorText(err))+ }+ },+ agents: async (ctx: C) => {+ const out = await env.withSlashOutput(ctx)++ if (!out) {+ return+ }++ try {+ const [subagents, processes] = await Promise.all([+ requestGateway<{ subagents?: SubagentRow[] }>('subagent.list', { session_id: out.sessionId }),+ requestGateway<{ processes?: ProcessRow[] }>('process.list', { session_id: out.sessionId })+ ])++ out.render(+ formatAgents(+ Array.isArray(subagents?.subagents) ? subagents.subagents : [],+ Array.isArray(processes?.processes) ? processes.processes : []+ )+ )+ } catch (err) {+ out.render(errorText(err))+ }+ },+ config: async (ctx: C) => {+ const out = await env.withSlashOutput(ctx)++ if (!out) {+ return+ }++ try {+ const result = await requestGateway<{ config?: unknown }>('config.get', {+ session_id: out.sessionId,+ key: 'full'+ })++ const body = result?.config && typeof result.config === 'object' ? yamlLines(result.config) : []++ out.render(+ [+ 'Configuration (display settings; secrets and provider config are not shown):',+ ...(body.length ? body : ['(defaults)']),+ '',+ 'Change settings in Settings, or edit config.yaml with `hermes config edit` on the gateway host.'+ ].join('\n')+ )+ } catch (err) {+ out.render(errorText(err))+ }+ },+ history: async (ctx: C) => {+ const out = await env.withSlashOutput(ctx)++ if (!out) {+ return+ }++ try {+ const snapshot = await requestGateway<{ messages?: HistoryRow[] }>('session.resume', {+ session_id: out.sessionId+ })++ out.render(formatHistory(Array.isArray(snapshot?.messages) ? snapshot.messages : []))+ } catch (err) {+ out.render(errorText(err))+ }+ }+ }+}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex 2deb0a9a6bf..9ca3b84513b 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -72,6 +72,7 @@ import type {import { adoptPreparedSubmission, preparedSubmissionKey } from './prepared-submissions'import { queueKickoffIfSessionBusy } from './queue-if-busy'import { resolveTargetSessionId } from './resolve-target-session'+import { desktopReadCommandHandlers } from './slash-desktop-commands'import { sessionCommandHandlers } from './slash-session-commands'import { captureSubmissionDestination } from './submission-destination'import {@@ -642,6 +643,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {updateSessionState,withSlashOutput}),+ ...desktopReadCommandHandlers<SlashActionCtx>({ requestGateway, withSlashOutput }),new: async () => {prepareDefaultNewSession()startFreshSessionDraft()diff --git a/apps/desktop/src/lib/desktop-slash-commands.test.ts b/apps/desktop/src/lib/desktop-slash-commands.test.tsindex 834e4e72c1f..a224020819d 100644--- a/apps/desktop/src/lib/desktop-slash-commands.test.ts+++ b/apps/desktop/src/lib/desktop-slash-commands.test.ts@@ -199,7 +199,7 @@ describe('desktop slash command curation', () => {// print lands after the capture window closes, so the result never// reached the originating conversation).// /undo /retry /steer /queue are local actions now: the shared gateway refuses them as exec.- const execNames = ['/debug', '/goal', '/personality', '/rollback', '/tools', '/version']+ const execNames = ['/debug', '/goal', '/personality', '/tools', '/version']for (const name of execNames) {expect(resolveDesktopCommand(name)?.surface).toEqual({ kind: 'exec' })diff --git a/apps/desktop/src/lib/desktop-slash-commands.ts b/apps/desktop/src/lib/desktop-slash-commands.tsindex 6466cdbed03..443d6567800 100644--- a/apps/desktop/src/lib/desktop-slash-commands.ts+++ b/apps/desktop/src/lib/desktop-slash-commands.ts@@ -58,14 +58,17 @@ export interface DesktopThemeCommandOption {* keyed by the id.*/export type DesktopActionId =+ | 'agents'| 'background'| 'branch'| 'browser'| 'btw'| 'compress'+ | 'config'| 'handoff'| 'hatch'| 'help'+ | 'history'| 'journey'| 'new'| 'pet'@@ -73,6 +76,7 @@ export type DesktopActionId =| 'queue'| 'reasoning'| 'retry'+ | 'rollback'| 'skin'| 'steer'| 'stop'@@ -324,6 +328,22 @@ const DESKTOP_COMMAND_SPECS: readonly DesktopCommandSpec[] = [aliases: ['/generate-pet'],surface: action('hatch')},+ // T11: commands the shared gateway refuses as slash.exec (or Desktop marked terminal-only), on the+ // owner's existing verbs (slash-desktop-commands.ts).+ {+ name: '/rollback',+ description: 'List, diff or restore filesystem checkpoints [list|diff <n>|<n> [file] [--all]]',+ surface: action('rollback'),+ argumentMode: 'text'+ },+ {+ name: '/agents',+ description: 'Show active subagents and background processes',+ aliases: ['/tasks'],+ surface: action('agents')+ },+ { name: '/config', description: 'Show current configuration', surface: action('config') },+ { name: '/history', description: 'Show conversation history', surface: action('history') },{name: '/save',description: 'Save the current transcript to JSON',diff --git a/apps/desktop/src/lib/desktop-slash-registry.json b/apps/desktop/src/lib/desktop-slash-registry.jsonindex 64c0b577285..800005be64e 100644--- a/apps/desktop/src/lib/desktop-slash-registry.json+++ b/apps/desktop/src/lib/desktop-slash-registry.json@@ -19,7 +19,7 @@"/compact": null,"/compose": null,"/compress": null,- "/config": "terminal",+ "/config": null,"/context": null,"/copy": "terminal","/cron": "terminal",@@ -43,7 +43,7 @@"/hb": null,"/heartbeat": null,"/help": null,- "/history": "terminal",+ "/history": null,"/image": "terminal","/import": null,"/indicator": "terminal",diff --git a/hermes_cli/commands.py b/hermes_cli/commands.pyindex 94e44718986..be6363e516b 100644--- a/hermes_cli/commands.py+++ b/hermes_cli/commands.py@@ -94,7 +94,7 @@ COMMAND_REGISTRY: list[CommandDef] = [CommandDef("redraw", "Force a full UI repaint (recovers from terminal drift)", "Session",cli_only=True, desktop="terminal"),CommandDef("history", "Show conversation history", "Session",- cli_only=True, desktop="terminal"),+ cli_only=True),CommandDef("save", "Export the current conversation (bare /save shows usage)", "Session",args_hint="<json|md|html> [filename] [redact]"),CommandDef("retry", "Retry the last message (resend to agent)", "Session"),@@ -183,7 +183,7 @@ COMMAND_REGISTRY: list[CommandDef] = [# ConfigurationCommandDef("config", "Show current configuration", "Configuration",- cli_only=True, desktop="terminal"),+ cli_only=True),CommandDef("model", "Switch model (session-scoped; --global to persist)", "Configuration",args_hint="[model] [--provider name] [--reasoning level] [--global|--session] [--refresh]",busy_policy="reject", busy_handler="model", desktop="hidden"),