merge: refresh onto current main (take main's superior sequential-timeout de-flake)

This commit is contained in:
Teknium
2026-08-15 19:11:57 -07:00
28 changed files with 2532 additions and 639 deletions
@@ -1,8 +1,10 @@
import { useStore } from '@nanostores/react'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { useI18n } from '@/i18n'
import { installHubSkill } from '@/store/hub-actions'
import { Loader2 } from '@/lib/icons'
import { $hubActions, installHubSkill, UPDATE_ALL_KEY, updateHubSkills } from '@/store/hub-actions'
import { notify, notifyError } from '@/store/notifications'
// The REAL Skills Hub page (docs site) embedded as a one-click picker — the
@@ -24,20 +26,25 @@ interface SkillPickMessage {
}
interface EmbeddedHubPickerProps {
/** Names of skills already installed in the scoped profile — a pick that
* matches is refused with a toast instead of re-running the install. */
installedNames: ReadonlySet<string>
/** Capabilities profile-scope override — installs land in THIS profile;
* undefined/null targets the app-wide active profile. */
profile?: null | string
}
/** Collapsible "browse the full hub" strip for the Skills tab: a resizable
* iframe of the live Skills Hub where every card installs with one click. */
export function EmbeddedHubPicker({ profile }: EmbeddedHubPickerProps) {
/** The Skills Hub browser for the Skills tab: a resizable iframe of the live
* hub where every card installs with one click. Expanded by default —
* discovery IS the point — with a collapse toggle and an update-all action. */
export function EmbeddedHubPicker({ installedNames, profile }: EmbeddedHubPickerProps) {
const { t } = useI18n()
const h = t.skills.hub
const [open, setOpen] = useState(false)
const [open, setOpen] = useState(true)
const updating = useStore($hubActions)[UPDATE_ALL_KEY]?.running ?? false
// Picker messages from the embedded hub page. Origin-checked; installs route
// through the same store pipeline the Browse Hub tab uses, so the action log,
// through the same store pipeline the hub rows use, so the action log,
// optimistic flips, and Skills-list refresh all come for free.
useEffect(() => {
if (!open) {
@@ -58,6 +65,13 @@ export function EmbeddedHubPicker({ profile }: EmbeddedHubPickerProps) {
const target = String(data.identifier || data.name)
const label = String(data.name)
// Already installed in this scope → tell the user, don't reinstall.
if (installedNames.has(label) || installedNames.has(target)) {
notify({ kind: 'success', title: h.alreadyInstalled(label), message: '' })
return
}
notify({ kind: 'success', title: h.installStarted(label), message: h.actionLog })
void installHubSkill(target, profile).catch(err => notifyError(err, h.actionFailed))
}
@@ -65,30 +79,40 @@ export function EmbeddedHubPicker({ profile }: EmbeddedHubPickerProps) {
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [h, open, profile])
}, [h, installedNames, open, profile])
const updateAll = () => {
notify({ kind: 'success', title: h.updateStarted, message: h.actionLog })
void updateHubSkills(profile).catch(err => notifyError(err, h.actionFailed))
}
return (
<div className="border-b border-(--ui-stroke-secondary)">
<div className="border-t border-(--ui-stroke-secondary)">
<div className="flex items-center justify-between px-3 py-1.5">
<span className="text-[0.7rem] font-medium text-(--ui-text-tertiary)">{h.pickerTitle}</span>
<Button onClick={() => setOpen(v => !v)} size="xs" variant="text">
{open ? h.pickerHide : h.pickerBrowse}
</Button>
<div className="flex items-center gap-1">
<Button disabled={updating} onClick={updateAll} size="xs" variant="text">
{updating && <Loader2 className="size-3 animate-spin" />}
{updating ? h.updating : h.updateAll}
</Button>
<Button onClick={() => setOpen(v => !v)} size="xs" variant="text">
{open ? h.pickerHide : h.pickerBrowse}
</Button>
</div>
</div>
{open && (
<div className="grid gap-1 px-3 pb-2">
{/* Resizable viewport: native CSS resize handle (bottom-right corner)
lets the user drag it larger/smaller. The iframe is rendered
oversized and scaled DOWN (133% × 0.75) so the hub page starts
zoomed out — the cross-origin page itself can't be styled, but
scaling the frame is ours. */}
{/* Resizable viewport: native CSS resize handle lets the user drag it
larger/smaller. The iframe is rendered oversized and scaled DOWN
(133% × 0.75) so the hub page starts zoomed out — the cross-origin
page itself can't be styled, but scaling the frame is ours. */}
<div
style={{
border: '1px solid var(--ui-stroke-secondary)',
borderRadius: 8,
height: 480,
height: 380,
maxWidth: '100%',
minHeight: 240,
minHeight: 200,
minWidth: 320,
overflow: 'hidden',
position: 'relative',
-478
View File
@@ -1,478 +0,0 @@
import { useStore } from '@nanostores/react'
import { useQueries, useQuery } from '@tanstack/react-query'
import { useCallback, useMemo, useState } from 'react'
import { useDebounced } from '@/app/hooks/use-debounced'
import { DetailPane } from '@/app/master-detail'
import { LogTail } from '@/components/chat/log-tail'
import { PageLoader } from '@/components/page-loader'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Codicon } from '@/components/ui/codicon'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import {
getSkillHubSources,
previewSkillHub,
scanSkillHub,
searchSkillsHub,
type SkillHubResult,
type SkillHubScanResult
} from '@/hermes'
import { useI18n } from '@/i18n'
import { stripAnsi } from '@/lib/ansi'
import { Loader2 } from '@/lib/icons'
import { cn } from '@/lib/utils'
import {
$hubActions,
$hubActiveLog,
$hubInstalledOverride,
closeHubLog,
HUB_SOURCES_KEY,
installHubSkill,
uninstallHubSkill,
UPDATE_ALL_KEY,
updateHubSkills
} from '@/store/hub-actions'
import { notify, notifyError } from '@/store/notifications'
import { normalizeProfileKey } from '@/store/profile'
// Dedup rank when the same skill surfaces from multiple sources — higher trust
// wins. Mirrors the backend's unified_search `_TRUST_RANK`.
const TRUST_RANK: Record<string, number> = { builtin: 2, trusted: 1, community: 0 }
function trustTone(level: string): string {
switch (level) {
case 'builtin':
return 'bg-(--ui-bg-tertiary) text-(--ui-text-secondary)'
case 'trusted':
return 'bg-emerald-500/15 text-emerald-400'
default:
return 'bg-amber-500/15 text-amber-400'
}
}
function verdictTone(policy: string): string {
switch (policy) {
case 'allow':
return 'text-emerald-400'
case 'block':
return 'text-destructive'
default:
return 'text-amber-400'
}
}
// One hub result — a self-contained row that installs/uninstalls ITSELF and
// reads its own action status from the store, so parallel installs never desync.
// `rawInstalled` is the sources/search truth; the store's optimistic override
// wins so the row flips the instant its own action resolves.
function HubSkillRow({
installedName,
onPreview,
profile,
rawInstalled,
skill
}: {
installedName: null | string
onPreview: (skill: SkillHubResult) => void
profile?: null | string
rawInstalled: boolean
skill: SkillHubResult
}) {
const { t } = useI18n()
const h = t.skills.hub
const action = useStore($hubActions)[skill.identifier]
const override = useStore($hubInstalledOverride)[skill.identifier]
const installed = override ?? rawInstalled
const running = action?.running ?? false
const doInstall = () => {
notify({ kind: 'success', title: h.installStarted(skill.name), message: h.actionLog })
void installHubSkill(skill.identifier, profile).catch(err => notifyError(err, h.actionFailed))
}
const doUninstall = () => {
notify({ kind: 'success', title: h.uninstallStarted(skill.name), message: h.actionLog })
void uninstallHubSkill(skill.identifier, installedName || skill.name, profile).catch(err =>
notifyError(err, h.actionFailed)
)
}
return (
<div className="row-hover flex items-start gap-3 rounded-md px-2 py-2.5">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<span className="truncate text-[0.78rem] font-medium text-foreground/85">{skill.name}</span>
<span className={cn('rounded px-1.5 py-0.5 text-[0.6rem]', trustTone(skill.trust_level))}>
{h.trust[skill.trust_level] ?? skill.trust_level}
</span>
{installed && <span className="text-[0.6rem] text-emerald-400">{h.installed}</span>}
</div>
<p className="mt-0.5 line-clamp-2 text-[0.68rem] text-muted-foreground/70">{skill.description}</p>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button onClick={() => onPreview(skill)} size="xs" variant="text">
{h.preview}
</Button>
{installed ? (
<Button className="hover:text-destructive" disabled={running} onClick={doUninstall} size="xs" variant="text">
{running && <Loader2 className="size-3 animate-spin" />}
{running ? h.uninstalling : h.uninstall}
</Button>
) : (
<Button disabled={running} onClick={doInstall} size="xs" variant="textStrong">
{running && <Loader2 className="size-3 animate-spin" />}
{running ? h.installing : h.install}
</Button>
)}
</div>
</div>
)
}
interface SkillsHubProps {
/** Capabilities profile-scope override — hub browsing/installs target THIS
* profile's backend; undefined/null keeps the app-wide active profile. */
profile?: null | string
query: string
}
export function SkillsHub({ profile, query }: SkillsHubProps) {
const { t } = useI18n()
const h = t.skills.hub
const profileKey = normalizeProfileKey(profile)
// Sources + featured + the installed map — one cached fetch, revalidated on
// mount and re-fetched (from the store) after an action lands.
const sourcesQuery = useQuery({
queryKey: [...HUB_SOURCES_KEY, profileKey],
queryFn: () => getSkillHubSources(profile),
staleTime: 5 * 60_000
})
// Debounced hub search, keyed on the settled query so RQ dedupes/caches per
// term and abandons stale terms for us (no hand-rolled sequence guard).
const term = useDebounced(query.trim(), 350)
// Progressive per-source search: one query per source the backend says is
// worth hitting individually (it marks index-covered API sources unsearchable
// so we don't re-hammer ~70 GitHub calls). Each resolves independently, so the
// list fills in as sources return instead of blocking on the slowest one, and
// each source shows its own spinner. Stale terms key out and are abandoned.
const searchableSources = useMemo(
() => (sourcesQuery.data?.sources ?? []).filter(source => source.searchable !== false),
[sourcesQuery.data]
)
const sourceSearches = useQueries({
queries: searchableSources.map(source => ({
queryKey: ['skill-hub-search', term, source.id, profileKey],
queryFn: () => searchSkillsHub(term, source.id, 20, profile),
enabled: term.length > 0,
staleTime: 60_000
}))
})
// Per-item action lifecycle + log live in the store (store/hub-actions): each
// row reads ITS own entry, so concurrent installs never desync each other,
// and an optimistic installed-override flips a row the instant its own action
// resolves rather than racing the sources refetch.
const actions = useStore($hubActions)
const overrides = useStore($hubInstalledOverride)
const activeLogKey = useStore($hubActiveLog)
const activeLog = activeLogKey ? actions[activeLogKey] : undefined
// Preview/scan dialog. Preview is cache-worthy (keyed by identifier); scan is
// an explicit, on-demand security pass so it stays imperative.
const [detail, setDetail] = useState<null | SkillHubResult>(null)
const [scan, setScan] = useState<null | SkillHubScanResult>(null)
const [scanning, setScanning] = useState(false)
const previewQuery = useQuery({
queryKey: ['skill-hub-preview', detail?.identifier, profileKey],
queryFn: () => previewSkillHub(detail!.identifier, profile),
enabled: detail !== null,
staleTime: 5 * 60_000
})
const install = useCallback(
(identifier: string, name: string) => {
setDetail(null)
notify({ kind: 'success', title: h.installStarted(name), message: h.actionLog })
void installHubSkill(identifier, profile).catch(err => notifyError(err, h.actionFailed))
},
[h, profile]
)
const updateAll = useCallback(() => {
notify({ kind: 'success', title: h.updateStarted, message: h.actionLog })
void updateHubSkills(profile).catch(err => notifyError(err, h.actionFailed))
}, [h, profile])
const runScan = useCallback(
(identifier: string) => {
setScanning(true)
scanSkillHub(identifier, profile)
.then(setScan)
.catch(err => notifyError(err, h.scanFailed))
.finally(() => setScanning(false))
},
[h, profile]
)
const openDetail = useCallback((skill: SkillHubResult) => {
setDetail(skill)
setScan(null)
}, [])
// Per-source progress, keyed by source id (drives the connected-hub chips'
// spinner/degraded tint while a search is streaming in).
const searchStateById = new Map<string, { failed: boolean; fetching: boolean }>()
searchableSources.forEach((source, i) => {
const q = sourceSearches[i]
searchStateById.set(source.id, { failed: q.isError, fetching: term.length > 0 && q.isFetching })
})
// Merge every source's results, deduped by identifier preferring higher trust
// (mirrors the backend's unified_search rank). Recomputes as each source lands.
const results = useMemo(() => {
const seen = new Map<string, SkillHubResult>()
for (const q of sourceSearches) {
for (const r of q.data?.results ?? []) {
const prev = seen.get(r.identifier)
if (!prev || (TRUST_RANK[r.trust_level] ?? 0) > (TRUST_RANK[prev.trust_level] ?? 0)) {
seen.set(r.identifier, r)
}
}
}
return [...seen.values()].sort(
(a, b) => (TRUST_RANK[b.trust_level] ?? 0) - (TRUST_RANK[a.trust_level] ?? 0) || a.name.localeCompare(b.name)
)
}, [sourceSearches])
// Installed map: sources seeds it, search results patch it (a term can surface
// installs the sources list didn't feature); the optimistic override wins so a
// just-(un)installed row reflects its own outcome without the refetch race.
const installed = { ...(sourcesQuery.data?.installed ?? {}) }
for (const q of sourceSearches) {
Object.assign(installed, q.data?.installed ?? {})
}
const isInstalled = (identifier: string) => overrides[identifier] ?? Boolean(installed[identifier])
const sources = sourcesQuery.data?.sources ?? []
const featured = sourcesQuery.data?.featured ?? []
// Still fetching from at least one source; "done" only once every source has
// settled (so "No results" doesn't flash while slower sources are still in).
const anyFetching = term.length > 0 && sourceSearches.some(q => q.isFetching)
const searched = term.length > 0 && sourceSearches.length > 0 && sourceSearches.every(q => !q.isFetching)
const showLanding = term.length === 0
const listed = showLanding ? featured : results
// Only block the whole pane on the first sources landing; after that results
// stream in progressively while a subtle footer shows more are coming.
const searching = anyFetching && results.length === 0
const hasInstalled = Object.keys(installed).length > 0
return (
<div className="flex h-full min-h-0 flex-col">
{/* Connected hubs — label on its own line, chips below, roomy padding. */}
<div className="shrink-0 px-4 pt-5 pb-8 text-[0.68rem] text-(--ui-text-tertiary)">
<span className="mb-1.5 block">{h.connectedHubs}</span>
<div className="flex flex-wrap items-center gap-1.5">
{sourcesQuery.isLoading
? null
: sources.map(source => {
const state = searchStateById.get(source.id)
const degraded = source.available === false || source.rate_limited === true || state?.failed
const fetching = state?.fetching ?? false
return (
<span
className={cn(
'relative rounded px-1.5 py-0.5 text-[0.6rem] transition-opacity',
degraded ? 'bg-amber-500/15 text-amber-400' : 'bg-(--ui-bg-tertiary) text-(--ui-text-secondary)',
// While searching, un-hit sources dim so the active ones read clearly.
term.length > 0 && !fetching && !state?.failed && 'opacity-55'
)}
key={source.id}
>
{/* Spinner overlays the (dimmed) label rather than pushing it,
so a chip never resizes as its search starts/finishes. */}
<span className={cn(fetching && 'opacity-30')}>{source.label}</span>
{fetching && (
<span className="absolute inset-0 grid place-items-center">
<Loader2 className="size-2.5 animate-spin" />
</span>
)}
</span>
)
})}
</div>
</div>
{/* Result summary (left) + Update installed (right) — only when a results
table is actually on screen, and update only if something's installed. */}
{listed.length > 0 && (
<div className="flex shrink-0 items-center justify-between gap-3 px-4 pb-1.5 text-[0.68rem] text-(--ui-text-tertiary)">
<span className="min-w-0 truncate">
{term.length > 0 ? h.resultCount(results.length, null) : h.featured}
{anyFetching && results.length > 0 && (
<span className="ml-2 text-(--ui-text-quaternary)">{h.searching}</span>
)}
</span>
{hasInstalled && (
<Button
className="shrink-0"
disabled={actions[UPDATE_ALL_KEY]?.running}
onClick={updateAll}
size="xs"
variant="text"
>
{actions[UPDATE_ALL_KEY]?.running && <Loader2 className="size-3 animate-spin" />}
{actions[UPDATE_ALL_KEY]?.running ? h.updating : h.updateAll}
</Button>
)}
</div>
)}
{/* Scrollable results. */}
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 [scrollbar-gutter:stable]">
{searching ? (
<div className="grid min-h-40 place-items-center">
<PageLoader label={h.searching} />
</div>
) : listed.length === 0 ? (
<div className="grid min-h-40 place-items-center px-6 text-center">
<p className="max-w-md text-[0.72rem] text-(--ui-text-tertiary)">
{searched ? h.noResults : h.landingHint}
</p>
</div>
) : (
<div className="flex flex-col">
{listed.map(skill => (
<HubSkillRow
installedName={installed[skill.identifier]?.name ?? null}
key={skill.identifier}
onPreview={openDetail}
profile={profile}
rawInstalled={Boolean(installed[skill.identifier])}
skill={skill}
/>
))}
</div>
)}
</div>
{/* Action log — same resizable, flush-width bottom pane + LogTail surface
as the MCP logs. ANSI stripped so spawn output reads clean. Tails the
latest-started action ($hubActiveLog). */}
{activeLogKey && (
<DetailPane
defaultCollapsed
defaultHeight={176}
id="hub-action-log"
onClose={closeHubLog}
title={
<span className="flex items-center gap-1.5 text-[0.68rem] font-normal text-muted-foreground/60">
{h.actionLog}
{activeLog?.running && <Codicon name="loading" size="0.75rem" spinning />}
</span>
}
>
<LogTail emptyLabel={h.searching} lines={activeLog?.lines.length ? activeLog.lines.map(stripAnsi) : null} />
</DetailPane>
)}
<Dialog onOpenChange={open => !open && setDetail(null)} open={detail !== null}>
<DialogContent bodyClassName="overflow-hidden" className="max-h-[80vh] max-w-2xl">
{detail && (
<>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<span className="truncate">{detail.name}</span>
<Badge className={trustTone(detail.trust_level)}>
{h.trust[detail.trust_level] ?? detail.trust_level}
</Badge>
</DialogTitle>
<DialogDescription className="truncate">{detail.identifier}</DialogDescription>
</DialogHeader>
<div className="min-h-0 space-y-3 overflow-y-auto">
{scan && (
<div className="rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) p-3 text-xs">
<div className={cn('font-medium', verdictTone(scan.policy))}>
{scan.policy === 'allow' ? h.policyAllow : scan.policy === 'block' ? h.policyBlock : h.policyAsk}
{' · '}
{scan.verdict === 'safe'
? h.verdictSafe
: scan.verdict === 'dangerous'
? h.verdictDangerous
: h.verdictCaution}
</div>
<div className="mt-1 text-muted-foreground">
{scan.findings.length === 0 ? h.noFindings : h.findings(scan.findings.length)}
</div>
{scan.findings.slice(0, 12).map((finding, index) => (
<div className="mt-1.5 font-mono text-[0.65rem] text-(--ui-text-tertiary)" key={index}>
[{finding.severity}] {finding.file}
{finding.line !== null ? `:${finding.line}` : ''} — {finding.description}
</div>
))}
</div>
)}
{previewQuery.isLoading ? (
<PageLoader className="min-h-32" label={h.searching} />
) : previewQuery.data ? (
<>
<pre
className="max-h-72 overflow-auto whitespace-pre-wrap wrap-break-word rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) p-3 font-mono text-[0.68rem] leading-relaxed"
data-selectable-text="true"
>
{previewQuery.data.skill_md || h.noReadme}
</pre>
{previewQuery.data.files.length > 0 && (
<div className="text-xs text-muted-foreground">
<span className="font-medium">{h.files}:</span> {previewQuery.data.files.join(', ')}
</div>
)}
</>
) : null}
</div>
<DialogFooter>
<Button disabled={scanning} onClick={() => runScan(detail.identifier)} size="sm" variant="text">
{scanning ? h.scanning : h.scan}
</Button>
<Button
disabled={actions[detail.identifier]?.running || isInstalled(detail.identifier)}
onClick={() => install(detail.identifier, detail.name)}
size="sm"
>
{isInstalled(detail.identifier) ? h.installed : h.install}
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
</div>
)
}
+66 -1
View File
@@ -16,6 +16,7 @@ const getToolsetConfig = vi.fn()
const selectToolsetProvider = vi.fn()
const getUsageAnalytics = vi.fn()
const getProfiles = vi.fn()
const getSkillContent = vi.fn()
// Partial mock: keep the real module (SkillsView pulls in @/store/profile,
// whose import-time subscription calls setApiRequestProfile) and stub only the
@@ -31,7 +32,8 @@ vi.mock('@/hermes', async importOriginal => ({
getToolsetConfig: (name: string, profile?: null | string) => getToolsetConfig(name, profile),
selectToolsetProvider: (toolset: string, provider: string) => selectToolsetProvider(toolset, provider),
getUsageAnalytics: (days: number, profile?: null | string) => getUsageAnalytics(days, profile),
getProfiles: () => getProfiles()
getProfiles: () => getProfiles(),
getSkillContent: (name: string, profile?: null | string) => getSkillContent(name, profile)
}))
// Notifications hit nanostores/timers we don't care about here.
@@ -85,6 +87,11 @@ beforeEach(() => {
setToolsetEnabled.mockResolvedValue({ ok: true, name: 'web', enabled: false })
getToolsetConfig.mockResolvedValue({ has_category: true, active_provider: null, providers: [] })
getUsageAnalytics.mockResolvedValue({ tools: [] })
getSkillContent.mockResolvedValue({
name: 'web-research',
path: '/skills/web-research/SKILL.md',
content: '---\nname: web-research\nversion: 1.2.0\nauthor: Nous\n---\n\n# Web Research\n\nDeep research steps.'
})
// Single profile by default → the scope selector stays hidden (>1 gate),
// so existing tests see unchanged single-profile behavior.
getProfiles.mockResolvedValue({ profiles: [{ name: 'default', is_default: true }] })
@@ -227,6 +234,64 @@ describe('SkillsView toolset management', () => {
await waitFor(() => expect(setSkillEnabled).toHaveBeenCalledWith('web-research', false, 'researcher'))
})
it('shows the FULL skill in the detail pane — frontmatter metadata + body', async () => {
getSkills.mockResolvedValue([
{
name: 'web-research',
description: 'Research the web',
category: 'research',
enabled: true,
usage: 3,
provenance: 'bundled'
}
])
const { SkillsView } = await import('./index')
await act(async () => {
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/skills?tab=skills']}>
<SkillsView />
</MemoryRouter>
</QueryClientProvider>
)
})
// Frontmatter renders as metadata rows, the body as full text — not just
// the one-line description.
await waitFor(() => expect(getSkillContent).toHaveBeenCalled())
expect(getSkillContent.mock.calls[0][0]).toBe('web-research')
expect(await screen.findByText('version')).toBeTruthy()
expect(await screen.findByText('1.2.0')).toBeTruthy()
expect(await screen.findByText(/Deep research steps/)).toBeTruthy()
})
it('hub picker refuses to reinstall an already-installed skill', async () => {
const { notify } = await import('@/store/notifications')
const { EmbeddedHubPicker } = await import('./embedded-hub-picker')
render(<EmbeddedHubPicker installedNames={new Set(['web-research'])} profile={null} />)
// The picker is expanded by default — the hub iframe is live on mount.
expect(document.querySelector('iframe')).toBeTruthy()
await act(async () => {
window.dispatchEvent(
new MessageEvent('message', {
data: { type: 'hermes-skill-pick', name: 'web-research', identifier: 'web-research' },
origin: 'https://hermes-agent.nousresearch.com'
})
)
})
// Refused with an informational toast, no install action spawned.
await waitFor(() =>
expect(vi.mocked(notify)).toHaveBeenCalledWith(
expect.objectContaining({ title: '"web-research" is already installed' })
)
)
})
it('shows a vision explainer that deep-links to Settings → Models', async () => {
// Vision has no TOOL_CATEGORIES provider matrix — its model lives in the
// auxiliary model config, so the detail pane must point there instead of
+186 -72
View File
@@ -15,6 +15,7 @@ import {
editLearningNode,
getLearningNode,
getProfiles,
getSkillContent,
getSkills,
getToolsets,
getUsageAnalytics,
@@ -58,11 +59,13 @@ import { ToolsetConfigPanel } from '../settings/toolset-config-panel'
import type { SetStatusbarItemGroup } from '../shell/statusbar-controls'
import { EmbeddedHubPicker } from './embedded-hub-picker'
import { SkillsHub } from './hub'
import { McpTab } from './mcp-tab'
import { $skillsSortDesc, $toolsetsSortDesc } from './store'
const SKILLS_MODES = ['skills', 'toolsets', 'mcp', 'hub'] as const
// 'hub' is gone as a top-level tab — the Skills Hub browser lives inside the
// Skills tab now (EmbeddedHubPicker below the installed list). Legacy
// `?tab=hub` links fall back to 'skills' via useRouteEnumParam.
const SKILLS_MODES = ['skills', 'toolsets', 'mcp'] as const
// Skills + toolsets live in the RQ cache so switching tabs/pages paints the
// cached lists instantly (no reload flash) and mount only fires a deduped
@@ -180,12 +183,29 @@ const visibleToolsetCount = (toolsets: ToolsetInfo[]) => toolsets.filter(ts => i
interface SkillsViewProps extends React.ComponentProps<'section'> {
setStatusbarItemGroup?: SetStatusbarItemGroup
/** Embedded mode (plugin dialogs — e.g. Bot Mode's Advanced section): tab
* state lives in local React state instead of the route's `?tab=` param,
* so an embedding dialog never fights the page router. */
embedded?: boolean
/** Pin the WHOLE view to one profile: the scope selector is hidden and
* every tab reads/writes THAT profile. This is the plugin door — Bot Mode
* renders the real Capabilities surface pinned to a bot. */
fixedProfile?: string
}
export function SkillsView({ setStatusbarItemGroup: _setStatusbarItemGroup, ...props }: SkillsViewProps) {
export function SkillsView({
embedded = false,
fixedProfile,
setStatusbarItemGroup: _setStatusbarItemGroup,
...props
}: SkillsViewProps) {
const { t } = useI18n()
const [mode, setMode] = useRouteEnumParam('tab', SKILLS_MODES, 'skills')
// $gateway only feeds the MCP tab — gate the subscription so Skills/Toolsets/Hub
// Both hooks run unconditionally (rules of hooks); embedded picks the local
// one so tab clicks inside a dialog don't rewrite the page URL.
const routeTab = useRouteEnumParam('tab', SKILLS_MODES, 'skills')
const localTab = useState<(typeof SKILLS_MODES)[number]>('skills')
const [mode, setMode] = embedded ? localTab : routeTab
// $gateway only feeds the MCP tab — gate the subscription so Skills/Toolsets
// tabs don't re-render on connect/disconnect/reconnect.
const gateway = useStoreSelector($gateway, g => (mode === 'mcp' ? g : null))
@@ -195,15 +215,18 @@ export function SkillsView({ setStatusbarItemGroup: _setStatusbarItemGroup, ...p
// editing. Defaults to the app-wide active profile; overriding it here lets
// the user configure ANY profile's toolsets/MCP without switching the whole
// app into that profile. null = the active profile (unchanged behavior).
// A `fixedProfile` pins the scope outright (selector hidden).
const activeProfile = useStore($activeGatewayProfile)
const [scopeOverride, setScopeOverride] = useState<null | string>(null)
const scopeProfile = scopeOverride ?? activeProfile ?? null
const scopeProfile = fixedProfile ?? scopeOverride ?? activeProfile ?? null
const scopeKey = normalizeProfileKey(scopeProfile)
const { data: profilesData } = useQuery({
queryKey: ['capabilities-profiles'],
queryFn: getProfiles,
staleTime: 60_000
staleTime: 60_000,
// Pinned scope never shows the selector, so don't fetch the roster for it.
enabled: !fixedProfile
})
const profiles = profilesData?.profiles ?? []
@@ -323,6 +346,10 @@ export function SkillsView({ setStatusbarItemGroup: _setStatusbarItemGroup, ...p
const bulkSkills = skills ?? []
const bulkToolsets = useMemo(() => (toolsets ?? []).filter(ts => isDesktopToolsetVisible(ts.name)), [toolsets])
// Installed-name set for the hub picker's already-installed guard — the
// UNFILTERED list on purpose (search must not make a skill look absent).
const installedSkillNames = useMemo(() => new Set((skills ?? []).map(s => s.name)), [skills])
// Rotating placeholder nudges from the user's own data — teach that search
// understands categories and tool names, not just titles.
const searchHints = useMemo(() => {
@@ -630,36 +657,21 @@ export function SkillsView({ setStatusbarItemGroup: _setStatusbarItemGroup, ...p
// searching it is noise.
searchHidden={mode === 'mcp'}
searchHints={searchHints}
searchPlaceholder={
mode === 'skills'
? t.skills.searchSkills
: mode === 'hub'
? t.skills.hub.searchPlaceholder
: t.skills.searchToolsets
}
searchPlaceholder={mode === 'skills' ? t.skills.searchSkills : t.skills.searchToolsets}
searchValue={query}
tabs={[
{ id: 'skills', label: t.skills.tabSkills, meta: skills?.length ?? null },
{ id: 'toolsets', label: t.skills.tabToolsets, meta: toolsets ? visibleToolsetCount(toolsets) : null },
{ id: 'mcp', label: t.skills.tabMcp },
{ id: 'hub', label: t.skills.tabHub }
{ id: 'mcp', label: t.skills.tabMcp }
]}
>
{/* One shared column: the scope selector sits above whichever tab is
active, so Skills / Tools / MCP / Browse Hub all read and write the
SAME selected profile. */}
active, so Skills / Tools / MCP all read and write the SAME selected
profile. */}
<div className="flex h-full flex-col">
{profileScopeSelector}
{/* One-click hub installs live right on the Skills tab: an embedded
picker of the live Skills Hub (same postMessage trick Bot Mode
uses), scoped to the selected profile. Collapsed by default. */}
{mode === 'skills' && <EmbeddedHubPicker key={`picker-${scopeKey}`} profile={scopeProfile} />}
<div className="min-h-0 flex-1">
{mode === 'hub' ? (
// Keyed per scope so a scope change remounts the hub (drops the
// previous profile's action log / transient state).
<SkillsHub key={`hub-${scopeKey}`} profile={scopeProfile} query={query} />
) : mode === 'mcp' ? (
{mode === 'mcp' ? (
<McpTab gateway={gateway} key={`mcp-${scopeKey}`} profile={scopeProfile} />
) : (skillsFailed || toolsetsFailed) && (!skills || !toolsets) ? (
<PanelEmpty
@@ -675,52 +687,70 @@ export function SkillsView({ setStatusbarItemGroup: _setStatusbarItemGroup, ...p
) : !skills || !toolsets ? (
<PageLoader label={t.skills.loading} />
) : mode === 'skills' ? (
visibleSkills.length === 0 ? (
capabilityEmpty('skills')
) : (
<MasterDetail pane={skillEditorPane} split="wide">
<ListColumn
header={
<ListStrip
left={sortButton(skillsSortDesc, () => $skillsSortDesc.set(!$skillsSortDesc.get()))}
right={
<ListStripMenu
items={[
{ disabled: bulkBusy, label: t.skills.disableUnused, onSelect: () => void disableUnused() }
]}
label={t.skills.tabSkills}
toggle={bulkSwitch(allSkillsEnabled)}
// Installed skills on top, the Skills Hub browser underneath —
// discovery sits with management, expanded by default. The picker
// renders even when the (filtered) list is empty: a fresh install
// with zero skills is exactly when browsing the hub matters most.
<div className="flex h-full min-h-0 flex-col">
<div className="min-h-0 flex-1">
{visibleSkills.length === 0 ? (
capabilityEmpty('skills')
) : (
<MasterDetail pane={skillEditorPane} split="wide">
<ListColumn
header={
<ListStrip
left={sortButton(skillsSortDesc, () => $skillsSortDesc.set(!$skillsSortDesc.get()))}
right={
<ListStripMenu
items={[
{
disabled: bulkBusy,
label: t.skills.disableUnused,
onSelect: () => void disableUnused()
}
]}
label={t.skills.tabSkills}
toggle={bulkSwitch(allSkillsEnabled)}
/>
}
/>
}
/>
}
>
{visibleSkills.map(skill => (
<CapRow
active={activeSkill?.name === skill.name}
busy={bulkBusy}
enabled={skill.enabled}
key={skill.name}
meta={usageOf(skill) > 0 ? `×${compactNumber(usageOf(skill))}` : undefined}
onSelect={() => setSelectedSkill(skill.name)}
onToggle={enabled => void handleToggleSkill(skill, enabled)}
subtitle={skillSubtitle(skill)}
title={skill.name}
toggleLabel={skill.name}
/>
))}
</ListColumn>
<DetailColumn footer={t.skills.changesApplyNewSessions}>
{activeSkill && (
<SkillDetail
onArchive={() => setArchiveTarget(activeSkill.name)}
onEdit={() => void openSkillEditor(activeSkill.name)}
skill={activeSkill}
/>
)}
</DetailColumn>
</MasterDetail>
)
>
{visibleSkills.map(skill => (
<CapRow
active={activeSkill?.name === skill.name}
busy={bulkBusy}
enabled={skill.enabled}
key={skill.name}
meta={usageOf(skill) > 0 ? `×${compactNumber(usageOf(skill))}` : undefined}
onSelect={() => setSelectedSkill(skill.name)}
onToggle={enabled => void handleToggleSkill(skill, enabled)}
subtitle={skillSubtitle(skill)}
title={skill.name}
toggleLabel={skill.name}
/>
))}
</ListColumn>
<DetailColumn footer={t.skills.changesApplyNewSessions}>
{activeSkill && (
<SkillDetail
onArchive={() => setArchiveTarget(activeSkill.name)}
onEdit={() => void openSkillEditor(activeSkill.name)}
profile={scopeProfile}
skill={activeSkill}
/>
)}
</DetailColumn>
</MasterDetail>
)}
</div>
<EmbeddedHubPicker
installedNames={installedSkillNames}
key={`picker-${scopeKey}`}
profile={scopeProfile}
/>
</div>
) : visibleToolsets.length === 0 ? (
capabilityEmpty('tools')
) : (
@@ -826,12 +856,76 @@ function DetailHeader({
)
}
function SkillDetail({ onArchive, onEdit, skill }: { onArchive: () => void; onEdit: () => void; skill: SkillInfo }) {
// Frontmatter parse for display: the YAML block between the leading `---`
// fences, flattened to top-level `key: value` rows (nested blocks render as
// their raw indented text). Display-only — never fed back to the backend.
function parseFrontmatter(content: string): { body: string; meta: [string, string][] } {
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(content)
if (!match) {
return { body: content, meta: [] }
}
const meta: [string, string][] = []
let currentKey: null | string = null
let block: string[] = []
const flush = () => {
if (currentKey !== null) {
meta.push([currentKey, block.join('\n').trim()])
}
currentKey = null
block = []
}
for (const line of match[1].split(/\r?\n/)) {
const kv = /^(\w[\w-]*):\s?(.*)$/.exec(line)
if (kv) {
flush()
currentKey = kv[1]
block = kv[2] ? [kv[2]] : []
} else if (currentKey !== null) {
block.push(line.replace(/^ {2}/, ''))
}
}
flush()
return { body: content.slice(match[0].length), meta }
}
function SkillDetail({
onArchive,
onEdit,
profile,
skill
}: {
onArchive: () => void
onEdit: () => void
profile?: null | string
skill: SkillInfo
}) {
const { t } = useI18n()
// Only learned/local skills are the user's to rewrite or archive — bundled
// and hub skills are managed by their sources.
const editable = skill.provenance === 'agent'
// The FULL skill — frontmatter metadata + complete SKILL.md body — for any
// provenance, scoped to the Capabilities profile selector. The row list only
// carries name/description; the pane shows the whole thing.
const contentQuery = useQuery({
queryKey: ['skill-content', skill.name, normalizeProfileKey(profile)],
queryFn: () => getSkillContent(skill.name, profile),
staleTime: 60_000
})
const parsed = useMemo(
() => (contentQuery.data ? parseFrontmatter(contentQuery.data.content) : null),
[contentQuery.data]
)
return (
<>
<DetailHeader
@@ -858,6 +952,26 @@ function SkillDetail({ onArchive, onEdit, skill }: { onArchive: () => void; onEd
</Button>
</div>
)}
{parsed && parsed.meta.length > 0 && (
<div className="grid gap-1 rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) p-3">
{parsed.meta.map(([key, value]) => (
<div className="flex gap-2 text-[0.68rem] leading-4" key={key}>
<span className="w-24 shrink-0 font-medium text-(--ui-text-tertiary)">{key}</span>
<span className="min-w-0 whitespace-pre-wrap break-words text-(--ui-text-secondary)">{value}</span>
</div>
))}
</div>
)}
{contentQuery.isLoading ? (
<CountSkeleton />
) : parsed ? (
<pre
className="overflow-auto whitespace-pre-wrap wrap-break-word rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) p-3 font-mono text-[0.68rem] leading-relaxed"
data-selectable-text="true"
>
{parsed.body.trim() || t.skills.noDescription}
</pre>
) : null}
</>
)
}
+12
View File
@@ -1070,6 +1070,18 @@ export function getSkills(profile?: null | string): Promise<SkillInfo[]> {
})
}
/** Raw SKILL.md text (frontmatter included) for ANY skill — bundled, hub, or
* learned — backing the Capabilities detail pane's full-skill view. */
export function getSkillContent(
name: string,
profile?: null | string
): Promise<{ content: string; name: string; path: string }> {
return window.hermesDesktop.api<{ content: string; name: string; path: string }>({
...profileScoped(profile),
path: `/api/skills/content?name=${encodeURIComponent(name)}`
})
}
export function getStarmapGraph(): Promise<StarmapGraph> {
return window.hermesDesktop.api<StarmapGraph>({
...profileScoped(),
+1 -1
View File
@@ -1076,7 +1076,6 @@ export const en: Translations = {
tabToolsets: 'Tools',
configuringProfile: 'Configuring:',
tabMcp: 'MCP',
tabHub: 'Browse Hub',
all: 'All',
searchSkills: 'Search skills...',
searchToolsets: 'Search tools...',
@@ -1171,6 +1170,7 @@ export const en: Translations = {
updateStarted: 'Updating installed skills...',
actionFailed: 'Skill action failed',
actionLog: 'Action log',
alreadyInstalled: (name: string) => `"${name}" is already installed`,
pickerTitle: 'Skills Hub',
pickerBrowse: 'Browse the full hub',
pickerHide: 'Hide the hub browser',
+1 -1
View File
@@ -934,7 +934,6 @@ export interface Translations {
tabToolsets: string
configuringProfile: string
tabMcp: string
tabHub: string
all: string
searchSkills: string
searchToolsets: string
@@ -1019,6 +1018,7 @@ export interface Translations {
updateStarted: string
actionFailed: string
actionLog: string
alreadyInstalled: (name: string) => string
pickerTitle: string
pickerBrowse: string
pickerHide: string
+1 -1
View File
@@ -1271,7 +1271,6 @@ export const zh: Translations = {
tabToolsets: '工具集',
configuringProfile: '正在配置:',
tabMcp: 'MCP',
tabHub: '浏览技能中心',
all: '全部',
searchSkills: '搜索技能…',
searchToolsets: '搜索工具集…',
@@ -1364,6 +1363,7 @@ export const zh: Translations = {
updateStarted: '正在更新已安装技能…',
actionFailed: '技能操作失败',
actionLog: '操作日志',
alreadyInstalled: name => `“${name}”已安装`,
pickerTitle: '技能中心',
pickerBrowse: '浏览完整技能中心',
pickerHide: '隐藏技能中心浏览器',
+7
View File
@@ -253,6 +253,13 @@ export {
export type { StatusbarItem } from '@/app/shell/statusbar-controls'
export type { TitlebarTool } from '@/app/shell/titlebar-controls'
/** THE whole Capabilities surface (Skills / Tools / MCP tabs, installed
* lists, full-skill detail pane, embedded hub picker with one-click
* installs). For plugin dialogs pass `embedded` (tab state stays local —
* never touches the page router) and `fixedProfile` to pin every tab to one
* bot's backend; the internal profile selector hides itself. Bot Mode's
* Advanced section is the reference consumer. */
export { SkillsView } from '@/app/skills'
/** THE full MCP tab core Settings renders — per-server enable + OAuth sign-in
* + API-key setup + live probes, not a checkbox list. Route-decoupled so it
* renders anywhere (a plugin dialog); pass a live `gateway` (see
+21
View File
@@ -5056,6 +5056,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
timestamp_str = self.session_start.strftime("%Y%m%d_%H%M%S")
short_uuid = uuid.uuid4().hex[:6]
self.session_id = f"{timestamp_str}_{short_uuid}"
getattr(self, "_write_terminal_breadcrumb", lambda: None)()
# History file for persistent input recall across sessions
self._history_file = _hermes_home / ".hermes_history"
@@ -9251,6 +9252,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
timestamp_str = self.session_start.strftime("%Y%m%d_%H%M%S")
short_uuid = uuid.uuid4().hex[:6]
self.session_id = f"{timestamp_str}_{short_uuid}"
getattr(self, "_write_terminal_breadcrumb", lambda: None)()
self.conversation_history = []
self._pending_title = None
self._resumed = False
@@ -12263,6 +12265,22 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
}
_cprint(labels.get(self.tool_progress_mode, ""))
def _write_terminal_breadcrumb(self) -> None:
"""Record this terminal's live session for bare ``hermes -c``.
Called at session start and whenever ``self.session_id`` is
reassigned mid-run (/new, /branch, auto-compression rotation) so a
later bare ``-c`` in THIS terminal resumes THIS conversation's live
tip. Best-effort — never raises, no-op without a terminal identity
or when session.terminal_continue is false.
"""
try:
from hermes_cli.terminal_breadcrumbs import write_breadcrumb
write_breadcrumb(self.session_id)
except Exception:
pass
def _transfer_session_yolo(self, old_session_id: str, new_session_id: str) -> None:
"""Move YOLO bypass state from an old session key to a new one.
@@ -12586,6 +12604,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
and self.agent.session_id != self.session_id
):
self.session_id = self.agent.session_id
getattr(self, "_write_terminal_breadcrumb", lambda: None)()
self._pending_title = None
# Manual /compress replaces conversation_history with a new
# compressed handoff for the child session. Persist it from
@@ -15660,6 +15679,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
):
self._transfer_session_yolo(self.session_id, self.agent.session_id)
self.session_id = self.agent.session_id
getattr(self, "_write_terminal_breadcrumb", lambda: None)()
self._pending_title = None
# Get the final response
@@ -16044,6 +16064,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
agent._persist_session(messages, conversation_history)
if getattr(agent, "session_id", None):
self.session_id = agent.session_id
getattr(self, "_write_terminal_breadcrumb", lambda: None)()
try:
if persist_lock is None:
+9
View File
@@ -33,6 +33,15 @@ DEFAULT_CONFIG = {
# sessions (no live client) so accumulated agents don't pile up under memory
# pressure. Reopening one re-resumes it from disk. 0/null disables.
"max_live_sessions": 16,
"session": {
# Per-terminal `hermes -c`: each CLI session drops a breadcrumb file
# under $HERMES_HOME/terminal-sessions/<terminal-id>, and a bare
# -c/--continue resumes THIS terminal's session (tmux pane, kitty
# window, wezterm pane, plain tty, ...) instead of the globally
# most-recent one. Set false to restore the old latest-session
# behavior everywhere.
"terminal_continue": True,
},
"agent": {
"max_turns": 500,
# Inactivity timeout for gateway agent execution (seconds).
+484
View File
@@ -0,0 +1,484 @@
"""Import sessions from foreign coding agents (Claude Code, Codex CLI).
``hermes sessions import`` (and ``--resume @claude`` / ``--resume @codex``)
let a user pull a conversation they started in another agent CLI into
Hermes and continue it here.
Sources (read-only — foreign files are never modified):
* **Claude Code** stores one JSONL file per session under
``~/.claude/projects/<encoded-cwd>/<uuid>.jsonl``. Each line is a JSON
object; ``type: "user"`` / ``type: "assistant"`` lines carry an
Anthropic-format ``message`` payload whose ``content`` is either a string
or a list of blocks (``text``, ``tool_use``, ``tool_result``, ...).
``type: "summary"`` lines carry a human title for the thread.
* **Codex CLI** stores rollout JSONL under
``~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl``. The first line is a
``session_meta`` record (cwd, session id); conversation turns are
``response_item`` records whose payload is ``{"type": "message",
"role": user|assistant|developer, "content": [{"type": "input_text"|
"output_text", "text": ...}]}`` plus ``custom_tool_call`` /
``function_call`` payloads for tool activity. (Schema verified against
real rollout files, Codex CLI 0.147.)
Conversion contract — imported history must satisfy the provider
role-alternation invariant Hermes enforces everywhere else:
* only plain ``user`` / ``assistant`` text messages are produced (tool
calls become short bracketed summaries inside the assistant text; we
never fabricate ``tool_calls`` structures);
* consecutive same-role turns are merged rather than stubbed;
* system/developer payloads are never imported.
"""
from __future__ import annotations
import json
import re
import uuid
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# User-message texts that are really injected context wrappers, not typed
# input. Matched against the stripped start of the text.
_WRAPPER_TAG_RE = re.compile(
r"^<(?:user_instructions|environment_context|recommended_plugins|"
r"skills_instructions|permissions[_-]instructions|turn_context|"
r"command-name|command-message|local-command-stdout|system-reminder)\b",
re.IGNORECASE,
)
_TITLE_MAX = 60
@dataclass
class ForeignSession:
"""A discoverable session in another tool's on-disk store."""
source: str # "claude" | "codex"
path: Path
mtime: float
cwd: Optional[str] = None
title_guess: Optional[str] = None
turn_count: int = 0
session_id: Optional[str] = None # the foreign tool's own id
@property
def label(self) -> str:
name = {"claude": "Claude Code", "codex": "Codex CLI"}.get(
self.source, self.source
)
title = (self.title_guess or "").strip() or self.path.stem
return f"[{name}] {title[:_TITLE_MAX]}"
def _read_json_lines(path: Path):
"""Yield parsed JSON objects, silently skipping unparseable lines."""
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except (json.JSONDecodeError, ValueError):
continue
if isinstance(obj, dict):
yield obj
except OSError:
return
def _flatten_blocks(content: Any, *, source: str) -> str:
"""Flatten a message ``content`` (string or block list) to plain text.
Tool activity becomes a short bracketed summary; unknown block types
are skipped rather than guessed at.
"""
if isinstance(content, str):
return content
if not isinstance(content, list):
return ""
parts: List[str] = []
for block in content:
if not isinstance(block, dict):
if isinstance(block, str):
parts.append(block)
continue
btype = block.get("type")
if btype in ("text", "input_text", "output_text"):
text = block.get("text")
if isinstance(text, str) and text:
parts.append(text)
elif btype == "tool_use": # Claude Code assistant block
name = block.get("name") or "tool"
parts.append(f"[ran tool: {name}]")
elif btype == "tool_result":
# Tool output echoed into a user message — not typed input.
continue
elif btype in ("thinking", "redacted_thinking", "reasoning"):
continue
elif btype == "image":
parts.append("[image]")
return "\n\n".join(p for p in (s.strip() for s in parts) if p)
def _is_wrapper_text(text: str) -> bool:
return bool(_WRAPPER_TAG_RE.match(text.lstrip()))
def _merge_turns(raw_turns: List[Tuple[str, str]]) -> List[Dict[str, str]]:
"""Merge consecutive same-role turns; guarantee strict alternation.
A leading assistant turn (session began before the log window) gets a
minimal user stub so the first message is always ``user``; this is the
only place a stub is ever inserted.
"""
merged: List[Dict[str, str]] = []
for role, text in raw_turns:
text = text.strip()
if not text:
continue
if merged and merged[-1]["role"] == role:
merged[-1]["content"] += "\n\n" + text
else:
merged.append({"role": role, "content": text})
if merged and merged[0]["role"] == "assistant":
merged.insert(
0,
{
"role": "user",
"content": "(imported conversation begins with an assistant reply)",
},
)
return merged
# ── Claude Code ──────────────────────────────────────────────────────────
def parse_claude_session(path: Path) -> Dict[str, Any]:
"""Parse one Claude Code session JSONL into normalized turns + meta."""
turns: List[Tuple[str, str]] = []
cwd: Optional[str] = None
summary: Optional[str] = None
session_id: Optional[str] = None
for obj in _read_json_lines(path):
otype = obj.get("type")
if otype == "summary":
s = obj.get("summary")
if isinstance(s, str) and s.strip():
summary = s.strip()
continue
if otype not in ("user", "assistant"):
continue
if obj.get("isSidechain") or obj.get("isMeta"):
continue
if cwd is None and isinstance(obj.get("cwd"), str):
cwd = obj["cwd"]
if session_id is None and isinstance(obj.get("sessionId"), str):
session_id = obj["sessionId"]
message = obj.get("message")
if not isinstance(message, dict):
continue
role = message.get("role")
if role not in ("user", "assistant"):
continue
text = _flatten_blocks(message.get("content"), source="claude")
if not text or (role == "user" and _is_wrapper_text(text)):
continue
turns.append((role, text))
return {
"turns": _merge_turns(turns),
"cwd": cwd,
"title_guess": summary or _first_user_line(turns),
"session_id": session_id,
}
def list_claude_sessions(root: Optional[Path] = None) -> List[ForeignSession]:
"""Discover Claude Code sessions under ``~/.claude/projects``."""
root = Path(root) if root else Path.home() / ".claude" / "projects"
results: List[ForeignSession] = []
if not root.is_dir():
return results
for jsonl in sorted(root.glob("*/*.jsonl")):
try:
mtime = jsonl.stat().st_mtime
except OSError:
continue
parsed = parse_claude_session(jsonl)
if not parsed["turns"]:
continue
results.append(
ForeignSession(
source="claude",
path=jsonl,
mtime=mtime,
cwd=parsed["cwd"],
title_guess=parsed["title_guess"],
turn_count=len(parsed["turns"]),
session_id=parsed["session_id"],
)
)
results.sort(key=lambda s: s.mtime, reverse=True)
return results
# ── Codex CLI ────────────────────────────────────────────────────────────
def parse_codex_session(path: Path) -> Dict[str, Any]:
"""Parse one Codex CLI rollout JSONL into normalized turns + meta."""
turns: List[Tuple[str, str]] = []
cwd: Optional[str] = None
session_id: Optional[str] = None
for obj in _read_json_lines(path):
otype = obj.get("type")
payload = obj.get("payload")
if not isinstance(payload, dict):
continue
if otype == "session_meta":
if isinstance(payload.get("cwd"), str):
cwd = payload["cwd"]
sid = payload.get("session_id") or payload.get("id")
if isinstance(sid, str):
session_id = sid
continue
if otype != "response_item":
continue
ptype = payload.get("type")
if ptype == "message":
role = payload.get("role")
if role not in ("user", "assistant"):
continue # developer/system payloads never imported
text = _flatten_blocks(payload.get("content"), source="codex")
if not text or (role == "user" and _is_wrapper_text(text)):
continue
turns.append((role, text))
elif ptype in ("custom_tool_call", "function_call", "local_shell_call"):
name = payload.get("name") or payload.get("tool") or "tool"
# Attach as assistant activity; merged into neighbors later.
turns.append(("assistant", f"[ran tool: {name}]"))
# tool outputs / reasoning / web_search etc. are skipped
return {
"turns": _merge_turns(turns),
"cwd": cwd,
"title_guess": _first_user_line(turns),
"session_id": session_id,
}
def list_codex_sessions(root: Optional[Path] = None) -> List[ForeignSession]:
"""Discover Codex CLI rollouts under ``~/.codex/sessions``."""
root = Path(root) if root else Path.home() / ".codex" / "sessions"
results: List[ForeignSession] = []
if not root.is_dir():
return results
for jsonl in sorted(root.rglob("rollout-*.jsonl")):
try:
mtime = jsonl.stat().st_mtime
except OSError:
continue
parsed = parse_codex_session(jsonl)
if not parsed["turns"]:
continue
results.append(
ForeignSession(
source="codex",
path=jsonl,
mtime=mtime,
cwd=parsed["cwd"],
title_guess=parsed["title_guess"],
turn_count=len(parsed["turns"]),
session_id=parsed["session_id"],
)
)
results.sort(key=lambda s: s.mtime, reverse=True)
return results
def _first_user_line(turns: List[Tuple[str, str]]) -> Optional[str]:
for role, text in turns:
if role == "user":
line = text.strip().splitlines()[0].strip()
if line:
return line[:_TITLE_MAX * 2]
return None
# ── Import ───────────────────────────────────────────────────────────────
_SOURCE_LABELS = {"claude": "Claude Code", "codex": "Codex CLI"}
_SOURCE_DB_NAMES = {"claude": "claude-code", "codex": "codex-cli"}
def import_foreign_session(source: str, path, db=None) -> str:
"""Import one foreign session into the Hermes SessionDB.
Returns the new Hermes session id. The foreign file is only read.
Raises ``ValueError`` on unknown source or a session with no usable
conversation turns.
"""
source = (source or "").strip().lower().lstrip("@")
if source not in _SOURCE_LABELS:
raise ValueError(f"Unknown foreign session source: {source!r}")
path = Path(path).expanduser()
if not path.is_file():
raise ValueError(f"Session file not found: {path}")
parsed = (
parse_claude_session(path)
if source == "claude"
else parse_codex_session(path)
)
turns = parsed["turns"]
if not turns:
raise ValueError(
f"No user/assistant conversation turns found in {path}"
)
label = _SOURCE_LABELS[source]
first_user = _first_user_line(
[(t["role"], t["content"]) for t in turns]
) or path.stem
if len(first_user) > _TITLE_MAX:
first_user = first_user[: _TITLE_MAX - 1] + "…"
title = f"Imported from {label}: {first_user}"
owns_db = db is None
if owns_db:
from hermes_state import SessionDB
db = SessionDB()
try:
session_id = (
f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
)
origin = {
"imported_from": {
"tool": _SOURCE_DB_NAMES[source],
"path": str(path),
"foreign_session_id": parsed.get("session_id"),
}
}
db.create_session(
session_id,
source=_SOURCE_DB_NAMES[source],
cwd=parsed.get("cwd"),
origin_json=json.dumps(origin),
)
for turn in turns:
db.append_message(session_id, turn["role"], turn["content"])
try:
db.set_session_title(session_id, title)
except Exception:
pass # title is cosmetic; the import itself succeeded
return session_id
finally:
if owns_db:
try:
db.close()
except Exception:
pass
# ── Picker / CLI helpers ─────────────────────────────────────────────────
def gather_foreign_sessions(
source: Optional[str] = None,
*,
claude_root: Optional[Path] = None,
codex_root: Optional[Path] = None,
limit: int = 25,
) -> List[ForeignSession]:
"""List foreign sessions across sources, newest first."""
sessions: List[ForeignSession] = []
if source in (None, "claude"):
sessions.extend(list_claude_sessions(claude_root))
if source in (None, "codex"):
sessions.extend(list_codex_sessions(codex_root))
sessions.sort(key=lambda s: s.mtime, reverse=True)
return sessions[:limit] if limit else sessions
def pick_foreign_session(
source: Optional[str] = None, *, limit: int = 25
) -> Optional[ForeignSession]:
"""Interactive numbered picker. Returns None when nothing was chosen."""
import os
import sys
sessions = gather_foreign_sessions(source, limit=limit)
if not sessions:
where = _SOURCE_LABELS.get(source or "", "Claude Code or Codex CLI")
print(f"No {where} sessions found on this machine.")
return None
print("Foreign sessions (newest first):")
for i, s in enumerate(sessions, 1):
when = datetime.fromtimestamp(s.mtime).strftime("%Y-%m-%d %H:%M")
ws = ""
if s.cwd:
ws = f" ({os.path.basename(s.cwd.rstrip('/')) or s.cwd})"
print(f" {i:>2}. {when} {s.label}{ws} [{s.turn_count} turns]")
if not sys.stdin.isatty():
print(
"Non-interactive terminal — pass the file path directly:\n"
" hermes sessions import --from claude|codex <path>"
)
return None
try:
raw = input(f"Import which session? [1-{len(sessions)}, empty to cancel] ")
except (EOFError, KeyboardInterrupt):
return None
raw = raw.strip()
if not raw:
return None
try:
idx = int(raw)
except ValueError:
print(f"Not a number: {raw}")
return None
if not 1 <= idx <= len(sessions):
print(f"Out of range: {idx}")
return None
return sessions[idx - 1]
def run_sessions_import(args, db=None) -> Optional[str]:
"""`hermes sessions import` entry point. Returns new session id or None."""
source = getattr(args, "from_source", None)
path = getattr(args, "path", None)
if path:
if not source:
# Guess from the path shape.
p = str(path)
if "/.claude/" in p or p.endswith(".jsonl") and "claude" in p:
source = "claude"
if "/.codex/" in p or Path(p).name.startswith("rollout-"):
source = "codex"
if not source:
print("Cannot infer source from path; pass --from claude|codex.")
return None
chosen_path = Path(path)
else:
picked = pick_foreign_session(source)
if picked is None:
return None
source, chosen_path = picked.source, picked.path
try:
session_id = import_foreign_session(source, chosen_path, db=db)
except ValueError as e:
print(f"Error: {e}")
return None
label = _SOURCE_LABELS.get(source, source)
print(f"✓ Imported {label} session as {session_id}")
print(f" Continue it with: hermes --resume {session_id}")
return session_id
+232 -35
View File
@@ -1156,21 +1156,75 @@ def _confirm_startup_expensive_model_override(args) -> None:
raise SystemExit(1)
def _session_browse_picker(sessions: list) -> Optional[str]:
def _session_status_tag(status: Optional[str]) -> str:
"""Short fixed-width tag for a session lifecycle status."""
return {
"complete": "done",
"interrupted": "intr",
"error": "err",
"empty": "empty",
}.get(status or "", "-")
def _annotate_session_statuses(sessions: list, session_db) -> None:
"""Attach a ``_status`` key to each session row (best-effort, cheap).
Uses ``SessionDB.session_lifecycle_statuses`` — one indexed last-message
lookup per listed session, never a transcript scan. On any failure the
rows simply stay untagged and the picker renders '-' for status.
"""
if session_db is None or not sessions:
return
try:
statuses = session_db.session_lifecycle_statuses(
[s.get("id") for s in sessions]
)
except Exception:
return
for s in sessions:
s["_status"] = statuses.get(s.get("id"), "")
def _session_browse_picker(sessions: list, session_db=None) -> Optional[str]:
"""Interactive curses-based session browser with live search filtering.
Shows lifecycle status (done / intr / err / empty) and message count per
session when *session_db* is provided. With a live *session_db*, pressing
``d`` on a row (while the search filter is empty) prompts y/n and deletes
the session via ``SessionDB.delete_session``.
Returns the selected session ID, or None if cancelled.
"""
if not sessions:
print("No sessions found.")
return None
_annotate_session_statuses(sessions, session_db)
def _delete_session(session_id: str) -> bool:
if session_db is None:
return False
try:
sessions_dir = get_hermes_home() / "sessions"
except Exception:
sessions_dir = None
try:
return bool(
session_db.delete_session(session_id, sessions_dir=sessions_dir)
)
except Exception:
return False
# Try curses-based picker first
try:
import curses
result_holder = [None]
# Layout: [arrow 3] [title/preview flexible] [status 5] [msgs 5]
# [active 12] [src 6] [id 18]
_FIXED_COLS = 3 + 5 + 2 + 5 + 2 + 12 + 6 + 18 + 6
def _format_row(s, max_x):
"""Format a session row for display."""
title = (s.get("title") or "").strip()
@@ -1178,11 +1232,11 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
source = s.get("source", "")[:6]
last_active = _relative_time(s.get("last_active"))
sid = s["id"][:18]
status = _session_status_tag(s.get("_status"))
msgs = s.get("message_count")
msgs_str = str(msgs) if isinstance(msgs, int) else "-"
# Adaptive column widths based on terminal width
# Layout: [arrow 3] [title/preview flexible] [active 12] [src 6] [id 18]
fixed_cols = 3 + 12 + 6 + 18 + 6 # arrow + active + src + id + padding
name_width = max(20, max_x - fixed_cols)
name_width = max(20, max_x - _FIXED_COLS)
if title:
name = title[:name_width]
@@ -1191,7 +1245,10 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
else:
name = sid
return f"{name:<{name_width}} {last_active:<10} {source:<5} {sid}"
return (
f"{name:<{name_width}} {status:<5} {msgs_str:>5} "
f"{last_active:<10} {source:<5} {sid}"
)
def _match(s, query):
"""Check if a session matches the search query (case-insensitive)."""
@@ -1212,12 +1269,25 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
curses.init_pair(2, curses.COLOR_YELLOW, -1) # header
curses.init_pair(3, curses.COLOR_CYAN, -1) # search
curses.init_pair(4, 8 if curses.COLORS > 8 else curses.COLOR_WHITE, -1) # dim
curses.init_pair(5, curses.COLOR_RED, -1) # error/delete
cursor = 0
scroll_offset = 0
search_text = ""
confirm_delete = None # session dict pending y/n confirmation
flash = "" # one-frame notice (e.g. "deleted <title>")
filtered = list(sessions)
def _status_attr(status):
if not curses.has_colors():
return curses.A_NORMAL
return {
"complete": curses.color_pair(1),
"interrupted": curses.color_pair(2),
"error": curses.color_pair(5),
"empty": curses.color_pair(4),
}.get(status or "", curses.A_NORMAL)
while True:
stdscr.clear()
max_y, max_x = stdscr.getmaxyx()
@@ -1238,7 +1308,10 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
if curses.has_colors():
header_attr |= curses.color_pair(3)
else:
header = " Browse sessions — ↑↓ navigate Enter select Type to filter Esc quit"
header = (
" Browse sessions — ↑↓ navigate Enter select"
" Type to filter Esc quit"
)
header_attr = curses.A_BOLD
if curses.has_colors():
header_attr |= curses.color_pair(2)
@@ -1248,9 +1321,11 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
pass
# Column header line
fixed_cols = 3 + 12 + 6 + 18 + 6
name_width = max(20, max_x - fixed_cols)
col_header = f" {'Title / Preview':<{name_width}} {'Active':<10} {'Src':<5} {'ID'}"
name_width = max(20, max_x - _FIXED_COLS)
col_header = (
f" {'Title / Preview':<{name_width}} {'Stat':<5} "
f"{'Msgs':>5} {'Active':<10} {'Src':<5} {'ID'}"
)
try:
dim_attr = (
curses.color_pair(4) if curses.has_colors() else curses.A_DIM
@@ -1298,31 +1373,76 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
attr |= curses.color_pair(1)
try:
stdscr.addnstr(y, 0, row, max_x - 1, attr)
if i != cursor:
# Recolor the status tag column in place.
status = s.get("_status")
tag = _session_status_tag(status)
tag_x = 3 + max(20, (max_x - 3) - _FIXED_COLS) + 2
if tag_x + 5 < max_x - 1:
stdscr.addnstr(
y, tag_x, f"{tag:<5}", 5, _status_attr(status)
)
except curses.error:
pass
# Footer
footer_y = max_y - 1
if filtered:
footer = f" {cursor + 1}/{len(filtered)} sessions"
if len(filtered) < len(sessions):
footer += f" (filtered from {len(sessions)})"
else:
footer = f" 0/{len(sessions)} sessions"
try:
stdscr.addnstr(
footer_y,
0,
footer,
max_x - 1,
curses.color_pair(4) if curses.has_colors() else curses.A_DIM,
footer_attr = (
curses.color_pair(4) if curses.has_colors() else curses.A_DIM
)
if confirm_delete is not None:
label = (
(confirm_delete.get("title") or "").strip()
or (confirm_delete.get("preview") or "").strip()
or confirm_delete["id"]
)
if len(label) > 40:
label = label[:37] + "..."
footer = f" Delete session '{label}'? [y/N]"
footer_attr = curses.A_BOLD
if curses.has_colors():
footer_attr |= curses.color_pair(5)
elif flash:
footer = f" {flash}"
flash = ""
else:
if filtered:
footer = f" {cursor + 1}/{len(filtered)} sessions"
if len(filtered) < len(sessions):
footer += f" (filtered from {len(sessions)})"
else:
footer = f" 0/{len(sessions)} sessions"
if session_db is not None and not search_text:
footer += " d delete"
try:
stdscr.addnstr(footer_y, 0, footer, max_x - 1, footer_attr)
except curses.error:
pass
stdscr.refresh()
key = stdscr.getch()
if confirm_delete is not None:
# y/n confirmation mode — only an explicit 'y' deletes.
target = confirm_delete
confirm_delete = None
if key in {ord("y"), ord("Y")}:
if _delete_session(target["id"]):
sessions[:] = [
s for s in sessions if s["id"] != target["id"]
]
filtered = (
[s for s in sessions if _match(s, search_text)]
if search_text
else list(sessions)
)
flash = "Deleted."
if not sessions:
return
else:
flash = "Delete failed."
continue
if key in {curses.KEY_UP,}:
if filtered:
cursor = (cursor - 1) % len(filtered)
@@ -1354,6 +1474,15 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
scroll_offset = 0
elif key == ord("q") and not search_text:
return
elif (
key == ord("d")
and not search_text
and session_db is not None
and filtered
):
# 'd' only acts as delete when the filter is empty —
# while a search is active it types into the query below.
confirm_delete = filtered[cursor]
elif 32 <= key <= 126:
# Printable character → add to search filter
search_text += chr(key)
@@ -1367,7 +1496,8 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
except Exception:
pass
# Fallback: numbered list (Windows without curses, etc.)
# Fallback: numbered list (Windows without curses, etc.). Shows the same
# status/message-count columns but has no delete support.
print("\n Browse sessions (enter number to resume, q to cancel)\n")
for i, s in enumerate(sessions):
title = (s.get("title") or "").strip()
@@ -1377,7 +1507,13 @@ def _session_browse_picker(sessions: list) -> Optional[str]:
label = label[:47] + "..."
last_active = _relative_time(s.get("last_active"))
src = s.get("source", "")[:6]
print(f" {i + 1:>3}. {label:<50} {last_active:<10} {src}")
status = _session_status_tag(s.get("_status"))
msgs = s.get("message_count")
msgs_str = str(msgs) if isinstance(msgs, int) else "-"
print(
f" {i + 1:>3}. {label:<50} {status:<5} {msgs_str:>5} "
f"{last_active:<10} {src}"
)
while True:
try:
@@ -2672,17 +2808,56 @@ def cmd_chat(args):
print("Use 'hermes sessions list' to see available sessions.")
sys.exit(1)
else:
# -c with no argument — continue the most recent session
source = "tui" if use_tui else "cli"
last_id = _resolve_last_session(source=source)
if not last_id and source == "tui":
last_id = _resolve_last_session(source="cli")
if last_id:
args.resume = last_id
# -c with no argument — prefer this terminal's own breadcrumb
# (written at session start / rotation) so side-by-side terminals
# each continue their own conversation. Falls back to the
# most-recent session when there is no valid breadcrumb, or when
# session.terminal_continue is false in config.yaml.
try:
from hermes_cli.terminal_breadcrumbs import resolve_breadcrumb_session
_crumb_id = resolve_breadcrumb_session()
except Exception:
_crumb_id = None
if _crumb_id:
args.resume = _crumb_id
else:
kind = "TUI" if use_tui else "CLI"
print(f"No previous {kind} session found to continue.")
sys.exit(1)
# No valid breadcrumb — continue the most recent session
source = "tui" if use_tui else "cli"
last_id = _resolve_last_session(source=source)
if not last_id and source == "tui":
last_id = _resolve_last_session(source="cli")
if last_id:
args.resume = last_id
else:
kind = "TUI" if use_tui else "CLI"
print(f"No previous {kind} session found to continue.")
sys.exit(1)
# --resume @claude / --resume @codex: import a foreign session (Claude
# Code / Codex CLI) and resume the newly created Hermes session.
_resume_foreign = getattr(args, "resume", None)
if isinstance(_resume_foreign, str) and _resume_foreign.strip().lower() in (
"@claude",
"@codex",
):
from hermes_cli.foreign_sessions import (
import_foreign_session,
pick_foreign_session,
)
_foreign_source = _resume_foreign.strip().lower().lstrip("@")
_picked = pick_foreign_session(_foreign_source)
if _picked is None:
sys.exit(1)
try:
_imported_id = import_foreign_session(_picked.source, _picked.path)
except ValueError as e:
print(f"Error: {e}")
sys.exit(1)
print(f"✓ Imported as {_imported_id} — resuming it now.")
print(f" (later: hermes --resume {_imported_id})")
args.resume = _imported_id
# Resolve --resume by title if it's not a direct session ID
resume_val = getattr(args, "resume", None)
@@ -12987,6 +13162,28 @@ def main():
"--limit", type=int, default=500, help="Max sessions to load (default: 500)"
)
sessions_import = sessions_subparsers.add_parser(
"import",
help="Import a Claude Code or Codex CLI session into Hermes",
description=(
"Pull a conversation started in Claude Code (~/.claude/projects) "
"or Codex CLI (~/.codex/sessions) into the Hermes session store "
"so it can be resumed with 'hermes --resume <id>'. The foreign "
"files are only read, never modified."
),
)
sessions_import.add_argument(
"--from",
dest="from_source",
choices=["claude", "codex"],
help="Which tool to import from (default: pick across both)",
)
sessions_import.add_argument(
"path",
nargs="?",
help="Path to a specific session JSONL file (skips the picker)",
)
# cmd_sessions lives in hermes_cli/sessions_cmd.py (main.py decomposition).
# sessions_parser is threaded in via functools.partial because the
+15 -4
View File
@@ -39,8 +39,8 @@ def _relative_time(ts):
return _m()._relative_time(ts)
def _session_browse_picker(sessions):
return _m()._session_browse_picker(sessions)
def _session_browse_picker(sessions, session_db=None):
return _m()._session_browse_picker(sessions, session_db=session_db)
def _size_delta_label(saved_mb):
@@ -302,6 +302,12 @@ def cmd_sessions(args, sessions_parser=None):
print(" Do not install it. Review the JSON report for partial data or errors.")
return 1
if action == "import":
from hermes_cli.foreign_sessions import run_sessions_import
run_sessions_import(args)
return
try:
from hermes_state import SessionDB
@@ -1070,12 +1076,17 @@ def cmd_sessions(args, sessions_parser=None):
sessions = db.list_sessions_rich(
source=source, exclude_sources=_browse_exclude, limit=limit
)
db.close()
if not sessions:
db.close()
print("No sessions found.")
return
selected_id = _session_browse_picker(sessions)
# Keep the DB open: the picker uses it for lifecycle status tags and
# the 'd' delete-with-confirmation action.
try:
selected_id = _session_browse_picker(sessions, session_db=db)
finally:
db.close()
if not selected_id:
print("Cancelled.")
return
+185
View File
@@ -0,0 +1,185 @@
"""Per-terminal session breadcrumbs for ``hermes -c`` / ``--continue``.
Each CLI session writes a tiny breadcrumb file
``$HERMES_HOME/terminal-sessions/<terminal-id>`` containing
``{"session_id": ..., "cwd": ..., "ts": ...}``. A bare ``hermes -c`` then
resumes the session that belongs to THIS terminal (tty / tmux pane / kitty
window / wezterm pane / ...) instead of the globally most-recent session —
so two terminals side by side each continue their own conversation.
Everything here is strictly best-effort: no function raises, and when no
stable terminal identity can be derived (no tty and no known multiplexer
env var) breadcrumbs are skipped entirely and ``-c`` falls back to the
existing latest-session behavior. Gated by ``session.terminal_continue``
in config.yaml (default true).
"""
from __future__ import annotations
import json
import os
import re
import sys
import time
from pathlib import Path
from typing import Optional
# Multiplexer / terminal-emulator identity env vars, checked in order when
# no real tty path is available (e.g. stdin piped but stdout still a pty
# owned by a known terminal).
_TERMINAL_ENV_VARS = (
"ZELLIJ_PANE_ID",
"TMUX_PANE",
"KITTY_WINDOW_ID",
"WEZTERM_PANE",
"TERM_SESSION_ID",
"WT_SESSION",
)
# Breadcrumbs older than this are pruned opportunistically on each write —
# a pane id from a tmux server restarted last month means nothing today.
_STALE_AFTER_SECONDS = 30 * 24 * 60 * 60
_SANITIZE_RE = re.compile(r"[^A-Za-z0-9._-]")
def _breadcrumbs_dir() -> Path:
from hermes_constants import get_hermes_home
return get_hermes_home() / "terminal-sessions"
def _sanitize(raw: str) -> str:
"""Make an id safe to use as a filename (``/dev/pts/3`` -> ``dev-pts-3``)."""
return _SANITIZE_RE.sub("-", raw.strip().strip("/"))[:120]
def get_terminal_id() -> Optional[str]:
"""Derive a stable identity for the terminal this process runs in.
Prefers the real tty device path (stdin, then stdout), else the first
present multiplexer/emulator env var. Returns ``None`` when neither is
available — callers must then skip breadcrumbs entirely.
"""
for fd in (sys.stdin, sys.stdout):
try:
name = os.ttyname(fd.fileno())
except Exception:
continue
if name:
return f"tty-{_sanitize(name)}"
for var in _TERMINAL_ENV_VARS:
val = os.environ.get(var)
if val:
return f"{var.lower()}-{_sanitize(val)}"
return None
def is_enabled() -> bool:
"""Config gate: ``session.terminal_continue`` (default true)."""
try:
from hermes_cli.config import load_config
return bool((load_config().get("session") or {}).get("terminal_continue", True))
except Exception:
return True
def _prune_stale(directory: Path, now: float) -> None:
"""Best-effort removal of breadcrumbs older than the staleness window."""
try:
for entry in directory.iterdir():
try:
if entry.is_file() and now - entry.stat().st_mtime > _STALE_AFTER_SECONDS:
entry.unlink()
except OSError:
continue
except OSError:
pass
def write_breadcrumb(session_id: str, cwd: Optional[str] = None) -> None:
"""Record that this terminal's live session is ``session_id``.
Synchronous, best-effort, never raises. No-op when the feature is
disabled, the session id is empty, or no terminal identity exists.
"""
try:
if not session_id or not is_enabled():
return
terminal_id = get_terminal_id()
if not terminal_id:
return
directory = _breadcrumbs_dir()
directory.mkdir(parents=True, exist_ok=True)
now = time.time()
payload = {
"session_id": session_id,
"cwd": cwd or os.getcwd(),
"ts": now,
}
tmp = directory / f".{terminal_id}.tmp"
tmp.write_text(json.dumps(payload), encoding="utf-8")
os.replace(tmp, directory / terminal_id)
_prune_stale(directory, now)
except Exception:
pass
def read_breadcrumb() -> Optional[dict]:
"""Return this terminal's breadcrumb payload, or ``None``.
Ignores breadcrumbs older than the staleness window. Never raises.
"""
try:
terminal_id = get_terminal_id()
if not terminal_id:
return None
path = _breadcrumbs_dir() / terminal_id
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict) or not str(data.get("session_id") or "").strip():
return None
ts = data.get("ts")
if isinstance(ts, (int, float)) and time.time() - ts > _STALE_AFTER_SECONDS:
return None
return data
except Exception:
return None
def resolve_breadcrumb_session() -> Optional[str]:
"""Resolve a bare ``-c`` for this terminal, or ``None`` to fall back.
Returns the breadcrumb's session id only when it still exists in the
session DB, projected forward through the compression chain so the
resume lands on the live tip rather than a dead compressed parent
(same projection as ``main._resolve_session_by_name_or_id``).
"""
if not is_enabled():
return None
crumb = read_breadcrumb()
if not crumb:
return None
session_id = str(crumb.get("session_id") or "").strip()
if not session_id:
return None
db = None
try:
from hermes_state import SessionDB
db = SessionDB()
if not db.get_session(session_id):
return None # session was deleted — fall back to latest
try:
session_id = db.get_compression_tip(session_id) or session_id
except Exception:
pass
return session_id
except Exception:
return None
finally:
if db is not None:
try:
db.close()
except Exception:
pass
+3
View File
@@ -1204,6 +1204,9 @@ _CATEGORY_MERGE: Dict[str, str] = {
# field — fold it into the agent tab rather than spawning a one-field
# orphan category.
"runtime": "agent",
# `session.terminal_continue` is the only schema-surfaced session field —
# fold it into general rather than spawning a one-field orphan category.
"session": "general",
}
# Display order for tabs — unlisted categories sort alphabetically after these.
+89
View File
@@ -3021,6 +3021,48 @@ def count_db_holders(db_path: Path) -> Optional[int]:
return None
# Lifecycle statuses surfaced by session pickers. Classification looks ONLY at
# a session's final message row — role, whether it carries tool_calls, and its
# finish_reason — so it stays O(1) per session (see
# SessionDB.session_lifecycle_statuses).
SESSION_STATUS_COMPLETE = "complete"
SESSION_STATUS_INTERRUPTED = "interrupted"
SESSION_STATUS_ERROR = "error"
SESSION_STATUS_EMPTY = "empty"
# finish_reason values that mark the turn as having ended in a provider or
# agent error (vs. a normal 'stop'/'length'/'tool_calls' completion).
_ERROR_FINISH_REASONS = frozenset({"error", "agent_error", "content_filter"})
def classify_session_status(
role: Optional[str],
has_tool_calls: bool,
finish_reason: Optional[str],
) -> str:
"""Classify a session's lifecycle from the shape of its final message.
- assistant with a normal finish → ``complete``
- assistant that still has pending tool_calls (no tool result row ever
followed, or it would be the last row instead) → ``interrupted``
- user or tool as the last row → ``interrupted`` (the agent never got to
answer / never consumed the tool result)
- an error finish_reason on the last row → ``error``
- anything unrecognized → ``complete`` (benign default; pickers must not
alarm on unknown shapes)
"""
if (finish_reason or "").strip().lower() in _ERROR_FINISH_REASONS:
return SESSION_STATUS_ERROR
r = (role or "").strip().lower()
if r == "assistant":
# The last row being an assistant message WITH tool_calls means the
# matching tool result never landed — an interrupted tool turn.
return SESSION_STATUS_INTERRUPTED if has_tool_calls else SESSION_STATUS_COMPLETE
if r in {"user", "tool"}:
return SESSION_STATUS_INTERRUPTED
return SESSION_STATUS_COMPLETE
class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin):
"""
SQLite-backed session storage with FTS5 search.
@@ -8773,6 +8815,53 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return sessions
def session_lifecycle_statuses(
self, session_ids: List[str]
) -> Dict[str, str]:
"""Classify each session's lifecycle state from its LAST message row.
Returns ``{session_id: status}`` where status is one of:
- ``'complete'`` — last message is a normal assistant reply
- ``'interrupted'`` — last message is a user turn, a pending assistant
tool call (no tool result followed), or a tool result the assistant
never responded to
- ``'error'`` — last message carries an error finish_reason
- ``'empty'`` — session has no messages
Cost-bounded by design: one query that resolves each listed session's
newest message id via ``MAX(id)`` (an index seek on
``idx_messages_session_id``) and joins back for that single row's
role/tool_calls/finish_reason. Never scans transcripts, so it stays
cheap on large databases regardless of total message volume.
"""
ids = [sid for sid in (session_ids or []) if sid]
if not ids:
return {}
statuses: Dict[str, str] = {sid: "empty" for sid in ids}
placeholders = ",".join("?" for _ in ids)
query = f"""
SELECT m.session_id, m.role,
m.tool_calls IS NOT NULL AS has_tool_calls,
m.finish_reason
FROM messages m
JOIN (
SELECT session_id, MAX(id) AS max_id
FROM messages
WHERE session_id IN ({placeholders})
GROUP BY session_id
) latest ON m.id = latest.max_id
"""
with self._read_ctx() as conn:
rows = conn.execute(query, ids).fetchall()
for row in rows:
statuses[row["session_id"]] = classify_session_status(
role=row["role"],
has_tool_calls=bool(row["has_tool_calls"]),
finish_reason=row["finish_reason"],
)
return statuses
# =========================================================================
# Message storage
# =========================================================================
+261
View File
@@ -0,0 +1,261 @@
"""Tests for hermes_cli.foreign_sessions — Claude Code / Codex CLI import.
Fixture JSONL is synthesized inline (tmp_path); the SessionDB is opened
against a temp path so nothing touches the real HERMES_HOME store.
"""
import json
import pytest
from hermes_cli.foreign_sessions import (
gather_foreign_sessions,
import_foreign_session,
list_claude_sessions,
list_codex_sessions,
parse_claude_session,
parse_codex_session,
)
# ── fixture builders ─────────────────────────────────────────────────────
def _claude_lines():
def msg(role, content):
return {
"type": role,
"sessionId": "abc-123",
"cwd": "/home/user/proj",
"message": {"role": role, "content": content},
}
return [
{"type": "summary", "summary": "Fix the flaky test"},
msg("user", "Please fix the flaky test in CI."),
msg(
"assistant",
[
{"type": "text", "text": "Looking into it now."},
{"type": "tool_use", "name": "Bash", "id": "t1", "input": {}},
],
),
# tool_result echoed back as a user message — must NOT become a turn
msg("user", [{"type": "tool_result", "tool_use_id": "t1", "content": "ok"}]),
msg("assistant", [{"type": "text", "text": "Fixed — the sleep was too short."}]),
msg("user", "Great, thanks!"),
msg("assistant", [{"type": "text", "text": "Anytime."}]),
]
def _write_claude_fixture(tmp_path, extra_lines=None):
proj = tmp_path / ".claude" / "projects" / "-home-user-proj"
proj.mkdir(parents=True)
f = proj / "abc-123.jsonl"
lines = [json.dumps(entry) for entry in _claude_lines()]
if extra_lines:
lines = extra_lines + lines
f.write_text("\n".join(lines) + "\n", encoding="utf-8")
return f
def _codex_lines():
def item(payload):
return {"timestamp": "2026-08-15T21:35:28Z", "type": "response_item", "payload": payload}
def message(role, kind, text):
return item({"type": "message", "role": role, "content": [{"type": kind, "text": text}]})
return [
{
"type": "session_meta",
"payload": {"session_id": "0000-1111", "cwd": "/home/user/repo"},
},
# developer/system payloads must never be imported
message("developer", "input_text", "<skills_instructions>secret system stuff"),
message("user", "input_text", "<recommended_plugins>\ninjected wrapper"),
message("user", "input_text", "Summarize the transcripts please."),
message("assistant", "output_text", "Reading them one at a time."),
item({"type": "custom_tool_call", "name": "shell", "call_id": "c1"}),
item({"type": "custom_tool_call_output", "call_id": "c1", "output": "big output"}),
message("assistant", "output_text", "Done — here is the summary."),
message("user", "input_text", "Now write it to a file."),
message("assistant", "output_text", "Written to summary.md."),
]
def _write_codex_fixture(tmp_path, extra_lines=None):
day = tmp_path / ".codex" / "sessions" / "2026" / "08" / "15"
day.mkdir(parents=True)
f = day / "rollout-2026-08-15T21-35-28-0000-1111.jsonl"
lines = [json.dumps(entry) for entry in _codex_lines()]
if extra_lines:
lines = extra_lines + lines
f.write_text("\n".join(lines) + "\n", encoding="utf-8")
return f
@pytest.fixture
def session_db(tmp_path):
from hermes_state import SessionDB
db = SessionDB(db_path=tmp_path / "state.db")
yield db
db.close()
def _assert_alternating(messages):
roles = [m["role"] for m in messages]
assert roles, "no messages"
assert roles[0] == "user"
for a, b in zip(roles, roles[1:]):
assert a != b, f"two consecutive {a} messages"
# ── parsing ──────────────────────────────────────────────────────────────
def test_parse_claude_session(tmp_path):
f = _write_claude_fixture(tmp_path)
parsed = parse_claude_session(f)
turns = parsed["turns"]
_assert_alternating(turns)
assert len(turns) == 4 # tool_result-only user line skipped; assistants merge
assert parsed["cwd"] == "/home/user/proj"
assert parsed["title_guess"] == "Fix the flaky test"
assert parsed["session_id"] == "abc-123"
# tool_use flattened to a bracketed summary, merged with adjacent text
joined_assistant = "\n".join(t["content"] for t in turns if t["role"] == "assistant")
assert "[ran tool: Bash]" in joined_assistant
# no fabricated tool_call structures
assert all(set(t) == {"role", "content"} for t in turns)
def test_parse_codex_session(tmp_path):
f = _write_codex_fixture(tmp_path)
parsed = parse_codex_session(f)
turns = parsed["turns"]
_assert_alternating(turns)
assert len(turns) == 4
assert parsed["cwd"] == "/home/user/repo"
assert parsed["session_id"] == "0000-1111"
assert parsed["title_guess"].startswith("Summarize the transcripts")
# developer + wrapper user lines excluded
all_text = "\n".join(t["content"] for t in turns)
assert "skills_instructions" not in all_text
assert "recommended_plugins" not in all_text
# tool call summarized in assistant text
assert "[ran tool: shell]" in all_text
def test_malformed_lines_are_skipped(tmp_path):
garbage = [
"this is not json at all {{{",
'"just a string"',
json.dumps({"type": "user", "message": "not-a-dict-payload... wait, string"}),
json.dumps({"type": "user"}), # missing message
"",
]
f = _write_claude_fixture(tmp_path, extra_lines=garbage)
parsed = parse_claude_session(f)
assert len(parsed["turns"]) == 4 # good lines still parse
g = _write_codex_fixture(tmp_path, extra_lines=["not json", json.dumps({"type": "response_item"})])
parsed_codex = parse_codex_session(g)
assert len(parsed_codex["turns"]) == 4
# ── discovery ────────────────────────────────────────────────────────────
def test_list_sessions(tmp_path):
_write_claude_fixture(tmp_path)
_write_codex_fixture(tmp_path)
claude = list_claude_sessions(tmp_path / ".claude" / "projects")
codex = list_codex_sessions(tmp_path / ".codex" / "sessions")
assert len(claude) == 1 and claude[0].source == "claude"
assert claude[0].turn_count == 4
assert len(codex) == 1 and codex[0].source == "codex"
assert codex[0].turn_count == 4
both = gather_foreign_sessions(
claude_root=tmp_path / ".claude" / "projects",
codex_root=tmp_path / ".codex" / "sessions",
)
assert len(both) == 2
assert both[0].mtime >= both[1].mtime # newest first
def test_list_sessions_missing_roots(tmp_path):
assert list_claude_sessions(tmp_path / "nope") == []
assert list_codex_sessions(tmp_path / "nope") == []
# ── import into SessionDB ────────────────────────────────────────────────
def test_import_claude_session(tmp_path, session_db):
f = _write_claude_fixture(tmp_path)
session_id = import_foreign_session("claude", f, db=session_db)
row = session_db.get_session(session_id)
assert row is not None
assert row["source"] == "claude-code"
assert row["cwd"] == "/home/user/proj"
assert row["message_count"] == 4
title = session_db.get_session_title(session_id)
assert title.startswith("Imported from Claude Code: ")
assert "Please fix the flaky test" in title
messages = session_db.get_messages(session_id)
assert len(messages) == 4
_assert_alternating(messages)
origin = json.loads(row["origin_json"])
assert origin["imported_from"]["tool"] == "claude-code"
assert origin["imported_from"]["path"] == str(f)
def test_import_codex_session(tmp_path, session_db):
f = _write_codex_fixture(tmp_path)
session_id = import_foreign_session("@codex", f, db=session_db)
row = session_db.get_session(session_id)
assert row is not None
assert row["source"] == "codex-cli"
assert row["message_count"] == 4
title = session_db.get_session_title(session_id)
assert title.startswith("Imported from Codex CLI: ")
messages = session_db.get_messages(session_id)
_assert_alternating(messages)
# resumable: resolve_session_id round-trips
assert session_db.resolve_session_id(session_id) == session_id
def test_import_rejects_bad_input(tmp_path, session_db):
with pytest.raises(ValueError, match="Unknown foreign session source"):
import_foreign_session("gemini", tmp_path / "x.jsonl", db=session_db)
with pytest.raises(ValueError, match="not found"):
import_foreign_session("claude", tmp_path / "missing.jsonl", db=session_db)
empty = tmp_path / "empty.jsonl"
empty.write_text("not json\n", encoding="utf-8")
with pytest.raises(ValueError, match="No user/assistant conversation"):
import_foreign_session("claude", empty, db=session_db)
def test_leading_assistant_gets_single_stub(tmp_path):
day = tmp_path / ".codex" / "sessions" / "2026" / "01" / "01"
day.mkdir(parents=True)
f = day / "rollout-x.jsonl"
lines = [
json.dumps(
{
"type": "response_item",
"payload": {
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Continuing from before."}],
},
}
)
]
f.write_text("\n".join(lines) + "\n", encoding="utf-8")
parsed = parse_codex_session(f)
_assert_alternating(parsed["turns"])
assert len(parsed["turns"]) == 2
assert parsed["turns"][0]["role"] == "user"
@@ -0,0 +1,204 @@
"""Tests for hermes_cli/terminal_breadcrumbs.py — per-terminal ``hermes -c``.
Covers terminal id derivation (tty vs env vars vs none), breadcrumb
write/read roundtrip under a temp HERMES_HOME, stale-session fallback
(breadcrumb pointing at a deleted session), compression-tip projection,
and the session.terminal_continue config gate.
"""
import json
import os
import time
from pathlib import Path
import pytest
from hermes_cli import terminal_breadcrumbs as tb
TERMINAL_ENV_VARS = (
"ZELLIJ_PANE_ID",
"TMUX_PANE",
"KITTY_WINDOW_ID",
"WEZTERM_PANE",
"TERM_SESSION_ID",
"WT_SESSION",
)
@pytest.fixture
def hermes_home(tmp_path, monkeypatch):
home = tmp_path / ".hermes"
home.mkdir()
monkeypatch.setenv("HERMES_HOME", str(home))
return home
@pytest.fixture
def no_terminal_env(monkeypatch):
"""Strip every terminal-identity env var so tests control identity."""
for var in TERMINAL_ENV_VARS:
monkeypatch.delenv(var, raising=False)
def _fake_no_tty(monkeypatch):
monkeypatch.setattr(tb.os, "ttyname", lambda fd: (_ for _ in ()).throw(OSError()))
def _fake_tty(monkeypatch, name="/dev/pts/7"):
monkeypatch.setattr(tb.os, "ttyname", lambda fd: name)
# ---------------------------------------------------------------- identity
def test_terminal_id_prefers_tty(monkeypatch, no_terminal_env):
_fake_tty(monkeypatch, "/dev/pts/7")
monkeypatch.setenv("TMUX_PANE", "%3")
assert tb.get_terminal_id() == "tty-dev-pts-7"
def test_terminal_id_env_var_order(monkeypatch, no_terminal_env):
_fake_no_tty(monkeypatch)
monkeypatch.setenv("KITTY_WINDOW_ID", "12")
monkeypatch.setenv("WT_SESSION", "abc-123")
# KITTY_WINDOW_ID comes before WT_SESSION in the preference order
assert tb.get_terminal_id() == "kitty_window_id-12"
def test_terminal_id_sanitizes_env_value(monkeypatch, no_terminal_env):
_fake_no_tty(monkeypatch)
monkeypatch.setenv("TMUX_PANE", "%41")
tid = tb.get_terminal_id()
assert tid is not None
assert "/" not in tid and "%" not in tid
def test_terminal_id_none_when_no_identity(monkeypatch, no_terminal_env):
_fake_no_tty(monkeypatch)
assert tb.get_terminal_id() is None
# ---------------------------------------------------------- write / read
def test_breadcrumb_roundtrip(hermes_home, monkeypatch, no_terminal_env):
_fake_tty(monkeypatch)
tb.write_breadcrumb("20260815_120000_abc123", cwd="/tmp/project")
crumb = tb.read_breadcrumb()
assert crumb is not None
assert crumb["session_id"] == "20260815_120000_abc123"
assert crumb["cwd"] == "/tmp/project"
assert isinstance(crumb["ts"], float)
files = list((hermes_home / "terminal-sessions").iterdir())
assert [f.name for f in files] == ["tty-dev-pts-7"]
def test_write_skipped_without_terminal_identity(hermes_home, monkeypatch, no_terminal_env):
_fake_no_tty(monkeypatch)
tb.write_breadcrumb("20260815_120000_abc123")
assert not (hermes_home / "terminal-sessions").exists()
assert tb.read_breadcrumb() is None
def test_two_terminals_do_not_clobber(hermes_home, monkeypatch, no_terminal_env):
_fake_tty(monkeypatch, "/dev/pts/1")
tb.write_breadcrumb("session-one")
_fake_tty(monkeypatch, "/dev/pts/2")
tb.write_breadcrumb("session-two")
assert tb.read_breadcrumb()["session_id"] == "session-two"
_fake_tty(monkeypatch, "/dev/pts/1")
assert tb.read_breadcrumb()["session_id"] == "session-one"
def test_stale_breadcrumb_ignored_and_pruned(hermes_home, monkeypatch, no_terminal_env):
_fake_tty(monkeypatch, "/dev/pts/1")
directory = hermes_home / "terminal-sessions"
directory.mkdir(parents=True)
stale = directory / "tty-dev-pts-1"
stale.write_text(
json.dumps({"session_id": "old", "cwd": "/", "ts": time.time() - 40 * 86400})
)
old_mtime = time.time() - 40 * 86400
os.utime(stale, (old_mtime, old_mtime))
# read: stale payload rejected
assert tb.read_breadcrumb() is None
# write from another terminal prunes the stale file
_fake_tty(monkeypatch, "/dev/pts/2")
tb.write_breadcrumb("fresh")
assert not stale.exists()
def test_corrupt_breadcrumb_returns_none(hermes_home, monkeypatch, no_terminal_env):
_fake_tty(monkeypatch, "/dev/pts/1")
directory = hermes_home / "terminal-sessions"
directory.mkdir(parents=True)
(directory / "tty-dev-pts-1").write_text("not json{")
assert tb.read_breadcrumb() is None
# ------------------------------------------------------------- resolution
def _make_session(home: Path, session_id: str):
from hermes_state import SessionDB
db = SessionDB()
db.create_session(session_id, "cli")
db.close()
def test_resolve_picks_this_terminals_session(hermes_home, monkeypatch, no_terminal_env):
_fake_tty(monkeypatch, "/dev/pts/5")
_make_session(hermes_home, "20260815_100000_aaaaaa")
_make_session(hermes_home, "20260815_110000_bbbbbb") # newer, other terminal
tb.write_breadcrumb("20260815_100000_aaaaaa")
assert tb.resolve_breadcrumb_session() == "20260815_100000_aaaaaa"
def test_resolve_falls_back_when_session_deleted(hermes_home, monkeypatch, no_terminal_env):
_fake_tty(monkeypatch, "/dev/pts/5")
_make_session(hermes_home, "20260815_110000_bbbbbb")
tb.write_breadcrumb("20260815_100000_deleted") # never existed / deleted
assert tb.resolve_breadcrumb_session() is None
def test_resolve_projects_through_compression_chain(hermes_home, monkeypatch, no_terminal_env):
_fake_tty(monkeypatch, "/dev/pts/5")
_make_session(hermes_home, "20260815_100000_parent")
tb.write_breadcrumb("20260815_100000_parent")
from hermes_state import SessionDB
monkeypatch.setattr(
SessionDB,
"get_compression_tip",
lambda self, sid: "20260815_110000_child",
)
assert tb.resolve_breadcrumb_session() == "20260815_110000_child"
# ------------------------------------------------------------ config gate
def test_config_gate_off_disables_writes_and_resolution(
hermes_home, monkeypatch, no_terminal_env
):
_fake_tty(monkeypatch, "/dev/pts/9")
import hermes_cli.config as config_mod
monkeypatch.setattr(
config_mod, "load_config", lambda: {"session": {"terminal_continue": False}}
)
tb.write_breadcrumb("20260815_120000_abc123")
assert not (hermes_home / "terminal-sessions").exists()
# Even with a pre-existing breadcrumb, resolution must decline
monkeypatch.setattr(config_mod, "load_config", lambda: {})
tb.write_breadcrumb("20260815_120000_abc123")
monkeypatch.setattr(
config_mod, "load_config", lambda: {"session": {"terminal_continue": False}}
)
assert tb.resolve_breadcrumb_session() is None
def test_config_gate_default_is_enabled(monkeypatch):
import hermes_cli.config as config_mod
monkeypatch.setattr(config_mod, "load_config", lambda: {})
assert tb.is_enabled() is True
@@ -0,0 +1,188 @@
"""Lifecycle status classification for session pickers.
Covers ``classify_session_status`` (pure last-message shape → status) and
``SessionDB.session_lifecycle_statuses`` (batched last-message lookup), plus
the delete wiring the picker's 'd' key relies on.
"""
import pytest
from hermes_state import (
SESSION_STATUS_COMPLETE,
SESSION_STATUS_EMPTY,
SESSION_STATUS_ERROR,
SESSION_STATUS_INTERRUPTED,
SessionDB,
classify_session_status,
)
@pytest.fixture
def db(tmp_path):
database = SessionDB(tmp_path / "state.db")
try:
yield database
finally:
database.close()
# ---------------------------------------------------------------------------
# Pure classifier
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"role,has_tool_calls,finish_reason,expected",
[
("assistant", False, "stop", SESSION_STATUS_COMPLETE),
("assistant", False, None, SESSION_STATUS_COMPLETE),
("assistant", False, "length", SESSION_STATUS_COMPLETE),
("assistant", True, "tool_calls", SESSION_STATUS_INTERRUPTED),
("user", False, None, SESSION_STATUS_INTERRUPTED),
("tool", False, None, SESSION_STATUS_INTERRUPTED),
("assistant", False, "error", SESSION_STATUS_ERROR),
("assistant", True, "error", SESSION_STATUS_ERROR),
("user", False, "agent_error", SESSION_STATUS_ERROR),
("system", False, None, SESSION_STATUS_COMPLETE),
(None, False, None, SESSION_STATUS_COMPLETE),
],
)
def test_classify_session_status(role, has_tool_calls, finish_reason, expected):
assert classify_session_status(role, has_tool_calls, finish_reason) == expected
# ---------------------------------------------------------------------------
# DB-backed batch classification
# ---------------------------------------------------------------------------
def test_session_lifecycle_statuses_shapes(db):
# complete: normal user → assistant exchange
db.create_session("s_complete", source="cli")
db.append_message("s_complete", "user", "hi")
db.append_message("s_complete", "assistant", "hello", finish_reason="stop")
# interrupted: user asked, no reply landed
db.create_session("s_user_tail", source="cli")
db.append_message("s_user_tail", "user", "are you there?")
# interrupted: assistant fired tool calls, no tool result followed
db.create_session("s_pending_tool", source="cli")
db.append_message("s_pending_tool", "user", "run it")
db.append_message(
"s_pending_tool",
"assistant",
None,
tool_calls=[{"id": "c1", "function": {"name": "terminal", "arguments": "{}"}}],
finish_reason="tool_calls",
)
# complete: full tool round-trip then final assistant reply
db.create_session("s_tool_roundtrip", source="cli")
db.append_message("s_tool_roundtrip", "user", "run it")
db.append_message(
"s_tool_roundtrip",
"assistant",
None,
tool_calls=[{"id": "c1", "function": {"name": "terminal", "arguments": "{}"}}],
finish_reason="tool_calls",
)
db.append_message("s_tool_roundtrip", "tool", "ok", tool_call_id="c1")
db.append_message("s_tool_roundtrip", "assistant", "done", finish_reason="stop")
# interrupted: tool result present but assistant never consumed it
db.create_session("s_tool_tail", source="cli")
db.append_message("s_tool_tail", "user", "run it")
db.append_message(
"s_tool_tail",
"assistant",
None,
tool_calls=[{"id": "c2", "function": {"name": "terminal", "arguments": "{}"}}],
finish_reason="tool_calls",
)
db.append_message("s_tool_tail", "tool", "ok", tool_call_id="c2")
# error: last message carries an error finish_reason
db.create_session("s_error", source="cli")
db.append_message("s_error", "user", "hi")
db.append_message("s_error", "assistant", "boom", finish_reason="error")
# empty: session row exists, zero messages
db.create_session("s_empty", source="cli")
statuses = db.session_lifecycle_statuses(
[
"s_complete",
"s_user_tail",
"s_pending_tool",
"s_tool_roundtrip",
"s_tool_tail",
"s_error",
"s_empty",
]
)
assert statuses == {
"s_complete": SESSION_STATUS_COMPLETE,
"s_user_tail": SESSION_STATUS_INTERRUPTED,
"s_pending_tool": SESSION_STATUS_INTERRUPTED,
"s_tool_roundtrip": SESSION_STATUS_COMPLETE,
"s_tool_tail": SESSION_STATUS_INTERRUPTED,
"s_error": SESSION_STATUS_ERROR,
"s_empty": SESSION_STATUS_EMPTY,
}
def test_session_lifecycle_statuses_empty_input(db):
assert db.session_lifecycle_statuses([]) == {}
assert db.session_lifecycle_statuses([None, ""]) == {}
def test_session_lifecycle_statuses_unknown_id(db):
# Unknown ids classify as 'empty' (no messages), never raise.
assert db.session_lifecycle_statuses(["nope"]) == {
"nope": SESSION_STATUS_EMPTY
}
# ---------------------------------------------------------------------------
# Picker helpers (status annotation + delete wiring)
# ---------------------------------------------------------------------------
def test_annotate_session_statuses(db):
from hermes_cli.main import _annotate_session_statuses, _session_status_tag
db.create_session("s1", source="cli")
db.append_message("s1", "user", "hi")
db.append_message("s1", "assistant", "hello", finish_reason="stop")
db.create_session("s2", source="cli")
db.append_message("s2", "user", "hi")
rows = [{"id": "s1"}, {"id": "s2"}]
_annotate_session_statuses(rows, db)
assert rows[0]["_status"] == SESSION_STATUS_COMPLETE
assert rows[1]["_status"] == SESSION_STATUS_INTERRUPTED
# No db → rows untouched, tag falls back to '-'
bare = [{"id": "s1"}]
_annotate_session_statuses(bare, None)
assert "_status" not in bare[0]
assert _session_status_tag(bare[0].get("_status")) == "-"
# Tag mapping
assert _session_status_tag(SESSION_STATUS_COMPLETE) == "done"
assert _session_status_tag(SESSION_STATUS_INTERRUPTED) == "intr"
assert _session_status_tag(SESSION_STATUS_ERROR) == "err"
assert _session_status_tag(SESSION_STATUS_EMPTY) == "empty"
def test_delete_session_removes_session_and_messages(db, tmp_path):
db.create_session("doomed", source="cli")
db.append_message("doomed", "user", "hi")
db.append_message("doomed", "assistant", "hello", finish_reason="stop")
assert db.delete_session("doomed", sessions_dir=tmp_path / "sessions") is True
assert db.get_session("doomed") is None
remaining = db._conn.execute(
"SELECT COUNT(*) FROM messages WHERE session_id = ?", ("doomed",)
).fetchone()[0]
assert remaining == 0
# Deleting again reports False (not found)
assert db.delete_session("doomed") is False
+56 -24
View File
@@ -14,6 +14,51 @@ from run_agent import AIAgent
from tools.clarify_gateway import resolve_clarify_timeout
@pytest.fixture(autouse=True)
def _deterministic_worker_start(monkeypatch):
"""Deadline must race the TOOL, not the scheduler or the preamble.
The sequential timeout path computes ``deadline = now + timeout_s``
immediately after ``executor.submit()``. Two races made a sub-second
test deadline flaky on loaded CI workers (three slice-4 reds on
unrelated PRs, Aug 2026):
1. Thread-start latency — the pool thread took longer than the whole
deadline to START; the future was cancelled before the tool ever
dispatched. Killed here by blocking submit() until the worker
callable has begun.
2. Middleware preamble latency — after the worker starts, argument
parsing / hooks / cold imports run BEFORE ``handle_function_call``;
when the deadline expired in that window, the timeout interrupt made
the middleware return without dispatching (``first_started`` unset).
Killed by using a 1.0s deadline: tight enough to keep the suite
fast, ~7x the worst observed preamble.
Together the countdown starts only once the worker is running and has
generous headroom to reach the dispatch — which is the behavior these
tests mean to pin.
"""
import tools.daemon_pool as daemon_pool
real_executor = daemon_pool.DaemonThreadPoolExecutor
class _StartSyncedExecutor(real_executor):
def submit(self, fn, *args, **kwargs):
begun = threading.Event()
def _traced(*fa, **fk):
begun.set()
return fn(*fa, **fk)
future = super().submit(_traced, *args, **kwargs)
# Bounded: a wedged pool must fail the test loudly, not hang it.
assert begun.wait(timeout=10), "tool worker thread never started"
return future
monkeypatch.setattr(daemon_pool, "DaemonThreadPoolExecutor", _StartSyncedExecutor)
yield
def _make_agent(tmp_path: Path) -> AIAgent:
with (
patch(
@@ -93,7 +138,7 @@ def test_sequential_tool_timeout_emits_result_and_continues(tmp_path, monkeypatc
calls = [_tool_call("hung"), _tool_call("next")]
assistant = SimpleNamespace(tool_calls=calls)
messages: list[dict] = []
monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "0.05")
monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "1.0")
started = time.monotonic()
try:
@@ -105,29 +150,14 @@ def test_sequential_tool_timeout_emits_result_and_continues(tmp_path, monkeypatc
),
):
execute_tool_calls_sequential(agent, assistant, messages, "task")
elapsed = time.monotonic() - started
release_first.set()
# Give a late-scheduled worker a moment to drain inside the patch
# context (if the with block exits first, a late worker would hit
# the REAL handle_function_call).
for _ in range(100):
if "next" in dispatched:
break
time.sleep(0.05)
finally:
release_first.set()
assert elapsed < 1.0 # the EXECUTOR must not have waited for the hung call
# The hung call's dispatch is NOT guaranteed: on a loaded runner the
# 0.05s timeout can expire before its worker thread starts, in which case
# future.cancel() legitimately prevents the dispatch entirely
# (tool_executor timeout path). The contract is: the executor emitted a
# timeout result for it and CONTINUED — the next tool must have actually
# run, and the message stream must carry both call ids in order.
assert "next" in dispatched
assert set(dispatched) <= {"hung", "next"}
assert first_started.is_set()
assert time.monotonic() - started < 10.0
assert dispatched == ["hung", "next"]
assert [message["tool_call_id"] for message in messages] == ["hung", "next"]
assert "timed out after 0.1s" in messages[0]["content"]
assert "timed out after 1.0s" in messages[0]["content"]
assert messages[0]["effect_disposition"] == "unknown"
assert messages[1]["content"] == "second result"
timeout_events = [event for event in terminal_events if event.get("error_type") == "tool_timeout"]
@@ -157,7 +187,7 @@ def test_sequential_tool_timeout_suppresses_late_terminal_event(tmp_path, monkey
calls = [_tool_call("hung"), _tool_call("next")]
messages: list[dict] = []
monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "0.05")
monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "1.0")
try:
with (
@@ -199,14 +229,16 @@ def test_sequential_timeout_does_not_cut_clarify_human_wait(
outlast ``HERMES_CONCURRENT_TOOL_TIMEOUT_S`` (default 420s).
"""
agent = _make_agent(tmp_path)
monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "0.05")
monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "1.0")
monkeypatch.setattr(
"tools.clarify_gateway.get_clarify_timeout",
lambda: clarify_timeout,
)
def _callback(question, choices, multi_select=False):
time.sleep(0.15)
# Must OUTLAST the 1.0s sequential deadline — the test proves the
# generic timeout never cuts a human clarify wait.
time.sleep(1.3)
return "A"
agent.clarify_callback = _callback
@@ -234,7 +266,7 @@ def test_sequential_timeout_does_not_cut_clarify_human_wait(
"task",
)
assert time.monotonic() - started < 1.0
assert time.monotonic() - started < 10.0
assert [message["tool_call_id"] for message in messages] == ["clarify-1", "next"]
payload = json.loads(messages[0]["content"])
assert payload["user_response"] == "A"
@@ -0,0 +1,60 @@
"""macOS ScreenCaptureKit display_count=0 diagnosability.
Composed from PR #52949 (sujeet111, doctor guard) and PR #67259
(webtecnica, actionable-hint direction): a headless Mac or asleep panel
leaves SCK with zero shareable displays while TCC grants pass, so
health_report says ok and every capture returns 0x0 silently. The guard
turns that into a failed check + degraded overall + recovery hint.
"""
from tools.computer_use.doctor import _apply_display_count_guard
def _report(status="pass", count=0, overall="ok", name="screen_capture_capability"):
return {
"overall": overall,
"checks": [
{
"name": name,
"status": status,
"message": "ScreenCaptureKit reachable",
"data": {"display_count": count},
}
],
}
def test_zero_displays_downgrades_ok_to_degraded():
out = _apply_display_count_guard(_report(count=0))
assert out["overall"] == "degraded"
assert out["checks"][0]["status"] == "fail"
assert "0 shareable" in out["checks"][0]["message"]
assert "dongle" in out["checks"][0]["hint"]
def test_positive_display_count_untouched():
out = _apply_display_count_guard(_report(count=1))
assert out["overall"] == "ok"
assert out["checks"][0]["status"] == "pass"
def test_already_failed_check_not_rewritten():
out = _apply_display_count_guard(_report(status="fail", count=0, overall="degraded"))
# Guard only flips pass->fail; an existing failure keeps its message.
assert out["checks"][0]["message"] == "ScreenCaptureKit reachable"
def test_missing_data_and_other_checks_ignored():
out = _apply_display_count_guard(
{"overall": "ok", "checks": [{"name": "binary_version", "status": "pass"}]}
)
assert out["overall"] == "ok"
out2 = _apply_display_count_guard({"overall": "ok", "checks": "bogus"})
assert out2["overall"] == "ok"
def test_overall_failed_not_upgraded():
out = _apply_display_count_guard(_report(count=0, overall="failed"))
# fail-worse states are never softened to degraded.
assert out["overall"] == "failed"
assert out["checks"][0]["status"] == "fail"
@@ -0,0 +1,121 @@
"""Diagnosability of empty window discovery + CLI-fallback fail-fast.
Live-QA findings (Aug 2026, locked KDE desktop):
1. capture() returned a bare ``capture mode=ax 0x0`` with zero hint while
the desktop was locked — undiagnosable for the model AND the user.
2. `_call_tool_via_cli` retried 4x with ~3.5s of sleeps on "daemon is not
running", a permanent condition for that invocation.
"""
from typing import Any, Dict
import pytest
from tools.computer_use import cua_backend as cb
# ── _empty_discovery_reason ─────────────────────────────────────────────
def test_locked_session_reason_names_the_lock(monkeypatch):
monkeypatch.setattr(cb, "_linux_session_locked", lambda: True)
reason = cb._empty_discovery_reason()
assert "LOCKED" in reason
assert "unlock" in reason.lower()
def test_no_display_reason(monkeypatch):
monkeypatch.setattr(cb, "_linux_session_locked", lambda: False)
monkeypatch.setattr(cb.sys, "platform", "linux")
monkeypatch.delenv("DISPLAY", raising=False)
reason = cb._empty_discovery_reason()
assert "DISPLAY" in reason
def test_unknown_reason_points_at_doctor(monkeypatch):
monkeypatch.setattr(cb, "_linux_session_locked", lambda: None)
monkeypatch.setenv("DISPLAY", ":0")
reason = cb._empty_discovery_reason()
assert "doctor" in reason
def test_locked_probe_fails_safe(monkeypatch):
def _boom(*a, **kw):
raise OSError("no loginctl")
monkeypatch.setattr(cb.subprocess, "run", _boom)
assert cb._linux_session_locked() in (None, False) if cb.sys.platform != "linux" else cb._linux_session_locked() is None
def test_empty_capture_carries_reason(monkeypatch):
"""capture() with zero discovered windows must explain itself."""
backend = object.__new__(cb.CuaDriverBackend)
backend._active_pid = None
backend._active_window_id = None
backend._last_app = None
backend._last_target = None
backend._snapshot_tokens = {}
monkeypatch.setattr(backend, "_load_windows", lambda: [], raising=False)
monkeypatch.setattr(cb, "_empty_discovery_reason",
lambda: "the desktop session is LOCKED (test)")
cap = backend.capture(mode="ax")
assert cap.width == 0 and cap.height == 0
assert "LOCKED" in cap.window_title
# ── CLI fallback fail-fast on dead daemon ───────────────────────────────
class _Proc:
def __init__(self, stdout="", stderr=""):
self.stdout = stdout
self.stderr = stderr
self.returncode = 0
def _make_session():
session = object.__new__(cb._CuaDriverSession)
session._embedded_daemon = None
return session
def test_cli_fallback_fails_fast_on_daemon_not_running(monkeypatch):
session = _make_session()
calls = {"n": 0}
sleeps = []
def _fake_run(cmd, **kw):
calls["n"] += 1
return _Proc(stdout="Cua Driver daemon is not running on /x.sock.\nStart it first with: cua-driver serve")
monkeypatch.setattr(cb, "resolve_cua_driver_cmd", lambda override=None: "cua-driver")
import subprocess as _sp
import time as _time
monkeypatch.setattr(_sp, "run", _fake_run)
monkeypatch.setattr(_time, "sleep", lambda s: sleeps.append(s))
with pytest.raises(RuntimeError, match="daemon is not running"):
session._call_tool_via_cli("list_windows", {}, 10.0)
assert calls["n"] == 1, f"expected fail-fast, got {calls['n']} attempts"
assert sleeps == [], f"expected no backoff sleeps, got {sleeps}"
def test_cli_fallback_still_retries_transient_empty(monkeypatch):
"""Genuinely empty output (EAGAIN congestion) keeps the retry loop."""
session = _make_session()
calls = {"n": 0}
def _fake_run(cmd, **kw):
calls["n"] += 1
if calls["n"] < 3:
return _Proc(stdout="")
return _Proc(stdout='{"windows": []}')
monkeypatch.setattr(cb, "resolve_cua_driver_cmd", lambda override=None: "cua-driver")
import subprocess as _sp
import time as _time
monkeypatch.setattr(_sp, "run", _fake_run)
monkeypatch.setattr(_time, "sleep", lambda s: None)
out = session._call_tool_via_cli("list_windows", {}, 10.0)
assert calls["n"] == 3
assert out.get("structuredContent") == {"windows": []}
@@ -0,0 +1,107 @@
"""A zero-filled ``pid``/``window_id`` must not be read as exact targeting.
Several providers emit every declared schema property on every tool call,
filling unused optional integers with ``0``. ``capture()`` entered its
exact-target branch for any non-``None`` id, so those calls dropped the
caller's ``app=``, coerced both ids to ``None`` via ``_positive_int``, and
failed with a message pointing at pid/window_id rather than the real problem.
For that class of model ``capture(app=...)`` never worked at all.
"""
from __future__ import annotations
import sys
from pathlib import Path
from typing import Any, Dict, List
from unittest.mock import MagicMock
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
def _backend_with_windows(windows: List[Dict[str, Any]]):
from tools.computer_use.cua_backend import CuaDriverBackend
backend = CuaDriverBackend()
backend._session = MagicMock()
backend._session.call_tool.return_value = {
"data": "",
"images": [],
"structuredContent": {"windows": windows},
"isError": False,
}
return backend
_WINDOWS = [
{"app_name": "Fuwari", "pid": 100, "window_id": 1,
"is_on_screen": True, "title": "menu bar", "z_index": 0},
{"app_name": "Comet", "pid": 200, "window_id": 2,
"is_on_screen": True, "title": "Comet Browser", "z_index": 1},
]
def test_app_scoped_capture_survives_placeholder_ids():
"""The bug: app= was discarded and the capture failed outright."""
backend = _backend_with_windows(_WINDOWS)
cap = backend.capture(mode="som", app="Comet", pid=0, window_id=0)
assert cap.app == "Comet", (
f"app= was dropped for a zero-filled call; got app={cap.app!r} "
f"detail={cap.window_title!r}"
)
def test_frontmost_capture_survives_placeholder_ids():
"""Frontmost capture is the same failure with no app= to drop."""
backend = _backend_with_windows(_WINDOWS)
cap = backend.capture(mode="som", pid=0, window_id=0)
# Frontmost is the highest z_index window.
assert cap.app == "Comet", f"frontmost capture failed; detail={cap.window_title!r}"
def test_real_exact_target_still_wins_over_app():
"""Guard: a genuine pid/window pair keeps its exact-targeting behaviour."""
backend = _backend_with_windows(_WINDOWS)
# Ids that match no enumerated window: only the exact branch can produce
# this label, so it proves discovery was bypassed rather than consulted.
cap = backend.capture(mode="som", app="Ghost", pid=999, window_id=99)
assert cap.app == "Ghost", f"exact targeting was bypassed; detail={cap.window_title!r}"
def test_partial_target_still_reports_the_missing_half():
"""Guard: one real id and one placeholder is a caller error, not discovery."""
backend = _backend_with_windows(_WINDOWS)
cap = backend.capture(mode="som", app="Comet", pid=200, window_id=0)
assert "requires both pid and window_id" in cap.window_title
def test_malformed_ids_are_not_treated_as_placeholders():
"""Guard: garbage must still reach the validation error, not be ignored."""
backend = _backend_with_windows(_WINDOWS)
cap = backend.capture(mode="som", app="Comet", pid="abc", window_id="def")
assert "positive integer" in cap.window_title
def test_placeholder_predicate():
from tools.computer_use.cua_backend import _is_placeholder_id
assert _is_placeholder_id(0) is True
assert _is_placeholder_id("0") is True
assert _is_placeholder_id(-1) is True
assert _is_placeholder_id(200) is False
assert _is_placeholder_id("200") is False
# Garbage is not a placeholder: it must keep reaching the existing error.
assert _is_placeholder_id("abc") is False
assert _is_placeholder_id(None) is False
assert _is_placeholder_id(1.5) is False
# bools are ints in Python; False must not read as a placeholder id.
assert _is_placeholder_id(False) is False
assert _is_placeholder_id(True) is False
+102 -1
View File
@@ -311,6 +311,67 @@ def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str,
return env
def _linux_session_locked() -> Optional[bool]:
"""Best-effort: is the graphical session locked? (Linux only.)
A locked KDE/GNOME session freezes app renderers and half-disables the
AX tree, so window discovery legitimately returns nothing — but a bare
empty result reads as a driver bug (live QA, Aug 2026: every capture
came back 0x0 with no hint). True/False when loginctl answers, None
when unavailable (non-Linux, no systemd-logind, probe failure).
"""
if sys.platform != "linux":
return None
try:
proc = subprocess.run(
["loginctl", "list-sessions", "--no-legend"],
capture_output=True, text=True, timeout=2.0,
)
if proc.returncode != 0:
return None
any_seat = False
for line in proc.stdout.splitlines():
parts = line.split()
if len(parts) < 2 or "seat" not in line:
continue
any_seat = True
probe = subprocess.run(
["loginctl", "show-session", parts[0], "-p", "LockedHint"],
capture_output=True, text=True, timeout=2.0,
)
if "LockedHint=no" in probe.stdout:
return False
return True if any_seat else None
except Exception:
return None
def _empty_discovery_reason() -> str:
"""One-line diagnosis for 'window discovery found nothing'."""
locked = _linux_session_locked()
if locked is True:
return (
"the desktop session is LOCKED (loginctl LockedHint=yes) — "
"unlock the screen; a locked compositor hides windows and "
"freezes app renderers"
)
if sys.platform == "linux" and not os.environ.get("DISPLAY"):
return "no DISPLAY is set — X11/XWayland is not reachable from this process"
if sys.platform == "darwin":
# Headless Mac / asleep panel: ScreenCaptureKit has 0 shareable
# displays while TCC grants look fine (#67165, #52925 lineage).
return (
"window discovery returned no windows; on macOS this usually "
"means no shareable display (headless Mac or panel asleep) — "
"wake the display or attach a monitor/HDMI dummy, then run "
"`hermes computer-use doctor`"
)
return (
"window discovery returned no windows; run `hermes computer-use "
"doctor` (display reachability, AX capability)"
)
def _z_index_uninformative(windows: List[Dict[str, Any]]) -> bool:
"""True when every window shares the same z_index (common on Linux/X11)."""
if not windows:
@@ -1684,6 +1745,19 @@ class _CuaDriverSession:
out = (proc.stdout or "").strip()
last_err = out[:200] or (proc.stderr or "")[:200]
# "daemon is not running" is a PERMANENT condition for this
# invocation (`cua-driver call` requires the machine-wide
# daemon socket, which Linux installs typically never start —
# Hermes talks to the direct `cua-driver mcp` runtime
# instead). Retrying with backoff burns ~3.5s of sleeps per
# fallback for an outcome that cannot change; fail fast so
# callers surface a diagnosable error immediately.
if "daemon is not running" in out or "daemon is not running" in (proc.stderr or ""):
raise RuntimeError(
f"cua-driver CLI fallback for {name} unavailable: the "
"machine-wide cua-driver daemon is not running (the "
"CLI transport requires it; the MCP runtime does not)."
)
start = min(
(i for i in (out.find("{"), out.find("[")) if i != -1),
default=-1,
@@ -1914,6 +1988,24 @@ def _positive_int(value: Any) -> Optional[int]:
return parsed if parsed > 0 else None
def _is_placeholder_id(value: Any) -> bool:
"""True when *value* is a schema-filler id rather than a real target.
Several providers emit every declared schema property on every tool call,
filling unused optional integers with ``0``. A non-positive id cannot name
a window, so treating it as a targeting request drops the caller's ``app=``
and fails the capture. Malformed non-numeric values are deliberately NOT
placeholders: those still reach the existing validation error rather than
being silently ignored.
"""
if isinstance(value, bool) or not isinstance(value, (int, str)):
return False
try:
return int(value) <= 0
except ValueError:
return False
def _ingest_windows(raw_windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Normalise cua-driver ``list_windows`` entries, dropping unusable ones.
@@ -2349,6 +2441,13 @@ class CuaDriverBackend(ComputerUseBackend):
# PR's effective minimum (trycua/cua#1961 + #1908) is well past
# that, so the fallback is gone — the wrapper now treats the
# structured shape as the only contract.
# Drop schema-filler ids before they can be read as a targeting
# request, so `capture(app=...)` and frontmost capture still work for
# models that emit every optional property zero-filled.
if _is_placeholder_id(pid):
pid = None
if _is_placeholder_id(window_id):
window_id = None
# An exact pid/window pair is both the stable capture_after target and
# the escape hatch when app/window discovery is unavailable on X11.
if pid is not None or window_id is not None:
@@ -2377,7 +2476,9 @@ class CuaDriverBackend(ComputerUseBackend):
self._clear_active_target()
raise
if not windows:
return self._failed_capture(mode)
# Diagnose instead of returning a bare 0x0: the dominant
# real-world cause on Linux is a locked desktop session.
return self._failed_capture(mode, _empty_discovery_reason())
# Filter by app name (case-insensitive substring) if requested.
# When the filter matches nothing, surface that explicitly instead of
+42 -2
View File
@@ -693,13 +693,53 @@ def _drive_health_report_or_fallback(
) -> Dict[str, Any]:
"""Prefer real health_report; on denial/non-schema, synthesize via probes."""
try:
return _drive_health_report(
report = _drive_health_report(
binary, include=include, skip=skip, timeout=timeout,
)
except HealthReportUnavailable as e:
return _compose_fallback_report(
report = _compose_fallback_report(
binary, reason=str(e), timeout=timeout,
)
return _apply_display_count_guard(report)
def _apply_display_count_guard(report: Dict[str, Any]) -> Dict[str, Any]:
"""Downgrade an 'ok' report whose screen capture has zero displays.
macOS ScreenCaptureKit reports ``display_count=0`` on headless Macs and
when the built-in panel is asleep — TCC grants are fine, health_report
can still say pass/ok, but every capture will come back 0x0. Marking
the check failed (with the recovery actions) turns an undiagnosable
silent failure into an actionable one. Applied at the report seam so
the real health_report path and the composed fallback both get it.
Composed from PR #52949 (sujeet111) and PR #67259 (webtecnica).
"""
checks = report.get("checks")
if not isinstance(checks, list):
return report
for check in checks:
if not isinstance(check, dict):
continue
if check.get("name") != "screen_capture_capability":
continue
data = check.get("data")
count = data.get("display_count") if isinstance(data, dict) else None
if count == 0 and check.get("status") == "pass":
check["status"] = "fail"
check["message"] = (
"ScreenCaptureKit reachable but 0 shareable display(s) — "
"every capture will return 0x0."
)
check["hint"] = (
"Wake the built-in display, connect a monitor or HDMI dummy "
"dongle (e.g. Headless Ghost), or enable a virtual display "
"(Screen Sharing/VNC, BetterDisplay). Verify with "
"`system_profiler SPDisplaysDataType`."
)
if report.get("overall") == "ok":
report["overall"] = "degraded"
return report
def _print_text_report(
+1 -1
View File
@@ -1467,7 +1467,7 @@ Subcommands:
| Subcommand | Description |
|------------|-------------|
| `list` | List recent sessions. |
| `browse` | Interactive session picker with search and resume. |
| `browse` | Interactive session picker with search and resume. Each row shows a lifecycle status tag (`done` / `intr` / `err` / `empty`, derived from the session's final message) and its message count. Press `d` on a highlighted row (while the search filter is empty) to delete that session after a y/N confirmation; while a filter is active, `d` types into the search instead. |
| `export <output> [--session-id ID]` | Export sessions to JSONL. |
| `delete <session-id>` | Delete one session. |
| `prune` | Delete sessions matching filters: time bounds `--older-than`/`--newer-than`/`--before`/`--after` (durations like `5h`/`2d`, bare days, or ISO timestamps); attributes `--source`, `--title`, `--model`, `--provider`, `--branch`, `--end-reason`, `--user`, `--chat-id`, `--chat-type`, `--cwd`; numeric bounds `--min/--max-messages`, `--min/--max-tokens`, `--min/--max-cost`, `--min/--max-tool-calls`; plus `--include-archived`, `--dry-run`, `--yes`. Default: older than 90 days. |
+36
View File
@@ -115,6 +115,10 @@ hermes chat -c
This looks up the most recent `cli` session from the SQLite database and loads its full conversation history.
#### Per-Terminal Continue
A bare `-c` is terminal-aware: each CLI session drops a small breadcrumb file under `~/.hermes/terminal-sessions/` keyed by the terminal it runs in (tty device, tmux pane, kitty window, wezterm pane, Zellij pane, Windows Terminal session, ...). When you run `hermes -c` again in the *same* terminal, Hermes resumes that terminal's own session — so two panes side by side each continue their own conversation instead of both grabbing the globally most-recent one. If there's no breadcrumb for the terminal (first use, deleted session, or a stale breadcrumb older than 30 days), `-c` falls back to the most-recent-session behavior. `-c "name"` and `--resume` are unaffected. Disable with `session.terminal_continue: false` in `config.yaml`.
### Resume by Name
If you've given a session a title (see [Session Naming](#session-naming) below), you can resume it by name:
@@ -610,6 +614,38 @@ routing is the only thing the repair changes. Back up first
(`cp ~/.hermes/state.db ~/.hermes/state.db.bak`).
## Importing Sessions from Claude Code and Codex CLI
Started a conversation in another agent CLI? You can pull it into Hermes and
continue it here. Hermes reads Claude Code's session logs
(`~/.claude/projects/`) and Codex CLI's rollouts (`~/.codex/sessions/`) —
the foreign files are only read, never modified.
```bash
# Interactive picker across both tools, newest first
hermes sessions import
# Limit to one tool, or point at a specific file
hermes sessions import --from claude
hermes sessions import --from codex ~/.codex/sessions/2026/08/15/rollout-....jsonl
# Import-and-resume in one step
hermes --resume @claude
hermes --resume @codex
```
`hermes sessions import` creates a new Hermes session titled
`Imported from Claude Code: <first user message>` (or Codex CLI) and prints
the id plus a ready-to-paste `hermes --resume <id>` command.
`--resume @claude` / `--resume @codex` show the same picker and drop you
straight into the imported conversation.
What carries over: the ordered user/assistant conversation, with tool
activity condensed to short `[ran tool: …]` notes inside assistant turns.
System prompts, injected context, reasoning traces, and raw tool output are
left behind — the import is a clean transcript, not a byte-for-byte replay.
## Session Search Tool
The agent has a built-in `session_search` tool that performs full-text search across all past conversations using SQLite's FTS5 engine — and lets the agent scroll through any session it finds. It makes no LLM calls and returns views of actual messages from the DB rather than generating summaries.