Skip to content

The agent that grows with you

fix(desktop): /save writes through Electron; wire /export /import /timestamps /palette; refuse /worktree by name

Teknium44d0526689b6
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index d59ff7c1197..510d9ddfc37 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -1,12 +1,26 @@
import { type ChildProcess, execFileSync, spawn } from 'node:child_process'
import type { GatewayEndpoint } from './local-gateway'
-import { configurePythonGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, localGatewayDial, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'
+import {
+ configurePythonGatewayTicketClient,
+ createLocalGatewayDials,
+ createStaleGatewayRestarter,
+ ensureLocalGateway,
+ gatewayOwnerProfile,
+ localGatewayDial,
+ nativeGatewayHttpHeaders,
+ redialLocalGateway,
+ runGatewayEnsure
+} from './local-gateway'
import { closeGatewayTicketBridges, createGatewayTicketResolver } from './local-gateway-python'
import { createPluginWsUrlHandler } from './plugin-ws-url'
const localGatewayDials = createLocalGatewayDials()
-configurePythonGatewayTicketClient(createGatewayTicketResolver(
- async () => ensureRuntime(await resolveHermesBackend([]), () => undefined), resolveHermesCwd))
+configurePythonGatewayTicketClient(
+ createGatewayTicketResolver(
+ async () => ensureRuntime(await resolveHermesBackend([]), () => undefined),
+ resolveHermesCwd
+ )
+)
import crypto from 'node:crypto'
import fs from 'node:fs'
import http from 'node:http'
@@ -538,6 +552,7 @@ import { loadRendererLoadErrorPage } from './renderer-load-error-page'
import { attachRendererConsoleCapture, formatRendererBoundaryReport } from './renderer-log'
import { fetchRosterSourceData } from './roster-source-fetch'
import { rosterSourceStatus } from './roster-source-status'
+import { saveTextFileAs } from './save-text-file'
import {
classifyStoredSecret,
readSecretStoragePolicy,
@@ -5108,7 +5123,8 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
env: {},
kind: 'command',
shell: shellForProbe,
- local: 'installed', root: await launcherInstallRoot(hermesCommand) // ticket minting needs it (#138774)
+ local: 'installed',
+ root: await launcherInstallRoot(hermesCommand) // ticket minting needs it (#138774)
}
}
@@ -5384,7 +5400,13 @@ function fetchJson(url, token, options: any = {}) {
async (requestState: any) => {
// Mint inside each retry: a grant authorizes exactly one HTTP request.
const nativeHeaders = options.gatewayDescriptor
- ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url, HERMES_HOME, options.method || 'GET', options.upload ? undefined : options.body)
+ ? await nativeGatewayHttpHeaders(
+ options.gatewayDescriptor,
+ url,
+ HERMES_HOME,
+ options.method || 'GET',
+ options.upload ? undefined : options.body
+ )
: null
return new Promise((resolve, reject) => {
@@ -7793,8 +7815,13 @@ async function freshGatewayWsUrl(profile, webContentsId) {
const connection = await ensureBackend(profile)
if (connection.gatewayEndpoint) {
- return localGatewayDial({ ensure: () => ensureBackend(profile), forget: () => forgetLocalGatewayDescriptor(profile), launchHome: HERMES_HOME,
- prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, webContentsId), profile: String(profile ?? '') })
+ return localGatewayDial({
+ ensure: () => ensureBackend(profile),
+ forget: () => forgetLocalGatewayDescriptor(profile),
+ launchHome: HERMES_HOME,
+ prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, webContentsId),
+ profile: String(profile ?? '')
+ })
}
if (connection.authMode === 'oauth') {
@@ -10708,14 +10735,13 @@ async function forgetRegistryLocalGatewayDescriptor(connectionId, profile) {
}
if (backendPool.delete(localRoute.poolKey)) {
- rememberLog(`[gateway] forgot stale canonical endpoint for connection "${String(connectionId || '').trim() || 'primary'}" profile "${profileKey}"; re-ensuring`)
+ rememberLog(
+ `[gateway] forgot stale canonical endpoint for connection "${String(connectionId || '').trim() || 'primary'}" profile "${profileKey}"; re-ensuring`
+ )
}
}
-async function ensureBackend(
- profile,
- opts: { passive?: boolean; request?: { method?: string; path?: string } } = {}
-) {
+async function ensureBackend(profile, opts: { passive?: boolean; request?: { method?: string; path?: string } } = {}) {
const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()
const passive = Boolean(opts.passive)
@@ -11644,41 +11670,47 @@ async function dialPoolBackend(profile, entry, opts: { forceLocal?: boolean; poo
directoryExists(path.join(HERMES_HOME, 'profiles', key))
)
- const connection = await ensureLocalGateway(async () => {
- const backend = await ensureRuntime(
- await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),
- () => assertPoolEntryStillOwned(poolKey, entry)
- )
+ const connection = await ensureLocalGateway(
+ async () => {
+ const backend = await ensureRuntime(
+ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),
+ () => assertPoolEntryStillOwned(poolKey, entry)
+ )
- profileDeletionGate.assertCanStart(profile)
- assertPoolEntryStillOwned(poolKey, entry)
+ profileDeletionGate.assertCanStart(profile)
+ assertPoolEntryStillOwned(poolKey, entry)
- // Never another profile's dotenv credentials from the Desktop env (#68367).
- return runGatewayEnsure(
- { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
- resolveHermesCwd(),
- HERMES_HOME,
- profileBackendParentEnv({ hermesHome: HERMES_HOME, profile })
- )
- }, async () => {
- // Same update mutual exclusion as the primary's waitForLocalStart (#73822);
- // a held update shows the window's blocked screen for this profile too.
- await waitForPoolUpdateClearance({
- profile,
- poolKey,
- gateDeps: updateGateDeps,
- signal: localBackendLifecycle.signal,
- isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
- log: rememberLog,
- showHold: showUpdateHold,
- clearHold: clearUpdateHold,
- pollMs: UPDATE_WAIT_POLL_MS,
- timeoutMs: UPDATE_WAIT_TIMEOUT_MS
- })
- // Update waits yield: retirement or profile deletion may win in that gap.
- assertPoolEntryStillOwned(poolKey, entry)
- assertLocalProfileCanStart(profile, profileDeletionGate, key => directoryExists(path.join(HERMES_HOME, 'profiles', key)))
- }, restartStaleLocalGateway)
+ // Never another profile's dotenv credentials from the Desktop env (#68367).
+ return runGatewayEnsure(
+ { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile })
+ )
+ },
+ async () => {
+ // Same update mutual exclusion as the primary's waitForLocalStart (#73822);
+ // a held update shows the window's blocked screen for this profile too.
+ await waitForPoolUpdateClearance({
+ profile,
+ poolKey,
+ gateDeps: updateGateDeps,
+ signal: localBackendLifecycle.signal,
+ isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
+ log: rememberLog,
+ showHold: showUpdateHold,
+ clearHold: clearUpdateHold,
+ pollMs: UPDATE_WAIT_POLL_MS,
+ timeoutMs: UPDATE_WAIT_TIMEOUT_MS
+ })
+ // Update waits yield: retirement or profile deletion may win in that gap.
+ assertPoolEntryStillOwned(poolKey, entry)
+ assertLocalProfileCanStart(profile, profileDeletionGate, key =>
+ directoryExists(path.join(HERMES_HOME, 'profiles', key))
+ )
+ },
+ restartStaleLocalGateway
+ )
assertPoolEntryStillOwned(poolKey, entry)
@@ -11708,7 +11740,9 @@ async function restartLocalGatewayOwner(ownerProfile: string): Promise<void> {
)
const reason = `${result.stdout}\n${result.stderr}`.trim().split(/\r?\n/).filter(Boolean).pop()
- rememberLog(`[gateway] hermes --profile ${ownerProfile} gateway restart exited ${result.code}${reason ? `: ${reason}` : ''}`)
+ rememberLog(
+ `[gateway] hermes --profile ${ownerProfile} gateway restart exited ${result.code}${reason ? `: ${reason}` : ''}`
+ )
}
// A ready gateway whose boot commit differs from this Hermes (it outlived `hermes update`) is
@@ -11718,9 +11752,12 @@ const restartStaleLocalGateway = createStaleGatewayRestarter(restartLocalGateway
// Models-page "Restart Hermes": restart the local gateway behind `profile`'s cached descriptor.
// A remote/SSH descriptor has no gatewayEndpoint, so nothing local is touched for it.
async function restartAttachedLocalGateway(profile: string): Promise<void> {
- const pending = profile === primaryProfileKey()
- ? backendConnectionState.getPromise()
- : localProfilePoolKeys(profile).map(key => backendPool.get(key)?.connectionPromise).find(Boolean)
+ const pending =
+ profile === primaryProfileKey()
+ ? backendConnectionState.getPromise()
+ : localProfilePoolKeys(profile)
+ .map(key => backendPool.get(key)?.connectionPromise)
+ .find(Boolean)
const connection = await pending?.catch(() => null)
const endpoint = connection?.gatewayEndpoint
@@ -12122,18 +12159,29 @@ async function startHermes(requestedProfile?: string) {
// Local WSL backend — paths are bridgeable.
setWslBridgeProfileState(primaryProfile, true)
- const connection = await ensureLocalGateway(() => runGatewayEnsure(
- { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}) },
- resolveHermesCwd(),
- HERMES_HOME,
- profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })
- ), undefined, restartStaleLocalGateway)
+ const connection = await ensureLocalGateway(
+ () =>
+ runGatewayEnsure(
+ { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })
+ ),
+ undefined,
+ restartStaleLocalGateway
+ )
backendConnectionState.assertCurrentAttempt(connectionAttempt)
backendStartFailure = null
rememberLog('[backend] Hermes gateway is ready')
- updateBootProgress({ phase: 'backend.ready', message: 'Hermes gateway is ready', progress: 94, running: true, error: null })
+ updateBootProgress({
+ phase: 'backend.ready',
+ message: 'Hermes gateway is ready',
+ progress: 94,
+ running: true,
+ error: null
+ })
bootstrapRepairAttempt = 0
// The primary descriptor names its own profile: a profile-less descriptor
@@ -14285,7 +14333,10 @@ ipcMain.handle('hermes:connection:for', async (event, payload) => {
const registry = readDesktopConnectionsRegistry()
const id = registryDialConnectionId(connectionId, registry.primary)
- return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' }, event.sender)
+ return connectDesktopProfileRoute(
+ { connectionId: id, profile: String(profile ?? '').trim() || 'default' },
+ event.sender
+ )
})
const windowConnectionRoutes = new WindowConnectionRouteRegistry()
@@ -15275,17 +15326,27 @@ ipcMain.handle('hermes:gateway:ws-url-for', async (_event, payload) => {
const connection = await ensureRegistryBackend(payload?.connectionId, payload?.profile)
if (connection.gatewayEndpoint) {
- return localGatewayDial({ ensure: () => ensureRegistryBackend(payload?.connectionId, payload?.profile), launchHome: HERMES_HOME,
- forget: () => forgetRegistryLocalGatewayDescriptor(payload?.connectionId, payload?.profile), profile: String(payload?.profile ?? ''),
- prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, _event.sender.id) })
+ return localGatewayDial({
+ ensure: () => ensureRegistryBackend(payload?.connectionId, payload?.profile),
+ launchHome: HERMES_HOME,
+ forget: () => forgetRegistryLocalGatewayDescriptor(payload?.connectionId, payload?.profile),
+ profile: String(payload?.profile ?? ''),
+ prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, _event.sender.id)
+ })
}
return registryGatewayWsUrlHandler(payload)
})
})
-const pluginWsUrl = createPluginWsUrlHandler({ ensureBackend, ensureRegistryBackend, forgetLocalGatewayDescriptor,
- forgetRegistryLocalGatewayDescriptor, launchHome: HERMES_HOME, prepare: localGatewayDials.preparePlugin })
+const pluginWsUrl = createPluginWsUrlHandler({
+ ensureBackend,
+ ensureRegistryBackend,
+ forgetLocalGatewayDescriptor,
+ forgetRegistryLocalGatewayDescriptor,
+ launchHome: HERMES_HOME,
+ prepare: localGatewayDials.preparePlugin
+})
ipcMain.handle('hermes:plugin:ws-url', (event, payload) => pluginWsUrl(payload ?? {}, event.sender.id))
// Transactional update for a Desktop-managed SSH install. Unlike the generic
@@ -15448,7 +15509,12 @@ async function fetchJsonForBackend(
.filter(name => typeof name === 'string' && name)
const readProfile = (_profile, scoped) =>
- fetchJsonForBackend(descriptor, scoped, { method: opts.method, body: opts.body, timeoutMs: opts.timeoutMs, profileScoped: true })
+ fetchJsonForBackend(descriptor, scoped, {
+ method: opts.method,
+ body: opts.body,
+ timeoutMs: opts.timeoutMs,
+ profileScoped: true
+ })
return sessions
? fetchAllProfilesSessionsPerProfile(path, profiles, readProfile)
@@ -16119,7 +16185,14 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles, registry
const getRegistryJson = (descriptor, path) => getJsonForBackend(descriptor, path, { timeoutMs: 10_000 })
// RT-42: count each backend (install_id) once; remote-override profiles are another backend.
const identity = { primaryBackendId: await primaryBackendInstallId(), unknownPrimaryProfiles: remoteProfiles }
- total += await mergeRegistrySessionRows(registrySources, remoteParams, getRegistryJson, merged, profileTotals, identity)
+ total += await mergeRegistrySessionRows(
+ registrySources,
+ remoteParams,
+ getRegistryJson,
+ merged,
+ profileTotals,
+ identity
+ )
}
const recency = s => s?.[order] ?? s?.started_at ?? 0
@@ -16127,7 +16200,9 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles, registry
const archivedOnly = searchParams.get('archived') === 'only'
- return composeUnifiedSessionResponse(base, merged, offset, limit, total, profileTotals, remoteErrors, { archivedOnly })
+ return composeUnifiedSessionResponse(base, merged, offset, limit, total, profileTotals, remoteErrors, {
+ archivedOnly
+ })
}
// Every CONNECTED registry gateway as a session source: resolved descriptors
@@ -16326,12 +16401,13 @@ async function handleHermesApiRequest(request) {
// Main's shared transport for every descriptor: configured headers, a native
// gateway grant per attempt, and the OAuth bearer→cookie fallback that
// survives refresh failures and login races (requestWithOauthFallback).
- const send = current => fetchJsonForBackend(current, apiRoute.requestPath, {
- method: request?.method,
- body: request?.body,
- upload: request?.upload,
- timeoutMs
- })
+ const send = current =>
+ fetchJsonForBackend(current, apiRoute.requestPath, {
+ method: request?.method,
+ body: request?.body,
+ upload: request?.upload,
+ timeoutMs
+ })
response = connection.gatewayEndpoint
? await redialLocalGateway({
@@ -16659,6 +16735,15 @@ ipcMain.handle('hermes:readClipboard', () => clipboard.readText())
ipcMain.handle('hermes:saveGatewayFile', (_event, payload) => saveGatewayFile(payload))
+// T11: /save writes here, not on the gateway (which may be remote): the renderer passes the content
+// the owner rendered (session.export) and the user picks the destination.
+ipcMain.handle('hermes:saveTextFileAs', (_event, request) =>
+ saveTextFileAs(request || {}, {
+ defaultDir: () => app.getPath('documents'),
+ showSaveDialog: options => dialog.showSaveDialog(mainWindow, options)
+ })
+)
+
ipcMain.handle('hermes:saveImageFromUrl', (_event, url) => saveImageFromUrl(String(url || '')))
// The custom context menu's edit verbs. They act on the SENDER's focused
@@ -17941,8 +18026,14 @@ ipcMain.handle('hermes:deep-link-ready', () => {
function registerDeepLinkProtocol() {
registerDeepLinkProtocolWith({
- app, protocol: HERMES_PROTOCOL, env: process.env, defaultApp: Boolean(process.defaultApp),
- argv: process.argv, execPath: process.execPath, resolve: entry => path.resolve(entry), log: rememberLog
+ app,
+ protocol: HERMES_PROTOCOL,
+ env: process.env,
+ defaultApp: Boolean(process.defaultApp),
+ argv: process.argv,
+ execPath: process.execPath,
+ resolve: entry => path.resolve(entry),
+ log: rememberLog
})
}
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 5efa4066582..84638b74c65 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -351,6 +351,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
readPluginSource: (filePath: string) => ipcRenderer.invoke('hermes:readPluginSource', filePath),
selectPaths: options => ipcRenderer.invoke('hermes:selectPaths', options),
selectSavePath: options => ipcRenderer.invoke('hermes:selectSavePath', options),
+ saveTextFileAs: request => ipcRenderer.invoke('hermes:saveTextFileAs', request),
writeClipboard: text => ipcRenderer.invoke('hermes:writeClipboard', text),
readClipboard: () => ipcRenderer.invoke('hermes:readClipboard'),
saveGatewayFile: payload => ipcRenderer.invoke('hermes:saveGatewayFile', payload),
diff --git a/apps/desktop/electron/save-text-file.test.ts b/apps/desktop/electron/save-text-file.test.ts
new file mode 100644
index 00000000000..0d2f3712fe1
--- /dev/null
+++ b/apps/desktop/electron/save-text-file.test.ts
@@ -0,0 +1,87 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { SAVE_TEXT_FILE_MAX_BYTES, saveTextFileAs } from './save-text-file'
+
+const scratch: string[] = []
+
+function tempDir(): string {
+ const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'save-text-'))
+ scratch.push(dir)
+
+ return dir
+}
+
+afterEach(() => {
+ for (const dir of scratch.splice(0)) {
+ fs.rmSync(dir, { force: true, recursive: true })
+ }
+})
+
+describe('saveTextFileAs (Electron-side /save write)', () => {
+ it('writes the content where the user chose, defaulting to a bare name in the default dir', async () => {
+ const dir = tempDir()
+ const target = path.join(dir, 'picked.md')
+ let seen: { defaultPath?: string; filters?: unknown; title: string } | null = null
+
+ const result = await saveTextFileAs(
+ {
+ content: '# hello',
+ defaultPath: '../../etc/hermes_session_x.md',
+ filters: [{ name: 'Markdown', extensions: ['md'] }]
+ },
+ {
+ defaultDir: () => dir,
+ showSaveDialog: async options => {
+ seen = options
+
+ return { canceled: false, filePath: target }
+ }
+ }
+ )
+
+ expect(result).toEqual({ saved: true, path: target })
+ expect(fs.readFileSync(target, 'utf8')).toBe('# hello')
+ // The renderer's suggestion never picks the directory.
+ expect(seen!.defaultPath).toBe(path.join(dir, 'hermes_session_x.md'))
+ expect(seen!.filters).toEqual([{ name: 'Markdown', extensions: ['md'] }])
+ })
+
+ it('writes nothing when the dialog is cancelled', async () => {
+ const writes: string[] = []
+
+ const result = await saveTextFileAs(
+ { content: 'x', defaultPath: 'a.json' },
+ {
+ defaultDir: () => '/nowhere',
+ showSaveDialog: async () => ({ canceled: true }),
+ writeFile: async filePath => void writes.push(filePath)
+ }
+ )
+
+ expect(result).toEqual({ saved: false, canceled: true })
+ expect(writes).toEqual([])
+ })
+
+ it('refuses non-string or oversized content before opening a dialog', async () => {
+ let opened = false
+
+ const deps = {
+ defaultDir: () => '/nowhere',
+ showSaveDialog: async () => {
+ opened = true
+
+ return { canceled: true }
+ }
+ }
+
+ await expect(saveTextFileAs({ content: 42 }, deps)).rejects.toThrow('Invalid content')
+ await expect(saveTextFileAs({ content: 'x'.repeat(SAVE_TEXT_FILE_MAX_BYTES + 1) }, deps)).rejects.toThrow(
+ 'Content too large'
+ )
+ expect(opened).toBe(false)
+ })
+})
diff --git a/apps/desktop/electron/save-text-file.ts b/apps/desktop/electron/save-text-file.ts
new file mode 100644
index 00000000000..e67534e1a0a
--- /dev/null
+++ b/apps/desktop/electron/save-text-file.ts
@@ -0,0 +1,97 @@
+// T11 (#134889): file-writing slash commands (/save) write on the Electron side. The gateway may be
+// remote, so it only returns the rendered content; this module asks the user where the file goes
+// (native save dialog) and writes it from the main process. Never a gateway write to the client's disk.
+
+import fs from 'node:fs'
+import path from 'node:path'
+
+export interface SaveTextFileRequest {
+ content?: unknown
+ defaultPath?: unknown
+ filters?: unknown
+ title?: unknown
+}
+
+export interface SaveTextFileResult {
+ canceled?: boolean
+ path?: string
+ saved: boolean
+}
+
+export interface SaveTextFileDeps {
+ defaultDir: () => string
+ showSaveDialog: (options: {
+ defaultPath?: string
+ filters?: Array<{ extensions: string[]; name: string }>
+ title: string
+ }) => Promise<{ canceled: boolean; filePath?: string }>
+ writeFile?: (filePath: string, content: string) => Promise<void>
+}
+
+/** Rendered transcripts can be large; cap well above any realistic /save output. */
+export const SAVE_TEXT_FILE_MAX_BYTES = 64 * 1024 * 1024
+
+function safeFilters(value: unknown): Array<{ extensions: string[]; name: string }> | undefined {
+ if (!Array.isArray(value)) {
+ return undefined
+ }
+
+ const filters = value.flatMap(entry => {
+ if (!entry || typeof entry !== 'object') {
+ return []
+ }
+
+ const { extensions, name } = entry as { extensions?: unknown; name?: unknown }
+
+ if (typeof name !== 'string' || !Array.isArray(extensions)) {
+ return []
+ }
+
+ return [{ name, extensions: extensions.filter((ext): ext is string => typeof ext === 'string') }]
+ })
+
+ return filters.length ? filters : undefined
+}
+
+/** Only a bare file name is honoured from the renderer: the directory is always the user's pick. */
+function suggestedName(value: unknown): string | undefined {
+ if (typeof value !== 'string' || !value.trim()) {
+ return undefined
+ }
+
+ const base = path.basename(value.trim().replaceAll('\\', '/'))
+
+ return base && base !== '.' && base !== '..' ? base : undefined
+}
+
+export async function saveTextFileAs(
+ request: SaveTextFileRequest,
+ deps: SaveTextFileDeps
+): Promise<SaveTextFileResult> {
+ if (typeof request?.content !== 'string') {
+ throw new Error('Invalid content')
+ }
+
+ const content = request.content
+
+ if (Buffer.byteLength(content, 'utf8') > SAVE_TEXT_FILE_MAX_BYTES) {
+ throw new Error('Content too large')
+ }
+
+ const name = suggestedName(request.defaultPath)
+
+ const result = await deps.showSaveDialog({
+ title: typeof request.title === 'string' && request.title ? request.title : 'Save',
+ defaultPath: name ? path.join(deps.defaultDir(), name) : undefined,
+ filters: safeFilters(request.filters)
+ })
+
+ if (result.canceled || !result.filePath) {
+ return { saved: false, canceled: true }
+ }
+
+ const write = deps.writeFile ?? ((filePath: string, text: string) => fs.promises.writeFile(filePath, text, 'utf8'))
+ await write(result.filePath, content)
+
+ return { saved: true, path: result.filePath }
+}
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.tsx
index 70a03901d38..8d90fc9c58b 100644
--- 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.tsx
@@ -231,3 +231,111 @@ describe('/history', () => {
expect(text).not.toContain('tool noise')
})
})
+
+describe('/save writes on the Electron side', () => {
+ it('asks the owner for the rendered file (session.export) and saves it through the main process', async () => {
+ const saveTextFileAs = vi.fn(async () => ({ saved: true, path: '/home/u/Documents/notes.md' }))
+
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { saveTextFileAs }
+
+ const requestGateway = gateway(method =>
+ method === 'session.export'
+ ? { format: 'md', filename: 'hermes_session_s1.md', content: '# transcript' }
+ : undefined
+ )
+
+ const handle = await mount(requestGateway)
+
+ await handle.submitText('/save md notes.md redact')
+
+ expect(callsOf(requestGateway, 'session.export')).toEqual([
+ { session_id: RUNTIME_SESSION_ID, format: 'md', redact: true }
+ ])
+ expect(callsOf(requestGateway, 'session.save')).toEqual([])
+ expect(saveTextFileAs).toHaveBeenCalledWith(
+ expect.objectContaining({ content: '# transcript', defaultPath: 'notes.md' })
+ )
+ expect(renderedText(handle)).toContain('/home/u/Documents/notes.md')
+ })
+
+ it('defaults to json and the owner filename, and reports a cancelled dialog', async () => {
+ const saveTextFileAs = vi.fn(async () => ({ saved: false, canceled: true }))
+
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { saveTextFileAs }
+
+ const requestGateway = gateway(method =>
+ method === 'session.export' ? { format: 'json', filename: 'hermes_session_s1.json', content: '{}' } : undefined
+ )
+
+ const handle = await mount(requestGateway)
+
+ await handle.submitText('/save')
+
+ expect(callsOf(requestGateway, 'session.export')).toEqual([{ session_id: RUNTIME_SESSION_ID, format: 'json' }])
+ expect(saveTextFileAs).toHaveBeenCalledWith(expect.objectContaining({ defaultPath: 'hermes_session_s1.json' }))
+ expect(renderedText(handle)).toMatch(/not saved/i)
+ })
+
+ it('rejects an unknown format without a gateway call', async () => {
+ const requestGateway = gateway(() => undefined)
+ const handle = await mount(requestGateway)
+
+ await handle.submitText('/save pdf')
+
+ expect(callsOf(requestGateway, 'session.export')).toEqual([])
+ expect(renderedText(handle)).toMatch(/usage: \/save/i)
+ })
+})
+
+describe('/timestamps, /palette, /worktree, /snapshot', () => {
+ it('/timestamps toggles the transcript timestamps locally (UI state, no gateway call)', async () => {
+ const { $displayTimestamps } = await import('@/store/display-timestamps')
+ $displayTimestamps.set(false)
+ const requestGateway = gateway(() => undefined)
+ const handle = await mount(requestGateway)
+
+ await handle.submitText('/timestamps on')
+ expect($displayTimestamps.get()).toBe(true)
+ await handle.submitText('/ts')
+ expect($displayTimestamps.get()).toBe(false)
+ await handle.submitText('/timestamps status')
+
+ expect(requestGateway.mock.calls.filter(([m]) => m === 'slash.exec' || m === 'command.dispatch')).toEqual([])
+ expect(renderedText(handle)).toMatch(/timestamps: off/i)
+ })
+
+ it('/palette opens the desktop command palette', async () => {
+ const { $commandPaletteOpen } = await import('@/store/command-palette')
+ $commandPaletteOpen.set(false)
+ const handle = await mount(gateway(() => undefined))
+
+ await handle.submitText('/palette')
+
+ expect($commandPaletteOpen.get()).toBe(true)
+ })
+
+ it('/worktree and /snapshot are named refusals that say what to use instead', () => {
+ expect(resolveDesktopCommand('/worktree')?.surface.kind).toBe('unavailable')
+ expect(resolveDesktopCommand('/snapshot')?.surface.kind).toBe('unavailable')
+ })
+})
+
+describe('/export and /import (profile archives)', () => {
+ it('route to the desktop profile share flows on a local gateway', () => {
+ expect(resolveDesktopCommand('/export')?.surface).toEqual({ kind: 'action', action: 'export' })
+ expect(resolveDesktopCommand('/import')?.surface).toEqual({ kind: 'action', action: 'import' })
+ })
+
+ it('refuse by name on a remote gateway, whose filesystem is not this machine', async () => {
+ $connection.set({ mode: 'remote', wsUrl: 'wss://example.test/api/ws' } as never)
+ const requestGateway = gateway(() => undefined)
+ const handle = await mount(requestGateway)
+
+ await handle.submitText('/export')
+ await handle.submitText('/import')
+
+ expect(callsOf(requestGateway, 'slash.exec')).toEqual([])
+ expect(renderedText(handle)).toMatch(/hermes profile export/)
+ expect(renderedText(handle)).toMatch(/hermes profile import/)
+ })
+})
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.ts
index 8d0241ec131..47ebb3acbff 100644
--- 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.ts
@@ -1,3 +1,9 @@
+import { isMissingRpcMethod } from '@/lib/gateway-rpc'
+import { openCommandPalette } from '@/store/command-palette'
+import { $displayTimestamps } from '@/store/display-timestamps'
+import { runExportProfileFlow, runImportProfileFlow } from '@/store/profile-share'
+import { $connection } from '@/store/session'
+
import type { GatewayRequest } from './utils'
// T11 (#134889): /rollback, /agents (/tasks), /config and /history on the session owner's existing
@@ -33,6 +39,44 @@ interface RestoreResult {
const errorText = (err: unknown) => `error: ${err instanceof Error ? err.message : String(err)}`
+const SAVE_USAGE = 'usage: /save [json|md|html] [filename] [redact]'
+
+const SAVE_FORMATS: Record<string, 'html' | 'json' | 'md'> = {
+ html: 'html',
+ json: 'json',
+ markdown: 'md',
+ md: 'md',
+ snapshot: 'json'
+}
+
+const SAVE_FILTERS: Record<string, { extensions: string[]; name: string }> = {
+ html: { extensions: ['html'], name: 'HTML' },
+ json: { extensions: ['json'], name: 'JSON' },
+ md: { extensions: ['md'], name: 'Markdown' }
+}
+
+/** `/save` words → format, optional filename and redact flag (main's `/save` grammar); null = usage. */
+export function saveRequest(
+ arg: string
+): { filename?: string; format: 'html' | 'json' | 'md'; redact: boolean } | null {
+ const words = arg.trim().split(/\s+/).filter(Boolean)
+ const redact = words.length > 0 && ['redact', '--redact'].includes(words[words.length - 1].toLowerCase())
+ const rest = redact ? words.slice(0, -1) : words
+ const format = rest.length ? SAVE_FORMATS[rest[0].toLowerCase()] : 'json'
+
+ if (!format || rest.length > 2) {
+ return null
+ }
+
+ return { format, redact, ...(rest[1] ? { filename: rest[1] } : {}) }
+}
+
+const isRemoteGateway = () => {
+ const mode = ($connection.get() as { mode?: string } | null)?.mode
+
+ return Boolean(mode && mode !== 'local')
+}
+
const ROLLBACK_USAGE = 'usage: /rollback [list] | diff <n|hash> | <n|hash> [file] [--all]'
const HISTORY_PREVIEW = 400
@@ -289,6 +333,106 @@ export function desktopReadCommandHandlers<C extends { arg: string }>(env: Deskt
out.render(errorText(err))
}
},
+ save: async (ctx: C) => {
+ const out = await env.withSlashOutput(ctx)
+
+ if (!out) {
+ return
+ }
+
+ const request = saveRequest(ctx.arg)
+
+ if (!request) {
+ return out.render(SAVE_USAGE)
+ }
+
+ let file: { content?: string; filename?: string; format?: string } | null
+
+ try {
+ file = await requestGateway('session.export', {
+ session_id: out.sessionId,
+ format: request.format,
+ ...(request.redact ? { redact: true } : {})
+ })
+ } catch (err) {
+ if (!isMissingRpcMethod(err)) {
+ return out.render(errorText(err))
+ }
+
+ // An older gateway without session.export: its session.save writes JSON on the gateway host.
+ try {
+ const saved = await requestGateway<{ file?: string }>('session.save', { session_id: out.sessionId })
+
+ return out.render(`Saved on the gateway host: ${saved?.file ?? '(unknown path)'}`)
+ } catch (fallbackErr) {
+ return out.render(errorText(fallbackErr))
+ }
+ }
+
+ const save = window.hermesDesktop?.saveTextFileAs
+
+ if (typeof file?.content !== 'string' || !save) {
+ return out.render('error: this desktop build cannot save files')
+ }
+
+ try {
+ const result = await save({
+ content: file.content,
+ defaultPath: request.filename || file.filename,
+ filters: [SAVE_FILTERS[request.format]],
+ title: 'Save conversation'
+ })
+
+ out.render(result?.saved && result.path ? `Saved conversation to ${result.path}` : 'Not saved (cancelled).')
+ } catch (err) {
+ out.render(errorText(err))
+ }
+ },
+ export: async (ctx: C) => {
+ if (isRemoteGateway()) {
+ const out = await env.withSlashOutput(ctx)
+
+ return out?.render(
+ '/export packages a profile from the gateway host, which is not this machine. Run `hermes profile export` on that host.'
+ )
+ }
+
+ await runExportProfileFlow(ctx.arg.trim().split(/\s+/)[0] || undefined)
+ },
+ import: async (ctx: C) => {
+ if (isRemoteGateway()) {
+ const out = await env.withSlashOutput(ctx)
+
+ return out?.render(
+ '/import installs a profile on the gateway host, which is not this machine. Run `hermes profile import <archive>` on that host.'
+ )
+ }
+
+ await runImportProfileFlow()
+ },
+ timestamps: async (ctx: C) => {
+ const word = ctx.arg.trim().toLowerCase()
+ const current = $displayTimestamps.get()
+ const next = word === 'on' ? true : word === 'off' ? false : word === '' || word === 'toggle' ? !current : current
+
+ if (word && !['on', 'off', 'toggle', 'status'].includes(word)) {
+ const out = await env.withSlashOutput(ctx)
+
+ return out?.render('usage: /timestamps [on|off|status]')
+ }
+
+ $displayTimestamps.set(next)
+
+ if (word === 'status') {
+ const out = await env.withSlashOutput(ctx)
+ out?.render(
+ `Timestamps: ${next ? 'on' : 'off'} (this window; set display.timestamps in config.yaml to keep it)`
+ )
+ }
+ },
+ palette: async () => {
+ openCommandPalette()
+ },
history: async (ctx: C) => {
const out = await env.withSlashOutput(ctx)
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index b2512e1e96d..b2461278012 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -317,6 +317,13 @@ declare global {
filters?: Array<{ extensions: string[]; name: string }>
title?: string
}) => Promise<null | string>
+ /** Save dialog + main-process write of renderer-supplied text (/save; the gateway may be remote). */
+ saveTextFileAs?: (request: {
+ content: string
+ defaultPath?: string
+ filters?: Array<{ extensions: string[]; name: string }>
+ title?: string
+ }) => Promise<{ canceled?: boolean; path?: string; saved: boolean }>
writeClipboard: (text: string) => Promise<boolean>
readClipboard: () => Promise<string>
saveGatewayFile?: (payload: {
diff --git a/apps/desktop/src/lib/desktop-slash-commands.test.ts b/apps/desktop/src/lib/desktop-slash-commands.test.ts
index a224020819d..c432e2f6988 100644
--- a/apps/desktop/src/lib/desktop-slash-commands.test.ts
+++ b/apps/desktop/src/lib/desktop-slash-commands.test.ts
@@ -173,8 +173,8 @@ describe('desktop slash command curation', () => {
})
it('routes only stateless session commands through dedicated gateway RPCs', () => {
+ // /save is an action now: it renders on the owner (session.export) and writes through Electron (T11).
const expected = {
- '/save': 'session.save',
'/status': 'session.status'
} as const
diff --git a/apps/desktop/src/lib/desktop-slash-commands.ts b/apps/desktop/src/lib/desktop-slash-commands.ts
index 443d6567800..96193a991e6 100644
--- a/apps/desktop/src/lib/desktop-slash-commands.ts
+++ b/apps/desktop/src/lib/desktop-slash-commands.ts
@@ -65,21 +65,26 @@ export type DesktopActionId =
| 'btw'
| 'compress'
| 'config'
+ | 'export'
| 'handoff'
| 'hatch'
| 'help'
| 'history'
+ | 'import'
| 'journey'
| 'new'
+ | 'palette'
| 'pet'
| 'profile'
| 'queue'
| 'reasoning'
| 'retry'
| 'rollback'
+ | 'save'
| 'skin'
| 'steer'
| 'stop'
+ | 'timestamps'
| 'title'
| 'undo'
| 'wake'
@@ -344,11 +349,29 @@ const DESKTOP_COMMAND_SPECS: readonly DesktopCommandSpec[] = [
},
{ name: '/config', description: 'Show current configuration', surface: action('config') },
{ name: '/history', description: 'Show conversation history', surface: action('history') },
+ // /save renders on the owner (session.export) and writes on this machine through Electron: the
+ // gateway may be remote, so it never writes the client's file (T11).
{
name: '/save',
- description: 'Save the current transcript to JSON',
- surface: rpc('session.save', ctx => ({ session_id: ctx.sessionId }))
+ description: 'Save the transcript to a file [json|md|html] [filename] [redact]',
+ surface: action('save'),
+ argumentMode: 'text'
+ },
+ {
+ name: '/export',
+ description: 'Export a profile to a shareable archive',
+ surface: action('export'),
+ argumentMode: 'text'
+ },
+ { name: '/import', description: 'Import a shared profile archive as a new profile', surface: action('import') },
+ {
+ name: '/timestamps',
+ description: 'Toggle message timestamps [on|off|status]',
+ aliases: ['/ts'],
+ surface: action('timestamps'),
+ argumentMode: 'options'
},
+ { name: '/palette', description: 'Open the command palette', surface: action('palette') },
{
name: '/status',
description: 'Show current session status',
diff --git a/apps/desktop/src/lib/desktop-slash-registry.json b/apps/desktop/src/lib/desktop-slash-registry.json
index 800005be64e..29e3c71347a 100644
--- a/apps/desktop/src/lib/desktop-slash-registry.json
+++ b/apps/desktop/src/lib/desktop-slash-registry.json
@@ -126,6 +126,6 @@
"/voice": "composer-voice",
"/wake": null,
"/whoami": null,
- "/worktree": null,
+ "/worktree": "terminal",
"/yolo": null
}
diff --git a/hermes_cli/commands.py b/hermes_cli/commands.py
index be6363e516b..190805a6e6c 100644
--- a/hermes_cli/commands.py
+++ b/hermes_cli/commands.py
@@ -109,7 +109,7 @@ COMMAND_REGISTRY: list[CommandDef] = [
"Session", aliases=("fork",), args_hint="[--here] [name]"),
CommandDef("worktree", "Show, list, create, or prune isolated git worktrees", "Session",
cli_only=True, args_hint="[new [name]|list|prune [--dry-run]]",
- subcommands=("new", "list", "prune")),
+ subcommands=("new", "list", "prune"), desktop="terminal"),
CommandDef("compress", "Compress conversation context (add 'here [N]' to keep recent N turns; --preview shows what would happen)", "Session",
aliases=("compact",), args_hint="[here [N] | focus topic | --preview|--dry-run]"),
CommandDef("rollback", "List or restore filesystem checkpoints (restores keep your hand-edits; --all overrides)", "Session",