mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-06-14 09:11:54 +00:00
* feat(desktop): session-scoped status stack + kill new-window theme flash Stack subagents, background tasks, and the queue into one collapsible "sink" above the composer, reusing the queue's chrome so every status reads as one piece. Extracts shared StatusSection / StatusRow / TerminalOutput primitives and a unified $statusItemsBySession store (subagents mirrored, background owned here, merged + grouped for render). Renames BrailleSpinner → GlyphSpinner now that it drives more than braille. Separately, fix the white flash on every new/cmd-clicked window: macOS `vibrancy` paints an NSVisualEffectView that follows the OS appearance and ignores `backgroundColor`, so a dark app on a light-mode Mac flashed white until the renderer painted over it. Pin `nativeTheme.themeSource` to the app theme (persisted to userData so cold launches paint right before the renderer loads), hold windows with `show:false` until `ready-to-show`, and pre-paint the themed background via an inline script before the bundle runs. * feat(desktop): dock the slash popover to the composer via one shared fill var The slash·@ popover (and ? help) now docks onto the composer's edge with the same chrome as the queue/status stack — rounded outer corners, fused borderless edge, no shadow — but keeps its own narrow width. Surface + drawer paint a single --composer-fill var; the state ladder (rest / scrolled / focused / drawer-open) lives once in styles.css on [data-slot='composer-root']. The :has() drawer-open rule is last and forces an opaque fill, since translucent glass sampling different backdrops (thread vs fade gradient) can never match. This replaces the focus-within !important override that repainted the surface behind every previous matching attempt. Also drop the chevron column from the project file tree — the folder open/closed icon already carries the expand state. * feat(desktop): base inset for file tree rows (post-chevron alignment) * feat(desktop): wire the status stack's background tasks to the real process registry The background group was UI-only (dev-mock seeded). Now it's live e2e: - tui_gateway: new session-scoped `process.list` (registry snapshot filtered by the session's session_key, plus a 4KB output tail for the inline terminal viewer) and `process.kill` (single process, ownership-checked — unlike process.stop's kill_all). - Renderer: `reconcileBackgroundProcesses` syncs snapshots into the store layout-stably — rows keep their position when state flips (never re-sort), new processes append, unchanged rows keep object identity so memoised rows skip re-rendering, and a dismissed-set stops the registry's retained finished procs from resurrecting X-ed rows. - Refresh triggers: session open, terminal/process tool.complete, status.update(kind=process) from the gateway's notification poller, and a 5s poll armed only while a running row is visible (catches silent exits). - Stop = real `process.kill` + optimistic dismiss; Dismiss = client-side with resurrection guard. - Re-keyed the stack to the RUNTIME session id: it was keyed by the stored session id, where neither subagent events nor process.list would ever land. - Deleted dev-status-mocks.ts (__hermesStatusMocks) — no more seed shit. Reconcile invariants covered in store/composer-status.test.ts. * feat(desktop): todos + openable subagents in the status stack, self-healing file tree - todo lists move out of the inline chat panel into the composer status stack (checklist icon, dashed ring = pending, spinner = in progress, check = done), fed live from todo tool events and seeded from history on session open - subagent rows carry the child's real session id end-to-end (delegate_tool → gateway → renderer) so clicking one opens ITS session window - status stack publishes its measured height so the thread's bottom clearance grows with it; card paints the shared --composer-fill so focused/scrolled states match the composer exactly - file tree self-heals: ENOENT roots retry on a 3s cadence + Try again button, and the main process expands ~ in IPC paths (gateway cwds arrive as ~/...) - composer drag-drop of tree entries inserts inline refs instead of attachments * fix(desktop): file tree falls back to the workspace dir when a session's cwd is gone Sessions record their launch cwd; deleted worktrees leave that path dead, so opening such a session swapped the tree from the default workspace to a directory that ENOENTs forever — the 3s retry just spun on it. On a root read error the tree now asks main to sanitize the cwd (prefers the configured default project dir), displays that fallback, and quietly re-probes the original path so it switches back if the dir reappears. * feat(desktop): working restore-checkpoint button on past user prompts The discard icon on hover of a past user bubble was decorative — clicking did nothing. It's now a real control: a confirmation dialog explains that everything after the prompt is removed, then the session rewinds to that turn and reruns the same prompt (prompt.submit with truncate_before_user_ordinal, the same mechanism the edit composer uses). Failures rethrow into the dialog's inline error instead of toasting. * fix(desktop): show the restore-checkpoint button on the latest user prompt too Restoring the most recent prompt is just 'retry this turn' — no reason to exclude it. Stop still takes the slot while the turn is running. * fix(desktop): finished todo lists clear themselves out of the status stack A list whose every item is completed/cancelled lingers ~4s so the final checkmark is visible, then the todo group drops out of the stack. A fresh active list arriving within the linger cancels the scheduled clear. * chore(desktop): drop dead editableCheckpoint copy, terser restore confirm * fix(desktop): rewind clears the abandoned timeline's todos + background Restoring to (or editing) an earlier prompt rewinds the conversation, but the todos and background processes spawned by the now-discarded turns kept showing in the status stack — and the real background processes kept running. Both rewind paths now clear the session's todo rows and kill + drop its background processes before the fresh run repopulates them. Also drops the click-to-edit clamp transition, which flashed a half-expanded bubble on the way into the edit composer. * feat(desktop): user messages are always editable; edit/restore revert mid-stream The bubble is now always click-to-edit — even while a turn streams — instead of going inert during a run. Sending an edit acts like restore: it rewinds to that prompt and re-runs with the new text. Both edit and restore can fire mid-stream now; the gateway refuses prompt.submit while a turn runs (4009 "session busy"), so they interrupt the live turn first and retry the submit until the cooperative interrupt winds it down. Restore (re-run as-is) shows on every prompt except the latest running one, which keeps the Stop button. * fix(desktop): label preview-pane ⌘L selections with the filename, not "zsh" The terminal owns a global ⌘/Ctrl+L "send selection to composer" shortcut, so selecting text in the file preview pane and hitting it fell through to the terminal handler — which imported the right text but labelled the composer ref "zsh:N lines" off the shell name. When the selection isn't an xterm selection, label it with the previewed file instead. * fix(desktop): ⌘L on a preview line selection inserts the @line ref, like dragging The source preview lets you select lines in the gutter and drag them into the composer as an @line:path:start-end ref. ⌘/Ctrl+L now does the same when a line selection is active — it drops the identical ref instead of falling through to the terminal's global handler (which grabbed the native text selection and sent a bogus terminal block). Capture-phase + stopPropagation so it wins; with a line selection there's no native selection, so the terminal handler stays out of it. * chore: gitignore apps/desktop/demo/ scratch output The desktop demo prompt writes demo/*.txt during recorded walkthroughs; it's throwaway, never part of the app. Ignore it so it stops cluttering git status. * feat(desktop): subagent watch windows, hard stop, sidebar hygiene Child-session mirror for live subagent windows, delegate sessions tagged and excluded from the sidebar, composer focus/stop polish, and WS stall resilience on the gateway transport. * refactor: DRY delegate SQL + trim status-stack noise Extract shared listable-child and delegate-delete helpers in hermes_state, collapse cancelRun busy release, and cut comment bloat in resume/status paths. * fix(desktop): hide orphaned subagent sessions in sidebar Cascade-delete all ephemeral children on parent delete (not just tagged rows), run v16 backfill to tag legacy orphans, and record new delegates as source=subagent. * fix: restore orphan contract for untagged children + lazy session eviction Cascade-delete only _delegate_from-tagged rows (v16 backfill covers legacy), walk marker chains recursively with FK-safe orphaning, gate lazy watch sessions out of the still-starting eviction exemption via an explicit flag, pass session_id to _make_agent only when resuming, and hide source=subagent from session search. * fix(gateway): gate child mirror off upgraded sessions + age out stale run entries Review findings: the mirror could interleave synthetic events with a real native stream once a watch window upgrades (prompt.submit builds an agent), and a lost subagent.complete left _active_child_runs pinning running=true forever. Mirror now stops when the live session owns an agent; liveness reads ignore entries older than an hour. * fix(gateway): reject prompt.submit into a watch session while its child runs A lazy watch session's running flag is False (the run lives in the parent turn), so typing mid-run sailed past the busy guard and built a second agent racing the in-flight child on the same stored session. Busy error until the run completes; afterwards the submit upgrades into a normal conversation. * refactor(gateway): DRY watch-resume payload + compose listable-child SQL Fold the duplicated child-run busy overlay into one _reuse_live_payload helper across both resume reuse paths, collapse the twin mirror early-returns, and build _LISTABLE_CHILD_SQL from _BRANCH_CHILD_SQL instead of restating it. * fix(desktop): clip horizontal overflow on sidebar scroll areas Add overflow-x-hidden alongside overflow-y-auto on session list scrollers and the shared SidebarContent primitive — vertical scroll unchanged.
279 lines
8.6 KiB
JavaScript
279 lines
8.6 KiB
JavaScript
const fs = require('node:fs')
|
|
const os = require('node:os')
|
|
const path = require('node:path')
|
|
const { fileURLToPath } = require('node:url')
|
|
|
|
const DEFAULT_FETCH_TIMEOUT_MS = 15_000
|
|
const DATA_URL_READ_MAX_BYTES = 16 * 1024 * 1024
|
|
const TEXT_PREVIEW_SOURCE_MAX_BYTES = 64 * 1024 * 1024
|
|
|
|
const SAFE_ENV_SUFFIXES = new Set(['dist', 'example', 'sample', 'template'])
|
|
const SENSITIVE_EXTENSIONS = new Set(['.kdbx', '.p12', '.pem', '.pfx'])
|
|
|
|
function resolveTimeoutMs(timeoutMs, fallbackMs = DEFAULT_FETCH_TIMEOUT_MS) {
|
|
const fallback =
|
|
Number.isFinite(fallbackMs) && Number(fallbackMs) > 0 ? Math.round(Number(fallbackMs)) : DEFAULT_FETCH_TIMEOUT_MS
|
|
const parsed = Number(timeoutMs)
|
|
|
|
if (Number.isFinite(parsed) && parsed > 0) {
|
|
return Math.round(parsed)
|
|
}
|
|
|
|
return fallback
|
|
}
|
|
|
|
function encryptDesktopSecret(value, safeStorageApi) {
|
|
const raw = String(value || '')
|
|
|
|
if (!raw) {
|
|
return null
|
|
}
|
|
|
|
let encryptionAvailable = false
|
|
|
|
try {
|
|
encryptionAvailable = Boolean(safeStorageApi?.isEncryptionAvailable?.())
|
|
} catch {
|
|
encryptionAvailable = false
|
|
}
|
|
|
|
if (!encryptionAvailable) {
|
|
throw new Error(
|
|
'Secure token storage is unavailable, so Hermes Desktop cannot save remote gateway tokens. ' +
|
|
'Set HERMES_DESKTOP_REMOTE_URL and HERMES_DESKTOP_REMOTE_TOKEN in your environment, or enable OS keychain access and try again.'
|
|
)
|
|
}
|
|
|
|
try {
|
|
return {
|
|
encoding: 'safeStorage',
|
|
value: safeStorageApi.encryptString(raw).toString('base64')
|
|
}
|
|
} catch (error) {
|
|
const detail = error instanceof Error && error.message ? ` (${error.message})` : ''
|
|
throw new Error(
|
|
`Failed to encrypt the remote gateway token for secure storage${detail}. ` +
|
|
'Set HERMES_DESKTOP_REMOTE_URL and HERMES_DESKTOP_REMOTE_TOKEN in your environment as a fallback.'
|
|
)
|
|
}
|
|
}
|
|
|
|
function sensitiveFileBlockReason(filePath) {
|
|
const normalized = String(filePath || '')
|
|
.replace(/\\/g, '/')
|
|
.toLowerCase()
|
|
const basename = path.basename(normalized)
|
|
const ext = path.extname(basename)
|
|
|
|
if (!basename) {
|
|
return null
|
|
}
|
|
|
|
if (normalized.includes('/.ssh/')) {
|
|
return 'SSH key/config files are blocked.'
|
|
}
|
|
|
|
if (normalized.includes('/.gnupg/')) {
|
|
return 'GPG key material is blocked.'
|
|
}
|
|
|
|
if (normalized.endsWith('/.aws/credentials')) {
|
|
return 'AWS credential files are blocked.'
|
|
}
|
|
|
|
if (basename === '.env') {
|
|
return '.env files are blocked because they commonly contain secrets.'
|
|
}
|
|
|
|
if (basename.startsWith('.env.')) {
|
|
const suffix = basename.slice('.env.'.length)
|
|
if (!SAFE_ENV_SUFFIXES.has(suffix)) {
|
|
return `${basename} is blocked because it appears to contain environment secrets.`
|
|
}
|
|
}
|
|
|
|
if (/^id_(rsa|dsa|ecdsa|ed25519)(?:\..+)?$/.test(basename) && !basename.endsWith('.pub')) {
|
|
return 'SSH private key files are blocked.'
|
|
}
|
|
|
|
if (SENSITIVE_EXTENSIONS.has(ext)) {
|
|
return `${ext} key/certificate files are blocked.`
|
|
}
|
|
|
|
if (basename === '.npmrc' || basename === '.netrc' || basename === '.pypirc') {
|
|
return `${basename} is blocked because it may include auth credentials.`
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
function ipcPathError(code, message) {
|
|
const error = new Error(message)
|
|
error.code = code
|
|
return error
|
|
}
|
|
|
|
function rejectUnsafePathSyntax(filePath, purpose = 'File read') {
|
|
if (typeof filePath !== 'string') {
|
|
throw ipcPathError('invalid-path', `${purpose} failed: file path is required.`)
|
|
}
|
|
|
|
const raw = filePath.trim()
|
|
|
|
if (!raw) {
|
|
throw ipcPathError('invalid-path', `${purpose} failed: file path is required.`)
|
|
}
|
|
|
|
if (raw.includes('\0')) {
|
|
throw ipcPathError('invalid-path', `${purpose} failed: file path is invalid.`)
|
|
}
|
|
|
|
const normalized = raw.replace(/\\/g, '/').toLowerCase()
|
|
if (
|
|
normalized.startsWith('//?/') ||
|
|
normalized.startsWith('//./') ||
|
|
normalized.startsWith('globalroot/device/') ||
|
|
normalized.includes('/globalroot/device/')
|
|
) {
|
|
throw ipcPathError('device-path', `${purpose} blocked: Windows device paths are not allowed.`)
|
|
}
|
|
|
|
return raw
|
|
}
|
|
|
|
function resolveRequestedPathForIpc(filePath, options = {}) {
|
|
const purpose = String(options.purpose || 'File read')
|
|
let raw = rejectUnsafePathSyntax(filePath, purpose)
|
|
|
|
// Gateway-reported cwds (config `terminal.cwd`, remote sessions) routinely
|
|
// arrive as `~/...`. Node's fs has no shell — without expansion the path
|
|
// resolves under process.cwd() and every read "ENOENT"s forever.
|
|
if (raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\')) {
|
|
raw = path.join(os.homedir(), raw.slice(1))
|
|
}
|
|
|
|
if (/^file:/i.test(raw)) {
|
|
let resolvedPath
|
|
try {
|
|
const parsed = new URL(raw)
|
|
if (parsed.protocol !== 'file:') {
|
|
throw new Error('not a file URL')
|
|
}
|
|
resolvedPath = fileURLToPath(parsed)
|
|
} catch {
|
|
throw ipcPathError('invalid-path', `${purpose} failed: file URL is invalid.`)
|
|
}
|
|
|
|
rejectUnsafePathSyntax(resolvedPath, purpose)
|
|
return path.resolve(resolvedPath)
|
|
}
|
|
|
|
const baseInput = typeof options.baseDir === 'string' && options.baseDir.trim() ? options.baseDir : process.cwd()
|
|
const safeBaseInput = rejectUnsafePathSyntax(baseInput, purpose)
|
|
const resolvedBase = path.resolve(safeBaseInput)
|
|
rejectUnsafePathSyntax(resolvedBase, purpose)
|
|
const resolvedPath = path.resolve(resolvedBase, raw)
|
|
rejectUnsafePathSyntax(resolvedPath, purpose)
|
|
|
|
return resolvedPath
|
|
}
|
|
|
|
async function statForIpc(fsImpl, resolvedPath, purpose, typeLabel) {
|
|
try {
|
|
return await fsImpl.promises.stat(resolvedPath)
|
|
} catch (error) {
|
|
const code = error && typeof error === 'object' ? error.code : ''
|
|
if (code === 'ENOENT' || code === 'ENOTDIR') {
|
|
throw ipcPathError(code || 'ENOENT', `${purpose} failed: ${typeLabel} does not exist.`)
|
|
}
|
|
throw ipcPathError(code || 'read-error', `${purpose} failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
}
|
|
}
|
|
|
|
async function realpathForIpc(fsImpl, resolvedPath, purpose) {
|
|
if (typeof fsImpl.promises.realpath !== 'function') {
|
|
return resolvedPath
|
|
}
|
|
|
|
try {
|
|
const realPath = await fsImpl.promises.realpath(resolvedPath)
|
|
rejectUnsafePathSyntax(realPath, purpose)
|
|
return realPath
|
|
} catch (error) {
|
|
const code = error && typeof error === 'object' ? error.code : ''
|
|
throw ipcPathError(code || 'read-error', `${purpose} failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
}
|
|
}
|
|
|
|
function rejectSensitiveFilePath(filePath, purpose) {
|
|
const blockReason = sensitiveFileBlockReason(filePath)
|
|
if (blockReason) {
|
|
throw ipcPathError('sensitive-file', `${purpose} blocked for sensitive file: ${blockReason}`)
|
|
}
|
|
}
|
|
|
|
async function resolveDirectoryForIpc(dirPath, options = {}) {
|
|
const purpose = String(options.purpose || 'Directory read')
|
|
const fsImpl = options.fs || fs
|
|
const resolvedPath = resolveRequestedPathForIpc(dirPath, { baseDir: options.baseDir, purpose })
|
|
const stat = await statForIpc(fsImpl, resolvedPath, purpose, 'directory')
|
|
|
|
if (!stat.isDirectory()) {
|
|
throw ipcPathError('ENOTDIR', `${purpose} failed: path is not a directory.`)
|
|
}
|
|
|
|
const realPath = await realpathForIpc(fsImpl, resolvedPath, purpose)
|
|
|
|
return { realPath, resolvedPath, stat }
|
|
}
|
|
|
|
async function resolveReadableFileForIpc(filePath, options = {}) {
|
|
const purpose = String(options.purpose || 'File read')
|
|
const fsImpl = options.fs || fs
|
|
const resolvedPath = resolveRequestedPathForIpc(filePath, { baseDir: options.baseDir, purpose })
|
|
|
|
if (options.blockSensitive !== false) {
|
|
rejectSensitiveFilePath(resolvedPath, purpose)
|
|
}
|
|
|
|
const stat = await statForIpc(fsImpl, resolvedPath, purpose, 'file')
|
|
|
|
if (stat.isDirectory()) {
|
|
throw ipcPathError('EISDIR', `${purpose} failed: path points to a directory.`)
|
|
}
|
|
|
|
if (!stat.isFile()) {
|
|
throw ipcPathError('EINVAL', `${purpose} failed: only regular files can be read.`)
|
|
}
|
|
|
|
const realPath = await realpathForIpc(fsImpl, resolvedPath, purpose)
|
|
if (options.blockSensitive !== false) {
|
|
rejectSensitiveFilePath(realPath, purpose)
|
|
}
|
|
|
|
const maxBytes = Number.isFinite(options.maxBytes) && Number(options.maxBytes) > 0 ? Number(options.maxBytes) : null
|
|
if (maxBytes && stat.size > maxBytes) {
|
|
throw ipcPathError('EFBIG', `${purpose} failed: file is too large (${stat.size} bytes; limit ${maxBytes} bytes).`)
|
|
}
|
|
|
|
try {
|
|
await fsImpl.promises.access(resolvedPath, fs.constants.R_OK)
|
|
} catch {
|
|
throw ipcPathError('EACCES', `${purpose} failed: file is not readable.`)
|
|
}
|
|
|
|
return { realPath, resolvedPath, stat }
|
|
}
|
|
|
|
module.exports = {
|
|
DATA_URL_READ_MAX_BYTES,
|
|
DEFAULT_FETCH_TIMEOUT_MS,
|
|
TEXT_PREVIEW_SOURCE_MAX_BYTES,
|
|
encryptDesktopSecret,
|
|
rejectUnsafePathSyntax,
|
|
resolveDirectoryForIpc,
|
|
resolveReadableFileForIpc,
|
|
resolveRequestedPathForIpc,
|
|
resolveTimeoutMs,
|
|
sensitiveFileBlockReason
|
|
}
|