Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

ethernet612d542281bd
diff --cc .dockerignore
index ababbcda826,f773f542631..6d9a841184b
--- a/.dockerignore
+++ b/.dockerignore
@@@ -86,18 -80,11 +86,17 @@@ apps
# Test suite — not shipped in production images
tests/
- # Documentation site (Docusaurus) and supplementary docs
+ # Documentation site (Docusaurus)
website/
- docs/
-# Assets only used by the GitHub README
+# Keep the source artwork needed by web's icon-generation prebuild.
assets/
+!assets/
+assets/*
+!assets/nous-girl-black.svg
+!assets/nous-girl-white.svg
+!assets/backgrounds/
+!assets/backgrounds/**
infographic/
# Plugin-level docs (hermes-achievements ships docs/ but the runtime doesn't read them)
diff --cc .gitignore
index 9c9e2c4d529,5d35cd36677..ab3936a1372
--- a/.gitignore
+++ b/.gitignore
@@@ -319,12 -188,10 +319,13 @@@ docs/superpowers/
# Runtime metadata only — never a code change. Ignore so `git status` stays clean
# and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855).
/.install_method
+install-stamp.json
# Tool Search live-test harness output — non-deterministic model transcripts,
-# regenerated by evals/tool_search/tool_search_livetest*.py. Never an artifact of the repo.
+# regenerated by scripts/tool_search_livetest.py. Never an artifact of the repo.
+
+scripts/out/
+ evals/tool_search/out*/
# Per-release changelog drafts. These exist only transiently during a release
# cut (passed to `gh release create --notes-file`); the GitHub Release itself
diff --cc Dockerfile
index 657827377e9,30774bdf31e..67904451bba
--- a/Dockerfile
+++ b/Dockerfile
@@@ -262,7 -230,7 +262,7 @@@ RUN cd plugins/platforms/photon/sideca
# frontend stats the readme path during dep resolution, so we `touch` an
# empty placeholder — the real README is restored by `COPY . .` below.
#
--# `uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp`
++# `pm.build_env --no-install-project --extra all --extra messaging --extra otlp`
# installs the deps reachable through the composite `[all]` extra
# (handpicked set intended for the production image — excludes `[dev]`),
# plus gateway messaging adapters that should work in the published image
@@@ -293,17 -261,24 +293,21 @@@
# avoids the cross-platform failures that kept [matrix] out of [all]
# while still making Matrix work in the published container. Fixes #30399.
#
+ # Google Chat's [google-chat] extra (google-cloud-pubsub + Chat API clients)
+ # is baked so hosted/immutable images can enable the adapter without writing
-# the sealed venv. Runtime --install-deps still routes through lazy_deps into
-# HERMES_LAZY_INSTALL_TARGET when the extra is not present.
++# the sealed venv.
+ #
-# The editable link is created after the source copy below.
+# Source binding is created after the source copy below.
COPY pyproject.toml uv.lock ./
RUN touch ./README.md
-RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock --extra azure-identity --extra hindsight --extra matrix --extra google-chat
+RUN python3 -m pm.build_env --source /opt/hermes --python /usr/local/bin/python3 \
+ --out /opt/hermes/.venv --no-install-project --sealed \
+ --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock \
- --extra azure-identity --extra hindsight --extra matrix
++ --extra azure-identity --extra hindsight --extra matrix --extra google-chat
-# ---------- Frontend build (cached independently from Python source) ----------
-# Copy only the frontend source trees first so that Python-only changes don't
-# invalidate the (relatively slow) web + ui-tui build layer.
-COPY web/ web/
-COPY ui-tui/ ui-tui/
-COPY apps/shared/ apps/shared/
-RUN cd web && npm run build && \
- cd ../ui-tui && npm run build
+# Shared product outputs are independent of application dependency assembly.
+COPY --from=frontend_build /opt/products/tui /opt/hermes/ui-tui
+COPY --from=frontend_build /opt/products/web /opt/hermes/hermes_cli/web_dist
# ---------- Source code ----------
# .dockerignore excludes node_modules, so the installs above survive.
@@@ -315,11 -290,14 +319,11 @@@
# write so the build steps below don't need chmod u+w dances.
COPY --link --chmod=a+rX,go-w . .
-# ---------- Permissions ----------
-# Link hermes-agent itself (editable). Deps are already installed in the
-# cached layer above; `--no-deps` makes this a fast egg-link creation with no
-# resolution or downloads.
-RUN uv pip install --no-cache-dir --no-deps -e "."
+# The shared assembler binds the prepared environment and frontend products.
+RUN /opt/hermes/.venv/bin/python -m docker.build_agent
# Wire the exec shim and install-method stamp. Files under /opt/hermes are
--# already root-owned (COPY, uv sync, npm install all run as root) and
++# already root-owned (COPY, dep assembly, npm install all run as root) and
# read-only for the hermes user (go-w from the --chmod above).
USER root
diff --cc agent/model_metadata.py
index d3873869ad8,c9a7824a81b..3b0f1d54027
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@@ -1580,7 -1636,8 +1587,8 @@@ def _fetch_codex_oauth_context_lengths_
if acct_id:
headers["ChatGPT-Account-Id"] = acct_id
try:
- resp = model_metadata_http.get("https://chatgpt.com/backend-api/codex/models?client_version=1.0.0", headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify())
- _ensure_requests()
- resp = requests.get(CODEX_MODELS_CATALOG_URL, headers=headers, timeout=(5, 10), verify=_resolve_requests_verify())
++
++ resp = model_metadata_http.get(CODEX_MODELS_CATALOG_URL, headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify())
if resp.status_code != 200:
logger.debug("Codex /models probe returned HTTP %s; falling back to hardcoded defaults", resp.status_code)
return {}, False
diff --cc agent/proxy_sources/iron_proxy.py
index e8f10cac08f,ca281e4de31..1ac7bbbfc39
--- a/agent/proxy_sources/iron_proxy.py
+++ b/agent/proxy_sources/iron_proxy.py
@@@ -28,8 -29,19 +28,10 @@@ from dataclasses import dataclass, fiel
from pathlib import Path
from typing import Dict, List, Optional, Tuple
+ from utils import atomic_json_write, atomic_write_text
+
logger = logging.getLogger(__name__)
-# Pinned: never auto-resolve "latest" — the YAML schema may change between releases.
-_IRON_PROXY_VERSION = "0.39.0"
-_IRON_PROXY_RELEASE_BASE = f"https://github.com/ironsh/iron-proxy/releases/download/v{_IRON_PROXY_VERSION}"
-_IRON_PROXY_CHECKSUM_NAME = "checksums.txt"
-# Optional GPG verification of checksums.txt (SHA-256 alone trusts the release channel).
-_IRON_PROXY_CHECKSUM_SIG_NAME = "checksums.txt.asc"
-_IRON_PROXY_PUBKEY_NAME = "public-key.asc"
-
-_DOWNLOAD_TIMEOUT = 120 # binary is ~16MB
_RUN_TIMEOUT = 30
_STARTUP_GRACE_SECONDS = 5
@@@ -499,21 -579,15 +501,15 @@@ def ensure_audit_log(audit_path: Path)
) from exc
- def _write_state_file_atomic(state: Path, name: str, dump) -> Path:
- """0600 temp file + atomic replace: the file holds proxy tokens; chmod-after-replace would be a world-readable TOCTOU window."""
- tmp_path = state / f".{name}.tmp"
- with open(tmp_path, "w", encoding="utf-8") as f:
- dump(f)
- os.chmod(tmp_path, 0o600)
- os.replace(tmp_path, state / name)
- return state / name
-
-
def write_proxy_config(config: Dict) -> Path:
- """Serialize the config dict to ``<hermes_home>/proxy/proxy.yaml`` (safe_dump, no Python tags)."""
+ """Serialize the config dict to ``<hermes_home>/proxy/proxy.yaml`` (safe_dump, no Python tags).
+
+ The file holds proxy tokens: written 0600 from creation, never at process umask."""
if (yaml := _yaml()) is None:
- raise RuntimeError("PyYAML is required to write the iron-proxy config but is not installed.")
+ raise RuntimeError("ruamel.yaml is required to write the iron-proxy config but is not installed.")
- return _write_state_file_atomic(_proxy_state_dir(), "proxy.yaml", lambda f: yaml.safe_dump(config, f, default_flow_style=False, sort_keys=False))
+ path = _proxy_state_dir() / "proxy.yaml"
+ atomic_write_text(path, yaml.safe_dump(config, default_flow_style=False, sort_keys=False), mode=0o600)
+ return path
def write_mappings(mappings: List[TokenMapping]) -> Path:
diff --cc apps/desktop/electron/backend-stop-overlap.test.ts
index 2cd57774bc9,00000000000..fbc08cc103d
mode 100644,000000..100644
--- a/apps/desktop/electron/backend-stop-overlap.test.ts
+++ b/apps/desktop/electron/backend-stop-overlap.test.ts
@@@ -1,183 -1,0 +1,188 @@@
+import assert from 'node:assert/strict'
+import { type ChildProcess, spawn } from 'node:child_process'
+import { once } from 'node:events'
+
+import { test } from 'vitest'
+
+import { stopBackendChild, waitForBackendExit } from './backend-child'
+import { createLocalBackendLifecycle } from './local-backend-lifecycle'
+import {
+ assertPoolEntryStillOwned,
+ type LocalBackendSlotEntry,
+ LocalBackendSpawnCoordinator,
+ releaseLocalBackendSlot,
+ releaseLocalBackendSlotAfterExit
+} from './pool-spawn-coordinator'
+import { createPoolStopper } from './pool-stop'
+
+test.skipIf(process.platform === 'win32')(
+ 'eviction, update and quit share physical exit before releasing a slot',
+ async (): Promise<void> => {
+ let signals = 0
+ let released = false
+
+ const physical = {
+ forceKillProcessTree: (): never => {
+ throw new Error('POSIX test')
+ }
+ }
+
+ const lifecycle = createLocalBackendLifecycle<ChildProcess>({
+ cancelSetup: (): void => {},
+ stopChild: (child: ChildProcess): void => {
+ signals++
+ stopBackendChild(child, physical)
+ },
+ waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child, physical)
+ })
+
+ const child = lifecycle.spawn((): ChildProcess =>
+ spawn(
+ process.execPath,
+ [
+ '-e',
+ `
+ process.on('SIGTERM', () => process.send('stopping'));
+ process.on('message', () => process.exit(0));
+ setInterval(() => {}, 1000);
+ process.send('ready');
+ `
+ ],
+ { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }
+ )
+ )
+
+ child.once('exit', (): boolean => lifecycle.release(child))
+
+ const deps = {
+ pool: new Map([['profile', { process: child }]]),
- stopChild: lifecycle.stop
++ stopChild: (c: unknown): void => { void lifecycle.stop(c as ChildProcess) },
++ waitForExit: (c: unknown): Promise<void> => lifecycle.stop(c as ChildProcess)
+ }
+
+ const pool = createPoolStopper(deps)
+
+ try {
+ await once(child, 'message')
+ const signalled = once(child, 'message')
+
+ const eviction = releaseLocalBackendSlotAfterExit(
+ (): void => {
+ released = true
+ },
+ (): Promise<void> => pool.stop('profile')
+ )
+
+ const update = lifecycle.stop(child)
+ const quit = lifecycle.shutdown()
+ await signalled
+ assert.equal(signals, 1)
+ assert.equal(released, false, 'a pool slot must remain occupied while its process is alive')
+ assert.ok(pool.inFlight('profile'))
+ assert.throws((): ChildProcess => lifecycle.spawn((): ChildProcess => child))
+ child.send('exit')
+ await Promise.all([eviction, update, quit])
+ assert.equal(child.exitCode, 0)
+ assert.equal(released, true)
+ assert.equal(pool.inFlight('profile'), undefined)
+ assert.equal(lifecycle.hasPending(), false)
+ } finally {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill('SIGKILL')
+ await once(child, 'exit')
+ }
+ }
+ }
+)
+
+test.skipIf(process.platform === 'win32')(
+ 'a claim completed after eviction retains its live child capacity',
+ async (): Promise<void> => {
+ const slots = new LocalBackendSpawnCoordinator(1)
+ const signal = new AbortController().signal
+ const unspawned: LocalBackendSlotEntry = { releaseLocalBackendSlot: await slots.acquire('not-spawned') }
+ assert.throws((): void => assertPoolEntryStillOwned('not-spawned', unspawned, new Map(), signal))
+ assert.equal(slots.activeCount, 0, 'pre-spawn cancellation releases its reservation')
+
+ const physical = {
+ forceKillProcessTree: (): never => {
+ throw new Error('POSIX test')
+ }
+ }
+
+ const lifecycle = createLocalBackendLifecycle<ChildProcess>({
+ cancelSetup: (): void => {},
+ stopChild: (child: ChildProcess): void => stopBackendChild(child, physical),
+ waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child, physical)
+ })
+
+ const release = await slots.acquire('claiming')
+
+ const child = lifecycle.spawn((): ChildProcess =>
+ spawn(
+ process.execPath,
+ [
+ '-e',
+ `
+ process.on('SIGTERM', () => process.send('stopping'));
+ process.on('message', () => process.exit(0));
+ setInterval(() => {}, 1000);
+ process.send('ready');
+ `
+ ],
+ { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }
+ )
+ )
+
+ child.once('exit', (): boolean => lifecycle.release(child))
+ const entry = { process: child, releaseLocalBackendSlot: release }
+ const entries = new Map([['claiming', entry]])
- const pool = createPoolStopper({ pool: entries, stopChild: lifecycle.stop })
++ const pool = createPoolStopper({
++ pool: entries,
++ stopChild: (c: unknown): void => { void lifecycle.stop(c as ChildProcess) },
++ waitForExit: (c: unknown): Promise<void> => lifecycle.stop(c as ChildProcess)
++ })
+ let finishClaim!: () => void
+
+ const claim = new Promise<void>((resolve: () => void): void => {
+ finishClaim = resolve
+ })
+
+ const starting = claim.then((): void => assertPoolEntryStillOwned('claiming', entry, entries, signal))
+ const rejected = assert.rejects(starting, /cancelled/)
+
+ try {
+ await once(child, 'message')
+ const signalled = once(child, 'message')
+
+ const eviction = releaseLocalBackendSlotAfterExit(
+ (): void => releaseLocalBackendSlot(entry),
+ (): Promise<void> => pool.stop('claiming')
+ )
+
+ await signalled
+ finishClaim()
+ await rejected
+ assert.equal(child.exitCode, null)
+ assert.equal(child.signalCode, null)
+ assert.ok(pool.inFlight('claiming'))
+ assert.equal(slots.activeCount, 1, 'the post-claim guard must not release a live child slot')
+ const replacement = slots.request('different-profile')
+ assert.equal(replacement.queued, true)
+ child.send('exit')
+ await eviction
+ const releaseReplacement = await replacement.acquired
+ assert.equal(child.exitCode, 0)
+ releaseReplacement()
+ assert.equal(slots.activeCount, 0)
+ } finally {
+ finishClaim()
+ await rejected
+
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill('SIGKILL')
+ await once(child, 'exit')
+ }
+ }
+ }
+)
diff --cc apps/desktop/electron/main.ts
index 8bbebaedb8c,7bf419e310e..d65896101fc
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -11669,12 -12731,25 +11678,30 @@@ async function spawnPoolBackend
// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —
// idle reaper, LRU eviction, profile delete/rename, quit — shares one
// in-flight stop per key and retains the process handle until the bounded
-// SIGTERM -> SIGKILL escalation in waitForBackendExit() resolves. Previously
+// physical shutdown promise resolves. Previously
// SIGTERM + immediate entry delete dropped the handle and a slow child
// survived detached under PID 1.
- const poolStopper = createPoolStopper<ChildProcess>({
+ const poolStopper = createPoolStopper({
pool: backendPool,
- stopChild: localBackendLifecycle.stop
- stopChild: child => stopBackendChild(child),
- waitForExit: child => waitForBackendExit(child),
- // Remote / SSH-isolated pool entries keep `process: null`. Child exit is
- // immediate; hold the same in-flight fence through bootstrap drain + SSH
- // teardown so a reconnect cannot publish into a dying scope (#106935).
++ // localBackendLifecycle is the single owner of local child stop semantics:
++ // stopChild triggers its stop (stop + bounded exit wait + slot release);
++ // waitForExit resolves when that same stop promise settles. Remote /
++ // SSH-isolated pool entries keep `process: null` — child exit is immediate
++ // there, so the same in-flight fence carries only the bootstrap drain +
++ // SSH teardown below (#106935).
++ stopChild: child => {
++ void localBackendLifecycle.stop(child as ChildProcess | null | undefined)
++ },
++ waitForExit: child => localBackendLifecycle.stop(child as ChildProcess | null | undefined),
+ afterStop: async key => {
+ try {
+ await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))
+ } catch (err) {
+ // The idle reaper calls stopPoolBackend un-awaited; a failed SSH teardown
+ // must not surface as an unhandled rejection or block the pool fence.
+ sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)
+ }
+ }
})
async function stopPoolBackend(profile: string) {
diff --cc apps/desktop/src/app/messaging/index.test.tsx
index ed581cc0f34,d60fed80fd5..46b80f283e0
--- a/apps/desktop/src/app/messaging/index.test.tsx
+++ b/apps/desktop/src/app/messaging/index.test.tsx
@@@ -105,6 -95,13 +105,13 @@@ afterEach(() =>
vi.clearAllMocks()
})
-// Import at module scope (after the hoisted vi.mock calls) so the heavy
-// component-tree transform is paid during collection, not billed against the
-// first test's testTimeout — inside a test body it exceeded the budget on
++// Static import at module scope (after the hoisted vi.mock calls) so the
++// heavy component-tree transform is paid during collection, not billed against
++// the first test's testTimeout — inside a test body it exceeded the budget on
+ // loaded CI runners and cascaded the whole file (main runs 34599517793,
+ // 34600757569, 34601269252). Same pattern as chat/index.test.tsx.
-const { MessagingView } = await import('./index')
++void import('./index')
+
async function renderMessaging() {
let result: ReturnType<typeof render>
await act(async () => {
diff --cc apps/desktop/src/app/settings/uninstall-section.tsx
index 8fb08e6102f,14266a61309..595c8119f89
--- a/apps/desktop/src/app/settings/uninstall-section.tsx
+++ b/apps/desktop/src/app/settings/uninstall-section.tsx
@@@ -1,7 -1,8 +1,8 @@@
-import { useEffect, useState } from 'react'
+import { type ReactElement, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
-import type { DesktopUninstallMode, DesktopUninstallSummary } from '@/global'
+import type { DesktopUninstallMode, DesktopUninstallResult, DesktopUninstallSummary } from '@/global'
+ import { useI18n } from '@/i18n'
import { AlertTriangle, Loader2, Trash2 } from '@/lib/icons'
import { cn } from '@/lib/utils'
@@@ -45,17 -46,21 +46,18 @@@ const OPTIONS: ModeOption[] =
}
]
-export function UninstallSection() {
+export function UninstallSection(): ReactElement | null {
+ const { t } = useI18n()
const [summary, setSummary] = useState<DesktopUninstallSummary | null>(null)
- const [loading, setLoading] = useState(true)
const [pending, setPending] = useState<DesktopUninstallMode | null>(null)
- const [running, setRunning] = useState(false)
+ const [running, setRunning] = useState<boolean>(false)
const [error, setError] = useState<string | null>(null)
- useEffect(() => {
- let alive = true
- const bridge = window.hermesDesktop?.uninstall
+ useEffect((): (() => void) | undefined => {
+ let alive: boolean = true
+ const bridge: Window['hermesDesktop']['uninstall'] | undefined = window.hermesDesktop?.uninstall
if (!bridge) {
- setLoading(false)
-
return
}
@@@ -116,12 -124,17 +118,12 @@@
return (
<div className="mx-auto mt-8 w-full max-w-2xl">
- <SectionHeading icon={AlertTriangle} title="Danger zone" />
+ <SectionHeading icon={AlertTriangle} title={t.settings.uninstallSection.dangerZone} />
<div className="rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3">
- {loading ? (
- <div className="flex items-center gap-2 py-2 text-sm text-muted-foreground">
- <Loader2 className="size-3.5 animate-spin" />
- Checking what&apos;s installed…
- </div>
- ) : pendingOption ? (
+ {pendingOption ? (
<div>
- <p className="text-sm font-medium text-destructive">Confirm uninstall</p>
+ <p className="text-sm font-medium text-destructive">{t.settings.uninstallSection.confirmUninstall}</p>
<p className="mt-1 text-xs text-muted-foreground">
This removes {pendingOption.consequence}. This can&apos;t be undone.
</p>
diff --cc apps/desktop/src/app/shell/model-catalog-menu.tsx
index b197f7fa1ee,f99d8862c05..4dc8ad447dd
--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx
+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx
@@@ -1,15 -1,8 +1,17 @@@
+ import type { ModelOptionProvider, ModelOptionsResult } from '@hermes/shared'
+ import { DEFAULT_REASONING_EFFORT } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
-import { createContext, type ReactNode, useContext, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ createContext,
+ type ReactElement,
+ type ReactNode,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from 'react'
import { Codicon } from '@/components/ui/codicon'
import { DisclosureCaret } from '@/components/ui/disclosure-caret'
@@@ -28,20 -21,17 +30,21 @@@ import { HighlightMatches } from '@/com
import { usePointerQuiet } from '@/components/ui/keyboard-first'
import { Skeleton } from '@/components/ui/skeleton'
import type { HermesGateway } from '@/hermes'
-import { getLocalModelsStatus } from '@/hermes'
import { useI18n } from '@/i18n'
+ import { isSubmitEnter } from '@/lib/ime'
import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
import { displayModelName, modelDisplayParts } from '@/lib/model-status-label'
- import { DEFAULT_REASONING_EFFORT, reasoningEffortLabel } from '@/lib/reasoning-effort'
+ import { reasoningEffortLabel } from '@/lib/reasoning-effort'
import { foldIncludes, normalize } from '@/lib/text'
-import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs, runningModelDownloads, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
+import {
+ type LocalModelsOwner,
+ runningModelDownloads,
+ useLocalModelsOwner,
+ useLocalModelsStatus,
+ useLocalRuntimeJobs
+} from '@/store/local-runtime-jobs'
import {
$visibleModels,
collapseModelFamilies,
@@@ -53,7 -43,7 +56,7 @@@
} from '@/store/model-visibility'
import { $collapsedProviders, toggleCollapsedProvider } from '@/store/provider-collapse'
import { $defaultReasoningEffort } from '@/store/session'
- import type { LocalModelLoadProgress, LocalRuntimeJob, ModelOptionProvider, ModelOptionsResponse } from '@/types/hermes'
-import type { LocalModelLoadProgress } from '@/types/hermes'
++import type { LocalModelLoadProgress, LocalRuntimeJob } from '@/types/hermes'
import { type FastControl, ModelEditSubmenu, resolveFastControl } from './model-edit-submenu'
diff --cc apps/desktop/src/components/model-picker.test.tsx
index ba650d002e2,f6a73ebba5a..be5aeec50e7
--- a/apps/desktop/src/components/model-picker.test.tsx
+++ b/apps/desktop/src/components/model-picker.test.tsx
@@@ -16,11 -6,10 +6,10 @@@ import type { ReactElement } from 'reac
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { I18nProvider } from '@/i18n'
- import { queryClient } from '@/lib/query-client'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs } from '@/store/local-runtime-jobs'
+import { localModelsKey, localModelsOwner } from '@/store/local-runtime-jobs'
import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'
- import type { LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes'
+ import type { LocalRuntimeJob } from '@/types/hermes'
import { ModelPickerDialog } from './model-picker'
@@@ -74,8 -60,8 +60,17 @@@ const DOWNLOAD_JOB: LocalRuntimeJob =
error: null
}
++let seedClient: QueryClient | null = null
++
++function setRuntimeJobs(jobs: readonly LocalRuntimeJob[]): void {
++ // Banana's store keeps jobs in react-query, not the old atom: seed the cache
++ // directly the way production populates it (localModelsKey(owner, 'jobs')).
++ seedClient?.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), jobs)
++}
++
function renderPicker(ui?: Partial<Parameters<typeof ModelPickerDialog>[0]>) {
- const client: QueryClient = queryClient
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
++ seedClient = client
const element: ReactElement = (
<QueryClientProvider client={client}>
@@@ -95,11 -81,9 +90,9 @@@
return render(element)
}
- beforeEach((): void => {
- queryClient.clear()
- queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, retry: false } })
+ beforeEach(() => {
vi.mocked(requestModelOptions).mockResolvedValue(OPTIONS)
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])
- $localRuntimeJobs.set([])
++ setRuntimeJobs([])
// These suites exercise the local-models rows, which ship behind --local.
$localModelsEnabled.set(true)
})
@@@ -112,7 -95,7 +104,7 @@@ afterEach(() =>
describe('ModelPickerDialog download rows', () => {
it('shows an in-flight download as a disabled progress row in the Local group', async () => {
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
- $localRuntimeJobs.set([DOWNLOAD_JOB])
++ setRuntimeJobs([DOWNLOAD_JOB])
renderPicker()
expect(await screen.findByText('Qwen3.6-27B-UD-Q4_K_XL')).toBeTruthy()
@@@ -129,7 -112,7 +121,7 @@@
})
it('shows a first-ever download under its own Local group when no local provider exists yet', async () => {
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
- $localRuntimeJobs.set([DOWNLOAD_JOB])
++ setRuntimeJobs([DOWNLOAD_JOB])
vi.mocked(requestModelOptions).mockResolvedValue({
providers: [OPTIONS.providers![1]]
})
@@@ -143,28 -126,26 +135,26 @@@
it('quickstart shows while downloading but not during later phases', async () => {
const quickstart: LocalRuntimeJob = { ...DOWNLOAD_JOB, job_id: 'q1', kind: 'quickstart', phase: 'downloading' }
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [quickstart])
- $localRuntimeJobs.set([quickstart])
++ setRuntimeJobs([quickstart])
renderPicker()
expect(await screen.findByText('Qwen3.8 Flash Next (UD-Q4_K_XL)')).toBeTruthy()
// The model is staged once quickstart moves on to activating it — the
// placeholder row must leave rather than sit beside the real model.
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [{ ...quickstart, phase: 'starting-server' }])
- $localRuntimeJobs.set([{ ...quickstart, phase: 'starting-server' }])
++ setRuntimeJobs([{ ...quickstart, phase: 'starting-server' }])
await waitFor(() => {
expect(screen.queryByText('Qwen3.8 Flash Next (UD-Q4_K_XL)')).toBeNull()
})
})
it('refetches the model options when a download it saw running completes', async () => {
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [DOWNLOAD_JOB])
- $localRuntimeJobs.set([DOWNLOAD_JOB])
++ setRuntimeJobs([DOWNLOAD_JOB])
renderPicker()
await screen.findByText('Qwen3.6-27B-UD-Q4_K_XL')
expect(vi.mocked(requestModelOptions).mock.calls.length).toBe(1)
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
- { ...DOWNLOAD_JOB, status: 'done', phase: 'done' }
- ])
- $localRuntimeJobs.set([{ ...DOWNLOAD_JOB, status: 'done', phase: 'done' }])
++ setRuntimeJobs([{ ...DOWNLOAD_JOB, status: 'done', phase: 'done' }])
await waitFor(() => {
expect(vi.mocked(requestModelOptions).mock.calls.length).toBe(2)
})
diff --cc apps/desktop/src/components/model-picker.tsx
index 7eb75c95ce2,e6d41580907..2a8a0768c9f
--- a/apps/desktop/src/components/model-picker.tsx
+++ b/apps/desktop/src/components/model-picker.tsx
@@@ -1,23 -1,20 +1,24 @@@
+ import type { ModelOptionProvider, ModelPricing } from '@hermes/shared'
+ import { fuzzyRank, modelSearchText } from '@hermes/shared'
import { useQuery } from '@tanstack/react-query'
-import { useEffect, useMemo, useState } from 'react'
+import { type ReactElement, useMemo, useState } from 'react'
-import { getLocalModelsStatus } from '@/hermes'
import { useI18n } from '@/i18n'
import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
- import { modelSearchText } from '@/lib/model-search-text'
import { currentPickerSelection } from '@/lib/model-status-label'
import { foldIncludes, normalize } from '@/lib/text'
-import { useStoreSelector } from '@/lib/use-session-slice'
+import { cn } from '@/lib/utils'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs, runningModelDownloads, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
-import type { LocalModelLoadProgress } from '@/types/hermes'
+import {
+ type LocalModelsOwner,
+ runningModelDownloads,
+ useLocalModelsOwner,
+ useLocalModelsStatus,
+ useLocalRuntimeJobs
+} from '@/store/local-runtime-jobs'
- import type { LocalModelLoadProgress, LocalRuntimeJob, ModelOptionProvider, ModelPricing } from '@/types/hermes'
++import type { LocalModelLoadProgress, LocalRuntimeJob } from '@/types/hermes'
import type { HermesGateway } from '../hermes'
-import { cn } from '../lib/utils'
import { startManualOnboarding } from '../store/onboarding'
import { InlineNotice } from './notifications'
@@@ -65,9 -62,9 +66,9 @@@ export function ModelPickerDialog(
// Own the search term so we can filter manually. cmdk's built-in
// shouldFilter reorders items by its fuzzy-match score (≈alphabetical with
// an empty query), which destroys the backend's curated order. We disable
- // it and do a plain substring filter that preserves array order — matching
- // the `hermes model` CLI picker, which shows the curated list verbatim.
+ // it: an empty query shows the curated list verbatim (like the `hermes
+ // model` CLI picker) and a query ranks with the shared fuzzyRank.
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState<string>('')
const modelOptions = useQuery({
queryKey: modelOptionsQueryKey(profile, sessionId, ownerConnectionId),
diff --cc apps/desktop/src/i18n/en.ts
index 7763e4ade98,3014a98acb0..2b3d58bbd0c
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -844,8 -837,66 +848,32 @@@ export const en: Translations =
},
fieldLabels: FIELD_LABELS,
fieldDescriptions: FIELD_DESCRIPTIONS,
+ uninstallSection: {
+ dangerZone: 'Danger zone',
+ confirmUninstall: 'Confirm uninstall',
+ uninstallHermes: 'Uninstall Hermes'
+ },
+ poolLimits: {
+ warmBotBackendsAria: 'Warm bot backends',
+ warmBotBackendsTitle: 'Warm Bot Backends',
+ backendIdleTimeoutAria: 'Backend idle timeout in milliseconds',
+ backendIdleTimeoutTitle: 'Backend Idle Timeout'
+ },
+ customEndpoints: {
+ title: 'Custom Endpoints',
+ deleteEndpoint: 'Delete endpoint',
+ emptyDescription: 'Add an OpenAI-compatible endpoint below.',
+ emptyTitle: 'No custom endpoints',
+ namePlaceholder: 'Axet Proxy',
+ contextPlaceholder: 'Auto'
+ },
+ computerUse: {
+ accessibility: 'Accessibility',
+ screenRecording: 'Screen Recording',
+ driverHealth: 'Driver health'
+ },
about: {
- heading: 'Hermes Desktop',
- version: value => `Version ${value}`,
- versionUnavailable: 'Version unavailable',
- bundleOutOfSync: 'App build out of date',
- bundleOutOfSyncDesc:
- 'The Hermes runtime was updated, but the desktop app itself is still an older build — new interface features (like Bot Mode) will be missing until it updates. Run the update below to rebuild the app. If that doesn\u2019t clear this warning, reinstall from the latest desktop installer.',
- bundleOutOfSyncAction: 'Get the installer',
- bundleSwapPending: 'Restart to finish the update',
- bundleSwapPendingDesc:
- 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',
- bundleSwapPendingAction: 'Restart Hermes',
updates: 'Updates',
- checkNow: 'Check now',
- checking: 'Checking…',
- seeWhatsNew: "See what's new",
- updateNow: 'Update now',
- releaseNotes: 'Release notes',
- onLatest: "You're on the latest version.",
- installing: 'An update is currently installing.',
- cantUpdate: "This build can't update itself from inside the app.",
- cantReach: "We couldn't reach the update server.",
- tapCheck: 'Tap "Check now" to look for updates.',
- updateReady: count => `A new update is ready (${count} change${count === 1 ? '' : 's'} included).`,
- updateReadyUnknown: 'A new update is ready.',
- lastChecked: age => `Last checked ${age}`,
- justNowSuffix: ' · just now',
- automaticUpdates: 'Automatic updates',
- automaticUpdatesDesc:
- 'Hermes checks for updates automatically in the background and lets you know when one is ready.',
- branchCommit: (branch, commit) => `Branch ${branch} · Commit ${commit}`,
- never: 'never',
- justNow: 'just now',
- minAgo: count => `${count} min ago`,
- hoursAgo: count => `${count} hours ago`,
- daysAgo: count => `${count} days ago`
},
config: {
none: 'None',
diff --cc apps/desktop/src/i18n/types.ts
index 847bf743cb1,baf2a1b2068..bd867cdaf4d
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@@ -716,8 -710,63 +720,32 @@@ export interface Translations
}
fieldLabels: Record<string, string>
fieldDescriptions: Record<string, string>
+ uninstallSection: {
+ dangerZone: string
+ confirmUninstall: string
+ uninstallHermes: string
+ }
+ poolLimits: {
+ warmBotBackendsAria: string
+ warmBotBackendsTitle: string
+ backendIdleTimeoutAria: string
+ backendIdleTimeoutTitle: string
+ }
+ customEndpoints: {
+ title: string
+ deleteEndpoint: string
+ emptyDescription: string
+ emptyTitle: string
+ namePlaceholder: string
+ contextPlaceholder: string
+ }
+ computerUse: {
+ accessibility: string
+ screenRecording: string
+ driverHealth: string
+ }
about: {
- heading: string
- version: (value: string) => string
- versionUnavailable: string
- bundleOutOfSync: string
- bundleOutOfSyncDesc: string
- bundleOutOfSyncAction: string
- bundleSwapPending: string
- bundleSwapPendingDesc: string
- bundleSwapPendingAction: string
updates: string
- checkNow: string
- checking: string
- seeWhatsNew: string
- updateNow: string
- releaseNotes: string
- onLatest: string
- installing: string
- cantUpdate: string
- cantReach: string
- tapCheck: string
- updateReady: (count: number) => string
- updateReadyUnknown: string
- lastChecked: (age: string) => string
- justNowSuffix: string
- automaticUpdates: string
- automaticUpdatesDesc: string
- branchCommit: (branch: string, commit: string) => string
- never: string
- justNow: string
- minAgo: (count: number) => string
- hoursAgo: (count: number) => string
- daysAgo: (count: number) => string
}
config: {
none: string
diff --cc apps/desktop/src/i18n/zh-hant.ts
index f56bbe89b62,846b41d5ec7..2dd333146d1
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -824,8 -861,65 +868,32 @@@ export const zhHant = defineLocale(
'Hermes 從應用程式內更新自身時,保留本機原始碼變更(stash)或丟棄(discard)。終端機更新一律會詢問。'
}
}),
+ uninstallSection: {
+ dangerZone: '危險操作',
+ confirmUninstall: '確認解除安裝',
+ uninstallHermes: '解除安裝 Hermes'
+ },
+ poolLimits: {
+ warmBotBackendsAria: '預熱機器人後端',
+ warmBotBackendsTitle: '預熱機器人後端',
+ backendIdleTimeoutAria: '後端閒置逾時(毫秒)',
+ backendIdleTimeoutTitle: '後端閒置逾時(毫秒)'
+ },
+ customEndpoints: {
+ title: '自訂端點',
+ deleteEndpoint: '刪除端點',
+ emptyDescription: '在下方新增 OpenAI 相容端點。',
+ emptyTitle: '尚無自訂端點',
+ namePlaceholder: '我的代理',
+ contextPlaceholder: '自動'
+ },
+ computerUse: {
+ accessibility: '輔助使用',
+ screenRecording: '螢幕錄製',
+ driverHealth: '驅動程式健康狀態'
+ },
about: {
- heading: 'Hermes Desktop',
- version: value => `版本 ${value}`,
- versionUnavailable: '版本不可用',
- bundleOutOfSync: '應用程式建置版本過舊',
- bundleOutOfSyncDesc:
- 'Hermes 執行環境已更新,但桌面應用程式本身仍是舊建置——在應用程式更新之前,新的介面功能(如 Bot Mode)不會顯示。請執行下方的更新以重新建置應用程式。如果此警告仍未消除,請從最新的桌面安裝程式重新安裝。',
- bundleOutOfSyncAction: '取得安裝程式',
- bundleSwapPending: '重新啟動以完成更新',
- bundleSwapPendingDesc:
- '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',
- bundleSwapPendingAction: '重新啟動 Hermes',
updates: '更新',
- checkNow: '立即檢查',
- checking: '檢查中…',
- seeWhatsNew: '查看新增內容',
- updateNow: '立即更新',
- releaseNotes: '發行說明',
- onLatest: '你已是最新版本。',
- installing: '正在安裝更新。',
- cantUpdate: '此版本無法從應用程式內自行更新。',
- cantReach: '無法連線到更新伺服器。',
- tapCheck: '點選「立即檢查」以尋找更新。',
- updateReady: count => `新更新已就緒(包含 ${count} 項變更)。`,
- updateReadyUnknown: '新更新已就緒。',
- lastChecked: age => `上次檢查:${age}`,
- justNowSuffix: ' · 剛剛',
- automaticUpdates: '自動更新',
- automaticUpdatesDesc: 'Hermes 會在背景自動檢查更新,並在有可用更新時通知你。',
- branchCommit: (branch, commit) => `分支 ${branch} · 提交 ${commit}`,
- never: '從未',
- justNow: '剛剛',
- minAgo: count => `${count} 分鐘前`,
- hoursAgo: count => `${count} 小時前`,
- daysAgo: count => `${count} 天前`
},
config: {
none: '無',
diff --cc apps/desktop/src/i18n/zh.ts
index bac6756a0b4,2d6f87f8844..b62164fadca
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@@ -1043,8 -1066,64 +1076,32 @@@ export const zh = defineLocale(
'Hermes 从应用内更新时(无终端提示),保留本地源码修改(暂存)或丢弃(放弃)。通过终端更新时始终会询问。'
}
}),
+ uninstallSection: {
+ dangerZone: '危险操作',
+ confirmUninstall: '确认卸载',
+ uninstallHermes: '卸载 Hermes'
+ },
+ poolLimits: {
+ warmBotBackendsAria: '预热机器人后端',
+ warmBotBackendsTitle: '预热机器人后端',
+ backendIdleTimeoutAria: '后端空闲超时(毫秒)',
+ backendIdleTimeoutTitle: '后端空闲超时(毫秒)'
+ },
+ customEndpoints: {
+ title: '自定义端点',
+ deleteEndpoint: '删除端点',
+ emptyDescription: '在下方添加兼容 OpenAI 的端点。',
+ emptyTitle: '暂无自定义端点',
+ namePlaceholder: '我的代理',
+ contextPlaceholder: '自动'
+ },
+ computerUse: {
+ accessibility: '辅助功能',
+ screenRecording: '屏幕录制',
+ driverHealth: '驱动健康状态'
+ },
about: {
- heading: 'Hermes Desktop',
- version: value => `版本 ${value}`,
- versionUnavailable: '版本不可用',
- bundleOutOfSync: '应用构建版本过旧',
- bundleOutOfSyncDesc:
- 'Hermes 运行时已更新,但桌面应用本身仍是旧构建——在应用更新之前,新的界面功能(如 Bot Mode)不会显示。请运行下方的更新以重新构建应用。如果此警告仍未消除,请从最新的桌面安装程序重新安装。',
- bundleOutOfSyncAction: '获取安装程序',
- bundleSwapPending: '重启以完成更新',
- bundleSwapPendingDesc: '更新后的应用已安装完成,只需重启 Hermes 即可加载新版本。聊天记录和设置不会受到影响。',
- bundleSwapPendingAction: '重启 Hermes',
updates: '更新',
- checkNow: '立即检查',
- checking: '检查中…',
- seeWhatsNew: '查看新增内容',
- updateNow: '立即更新',
- releaseNotes: '发行说明',
- onLatest: '你已是最新版本。',
- installing: '正在安装更新。',
- cantUpdate: '此版本无法在应用内自我更新。',
- cantReach: '无法连接更新服务器。',
- tapCheck: '点击"立即检查"以查找更新。',
- updateReady: count => `已准备好新更新 (包含 ${count} 项更改)。`,
- updateReadyUnknown: '新更新已就绪。',
- lastChecked: age => `上次检查:${age}`,
- justNowSuffix: ' · 刚刚',
- automaticUpdates: '自动更新',
- automaticUpdatesDesc: 'Hermes 会在后台自动检查更新,并在有可用更新时通知你。',
- branchCommit: (branch, commit) => `分支 ${branch} · 提交 ${commit}`,
- never: '从未',
- justNow: '刚刚',
- minAgo: count => `${count} 分钟前`,
- hoursAgo: count => `${count} 小时前`,
- daysAgo: count => `${count} 天前`
},
config: {
none: '无',
diff --cc apps/desktop/src/store/local-models-surfaces.test.tsx
index 2d126b793b6,00000000000..2409efaf030
mode 100644,000000..100644
--- a/apps/desktop/src/store/local-models-surfaces.test.tsx
+++ b/apps/desktop/src/store/local-models-surfaces.test.tsx
@@@ -1,405 -1,0 +1,406 @@@
+import { QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, renderHook, type RenderResult, screen } from '@testing-library/react'
+import { MemoryRouter } from 'react-router'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import type { HermesApiRequest, HermesConnection } from '@/global'
- import type { LocalCatalogModel, LocalModelsStatus, LocalRuntimeJob, ModelOptionsResponse } from '@/types/hermes'
++import type { ModelOptionsResult } from '@hermes/shared'
++import type { LocalCatalogModel, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'
+
+vi.mock('@/hermes', async (): Promise<object> => ({
+ ...(await import('@/api/local-models')),
+ getHermesConfigRecord: async (): Promise<object> => ({}),
- getGlobalModelOptions: async (): Promise<ModelOptionsResponse> => ({ providers: [] })
++ getGlobalModelOptions: async (): Promise<ModelOptionsResult> => ({ providers: [] })
+}))
+vi.mock('@/store/profile', async (): Promise<object> => {
+ const { atom } = await import('nanostores')
+
+ return { $activeGatewayProfile: atom<string>('work') }
+})
+vi.mock('@/store/session', async (): Promise<object> => {
+ const { atom } = await import('nanostores')
+
+ return { $connection: atom<HermesConnection | null>(null), $defaultReasoningEffort: atom<string>('') }
+})
+vi.mock('@/store/notifications', (): object => ({ notify: vi.fn(), notifyError: vi.fn() }))
+
+import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'
+import { LocalModelsSettings } from '@/app/settings/local-models-settings'
+import { ModelCatalogMenu, type ModelMenuController } from '@/app/shell/model-catalog-menu'
+import { ModelPickerDialog } from '@/components/model-picker'
+import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu'
+import { I18nProvider } from '@/i18n'
+import { queryClient } from '@/lib/query-client'
+import { $localModelsEnabled } from '@/store/local-models-flag'
+import { notify, notifyError } from '@/store/notifications'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection } from '@/store/session'
+import { deferred } from '@/test/deferred'
+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'
+
+import {
+ checkLocalRuntimeUpdate,
+ localModelsKey,
+ localModelsOwner,
+ refreshLocalModels,
+ useLocalModelsOwner,
+ watchLocalRuntimeJobs
+} from './local-runtime-jobs'
+
+stubResizeObserver()
+stubMenuDomApis()
+
+const status: LocalModelsStatus = {
+ enabled: true,
+ tag: 'installed',
+ configured_tag: 'installed',
+ update_available: false,
+ runtime_installed: true,
+ runtime_backend: 'cpu',
+ server_running: false,
+ server_base_url: null,
+ active_model_id: null,
+ loaded_models: {},
+ models: [],
+ models_dir: '/models'
+}
+
+const running: LocalRuntimeJob = {
+ job_id: 'same-id',
+ kind: 'model-download',
+ model_id: 'model',
+ target: 'Download A',
+ status: 'running',
+ phase: 'downloading',
+ detail: '',
+ done_bytes: 1,
+ total_bytes: 2,
+ percent: 50,
+ error: null
+}
+
+let jobs: LocalRuntimeJob[] = []
+let catalog: LocalCatalogModel[] = []
+
+const model: LocalCatalogModel = {
+ id: 'model', display_name: 'Download A', description: '', size_bytes: 2, size_label: '2 B',
+ native_context: 4096, native_context_label: '4K', recommended: true, downloaded: false, fits: true, mtp: false, fit_summary: 'fits'
+}
+
+const api = vi.fn(async (request: HermesApiRequest): Promise<unknown> => {
+ if (request.path.endsWith('/status')) {
+ return structuredClone(status)
+ }
+
+ if (request.path.endsWith('/catalog')) {
+ return { models: catalog }
+ }
+
+ if (request.path.endsWith('/jobs')) {
+ return { jobs: structuredClone(jobs) }
+ }
+
+ if (request.path.endsWith('/download/pause') || request.path.endsWith('/download/resume')) {
+ expect(request).toMatchObject({ connectionId: 'A', profile: 'work', method: 'POST', body: { job_id: 'same-id' } })
+ const paused: boolean = request.path.endsWith('/pause')
+ jobs = jobs.map((job: LocalRuntimeJob): LocalRuntimeJob => ({ ...job, status: paused ? 'paused' : 'running', can_pause: !paused, can_resume: paused }))
+
+ return paused ? { ok: true, paused: true } : { ok: true, resumed: true }
+ }
+
+ if (request.path.endsWith('/hardware')) {
+ return {}
+ }
+
+ throw new Error(`Unexpected request ${request.path}`)
+})
+
+const controller: ModelMenuController = {
+ current: { model: '', provider: '', effort: '', fast: false },
+ applyPreset: (): void => {},
+ presetFor: (): object => ({}),
+ select: (): void => {},
+ setOptions: (): void => {}
+}
+
+beforeEach((): void => {
+ vi.useFakeTimers()
+ queryClient.clear()
+ jobs = []
+ catalog = []
+ api.mockClear()
+ $connection.set(null)
+ vi.mocked(notify).mockClear()
+ vi.mocked(notifyError).mockClear()
+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } })
+ setApiRequestConnection('A')
+ setApiRequestProfile('work')
+ $activeGatewayProfile.set('work')
+ $localModelsEnabled.set(true)
+})
+afterEach((): void => {
+ cleanup()
+ queryClient.clear()
+ vi.useRealTimers()
+})
+
+async function tick(ms: number = 0): Promise<void> {
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(ms)
+ })
+}
+
+function mountSettings(): RenderResult {
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <I18nProvider>
+ <LocalModelsSettings />
+ </I18nProvider>
+ </MemoryRouter>
+ </QueryClientProvider>
+ )
+}
+
+it('uses one status polling clock across staggered Settings, picker and menu mounts', async (): Promise<void> => {
+ const settings: RenderResult = mountSettings()
+ await tick(400)
+ render(
+ <QueryClientProvider client={queryClient}>
+ <I18nProvider>
+ <ModelPickerDialog
+ currentModel=""
+ currentProvider=""
+ onOpenChange={(): void => {}}
+ onSelect={(): void => {}}
+ open
+ ownerConnectionId="A"
+ profile="work"
+ />
+ </I18nProvider>
+ </QueryClientProvider>
+ )
+ await tick(400)
+ render(
+ <QueryClientProvider client={queryClient}>
+ <I18nProvider>
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <ModelCatalogMenu controller={controller} ownerConnectionId="A" profile="work" />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </I18nProvider>
+ </QueryClientProvider>
+ )
+ await tick(2_000)
+
+ expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status'))).toHaveLength(2)
+ settings.unmount()
+ await tick(2_000)
+ expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status'))).toHaveLength(3)
+ cleanup()
+ await tick(4_000)
+ expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status'))).toHaveLength(3)
+})
+
+it('keeps paused work alive after Settings unmount and isolates late results by owner', async (): Promise<void> => {
+ jobs = [{ ...running, status: 'paused' }]
+ const settings: RenderResult = mountSettings()
+ await tick()
+ settings.unmount()
+ jobs = [running]
+ await tick(3_000)
+ expect(queryClient.getQueryData(localModelsKey({ connectionId: 'A', profile: 'work' }, 'jobs'))).toEqual([running])
+
+ const pending = deferred<{ jobs: LocalRuntimeJob[] }>()
+ api.mockReturnValueOnce(pending.promise)
+ watchLocalRuntimeJobs({ connectionId: 'A', profile: 'work' })
+ setApiRequestConnection('B')
+ jobs = [{ ...running, target: 'Download B' }]
+ watchLocalRuntimeJobs({ connectionId: 'B', profile: 'work' })
+ await tick()
+ pending.resolve({ jobs: [{ ...running, status: 'done' }] })
+ await tick()
+ expect(queryClient.getQueryData(localModelsKey({ connectionId: 'B', profile: 'work' }, 'jobs'))).toEqual(jobs)
+ expect(notify).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(notify).mock.calls[0][0].title).toContain('A / work')
+ jobs = [{ ...running, target: 'Download B', status: 'done' }]
+ watchLocalRuntimeJobs({ connectionId: 'B', profile: 'work' })
+ await tick()
+ expect(notify).toHaveBeenCalledTimes(2)
+ watchLocalRuntimeJobs({ connectionId: 'B', profile: 'work' })
+ await tick()
+ expect(notify).toHaveBeenCalledTimes(2)
+})
+
+it.each(['connection', 'profile'] as const)(
+ 'does not paint a late Settings snapshot after a %s switch',
+ async (change: 'connection' | 'profile'): Promise<void> => {
+ const pending = deferred<LocalModelsStatus>()
+ api.mockReturnValueOnce(pending.promise)
+ const settings: RenderResult = mountSettings()
+ await tick()
+ await act(async (): Promise<void> => {
+ if (change === 'connection') {
+ setApiRequestConnection('B')
+ $connection.set({
+ baseUrl: 'http://B',
+ connectionId: 'B',
+ registryScoped: true,
+ token: '',
+ wsUrl: '',
+ logs: [],
+ isFullscreen: false,
+ nativeOverlayWidth: 0,
+ windowButtonPosition: null
+ })
+ } else {
+ setApiRequestProfile('personal')
+ $activeGatewayProfile.set('personal')
+ }
+
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ await tick()
+ expect(settings.container.textContent).toContain('installed')
+ pending.resolve({ ...status, tag: 'OLD-OWNER' })
+ await tick()
+ expect(settings.container.textContent).not.toContain('OLD-OWNER')
+
+ const expected =
+ change === 'connection' ? { connectionId: 'B', profile: 'work' } : { connectionId: 'A', profile: 'personal' }
+
+ expect(
+ api.mock.calls.some(
+ ([request]): boolean =>
+ request.path.endsWith('/status') &&
+ request.connectionId === expected.connectionId &&
+ request.profile === expected.profile
+ )
+ ).toBe(true)
+ }
+)
+
+it('follows an authoritative route change even when its descriptor is unchanged', async (): Promise<void> => {
+ const hook = renderHook(() => useLocalModelsOwner())
+ expect(hook.result.current.connectionId).toBe('A')
+ await act(async (): Promise<void> => {
+ setApiRequestConnection('B')
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ expect(hook.result.current.connectionId).toBe('B')
+})
+
+it('discards late legacy completions and update notices without invalidating the new catalog', async (): Promise<void> => {
+ setApiRequestConnection(null)
+
+ const connection: HermesConnection = {
+ baseUrl: 'http://A',
+ token: '',
+ wsUrl: '',
+ logs: [],
+ isFullscreen: false,
+ nativeOverlayWidth: 0,
+ windowButtonPosition: null
+ }
+
+ $connection.set(connection)
+ const owner = localModelsOwner()
+ jobs = [running]
+ watchLocalRuntimeJobs(owner)
+ await tick()
+
+ const pendingJobs = deferred<{ jobs: LocalRuntimeJob[] }>()
+ const pendingStatus = deferred<LocalModelsStatus>()
+ api.mockReturnValueOnce(pendingJobs.promise)
+ watchLocalRuntimeJobs(owner)
+ api.mockReturnValueOnce(pendingStatus.promise)
+ const update: Promise<void> = checkLocalRuntimeUpdate(owner)
+ $connection.set({ ...connection, baseUrl: 'http://B' })
+ const key: readonly string[] = ['model-options', 'work', 'global']
+ queryClient.setQueryData(key, { providers: [] })
+ pendingJobs.resolve({ jobs: [{ ...running, status: 'done' }] })
+ pendingStatus.resolve({ ...status, update_available: true })
+ await update
+ await tick()
+ expect(queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(owner, 'jobs'))).toEqual([running])
+ expect(queryClient.getQueryData(localModelsKey(owner, 'status'))).toBeUndefined()
+ // Mutation acknowledgments can refresh directly, without a jobs response.
+ refreshLocalModels(owner)
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ expect(notify).not.toHaveBeenCalled()
+})
+
+it('keeps menu focus and its scalar selection stable across byte updates and outages', async (): Promise<void> => {
+ jobs = [running]
+ let reads: number = 0
+
+ const menuController: ModelMenuController = {
+ ...controller,
+ get current() {
+ reads += 1
+
+ return controller.current
+ }
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <I18nProvider>
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <ModelCatalogMenu controller={menuController} ownerConnectionId="A" profile="work" />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </I18nProvider>
+ </QueryClientProvider>
+ )
+ await tick(1)
+ const input: HTMLElement = screen.getByRole('textbox', { name: 'Search models' })
+ fireEvent.change(input, { target: { value: 'Download' } })
+ input.focus()
+ await tick(1)
+ const before: number = reads
+ jobs = [{ ...running, done_bytes: 2, percent: 75 }]
+ await tick(700)
+ expect(screen.getByText('75%')).toBeTruthy()
+ expect(window.document.activeElement).toBe(input)
+ expect(reads).toBe(before)
+ const key = localModelsKey({ connectionId: 'A', profile: 'work' }, 'jobs')
+ const snapshot = queryClient.getQueryData(key)
+ api.mockRejectedValueOnce(new Error('offline'))
+ await tick(700)
+ expect(queryClient.getQueryData(key)).toBe(snapshot)
+ expect(screen.getByText('75%')).toBeTruthy()
+ expect(window.document.activeElement).toBe(input)
+})
+
+it.each(['model-download', 'quickstart', 'runtime-install'] as const)('%s pause and resume travel through the owner API and publish server truth', async (kind: LocalRuntimeJob['kind']): Promise<void> => {
+ catalog = [model]
+ jobs = [{ ...running, kind, can_pause: true, phase: kind === 'runtime-install' ? 'downloading-runtime' : 'downloading' }]
+ const settings: RenderResult = mountSettings()
+ await tick()
+ fireEvent.click(screen.getByRole('button', { name: /pause/i }))
+ await tick()
+ expect(jobs[0].status).toBe('paused')
+ expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy()
+ expect(screen.getAllByText(/paused/i).length).toBeGreaterThan(0)
+ expect(screen.getAllByRole('progressbar').some((bar: HTMLElement): boolean => bar.getAttribute('aria-valuenow') === '50')).toBe(true)
+ expect(notify).not.toHaveBeenCalled()
+ expect(notifyError).not.toHaveBeenCalled()
+
+ if (kind === 'quickstart') { expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull() }
+ fireEvent.click(screen.getByRole('button', { name: /resume/i }))
+ await tick()
+ expect(jobs[0].status).toBe('running')
+ expect(api.mock.calls.filter(([request]): boolean => request.method === 'POST').map(([request]): string => request.path))
+ .toEqual(['/api/local-models/download/pause', '/api/local-models/download/resume'])
+ jobs = [{ ...jobs[0], status: 'done' }]
+ await tick(3_000)
+ expect(notify).toHaveBeenCalledTimes(1)
+ settings.unmount()
+ watchLocalRuntimeJobs({ connectionId: 'A', profile: 'work' })
+ await tick()
+ expect(notify).toHaveBeenCalledTimes(1)
+ expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status')).length).toBeGreaterThan(1)
+})
diff --cc apps/desktop/src/store/updates.ts
index 19278c8763c,06fedccfe7d..53502b00920
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@@ -106,8 -101,11 +106,11 @@@ function isUpdateToastSnoozed(): boolea
// v4: requires explicit Fast-off session creation and session-scoped Fast edits.
// v5: requires raised WebSocket frame size for large one-shot file.attach.
// v6: requires key-addressed plugins.manage rows (keyless rows render
-// read-only in Capabilities → Plugins).
+// read-only in Settings → Plugins).
- const REQUIRED_BACKEND_CONTRACT = 6
+ // v7: requires JSON-RPC server->client requests for every blocking prompt
+ // (approval/clarify/sudo/secret/vault/MCP setup); a v6 backend's
+ // `<kind>.request` notifications would never render a card.
+ export const REQUIRED_BACKEND_CONTRACT = 7
const SKEW_TOAST_ID = 'backend-contract-skew'
// The contract check runs on every session.resume (applyRuntimeInfo), so
// without a snooze the warning re-popped on every thread the user opened, even
diff --cc gateway/platforms/qqbot/adapter.py
index 63b96b28b28,b7cad9f64b9..9e6d2af0067
--- a/gateway/platforms/qqbot/adapter.py
+++ b/gateway/platforms/qqbot/adapter.py
@@@ -1698,16 -1662,6 +1664,7 @@@ class QQAdapter(OwnAccessPolicyMixin, B
with contextlib.suppress(ValueError, TypeError):
return datetime.fromtimestamp(int(raw) / 1000, tz=timezone.utc)
return datetime.now(tz=timezone.utc)
-
- def _is_duplicate(self, msg_id: str) -> bool:
- now = time.time()
- if len(self._seen_messages) > DEDUP_MAX_SIZE:
- cutoff = now - DEDUP_WINDOW_SECONDS
- self._seen_messages = {k: ts for k, ts in self._seen_messages.items() if ts > cutoff}
- if msg_id in self._seen_messages:
- return True
- self._seen_messages[msg_id] = now
- return False
++
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
diff --cc hermes_cli/backup.py
index b057fd17ea2,a7cf772bd8e..f435741cc22
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@@ -22,32 -22,13 +22,33 @@@ from hermes_constants import
from hermes_state_dbfile import RETIRED_GENERATION_DIR_SUFFIX
from utils import (
_preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,
+ default_new_file_mode,
)
+from hermes_cli.archive_safe import normalize_archive_parts
+from hermes_cli.backup_sqlite import _close_quietly, _safe_copy_db
+from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, profile_root_entry
from hermes_cli.sizefmt import format_bytes as _format_size
+from hermes_cli.backup_restore import (
+ _count_session_rows,
+ _default_new_file_mode,
+ _detect_prefix,
+ _extract_member_atomically,
+ _import_db_member,
+ _safe_restore_db,
+ _validate_backup_zip,
+)
+
logger = logging.getLogger(__name__)
+
+def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:
+ # Shim to stop the old updater doing work until relaunch. None means unknown,
+ # not permission to restore over a database whose holders we did not scan.
+ return None
+
+
# --- Exclusion rules ---
# Where ``hermes backup --quick`` / ``/snapshot`` / the pre-update safety net write state
@@@ -938,301 -941,231 +939,304 @@@ def run_import(args) -> None
db_shrunk.append((rel, before, after))
else:
_extract_member_atomically(zf, member, target, new_file_mode)
- if tighten:
- try:
- os.chmod(target, 0o600)
- except OSError:
- if not external: # external configs are tightened best-effort only
- raise
+ if target.name in _SECRET_FILE_NAMES:
+ os.chmod(target, 0o600)
restored += 1
- restored_external += external
except (PermissionError, OSError) as exc:
- errors.append(f"{label}: {exc}")
+ errors.append(f" {rel}: {exc}")
- if restored % 500 == 0:
- print(f" {restored}/{file_count} files ...")
+ if restored % 500 == 0:
+ print(f" {restored}/{file_count} files ...")
- return restored, restored_external, errors, skipped_runtime, db_shrunk
+ elapsed = time.monotonic() - t0
+ # Summary
+ print()
+ print(f"Import complete: {restored} files restored in {elapsed:.1f}s")
+ print(f" Target: {display_hermes_home()}")
-def run_import(args) -> None:
- """Restore a Hermes backup from a zip file."""
- zip_path = Path(args.zipfile).expanduser().resolve()
- if not zip_path.is_file():
- print(f"Error: File not found: {zip_path}")
- sys.exit(1)
- if not zipfile.is_zipfile(zip_path):
- print(f"Error: Not a valid zip file: {zip_path}")
- sys.exit(1)
- # The restore target is the home the command operates under (the printed "Target:");
- # ``get_default_hermes_root()`` would silently retarget a profile restore at the live root.
- hermes_root = get_hermes_home()
- with zipfile.ZipFile(zip_path, "r") as zf:
- ok, reason = _validate_backup_zip(zf)
- if not ok:
- print(f"Error: {reason}")
- sys.exit(1)
- prefix = _detect_prefix(zf)
- members = [n for n in zf.namelist() if not n.endswith("/")]
- file_count = len(members)
- print(f"Backup contains {file_count} files\nTarget: {display_hermes_home()}")
- if prefix:
- print(f"Detected archive prefix: {prefix!r} (will be stripped)")
- if not args.force and not _confirm_import_overwrite(hermes_root):
- return
- print(f"\nImporting {file_count} files ...")
- hermes_root.mkdir(parents=True, exist_ok=True)
- t0 = time.monotonic()
- restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(
- zf, members, prefix, hermes_root, file_count)
- elapsed = time.monotonic() - t0
- print(f"\nImport complete: {restored} files restored in {elapsed:.1f}s\n Target: {display_hermes_home()}")
if restored_external:
- print(f"\n Restored {restored_external} memory-provider file(s) to "
- f"their original location(s) outside {display_hermes_home()}.")
+ print(
+ f"\n Restored {restored_external} memory-provider file(s) to "
+ f"their original location(s) outside {display_hermes_home()}."
+ )
+
if errors:
- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")
+ print(f"\n Warnings ({len(errors)} files skipped):")
+ for e in errors[:10]:
+ print(e)
+ if len(errors) > 10:
+ print(f" ... and {len(errors) - 10} more")
+
if db_shrunk:
- # The backup predates work that is now overwritten — say so (#100960: twelve sessions
- # disappeared with nothing logged anywhere).
+ # The backup predates work that is now overwritten. Say so: the
+ # reported incident was twelve sessions disappearing with nothing
+ # logged anywhere (issue #100960).
print("\n ⚠ Session data replaced by older backup contents:")
for rel, before, after in db_shrunk:
- print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"
- f" -> {after[0]} / {after[1]}")
- print(" Anything recorded after the backup was taken is not in it. "
- "Recover from a newer backup or snapshot: hermes snapshot list")
+ print(
+ f" {rel}: {before[0]} session(s) / {before[1]} message(s)"
+ f" -> {after[0]} / {after[1]}"
+ )
+ print(
+ " Anything recorded after the backup was taken is not in it. "
+ "Recover from a newer backup or snapshot: hermes snapshot list"
+ )
+
if skipped_runtime:
- _print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "
- f"file(s) (kept this machine's, not the backup's):",
- sorted(skipped_runtime), " ")
- restored_profiles = _restore_profile_wrappers(hermes_root)
+ print(
+ f"\n Preserved {len(skipped_runtime)} runtime state "
+ f"file(s) (kept this machine's, not the backup's):"
+ )
+ for rel in sorted(skipped_runtime)[:10]:
+ print(f" {rel}")
+ if len(skipped_runtime) > 10:
+ print(f" ... and {len(skipped_runtime) - 10} more")
+
+ # Post-import: restore profile wrapper scripts
+ profiles_dir = hermes_root / "profiles"
+ restored_profiles = []
+ if profiles_dir.is_dir():
+ try:
+ from hermes_cli.profiles import (
+ create_wrapper_script, check_alias_collision,
+ _is_wrapper_dir_in_path, _get_wrapper_dir,
+ )
+ for entry in sorted(profiles_dir.iterdir()):
+ if not entry.is_dir():
+ continue
+ profile_name = entry.name
+ # Only create wrappers for directories with config
+ if not (entry / "config.yaml").exists() and not (entry / ".env").exists():
+ continue
+ collision = check_alias_collision(profile_name)
+ if collision:
+ print(f" Skipped alias '{profile_name}': {collision}")
+ restored_profiles.append((profile_name, False))
+ else:
+ wrapper = create_wrapper_script(profile_name)
+ restored_profiles.append((profile_name, wrapper is not None))
+
+ if restored_profiles:
+ created = [n for n, ok in restored_profiles if ok]
+ skipped = [n for n, ok in restored_profiles if not ok]
+ if created:
+ print(f"\n Profile aliases restored: {', '.join(created)}")
+ if skipped:
+ print(f" Profile aliases skipped: {', '.join(skipped)}")
+ if not _is_wrapper_dir_in_path():
+ print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.")
+ print(' Add to your shell config (~/.bashrc or ~/.zshrc):')
+ print(' export PATH="$HOME/.local/bin:$PATH"')
+ except ImportError:
+ # hermes_cli.profiles might not be available (fresh install)
+ if any(profiles_dir.iterdir()):
+ print("\n Profiles detected but aliases could not be created.")
+ print(" Run: hermes profile list (after installing hermes)")
+
+ # Guidance
print()
if not (hermes_root / "hermes-agent").is_dir():
- print("Note: The hermes-agent codebase was not included in the backup.\n"
- " If this is a fresh install, run: hermes update")
+ print("Note: The hermes-agent codebase was not included in the backup.")
+ print(" If this is a fresh install, run: hermes update")
+
if restored_profiles:
+ gw_profiles = [n for n, _ in restored_profiles]
print("\nTo re-enable gateway services for profiles:")
- for pname in restored_profiles:
+ for pname in gw_profiles:
print(f" hermes -p {pname} gateway install")
- _revive_gateway_after_import(hermes_root)
- print("Done. Your Hermes configuration has been restored.")
+ # Bring the restored install to life: the backup may contain bot
+ # tokens and registered cron jobs, but they're inert without a
+ # gateway process. Install/start the service automatically (a
+ # platform-less gateway is a supported mode, so this is safe even
+ # for backups with no messaging config). Best-effort and prompt-free;
+ # failures print a manual fallback and never fail the import.
+ native_default = _get_platform_default_hermes_home()
+ default_has_install = any(
+ (native_default / marker).exists()
+ for marker in ("config.yaml", ".env", "state.db")
+ )
+ # A restore into a sandbox or profile home must not silently install
+ # a second gateway pointed at it — on the default service name that
+ # would shadow or hijack the machine's primary install. Only revive
+ # the service automatically when the restore landed in the default
+ # home, or when no other install exists on this machine.
+ if hermes_root != native_default and default_has_install:
+ print(
+ "\nRestored into a non-default home; leaving the gateway service "
+ "alone to avoid clashing with the install at "
+ f"{native_default}."
+ )
+ print("To start a gateway for this home, run: hermes gateway install")
+ else:
+ try:
+ from hermes_cli.gateway import ensure_gateway_service, _is_service_running
-def _restore_profile_wrappers(hermes_root: Path) -> List[str]:
- """Re-create shell wrapper scripts for restored named profiles; return the profile names seen."""
- profiles_dir = hermes_root / "profiles"
- restored_profiles: list[tuple[str, bool]] = []
- if not profiles_dir.is_dir():
- return []
- try:
- from hermes_cli.profiles import (
- create_wrapper_script, check_alias_collision, _is_wrapper_dir_in_path, _get_wrapper_dir)
- for entry in sorted(profiles_dir.iterdir()):
- if not entry.is_dir() or not any((entry / m).exists() for m in ("config.yaml", ".env")):
- continue # only profiles with config get wrappers
- profile_name = entry.name
- collision = check_alias_collision(profile_name)
- if collision:
- print(f" Skipped alias '{profile_name}': {collision}")
- restored_profiles.append(
- (profile_name, not collision and create_wrapper_script(profile_name) is not None))
- if restored_profiles:
- created = [n for n, ok in restored_profiles if ok]
- skipped = [n for n, ok in restored_profiles if not ok]
- if created:
- print(f"\n Profile aliases restored: {', '.join(created)}")
- if skipped:
- print(f" Profile aliases skipped: {', '.join(skipped)}")
- if not _is_wrapper_dir_in_path():
- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"
- " Add to your shell config (~/.bashrc or ~/.zshrc):\n"
- ' export PATH="$HOME/.local/bin:$PATH"')
- except ImportError: # hermes_cli.profiles unavailable (fresh install)
- if any(profiles_dir.iterdir()):
- print("\n Profiles detected but aliases could not be created.\n"
- " Run: hermes profile list (after installing hermes)")
- return [n for n, _ in restored_profiles]
-
-
-def _revive_gateway_after_import(hermes_root: Path) -> None:
- """Install/start the gateway service after a restore, best-effort and prompt-free.
-
- Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so
- this is safe for any backup); failures print a manual fallback, never fail the import. Only
- revived when the restore landed in the default home or no other install exists: a sandbox or
- profile restore must not install a second gateway on the default service name.
- """
- native_default = _get_platform_default_hermes_home()
- if hermes_root != native_default and any(
- (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):
- print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "
- f"with the install at {native_default}.\n"
- "To start a gateway for this home, run: hermes gateway install")
- return
- try:
- from hermes_cli.gateway import ensure_gateway_service, _is_service_running
- if not _is_service_running():
- print()
- ensure_gateway_service(context="import")
- except Exception:
- print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway install")
+ if not _is_service_running():
+ print()
+ ensure_gateway_service(context="import")
+ except Exception:
+ print("\nStart the gateway to activate cron jobs and messaging:")
+ print(" hermes gateway install")
+ print("Done. Your Hermes configuration has been restored.")
-# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---
-# Critical state files (relative to HERMES_HOME) for quick snapshots; everything else is
-# regeneratable or managed separately (skills, repo, sessions/). Entries may be files OR
-# directories (recursive); missing entries are skipped. Pairing data lives in platform JSON blobs
-# outside state.db, so it is listed explicitly — ``hermes update`` snapshots this set (#15733).
-_QUICK_STATE_FILES = (
- "state.db", "config.yaml", ".env", "auth.json", "cron/jobs.json", "cron/executions.db",
- "gateway_state.json", "channel_directory.json", "channel_aliases.json", "processes.json",
- "gateway/discord_message_recovery.db", # Discord reconnect replay ledger
- # Per-profile user stores, destroyed if the update flow replaces the file and the post-update
- # schema-init re-creates an empty one (#52889). Skipped when outside HERMES_HOME.
- "projects.db", # per-profile project store
- "response_store.db", # gateway conversation history / tool payloads
- "memory_store.db", # holographic memory facts/entities
- "verification_evidence.db", # agent verification audit trail
- "kanban.db", # default board (back-compat <root>/kanban.db)
- "kanban/boards", # non-default boards (workspaces/ + attachments/ skipped as regenerable)
- # Pairing stores (generic + per-platform JSONs outside state.db)
- "pairing", # legacy location (gateway/pairing.py)
- "platforms/pairing", # new location (gateway/pairing.py)
- "feishu_comment_pairing.json", # Feishu comment subscription pairings
-)
+# ---------------------------------------------------------------------------
+# Quick state snapshots (used by /snapshot slash command and hermes backup --quick)
+# ---------------------------------------------------------------------------
-_QUICK_DEFAULT_KEEP = 20
+def create_quick_snapshot(
+ label: Optional[str] = None,
+ hermes_home: Optional[Path] = None,
+ keep: Optional[int] = None,
+ max_file_size: Optional[int] = None,
+) -> Optional[str]:
+ """Create one atomic quick snapshot while holding the shared backup slot."""
+ home = hermes_home or get_hermes_home()
+ with _backup_operation_lock(home):
+ return _create_quick_snapshot_locked(
+ label=label,
+ hermes_home=home,
+ keep=keep,
+ max_file_size=max_file_size,
+ )
-def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:
+def _create_quick_snapshot_locked(
+ label: Optional[str] = None,
+ hermes_home: Optional[Path] = None,
+ keep: Optional[int] = None,
+ max_file_size: Optional[int] = None,
+) -> Optional[str]:
+ """Create a quick state snapshot of critical files.
+
+ Copies STATE_FILES to a timestamped directory under state-snapshots/.
+ Auto-prunes old snapshots beyond the keep limit.
+
+ Args:
+ max_file_size: When set, individual files larger than this many bytes
+ are skipped (with a printed warning) instead of copied. Used by
+ the pre-update safety snapshot so a multi-GB ``state.db`` can
+ never stall ``hermes update`` or silently eat disk — the small
+ pairing/cron/config files the snapshot exists to protect are
+ always captured. ``None`` (default) copies everything, which
+ preserves manual ``/snapshot`` and ``hermes backup --quick``
+ behavior.
+
+ Returns:
+ Snapshot ID (timestamp-based), or None if no files found.
+ """
home = hermes_home or get_hermes_home()
- return home / _QUICK_SNAPSHOTS_DIR
+ root = _quick_snapshot_root(home)
+ def _too_large(path: Path, rel_name: str) -> bool:
+ """True (and warn) when ``path`` exceeds the max_file_size cap."""
+ if max_file_size is None:
+ return False
+ try:
+ size = path.stat().st_size
+ except OSError:
+ return False
+ if size <= max_file_size:
+ return False
+ print(
+ f" ⚠ Snapshot: skipping {rel_name} "
+ f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)"
+ )
+ logger.warning(
+ "Quick snapshot skipped %s: %d bytes exceeds %d byte limit",
+ rel_name,
+ size,
+ max_file_size,
+ )
+ return True
-def create_quick_snapshot(
- label: Optional[str] = None, hermes_home: Optional[Path] = None, keep: Optional[int] = None,
- max_file_size: Optional[int] = None) -> Optional[str]:
- """Create one atomic quick snapshot while holding the shared backup slot."""
- home = hermes_home or get_hermes_home()
- with _backup_operation_lock(home):
- return _create_quick_snapshot_locked(label, home, keep, max_file_size)
+ ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ base_snap_id = f"{ts}-{label}" if label else ts
+ snap_id = base_snap_id
+ suffix = 2
+ while (root / snap_id).exists():
+ snap_id = f"{base_snap_id}-{suffix}"
+ suffix += 1
+ snap_dir = root / snap_id
+ staging_dir = root / f".{snap_id}.{os.getpid()}.partial"
+ shutil.rmtree(staging_dir, ignore_errors=True)
- staging_dir.mkdir(parents=True, exist_ok=False)
++ root.mkdir(parents=True, exist_ok=True, mode=0o700)
++ if os.name != "nt":
++ os.chmod(root, 0o700)
++ staging_dir.mkdir(mode=0o700, exist_ok=False)
+ logger.info("quick snapshot phase=copy status=started id=%s", snap_id)
+ manifest: Dict[str, int] = {} # rel_path -> file size
+ failed_dbs: list[str] = [] # present *.db that could not be snapshotted
+ # #68805: track protected DB files skipped for size — they are snapshot
+ # incompleteness just like a failed copy, so pruning must be suppressed
+ # to preserve the older complete snapshot that may contain the only
+ # recoverable database.
+ oversized_skipped: list[str] = []
-def _quick_snapshot_candidates(home: Path):
- """Yield ``(src, rel_posix, in_dir)`` for every regular file a quick snapshot captures; heavy
- regenerable per-board subtrees (workspaces, attachments) are skipped."""
for rel in _QUICK_STATE_FILES:
src = home / rel
+ if not src.exists():
+ continue
+
if src.is_dir():
- for sub in filter(Path.is_file, src.rglob("*")):
+ # Walk the directory and record each file individually in the
+ # manifest so restore can treat them uniformly. Empty dirs are
+ # skipped (nothing to snapshot).
+ for sub in src.rglob("*"):
+ if not sub.is_file():
+ continue
sub_rel = sub.relative_to(home).as_posix()
+ # Skip heavy, regenerable per-board subtrees (scratch
+ # workspaces and task attachments can be large); we only need
+ # the board databases + their metadata to restore a board.
if "/workspaces/" in f"/{sub_rel}/" or "/attachments/" in f"/{sub_rel}/":
continue
- yield sub, sub_rel, True
- elif src.is_file():
- yield src, rel, False
+ if _too_large(sub, sub_rel):
+ if sub.suffix == ".db":
+ oversized_skipped.append(sub_rel)
+ continue
+ dst = staging_dir / sub_rel
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ # Route SQLite DBs through the WAL-safe backup() path so a
+ # board DB with an open WAL (the gateway may hold it at
+ # snapshot time) is captured consistently.
+ if sub.suffix == ".db":
+ if not _safe_copy_db(sub, dst):
+ failed_dbs.append(sub_rel)
+ print(
+ f" ⚠ Snapshot: SQLite safe copy FAILED for {sub_rel} "
+ f"— file may be locked or corrupted"
+ )
+ if is_zeroed_sqlite_file(sub):
+ print(
+ f" ⚠ Snapshot: {sub_rel} looks ZEROED "
+ f"(no SQLite header; {sub.stat().st_size} bytes of NULs?)"
+ )
+ continue
+ else:
+ shutil.copy2(sub, dst)
+ manifest[sub_rel] = dst.stat().st_size
+ except (OSError, PermissionError) as exc:
+ logger.warning("Could not snapshot %s: %s", sub_rel, exc)
+ continue
+ if not src.is_file():
+ continue
-def _copy_quick_snapshot_files(
- home: Path, staging_dir: Path, max_file_size: Optional[int]
-) -> tuple[Dict[str, int], list[str], list[str]]:
- """Copy every quick-snapshot candidate into *staging_dir*.
+ if _too_large(src, rel):
+ if src.suffix == ".db":
+ oversized_skipped.append(rel)
+ continue
- Returns ``(manifest {rel: size}, failed_dbs, oversized_skipped)``. The last two are snapshot
- incompleteness (#68805): the caller must suppress pruning so the older snapshot that may hold
- the only recoverable DB survives.
- """
- manifest: Dict[str, int] = {}
- failed_dbs: list[str] = []
- oversized_skipped: list[str] = []
- for src, rel, in_dir in _quick_snapshot_candidates(home):
- if max_file_size is not None:
- try:
- size = src.stat().st_size
- except OSError:
- size = None
- if size is not None and size > max_file_size:
- print(f" ⚠ Snapshot: skipping {rel} "
- f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)")
- logger.warning("Quick snapshot skipped %s: %d bytes exceeds %d byte limit", rel, size, max_file_size)
- if src.suffix == ".db":
- oversized_skipped.append(rel)
- continue
dst = staging_dir / rel
dst.parent.mkdir(parents=True, exist_ok=True)
+
try:
- # SQLite DBs go through the WAL-safe backup() path (the gateway may hold the WAL open).
if src.suffix == ".db":
if not _safe_copy_db(src, dst):
failed_dbs.append(rel)
@@@ -1292,41 -1244,23 +1296,55 @@@
}
with open(staging_dir / "manifest.json", "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2)
- _secure_quick_snapshot_tree(root, staging_dir)
- os.replace(staging_dir, root / snap_id)
- # Auto-prune (pre-update callers pass a smaller keep so state.db copies don't accumulate).
- # Skip when a DB failed to capture OR was skipped for size (#68805): the snapshot is
- # incomplete and the older one may hold the only recoverable database.
- if not (failed_dbs or oversized_skipped):
- _prune_oldest(_snapshot_dirs(root), _QUICK_DEFAULT_KEEP if keep is None else keep, shutil.rmtree, "snapshot")
+
++ # Make the staged quick snapshot owner-only before it is published. The
++ # staging directory is private from creation, so copied source modes can
++ # be normalized safely before the final atomic rename exposes the
++ # snapshot. Permission failures are intentionally fatal: publishing a
++ # readable recovery bundle is worse than reporting a failed snapshot.
++ if os.name != "nt":
++ os.chmod(root, 0o700)
++ os.chmod(staging_dir, 0o700)
++ for path in staging_dir.rglob("*"):
++ if path.is_dir():
++ os.chmod(path, 0o700)
++ elif path.is_file():
++ os.chmod(path, 0o600)
++
+ os.replace(staging_dir, snap_dir)
+
+ # Auto-prune. Defaults preserve historical manual /snapshot behavior; callers
+ # with known high-churn safety snapshots (for example pre-update) can pass a
+ # smaller keep value so large state.db copies do not accumulate indefinitely.
+ # #68805 review: skip pruning when a present DB failed to capture OR was
+ # skipped for size — either way the snapshot is incomplete and the older
+ # snapshot may contain the only recoverable database.
+ incomplete = failed_dbs or oversized_skipped
+ if not incomplete:
+ _prune_quick_snapshots(root, keep=_QUICK_DEFAULT_KEEP if keep is None else keep)
else:
if oversized_skipped:
- print(" ⚠ Skipping snapshot prune: DB file(s) skipped for size: " + ", ".join(oversized_skipped))
- logger.warning("Quick snapshot skipped oversized DB file(s): %s", ", ".join(oversized_skipped))
+ print(
+ " ⚠ Skipping snapshot prune: DB file(s) skipped for size: "
+ + ", ".join(oversized_skipped)
+ )
+ logger.warning(
+ "Quick snapshot skipped oversized DB file(s): %s",
+ ", ".join(oversized_skipped),
+ )
logger.warning(
- "Skipping snapshot prune because %d DB(s) failed to capture and/or %d were oversized "
- "— preserving older snapshots as recovery source",
- len(failed_dbs), len(oversized_skipped))
- logger.info("quick snapshot phase=copy status=complete id=%s files=%d bytes=%d",
- snap_id, len(manifest), sum(manifest.values()))
+ "Skipping snapshot prune because %d DB(s) failed to capture "
+ "and/or %d were oversized — preserving older snapshots as "
+ "recovery source",
+ len(failed_dbs), len(oversized_skipped),
+ )
+
+ logger.info(
+ "quick snapshot phase=copy status=complete id=%s files=%d bytes=%d",
+ snap_id,
+ len(manifest),
+ sum(manifest.values()),
+ )
return snap_id
diff --cc hermes_cli/backup_sqlite.py
index 7fa12543228,00000000000..1f0177b1db4
mode 100644,000000..100644
--- a/hermes_cli/backup_sqlite.py
+++ b/hermes_cli/backup_sqlite.py
@@@ -1,102 -1,0 +1,117 @@@
+"""WAL-safe SQLite snapshots. Direct execution needs only the standard library.
+
+Desktop invokes this file before stopping its backend, even when application
+imports cannot load. Full and quick backups use the same SQLite copy operation.
+"""
+import json
+import logging
+import os
+import sqlite3
+import sys
+import tempfile
+import time
+from contextlib import suppress
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+
+class _SQLiteBackupTimeout(RuntimeError):
+ """Raised when a SQLite snapshot remains busy past its deadline."""
+
+
+def _close_quietly(conn: Optional[sqlite3.Connection]) -> None:
+ if conn is not None:
+ with suppress(Exception):
+ conn.close()
+
+
+def _safe_copy_db(src: Path, dst: Path, *, timeout_seconds: float = 10.0) -> bool:
+ """Copy a SQLite database with the backup() API (WAL-safe consistent snapshot).
+
+ Fails closed when no consistent snapshot can be made: copying only the main file loses WAL data.
+ """
+ conn = backup_conn = None
+ try:
++ # sqlite3.connect() creates a missing destination with the process
++ # umask, which is commonly 0022 (0644). Snapshot databases contain
++ # session and tool state, so create the inode owner-only before SQLite
++ # writes its first byte. O_NOFOLLOW also refuses a planted symlink on
++ # platforms that support it. Tighten an existing internal staging
++ # file as well (NamedTemporaryFile callers already create it 0600).
++ if os.name != "nt":
++ open_flags = os.O_WRONLY | os.O_CREAT
++ if hasattr(os, "O_NOFOLLOW"):
++ open_flags |= os.O_NOFOLLOW
++ secure_fd = os.open(dst, open_flags, 0o600)
++ try:
++ os.fchmod(secure_fd, 0o600)
++ finally:
++ os.close(secure_fd)
+ # timeout=0.0 disables sqlite3's implicit busy wait so the progress callback owns the
+ # full locked-source deadline instead of adding the default timeout before each callback.
+ conn = sqlite3.connect(f"{src.resolve().as_uri()}?mode=ro", uri=True, timeout=0.0)
+ backup_conn = sqlite3.connect(str(dst))
+ busy_deadline = time.monotonic() + max(0.0, timeout_seconds)
+
+ def _check_backup_progress(status: int, _remaining: int, _total: int) -> None:
+ nonlocal busy_deadline
+ now = time.monotonic()
+ if status in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):
+ if now >= busy_deadline:
+ raise _SQLiteBackupTimeout(f"database remained locked for {timeout_seconds:g} seconds")
+ else:
+ busy_deadline = now + max(0.0, timeout_seconds)
+
+ conn.backup(backup_conn, pages=256, progress=_check_backup_progress, sleep=0.1)
+ return True
+ except Exception as exc:
+ logger.warning("SQLite safe copy failed for %s: %s", src, exc)
+ # Windows won't remove the partial destination while SQLite still has it open.
+ _close_quietly(backup_conn)
+ backup_conn = None
+ with suppress(OSError):
+ dst.unlink(missing_ok=True)
+ return False
+ finally:
+ _close_quietly(backup_conn)
+ _close_quietly(conn)
+
+
+def preflight_state_db(home: Path) -> dict:
+ """Publish an emergency snapshot; do not prune recovery files on failure."""
+ source = home / "state.db"
+ if not source.exists():
+ return {"path": None, "message": "state.db not found (fresh install?)"}
+ prefix = "state.db.pre-update-emergency-"
+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H-%M-%S-%fZ")
+ destination = home / f"{prefix}{stamp}-{os.getpid()}.bak"
+ fd, name = tempfile.mkstemp(prefix=prefix, suffix=".partial", dir=home)
+ os.close(fd)
+ staged = Path(name)
+ try:
+ if not _safe_copy_db(source, staged):
+ raise RuntimeError("SQLite safe copy failed; previous emergency snapshots were retained")
+ connection = sqlite3.connect(str(staged))
+ try:
+ result = connection.execute("PRAGMA quick_check").fetchall()
+ if result != [("ok",)]:
+ raise RuntimeError(f"SQLite snapshot integrity check failed: {result}")
+ finally:
+ connection.close()
+ size = staged.stat().st_size
+ os.replace(staged, destination)
+ finally:
+ staged.unlink(missing_ok=True)
+ for old in sorted(home.glob(f"{prefix}*.bak"), reverse=True)[2:]:
+ try:
+ old.unlink()
+ except OSError as exc:
+ logger.warning("Could not prune emergency snapshot %s: %s", old, exc)
+ return {"path": str(destination), "bytes": size}
+
+
+if __name__ == "__main__":
+ print(json.dumps(preflight_state_db(Path(sys.argv[1]))))
diff --cc hermes_cli/banner.py
index f5290054fc4,106fd0a6688..44d54b0dcda
--- a/hermes_cli/banner.py
+++ b/hermes_cli/banner.py
@@@ -3,11 -3,12 +3,12 @@@ import jso
import logging
import os
import shutil
-import subprocess
+ import sys
import threading
-import time
from pathlib import Path
-from urllib.parse import urlparse
+from hermes_cli import source_check
+# Historical updater import (tests/compat/old_updater_surface.json). In-tree callers use the owner.
+from hermes_cli.source_check import _github_compare_behind
from hermes_constants import get_hermes_home
from typing import TYPE_CHECKING, Any, Dict, List, Optional
@@@ -245,11 -506,37 +246,37 @@@ def _daemon(name: Optional[str], target
threading.Thread(target=lambda: _quiet(target), name=name, daemon=True).start()
+ def _skip_background_prefetch() -> bool:
+ """True when the banner's background prefetch threads must not start.
+
+ Under pytest the prefetch daemon threads shell out to git (``rev-parse``,
+ ``remote get-url``, the banner's git state) at an arbitrary point after
+ import, and any test that patches the process-wide ``subprocess`` singleton
+ (``patch("subprocess.run")`` / ``patch("subprocess.Popen")``) can record
+ that stray spawn in place of the call it meant to pin. Importing
+ ``tui_gateway.server`` starts this prefetch, which is what flaked
+ tests/tui_gateway/test_subprocess_encoding.py and test_bot_relay_methods.py.
+ Nothing under pytest needs a live update check; tests that exercise the
+ prefetch itself monkeypatch this predicate to False.
+
+ ``PYTEST_CURRENT_TEST`` is only set while a test runs, not during
+ collection-time imports, hence the ``sys.modules`` check as well.
+ """
+ return "PYTEST_CURRENT_TEST" in os.environ or "pytest" in sys.modules
+
+
def prefetch_update_check():
- """Kick off update check in a background daemon thread."""
+ """Kick off update check in a background daemon thread.
+
+ No-op under pytest — see ``_skip_background_prefetch``.
+ """
+ if _skip_background_prefetch():
+ _update_check_done.set()
+ return
+
def _run():
global _update_result
- _update_result = check_for_updates(passive=True)
+ _update_result = source_check.check_for_updates(passive=True).get("behind")
_update_check_done.set()
_daemon(None, _run)
diff --cc hermes_cli/cli_commands_mixin.py
index 5893b56ce34,bca45fcf511..96f46413d7d
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@@ -28,7 -28,8 +28,8 @@@ from rich import box as rich_bo
from rich.markup import escape as _escape
from rich.panel import Panel
-from hermes_constants import display_hermes_home, is_termux as _is_termux_environment
+from hermes_constants import display_hermes_home
+ from hermes_state_ids import new_session_id as mint_session_id
from agent.turn_context import extract_api_content_sidecar
from hermes_cli.browser_connect import (
DEFAULT_BROWSER_CDP_URL, discover_local_cdp_url, find_free_debug_port, is_browser_debug_ready,
diff --cc hermes_cli/install_identity.py
index 6aad8107172,2f25436359a..772bdda3649
--- a/hermes_cli/install_identity.py
+++ b/hermes_cli/install_identity.py
@@@ -81,35 -65,22 +65,23 @@@ def read_or_create_install_id(root: Pat
"""
root = get_default_hermes_root() if root is None else root
path = root / _INSTALL_ID_FILENAME
- existing, mint = _read_existing(path)
- if not mint:
- return existing
- try:
- root.mkdir(parents=True, exist_ok=True)
- # Windows byte-range locks can report a same-process conflict instead of waiting for another
- # thread: serialize threads here, then keep the file lock as the cross-process publication fence.
- with _INSTALL_ID_PUBLICATION_LOCK, _install_id_file_lock(root):
- existing, mint = _read_existing(path)
- if not mint:
- return existing
- atomic_write_text(path, uuid.uuid4().hex + "\n", tmp_prefix=".install_id-", fsync_dir=True, mode=0o600)
- committed = path.read_text(encoding="utf-8").strip().lower()
- return committed if _INSTALL_ID_RE.fullmatch(committed) else None
- except OSError:
- return None
+ # A reader can collide with the first atomic replace on Windows. Serialize
+ # threads before reading, and recheck an unavailable file under the OS lock.
+ with _INSTALL_ID_PUBLICATION_LOCK:
+ existing, _ = _read_existing(path)
+ if existing is not None:
+ return existing # Existing identities remain readable on read-only roots.
+ try:
+ root.mkdir(parents=True, exist_ok=True)
+ with _install_id_file_lock(root):
+ existing, mint = _read_existing(path)
+ if not mint:
+ return existing
- fd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
- handle.write(uuid.uuid4().hex + "\n")
- handle.flush()
- os.fsync(handle.fileno())
- os.replace(tmp_name, path)
- _fsync_directory(root)
- except BaseException:
- with contextlib.suppress(OSError):
- os.unlink(tmp_name)
- raise
-
++ atomic_write_text(path, uuid.uuid4().hex + "\n", tmp_prefix=".install_id-", fsync_dir=True, mode=0o600)
+ committed = path.read_text(encoding="utf-8-sig").strip().lower()
+ return committed if _INSTALL_ID_RE.fullmatch(committed) else None
+ except OSError:
+ return None
def get_install_id(*, cache: dict[str, Optional[str]] | None = None) -> Optional[str]:
diff --cc hermes_cli/local_runtime/supervisor.py
index c4fce24ab61,1f20d1ac9bf..c81d9ae98f6
--- a/hermes_cli/local_runtime/supervisor.py
+++ b/hermes_cli/local_runtime/supervisor.py
@@@ -21,7 -22,8 +22,8 @@@ import urllib.erro
import urllib.request
from pathlib import Path
-from hermes_cli.local_runtime.binaries import server_binary, runtimes_root
+from hermes_cli.local_runtime.binaries import runtimes_root
+ from hermes_cli.local_runtime.processes import spawn_server
logger = logging.getLogger(__name__)
diff --cc hermes_cli/managed_scope.py
index 8398c67cfb2,ef954fb86a2..8bac4f84511
--- a/hermes_cli/managed_scope.py
+++ b/hermes_cli/managed_scope.py
@@@ -99,7 -98,7 +98,7 @@@ def _load_managed_file(name: str, cache
def load_managed_config() -> dict:
"""Parsed managed config.yaml, or {} when absent/malformed (fail-open)."""
- return _load_managed_file("config.yaml", _CONFIG_CACHE, lambda f: yaml.safe_load(f) or {})
- return _load_managed_file("config.yaml", _CONFIG_CACHE, lambda p: yaml.safe_load(p.read_text(encoding="utf-8")) or {})
++ return _load_managed_file("config.yaml", _CONFIG_CACHE, lambda p: yaml.safe_load(p.read_text(encoding="utf-8-sig")) or {})
def load_managed_env() -> Dict[str, str]:
diff --cc hermes_time.py
index bb9651ed1ff,a8cab27d478..417ebdf3114
--- a/hermes_time.py
+++ b/hermes_time.py
@@@ -48,13 -48,15 +48,15 @@@ def _resolve_timezone_name() -> str
if tz_env:
return tz_env
try:
- # Prefer the shared cached raw-config reader (mtime-keyed + libyaml): a direct safe_load of
- # a large config.yaml costs ~100 ms and this ran inside the FIRST system prompt build.
+ # Prefer the shared cached effective-config loader (mtime-keyed + libyaml, managed overlay
+ # included so an administrator can pin ``timezone``): a direct safe_load of a large
+ # config.yaml costs ~100 ms and this ran inside the FIRST system prompt build. The bare
+ # parse is the stdlib-safe fallback for bootstrap consumers without hermes_cli importable.
try:
- from hermes_cli.config import read_raw_config
- cfg = read_raw_config() or {}
+ from hermes_cli.config_effective import load_user_config_effective
+ cfg = load_user_config_effective(get_config_path())
except Exception:
- import yaml
+ import hermes_yaml as yaml
config_path = get_config_path()
cfg = (yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}) if config_path.exists() else {}
if cfg:
diff --cc plugins/google_meet/_jsonfile.py
index 38f9a325dd5,2231df9cee7..b1d224fa260
--- a/plugins/google_meet/_jsonfile.py
+++ b/plugins/google_meet/_jsonfile.py
@@@ -13,18 -12,6 +12,6 @@@ def read_json(path: Path) -> Optional[A
if not path.is_file():
return None
try:
- return json.loads(path.read_text(encoding="utf-8"))
+ return json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
-
-
- def write_json_atomic(path: Path, data: Any, mode: Optional[int] = None) -> None:
- """Write ``json.dumps(data, indent=2)`` via a ``.json.tmp`` sibling + rename; *mode* (e.g.
- ``0o600``) is applied to the temp file so the final file never exists with looser perms."""
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(".json.tmp")
- tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
- if mode is not None:
- with contextlib.suppress(OSError, NotImplementedError): # best-effort on non-POSIX filesystems
- tmp.chmod(mode)
- tmp.replace(path)
diff --cc plugins/google_meet/meet_bot.py
index f6def588076,5abdbfdd130..c6cc2340ff8
--- a/plugins/google_meet/meet_bot.py
+++ b/plugins/google_meet/meet_bot.py
@@@ -22,8 -22,7 +22,8 @@@ from pathlib import Pat
from types import SimpleNamespace
from typing import Optional
+from hermes_cli.browser_runtime import chromium_executable
- from plugins.google_meet._jsonfile import write_json_atomic
+ from utils import atomic_json_write
# Short three-segment code, a lookup URL, or /new. Anything else is rejected.
MEET_URL_RE = re.compile(
diff --cc plugins/google_meet/process_manager.py
index eca48e8ce42,572db16ae80..354d2361ef1
--- a/plugins/google_meet/process_manager.py
+++ b/plugins/google_meet/process_manager.py
@@@ -43,7 -34,7 +44,7 @@@ def _read_active() -> Optional[Dict[str
def _write_active(data: Dict[str, Any]) -> None:
- write_json_atomic(_active_file(), data)
- atomic_json_write(_root() / ".active.json", data)
++ atomic_json_write(_active_file(), data)
def _pid_alive(pid: int) -> bool:
diff --cc plugins/memory/retaindb/__init__.py
index 598d38acd71,b5b236107c5..91548326f19
--- a/plugins/memory/retaindb/__init__.py
+++ b/plugins/memory/retaindb/__init__.py
@@@ -343,10 -343,10 +343,10 @@@ class RetainDBMemoryProvider(MemoryProv
from hermes_constants import get_hermes_home
home = get_hermes_home()
self._queue = _WriteQueue(self._client, home / "retaindb_queue.db")
- soul = (home / "SOUL.md").read_text(encoding="utf-8", errors="replace").strip() if (home / "SOUL.md").exists() else ""
+ soul = (home / "SOUL.md").read_text(encoding="utf-8-sig", errors="replace").strip() if (home / "SOUL.md").exists() else ""
if soul: # seed agent identity from SOUL.md in background
seed = lambda: self._client.seed_agent_identity(self._agent_id, soul, source="soul_md") # noqa: E731
- threading.Thread(target=_quiet, args=("soul seed", seed), name="retaindb-soul-seed", daemon=True).start()
+ spawn_context_thread(_quiet, args=("soul seed", seed), name="retaindb-soul-seed").start()
def system_prompt_block(self) -> str:
project = self._client.project if self._client else "retaindb"
diff --cc pyproject.toml
index 67d039e61fb,4ddeea131d7..966e675c935
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -770,13 -604,16 +778,14 @@@ pm = ["lock.json", "artifact-mirror.jso
[tool.pytest.ini_options]
testpaths = ["tests"]
markers = [
- "integration: marks tests requiring external services (API keys, Modal, etc.)",
- "real_concurrent_gate: opt out of the autouse stub that disables _detect_concurrent_hermes_instances",
- "real_agent_prewarm: opt out of the autouse stub that disables the tui_gateway deferred agent pre-warm timer",
- "real_retry_backoff: opt out of the tests/agent autouse stub that zeroes jittered_backoff",
- "requires_wal: needs the runtime to actually enable SQLite WAL mode (skipped where Hermes falls back to journal_mode=DELETE)",
- "no_isolate: opt out of per-file subprocess isolation (tests share mutable module-level state)",
- "ssh: marks tests requiring a reachable SSH server (skipped in normal CI)",
- "linux_only: exercises Linux-specific behaviour; skipped on other hosts",
- "macos_only: exercises macOS-specific behaviour; skipped on other hosts",
- "windows_only: exercises native-Windows behaviour; skipped on other hosts",
+ "integration: marks tests requiring external services (API keys, Modal, etc.)",
+ "real_concurrent_gate: opt out of the autouse stub that disables _detect_concurrent_hermes_instances",
+ "real_agent_prewarm: opt out of the autouse stub that disables the tui_gateway deferred agent pre-warm timer",
++ "real_retry_backoff: opt out of the tests/agent autouse stub that zeroes jittered_backoff",
+ "requires_wal: needs the runtime to actually enable SQLite WAL mode (skipped where Hermes falls back to journal_mode=DELETE)",
+ "no_isolate: opt out of per-file subprocess isolation (tests share mutable module-level state)",
+ "ssh: marks tests requiring a reachable SSH server (skipped in normal CI)",
+ "platforms(*specs, arch=None, arch_negate=False): run only on hosts matching at least one spec — linux/macos/windows/posix/any, 'not X' negation, optional arch filter",
]
# integration tests take way too long to run in the normal CI environments
addopts = "-m 'not integration'"
diff --cc scripts/run_tests_parallel.py
index 9913c88c32c,5e20caf3cb7..bc9effec2fd
mode 100644,100755..100644
--- a/scripts/run_tests_parallel.py
+++ b/scripts/run_tests_parallel.py
diff --cc tests/agent/test_create_openai_client_ssl_verify.py
index 00000000000,43d82f67baf..1c5ec25147a
mode 000000,100644..100644
--- a/tests/agent/test_create_openai_client_ssl_verify.py
+++ b/tests/agent/test_create_openai_client_ssl_verify.py
@@@ -1,0 -1,46 +1,60 @@@
+ """Regression: keepalive httpx client must honor custom CA bundles for HTTPS providers."""
+
+ import ssl
+
+ import certifi
+ import httpx
+ import pytest
+
+ from agent.ssl_verify import resolve_httpx_verify
+ from run_agent import AIAgent
+
+ _CA_ENV_VARS = ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "HTTPS_PROXY")
+
++# install_truststore() rebinds ssl.SSLContext to the truststore subclass process-wide;
++# explicit-bundle contexts are deliberately built from the ORIGINAL base class (an
++# explicit bundle replaces OS trust). Pin the base class before any resolver call so
++# isinstance checks below assert against real TLS contexts either way.
++try:
++ from truststore._ssl_constants import _original_SSLContext as _AnyTlsContext
++except ImportError: # pragma: no cover - truststore layout changed
++ _AnyTlsContext = ssl.SSLContext
++
+
+ @pytest.fixture
+ def clean_tls_env(monkeypatch):
+ for var in _CA_ENV_VARS:
+ monkeypatch.delenv(var, raising=False)
+
+
-def test_build_keepalive_http_client_uses_hermes_ca_bundle(clean_tls_env, monkeypatch):
- monkeypatch.setenv("HERMES_CA_BUNDLE", certifi.where())
++def test_build_keepalive_http_client_ssl_cert_file_uses_shared_context(clean_tls_env, monkeypatch):
++ # The PM resolver passes a platform context when SSL_CERT_FILE is set
++ # (httpx reads CA env vars before the injected verifier gets control).
++ monkeypatch.setenv("SSL_CERT_FILE", certifi.where())
+ verify = resolve_httpx_verify()
++ assert isinstance(verify, (ssl.SSLContext, _AnyTlsContext))
+ client = AIAgent._build_keepalive_http_client(
+ "https://ollama.example.com/v1", verify=verify,
+ )
+ assert isinstance(client, httpx.Client)
- assert isinstance(client._transport._pool._ssl_context, ssl.SSLContext)
++ assert isinstance(client._transport._pool._ssl_context, (ssl.SSLContext, _AnyTlsContext))
+
+
+ def test_build_keepalive_http_client_honors_per_provider_ssl_ca_cert(clean_tls_env):
++ # An explicit bundle replaces OS trust: the context is an ORIGINAL-class
++ # SSLContext loaded with the bundle, never a truststore-injected subclass.
+ verify = resolve_httpx_verify(ca_bundle=certifi.where())
+ client = AIAgent._build_keepalive_http_client(
+ "https://ollama.example.com/v1", verify=verify,
+ )
+ assert isinstance(client, httpx.Client)
- assert isinstance(client._transport._pool._ssl_context, ssl.SSLContext)
++ assert isinstance(client._transport._pool._ssl_context, _AnyTlsContext)
+
+
+ def test_build_keepalive_http_client_ssl_verify_false(clean_tls_env):
+ verify = resolve_httpx_verify(ssl_verify=False)
+ client = AIAgent._build_keepalive_http_client(
+ "https://ollama.example.com/v1", verify=verify,
+ )
+ assert isinstance(client, httpx.Client)
+ assert client._transport._pool._ssl_context.check_hostname is False
diff --cc tests/agent/test_iron_proxy.py
index 70146e9f02a,995c771f627..0ec628f0d32
--- a/tests/agent/test_iron_proxy.py
+++ b/tests/agent/test_iron_proxy.py
@@@ -5,9 -6,8 +5,9 @@@ config + mappings I/O), the subprocess
(spawn / PID / pid_alive / stop, with subprocess.Popen mocked), and the
docker backend's egress arg builder.
+PM acquisition has real loopback/worker coverage in test_security_consumers.
Live network and the real ``iron-proxy`` binary are NEVER touched. See
- ``tests/test_iron_proxy_e2e.py`` (gated behind a marker) for the real-binary
+ ``tests/agent/test_iron_proxy_e2e.py`` (gated behind a marker) for the real-binary
smoke test.
"""
diff --cc tests/hermes_cli/test_cli_init.py
index b5838532b2e,7bcb49b1639..d5d8c0b57e4
--- a/tests/hermes_cli/test_cli_init.py
+++ b/tests/hermes_cli/test_cli_init.py
@@@ -258,7 -306,7 +308,7 @@@ class TestPromptToolkitTerminalCompatib
The native-Windows arm (``_terminal_may_leak_cpr() is False``, plus
the ``PROMPT_TOOLKIT_NO_CPR`` override that outranks it) lives in
- ``tests/cli/test_cpr_local_leak.py`` under ``platforms("windows")``, where it
- ``tests/hermes_cli/test_cpr_local_leak.py`` under ``windows_only``, where it
++ ``tests/hermes_cli/test_cpr_local_leak.py`` under ``platforms("windows")``, where it
runs against a real Windows console.
"""
from cli import _terminal_may_leak_cpr
diff --cc tests/hermes_cli/test_local_abandoned_requests.py
index 3eec27270ee,eea34600367..8c14258c455
--- a/tests/hermes_cli/test_local_abandoned_requests.py
+++ b/tests/hermes_cli/test_local_abandoned_requests.py
@@@ -202,9 -204,14 +204,11 @@@ def test_reap_orphans_kills_only_our_pa
AccessDenied=_NoSuch,
)
monkeypatch.setitem(__import__("sys").modules, "psutil", fake_psutil)
- monkeypatch.setattr("hermes_cli.local_runtime.supervisor.server_binary",
- lambda install_dir: exe)
-
sup = LlamaServerSupervisor.__new__(LlamaServerSupervisor)
- sup.install_dir = tmp_path
+ sup.binary = exe
sup.proc = None
+ sup._job = None
sup._reap_orphaned_children()
- assert reaped == [300], f"reaped {reaped}; wanted only the orphan (300)"
+ expected = [] if __import__("sys").platform == "win32" else [300]
+ assert reaped == expected # Windows uses retained job handles, never binary scans.
diff --cc tests/hermes_cli/test_local_preset_admission.py
index 599c194f9f1,ce4757d6871..d86b3fa39eb
--- a/tests/hermes_cli/test_local_preset_admission.py
+++ b/tests/hermes_cli/test_local_preset_admission.py
@@@ -79,9 -75,10 +79,10 @@@ def test_supervisor_with_presets_does_n
ini = tmp_path / "presets.ini"
ini.write_text("[allowed]\nmodel = allowed.gguf\nctx-size = 65536\n")
calls = []
- monkeypatch.setattr(supervisor, "server_binary", lambda p: Path("llama-server"))
+ binary = tmp_path / "llama-server"
- monkeypatch.setattr(supervisor.subprocess, "Popen", lambda cmd, **kw: calls.append(cmd) or SimpleNamespace(pid=123))
+ monkeypatch.setattr(supervisor, "spawn_server", lambda cmd, **kw: (calls.append(cmd) or SimpleNamespace(pid=123), None))
+ monkeypatch.setattr(supervisor.LlamaServerSupervisor, "_write_state", lambda self: None)
- sup = supervisor.LlamaServerSupervisor(tmp_path, tmp_path, port=1234, preset_path=ini)
+ sup = supervisor.LlamaServerSupervisor(binary, tmp_path, port=1234, preset_path=ini)
try:
sup._spawn()
finally:
diff --cc tests/hermes_cli/test_psutil_android_extract.py
index 00000000000,fd0fe53f6f9..2596e80c09d
mode 000000,100644..100644
--- a/tests/hermes_cli/test_psutil_android_extract.py
+++ b/tests/hermes_cli/test_psutil_android_extract.py
@@@ -1,0 -1,141 +1,73 @@@
+ """Regression tests for the Android psutil compatibility installer."""
+
+ from __future__ import annotations
+
+ import io
-import shutil
+ import tarfile
+ from pathlib import Path
-from unittest.mock import patch
+
+ import pytest
+
+ from hermes_cli.psutil_android import (
+ MARKER,
- REPLACEMENT,
- PSUTIL_URL,
+ PsutilAndroidInstallError,
+ prepare_patched_psutil_sdist,
+ )
-from hermes_cli import update_cmd
+
+
+ def _add_dir(tf: tarfile.TarFile, name: str) -> None:
+ info = tarfile.TarInfo(name)
+ info.type = tarfile.DIRTYPE
+ info.mode = 0o755
+ tf.addfile(info)
+
+
+ def _add_file(tf: tarfile.TarFile, name: str, content: str) -> None:
+ payload = content.encode("utf-8")
+ info = tarfile.TarInfo(name)
+ info.size = len(payload)
+ info.mode = 0o644
+ tf.addfile(info, io.BytesIO(payload))
+
+
+ def _build_psutil_archive(archive: Path, *, malicious_symlink: bool) -> None:
+ with tarfile.open(archive, "w:gz") as tf:
+ _add_dir(tf, "psutil-7.2.2")
+ if malicious_symlink:
+ link = tarfile.TarInfo("psutil-7.2.2/psutil")
+ link.type = tarfile.SYMTYPE
+ link.linkname = "../../outside"
+ tf.addfile(link)
+ else:
+ _add_dir(tf, "psutil-7.2.2/psutil")
+ _add_file(
+ tf,
+ "psutil-7.2.2/psutil/_common.py",
+ f"{MARKER}\n",
+ )
+
+
+ def test_prepare_patched_psutil_sdist_rejects_symlink_member(tmp_path):
+ """A symlink member must be rejected before any file payload is written."""
+ archive = tmp_path / "evil.tar.gz"
+ _build_psutil_archive(archive, malicious_symlink=True)
+
+ destination = tmp_path / "extract"
+ with pytest.raises(PsutilAndroidInstallError, match="Unsupported archive member type"):
+ prepare_patched_psutil_sdist(archive, destination)
+
+ assert not (tmp_path / "outside" / "_common.py").exists()
+
+
+ def test_prepare_patched_psutil_sdist_rejects_traversal_member(tmp_path):
+ """A ``..`` member must be refused the same way the shared archive guard refuses it
+ (one traversal check for every tar.gz we extract), surfaced as the installer's own error."""
+ archive = tmp_path / "evil.tar.gz"
+ with tarfile.open(archive, "w:gz") as tf:
+ _add_dir(tf, "psutil-7.2.2")
+ _add_file(tf, "psutil-7.2.2/../escaped.py", "x")
+
+ with pytest.raises(PsutilAndroidInstallError, match="Unsafe archive member path"):
+ prepare_patched_psutil_sdist(archive, tmp_path / "extract")
+
+ assert not (tmp_path / "escaped.py").exists()
-
-
-def test_install_psutil_android_compat_uses_patched_tree(tmp_path):
- """Updater path should install from the patched temporary sdist tree."""
- archive = tmp_path / "psutil.tar.gz"
- _build_psutil_archive(archive, malicious_symlink=False)
-
- from hermes_cli import main as hermes_main
-
- captured: dict[str, object] = {}
-
- def fake_urlretrieve(url: str, dest: Path):
- assert url == PSUTIL_URL
- shutil.copyfile(archive, dest)
- return str(dest), None
-
- def fake_run_install(cmd: list[str], *, env=None):
- src_root = Path(cmd[-1])
- captured["cmd"] = cmd
- captured["env"] = env
- captured["common_py"] = (src_root / "psutil" / "_common.py").read_text(
- encoding="utf-8"
- )
-
- with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve), \
- patch.object(hermes_main, "_run_install_with_heartbeat", side_effect=fake_run_install):
- update_cmd._install_psutil_android_compat(
- ["uv", "pip"],
- env={"HERMES_TEST": "1"},
- )
-
- assert captured["cmd"][:4] == ["uv", "pip", "install", "--no-build-isolation"]
- assert captured["env"] == {"HERMES_TEST": "1"}
- assert REPLACEMENT in str(captured["common_py"])
-
-
-def test_install_psutil_android_script_uses_patched_tree(tmp_path, monkeypatch, capsys):
- """Standalone installer script should reuse the same safe patched tree."""
- archive = tmp_path / "psutil.tar.gz"
- _build_psutil_archive(archive, malicious_symlink=False)
-
- import scripts.install_psutil_android as installer
-
- def fake_urlretrieve(url: str, dest: Path):
- assert url == PSUTIL_URL
- shutil.copyfile(archive, dest)
- return str(dest), None
-
- def fake_subprocess_run(cmd: list[str]):
- src_root = Path(cmd[-1])
- patched = (src_root / "psutil" / "_common.py").read_text(encoding="utf-8")
- assert REPLACEMENT in patched
- return type("RunResult", (), {"returncode": 0})()
-
- monkeypatch.setattr(installer.sys, "argv", ["install_psutil_android.py"])
- monkeypatch.setattr(installer, "_resolve_install_cmd", lambda *_args: ["python", "-m", "pip"])
-
- with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve), \
- patch.object(installer.subprocess, "run", side_effect=fake_subprocess_run):
- assert installer.main() == 0
-
- captured = capsys.readouterr()
- assert "psutil installed via Android compatibility shim" in captured.out
diff --cc tests/hermes_cli/test_session_vacuum_config.py
index 67edc392041,08f9e175bd3..ccde41f01cf
--- a/tests/hermes_cli/test_session_vacuum_config.py
+++ b/tests/hermes_cli/test_session_vacuum_config.py
@@@ -72,9 -72,9 +72,9 @@@ def test_shipped_template_does_not_pin_
uncommented ``sessions:`` value there becomes an EXPLICIT user setting that
would freeze the retention defaults. The template must leave them commented
so code defaults (and future flips) apply."""
- import yaml
+ import hermes_yaml as yaml
- template = Path(__file__).resolve().parents[1] / "cli-config.yaml.example"
+ template = Path(__file__).resolve().parents[2] / "cli-config.yaml.example"
data = yaml.safe_load(template.read_text(encoding="utf-8")) or {}
assert "sessions" not in data
diff --cc tests/hermes_cli/test_web_server_profile_unification.py
index 5e1bef076ac,cfb57f20499..f16fd3c8697
--- a/tests/hermes_cli/test_web_server_profile_unification.py
+++ b/tests/hermes_cli/test_web_server_profile_unification.py
@@@ -8,9 -8,10 +8,10 @@@ stays untouched, and the chat PTY env i
"""
import json
from contextlib import contextmanager
+ from pathlib import Path
import pytest
-import yaml
+import hermes_yaml as yaml
import gateway.status as _gw_status
import hermes_cli.config as _cfg_mod
import hermes_cli.web_server_chat as _web_server_chat
diff --cc tests/plugins/platforms/photon/test_inbound.py
index a71c5f4a0da,0bee1d169cf..67fb1adc16a
--- a/tests/plugins/platforms/photon/test_inbound.py
+++ b/tests/plugins/platforms/photon/test_inbound.py
@@@ -152,17 -152,17 +152,17 @@@ async def test_on_inbound_line_dispatch
def test_is_duplicate_window(monkeypatch: pytest.MonkeyPatch) -> None:
adapter = _make_adapter(monkeypatch)
- assert adapter._is_duplicate("id-1") is False
- assert adapter._is_duplicate("id-1") is True
- assert adapter._is_duplicate("id-2") is False
- assert adapter._is_duplicate("id-1") is True # still dup
+ assert adapter._dedup.is_duplicate("id-1") is False
+ assert adapter._dedup.is_duplicate("id-1") is True
+ assert adapter._dedup.is_duplicate("id-2") is False
+ assert adapter._dedup.is_duplicate("id-1") is True # still dup
-def test_check_requirements_without_node(monkeypatch: pytest.MonkeyPatch) -> None:
- # If no node binary on PATH the adapter should refuse to start.
+def test_check_requirements_without_node(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
from plugins.platforms.photon import adapter as adapter_mod
- monkeypatch.setattr(adapter_mod.shutil, "which", lambda _name: None)
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "missing-store"))
assert adapter_mod.check_requirements() is False
diff --cc tests/plugins/test_achievements_plugin.py
index 56ea983835e,0e5fac9e3e3..f9d51fcd2e4
--- a/tests/plugins/test_achievements_plugin.py
+++ b/tests/plugins/test_achievements_plugin.py
@@@ -120,10 -120,10 +120,10 @@@ def _install_fake_session_db(plugin_api
Uses the monkeypatch stashed on ``plugin_api`` by the fixture, so the
``sys.modules['hermes_state']`` swap is auto-restored at test teardown
- and cannot leak into unrelated tests in the same xdist worker.
+ and cannot leak into unrelated tests in the same process.
"""
fake_module = type(sys)("hermes_state")
- fake_module.SessionDB = lambda: fake_db
+ fake_module.SessionDB = lambda **_kw: fake_db
plugin_api._test_monkeypatch.setitem(sys.modules, "hermes_state", fake_module)
diff --cc tests/scripts/desktop_update/test_desktop_update_tcc_heal.py
index 519c856aee1,a9610ed4d12..a661319a958
--- a/tests/scripts/desktop_update/test_desktop_update_tcc_heal.py
+++ b/tests/scripts/desktop_update/test_desktop_update_tcc_heal.py
@@@ -28,12 -28,12 +28,12 @@@ from pathlib import Pat
import pytest
- REPO_ROOT = Path(__file__).resolve().parent.parent
+ REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
POSIX_SH = REPO_ROOT / "scripts" / "desktop-update" / "posix.sh"
-GOOD_STUB = "#!/bin/bash\n# bootable interpreter stub\nexit 0\n"
+GOOD_STUB = "#!/usr/bin/env bash\n# bootable interpreter stub\nexit 0\n"
BAD_STUB = (
- "#!/bin/bash\n"
+ "#!/usr/bin/env bash\n"
"echo \"Fatal Python error: init_fs_encoding: failed to get the Python "
"codec of the filesystem encoding\" >&2\n"
"echo \"ModuleNotFoundError: No module named 'encodings'\" >&2\n"
diff --cc tests/scripts/desktop_update/test_desktop_update_windows_progress.py
index a7c2b704e3a,f9ee92abb53..7a027d6833f
--- a/tests/scripts/desktop_update/test_desktop_update_windows_progress.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_progress.py
@@@ -20,9 -20,9 +20,9 @@@ from urllib.request import urlope
import pytest
-pytestmark = pytest.mark.windows_only
+pytestmark = pytest.mark.platforms("windows")
- REPO_ROOT = Path(__file__).resolve().parent.parent
+ REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
WINDOWS_UPDATE_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
diff --cc tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
index ea599fe84ca,679483a0c18..a53516ddcff
--- a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
@@@ -1,75 -1,131 +1,77 @@@
-"""Regression: the Windows Desktop update hand-off must run through python.exe.
+
-`scripts/desktop-update/windows.ps1` drives `hermes update` for the in-app
-Desktop updater. It used to invoke the update through the venv's
-`venv\\Scripts\\hermes.exe` console-script launcher. On Windows that launcher is
-a real process that keeps `hermes.exe` mapped as its running image and spawns
-`python.exe` as a child. The update ends in `uv pip install -e .`, which rewrites
-the console-script shims -- including the `hermes.exe` the launcher still has
-mapped -- and Windows refuses to replace a file mapped as a running image
-("os error 32"). The rename fallback then defers to next reboot via
-`MOVEFILE_DELAY_UNTIL_REBOOT`, which needs elevation a Desktop-driven update
-does not have, so `uv pip install -e .` exits non-zero, the ZIP fallback repeats
-the same sequence, the desktop build stage is never reached, and the pre-build
-clean has already removed `apps/desktop/release` -- leaving an install whose
-Start Menu shortcut points at a `Hermes.exe` that no longer exists.
-
-Driving the update as `python.exe -m hermes_cli.main update` puts the inherited
-image handle on `python.exe`, which uv never has to replace, so the shim is an
-ordinary unlocked file when uv rewrites it.
-
-This test is source-level because Linux CI cannot execute the PowerShell
-hand-off. The invariant it guards is that every `Invoke-HermesStep` call site
-(the update, its retry, and the desktop rebuild) drives `$pythonExe`, never the
-`$hermesExe` shim. `hermes.exe` may still be *named* in the file for the
-step-2 unlock preflight -- that is a lock probe, not an invocation -- so we
-assert against the invocation sites specifically.
-"""
+
+"""Native launch/result acceptance: real publisher, no checkout-local venv."""
from __future__ import annotations
-import re
+import json
+import os
from pathlib import Path
+import subprocess
+import pytest
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-WINDOWS_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
-
-
-def _read() -> str:
- # windows.ps1 is eol=crlf in .gitattributes, so checkouts materialize
- # CRLF on disk (CI included). Normalize so the SelfTest-block strip's
- # `\n}\n` anchors match regardless of the working-copy line endings.
- return WINDOWS_PS1.read_text(encoding="utf-8").replace("\r\n", "\n")
-
-
-def _handoff_source() -> str:
- """The script with its ``-SelfTest*`` fixture blocks removed.
-
- Those blocks exercise the hand-off machinery deliberately -- the pipe-drain
- fixture runs a synthetic PowerShell step through ``Invoke-HermesStep`` to
- prove the drain cannot deadlock (#90455) -- so they are not update steps
- and the "must drive python.exe" rule does not apply to them. Each exits
- before any venv/desktop machinery runs.
-
- Scoped here rather than allow-listing a target, so the rule stays absolute
- for every real step. The non-greedy match ends at the first closing brace
- at the opening statement's indentation; inner braces are deeper.
- """
- return re.sub(
- r"\n(?P<indent> *)if \(\$SelfTest\w+\) \{.*?\n(?P=indent)\}\n",
- "\n",
- _read(),
- flags=re.S,
- )
-
-
-def test_invoke_hermes_step_calls_drive_python_not_the_shim() -> None:
- source = _handoff_source()
-
- invocations = re.findall(r"Invoke-HermesStep\s+(\$\w+)", source)
- assert invocations, (
- "Expected at least one Invoke-HermesStep call in "
- "scripts/desktop-update/windows.ps1; the update hand-off structure "
- "changed -- update this guard."
- )
-
- offenders = [exe for exe in invocations if exe != "$pythonExe"]
- assert not offenders, (
- "Every Invoke-HermesStep call in scripts/desktop-update/windows.ps1 "
- "must drive $pythonExe, not the hermes.exe shim. Driving the update "
- "through the shim keeps hermes.exe mapped as a running image, so uv's "
- "final shim rewrite fails with os error 32 and the Desktop update can "
- "never complete. Offending target(s): "
- f"{sorted(set(offenders))}."
- )
-
-
-def test_update_invocation_uses_module_entrypoint() -> None:
- source = _read()
-
- assert '@("-m", "hermes_cli.main", "update"' in source, (
- "The update step must invoke `python.exe -m hermes_cli.main update ...` "
- "so the inherited image handle lands on python.exe, which uv never has "
- "to replace."
- )
- assert (
- '@("-m", "hermes_cli.main", "desktop", "--force-build", "--build-only")'
- in source
- ), (
- "The desktop rebuild step must also go through "
- "`python.exe -m hermes_cli.main desktop ...` for the same reason."
- )
-
-
-def test_update_no_longer_invokes_the_hermes_exe_shim() -> None:
- source = _read()
-
- assert "Invoke-HermesStep $hermesExe" not in source, (
- "scripts/desktop-update/windows.ps1 still invokes the update through "
- "the hermes.exe shim (`Invoke-HermesStep $hermesExe`). That is the "
- "exact self-lock this fix removes -- route it through $pythonExe "
- "instead."
- )
+from tests.installation_launcher_fixture import publish_fixture_launcher
- ROOT = Path(__file__).resolve().parents[1]
++ROOT = Path(__file__).resolve().parent.parent.parent.parent
+CLI = """
+import json, os, sys
+from pathlib import Path
+def main():
+ if '--version' in sys.argv:
+ print('Install directory: ' + str(Path(__file__).resolve().parents[1])); return 0
+ if '--help' in sys.argv:
+ print('--keep-stash'); return 0
+ with Path(os.environ['HANDOFF_CALLS']).open('a') as stream:
+ stream.write(json.dumps({'argv': sys.argv[1:], 'cwd': os.getcwd()}) + '\\n')
+ print('Desktop build failed') # no warning-driven second build on PM
+ return int(os.environ['HANDOFF_EXIT'])
+if __name__ == '__main__':
+ sys.exit(main())
+"""
-def test_desktop_relaunch_waits_for_an_in_place_rebuild() -> None:
- source = _read()
- relaunch = re.search(
- r"function Start-DesktopRelaunch \{(?P<body>.*?)\n\}\n\nfunction Invoke-HermesStep",
- source,
- re.DOTALL,
[email protected]('windows')
[email protected]('code', [0, 1, 2])
+def test_pm_handoff_runs_once_and_reports_the_actual_result(tmp_path: Path, code: int) -> None:
+ install = tmp_path / 'checkout with spaces'
+ publish_fixture_launcher(install, CLI)
+ (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n')
+ home = tmp_path / 'profile'; home.mkdir()
+ calls = tmp_path / 'calls.jsonl'
+ result = subprocess.run(
+ ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
+ str(ROOT / 'scripts/desktop-update/windows.ps1'), '-InstallRoot', str(install), '-NoUi'],
+ cwd=tmp_path, env={**os.environ, 'HERMES_HOME': str(home),
+ 'HERMES_RUNTIME_DIR': str(tmp_path / 'empty-store'),
+ 'HANDOFF_CALLS': str(calls), 'HANDOFF_EXIT': str(code)},
+ capture_output=True, text=True, timeout=120,
)
- assert relaunch, "Expected Start-DesktopRelaunch in the Windows hand-off script."
-
- body = relaunch.group("body")
- assert "if (-not $RelaunchExe) { return $false }" in body
- assert "$relaunchDeadline = (Get-Date).AddSeconds(120)" in body
- assert "while (-not (Test-Path -LiteralPath $RelaunchExe))" in body
- assert "if ((Get-Date) -ge $relaunchDeadline)" in body
- assert "Start-Sleep -Milliseconds 500" in body
- assert "[System.Windows.Forms.Application]::DoEvents()" in body
+ assert result.returncode == code, result.stdout + result.stderr
+ assert [json.loads(line) for line in calls.read_text().splitlines()] == [
+ {'argv': ['update', '--yes', '--gateway', '--branch', 'main', '--keep-stash'], 'cwd': str(install)}
+ ]
+ receipt = json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))
+ assert receipt['ok'] == (code == 0)
+ assert not (home / '.hermes-update-in-progress').exists()
+
+
[email protected]('windows')
+def test_earlier_pm_userbin_launcher_is_identity_checked(tmp_path: Path) -> None:
+ home = tmp_path / 'profile'
+ userbin = home / 'bin'; userbin.mkdir(parents=True)
+ root = tmp_path / 'source'
+ launcher = publish_fixture_launcher(root, CLI)
+ external = userbin / launcher.name
+ launcher.rename(external)
+ wrong = tmp_path / 'other'
+ (wrong / 'pm').mkdir(parents=True)
+ (wrong / 'hermes_cli').mkdir()
+ (wrong / 'hermes_cli/_launchers.py').touch()
+ helper = str(ROOT / 'scripts/desktop-update/runtime.ps1').replace("'", "''")
+ for target, expected_code in [(root, 0), (wrong, 1)]:
+ script = f". '{helper}'; try {{ @(Get-HermesRuntimeCommand -InstallRoot '{target}') | ConvertTo-Json -Compress }} catch {{ exit 1 }}"
+ result = subprocess.run(['powershell', '-NoProfile', '-Command', script],
+ env={**os.environ, 'HERMES_HOME': str(home)},
+ capture_output=True, text=True, timeout=45)
+ assert result.returncode == expected_code, result.stdout + result.stderr
+ if expected_code == 0:
+ assert json.loads(result.stdout) == str(external)
diff --cc tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
index a8cc5685d74,e8bd8306d98..922fa28c6cb
--- a/tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
@@@ -1,38 -1,34 +1,38 @@@
-"""Regression tests for Windows desktop-update Unix timestamps.
-
-PowerShell's ``Get-Date -UFormat %s`` is locale-sensitive. Under an ``es-ES``
-culture it can produce a comma decimal separator, and parsing that string with
-``InvariantCulture`` turns a ten-digit Unix timestamp plus fractional seconds
-into a value too large for ``System.Int32``. The detached Windows updater must
-use a locale-independent Unix timestamp API for both marker and result files.
-
-The updater script is not executable on the Linux CI lane, so these tests lock
-the source-level contract and reject the exact broken conversion.
-"""
-
-from __future__ import annotations
+"""The Windows handoff writes numeric Unix seconds under comma-decimal locales."""
+import json
+import os
from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-WINDOWS_UPDATE_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"
-
-
-def test_windows_update_uses_locale_independent_unix_seconds() -> None:
- source = WINDOWS_UPDATE_PS1.read_text(encoding="utf-8")
- safe_expression = "[DateTimeOffset]::UtcNow.ToUnixTimeSeconds()"
- unsafe_expression = "[int][double]::Parse((Get-Date -UFormat %s)"
-
- assert source.count(safe_expression) == 2, (
- "windows.ps1 must use DateTimeOffset Unix seconds for both the "
- "update marker and the finished result timestamp"
- )
- assert unsafe_expression not in source, (
- "windows.ps1 must not parse locale-sensitive Get-Date -UFormat %s "
- "output through System.Int32"
+import shutil
+import subprocess
+import time
+
+import pytest
+
+
[email protected]("windows")
+def test_windows_update_writes_locale_independent_marker_and_result(tmp_path, monkeypatch):
+ shell = shutil.which("powershell.exe")
+ assert shell, "native Windows acceptance requires PowerShell"
- script = Path(__file__).resolve().parents[1] / "scripts/desktop-update/windows.ps1"
++ script = Path(__file__).resolve().parent.parent.parent.parent / "scripts/desktop-update/windows.ps1"
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.delenv("HERMES_UPDATE_STARTED_AT", raising=False)
+ # -SelfTestMarker runs the actual claim and finally/result publication,
+ # but never updates a checkout, waits on Desktop, or launches processes.
+ command = (
+ "[Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo('es-ES'); "
+ "& $env:HERMES_TIMESTAMP_TEST_SCRIPT -InstallRoot $env:HERMES_HOME -NoUi -NoMarkerCleanup -SelfTestMarker"
)
+ started = int(time.time())
+ result = subprocess.run([shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", command],
+ env={**os.environ, "HERMES_TIMESTAMP_TEST_SCRIPT": str(script)},
+ capture_output=True, text=True, timeout=60)
+ finished = int(time.time())
+ assert result.returncode == 0, result.stdout + result.stderr
+ marker = (tmp_path / ".hermes-update-in-progress").read_text(encoding="utf-8-sig").splitlines()
+ receipt = json.loads((tmp_path / ".hermes-update-result.json").read_text(encoding="utf-8-sig"))
+ assert len(marker) == 2 and int(marker[0]) > 0
+ assert started <= int(marker[1]) <= finished
+ assert type(receipt["finished_at"]) is int
+ assert started <= receipt["finished_at"] <= finished
+ assert receipt["exit_code"] == 0
diff --cc tests/scripts/desktop_update/test_desktop_update_windows_ui_delivery.py
index 808b1e74866,3558ee385d8..0e2136fe7a1
--- a/tests/scripts/desktop_update/test_desktop_update_windows_ui_delivery.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_ui_delivery.py
@@@ -15,8 -15,8 +15,8 @@@ from urllib.request import Request, url
import pytest
-pytestmark = pytest.mark.windows_only
+pytestmark = pytest.mark.platforms("windows")
- SCRIPT = Path(__file__).resolve().parents[1] / "scripts/desktop-update/windows.ps1"
+ SCRIPT = Path(__file__).resolve().parents[3] / "scripts/desktop-update/windows.ps1"
@contextmanager
diff --cc tests/scripts/install/test_install_clone_throttle_fallback.py
index 71aff2e78be,973649e8ff9..bcbb4239d68
--- a/tests/scripts/install/test_install_clone_throttle_fallback.py
+++ b/tests/scripts/install/test_install_clone_throttle_fallback.py
@@@ -6,46 -31,105 +6,46 @@@ import subproces
import pytest
- ROOT = Path(__file__).resolve().parents[1]
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-pytestmark = pytest.mark.skipif(
- shutil.which("git") is None or shutil.which("bash") is None,
- reason="needs git and bash",
-)
-
-
-def _https_branch() -> str:
- text = INSTALL_SH.read_text()
- m = re.search(
- r"log_info \"SSH failed, trying HTTPS\.\.\..*?(?=\n fi\n)",
- text,
- re.DOTALL,
- )
- assert m is not None, "HTTPS clone branch not found in install.sh"
- return m.group(0)
-
-
-def test_https_clone_is_retried_with_backoff():
- branch = _https_branch()
- assert re.search(r"for attempt in \$\(seq 1 \"\$max_attempts\"\)", branch), (
- "the HTTPS clone must be retried a bounded number of times, with the "
- "loop bound driven by the same variable the messages report"
- )
- assert re.search(r"sleep \$\(\(attempt \* 5\)\)", branch), (
- "retries must back off between attempts"
- )
- # A failed direct attempt leaves a partial clone; it must be removed
- # before the next attempt or git refuses to clone into a non-empty dir.
- assert re.search(
- r"rm -rf \"\$INSTALL_DIR\" 2>/dev/null # partial clone is unusable",
- branch,
- ), "each failed direct attempt must clean up the partial clone"
-
-
-def test_blobless_partial_clone_fallback_exists():
- branch = _https_branch()
- assert "--filter=blob:none" in branch, (
- "after direct attempts fail, degrade to a blobless partial clone "
- "(many small packs — what gets past the repo-scoped 429)"
- )
- assert re.search(
- r"git clone --depth 1 --single-branch --filter=blob:none \\\n"
- r"\s*--no-checkout --branch \"\$BRANCH\"",
- branch,
- ), (
- "the partial clone must defer the checkout (--no-checkout): the blob "
- "fetch otherwise runs inside git clone's own checkout step, the "
- "throttle kills the whole clone, and the fallback never engages"
- )
- assert re.search(r"git reset --hard HEAD", branch), (
- "the partial clone's working tree must be materialized so the rest "
- "of the installer sees the normal files"
- )
-
-
-def test_materialization_fails_closed():
- """A failed blob materialization must not report a successful clone.
-
- The reset on a --no-checkout clone is the step that fetches the blobs,
- so it is the step most likely to be throttled. `|| true` plus an
- unconditional `clone_ok=true` would hand the rest of the installer a
- half-materialized tree while printing "Cloned via HTTPS".
- """
- branch = _https_branch()
- fallback = branch.split('log_info "Direct clone throttled')[1]
- assert "|| true" not in fallback, (
- "the materialization retry must not swallow a hard failure"
- )
- m = re.search(
- r"if \(cd \"\$INSTALL_DIR\" \\\n"
- r"\s*&& \(git reset --hard HEAD",
- fallback,
- )
- assert m is not None, (
- "the reset must be guarded: its success is the condition that sets "
- "clone_ok, and a failed reset must clean up the checkout"
- )
-
-
-def test_partial_clone_failure_still_cleans_up_and_exits():
- branch = _https_branch()
- m = re.search(
- r'if \[ "\$clone_ok" = true \]; then\n\s*log_success "Cloned via HTTPS"'
- r"\n\s*else\n\s*log_error \"Failed to clone repository\"\n\s*exit 1",
- branch,
- )
- assert m is not None, (
- "when the fallback also fails the installer must still report the "
- "failure and exit 1"
- )
-
-
-def test_fallback_runs_only_after_all_direct_attempts_fail():
- branch = _https_branch()
- direct = branch.split('log_info "Direct clone throttled')[0]
- assert re.search(r"clone_ok != true|clone_ok\" != true", direct), (
- "the blobless fallback must be gated on every direct attempt having "
- "failed — a successful direct clone must never take the fallback path"
- )
++ROOT = Path(__file__).resolve().parent.parent.parent.parent
+
+
[email protected]("materialize_fails", [False, True])
+def test_clone_retries_and_publishes_only_materialized_tree(tmp_path, materialize_fails):
+ origin = tmp_path / "origin"
+ origin.mkdir()
+ def git(*args):
+ return subprocess.run(["git", "-C", str(origin), *args], check=True, capture_output=True, text=True)
+ git("init", "-b", "main")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "Fixture")
+ (origin / "README").write_text("complete checkout\n")
+ git("add", "README")
+ git("commit", "-m", "fixture")
+ dest = tmp_path / "install"
+ attempts = tmp_path / "attempts"
+ env = dict(os.environ, HOME=tmp_path.as_posix(), HERMES_HOME=(tmp_path / "home").as_posix(),
+ HERMES_INSTALL_DIR=dest.as_posix(), HERMES_REPO_URL=origin.as_posix())
+ # Inject throttling at the network boundary; the fallback and checkout use real Git.
+ script = f'''source {shlex.quote((ROOT / 'scripts/install.sh').as_posix())} --manifest
+sleep() {{ :; }}
+git() {{
+ if [ "$1" = clone ]; then
+ printf '%s\\n' "$*" >> {shlex.quote(attempts.as_posix())}
+ case " $* " in *" --filter=blob:none "*) ;; *) return 1 ;; esac
+ fi
+ if [ "{int(materialize_fails)}" = 1 ] && [ "${{3:-}}" = reset ]; then return 1; fi
+ command git "$@"
+}}
+stage_repository
+'''
+ result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=30)
+ calls = attempts.read_text().splitlines()
+ assert len([x for x in calls if "--filter=blob:none" not in x]) > 1
+ assert "--no-checkout" in calls[-1]
+ if materialize_fails:
+ assert result.returncode != 0
+ assert not dest.exists()
+ else:
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert (dest / "README").read_text() == "complete checkout\n"
+ assert not list(tmp_path.glob(".hermes-clone-*"))
diff --cc tests/scripts/install/test_install_ps1_managed_python_provenance.py
index c61d912a4c1,2678bec980a..74792ea0070
--- a/tests/scripts/install/test_install_ps1_managed_python_provenance.py
+++ b/tests/scripts/install/test_install_ps1_managed_python_provenance.py
@@@ -8,67 -10,260 +8,67 @@@ import sy
import pytest
-from tests.install_ps1_fake_uv import compile_fake_uv
-
+pytestmark = pytest.mark.platforms("windows")
- INSTALLER = Path(__file__).resolve().parents[1] / "scripts" / "install.ps1"
++INSTALLER = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-pytestmark = pytest.mark.windows_only
-_INSTALL_PS1 = Path(__file__).resolve().parents[3] / "scripts" / "install.ps1"
-
-
-def test_fresh_install_manifest_orders_repo_before_checkout_scoped_python(
- tmp_path: Path,
-) -> None:
[email protected]("stage,exit_code", [("venv", 0), ("python-deps", 0), ("python-deps", 17)])
+def test_python_stage_delegates_to_pin_without_touching_existing_env(tmp_path, stage, exit_code):
powershell = shutil.which("powershell")
- if not powershell:
- pytest.skip("Windows PowerShell is required")
-
- install_dir = tmp_path / "install"
- run = subprocess.run(
- [
- powershell,
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(_INSTALL_PS1),
- "-Manifest",
- "-HermesHome",
- str(tmp_path / "hermes-home"),
- "-InstallDir",
- str(install_dir),
- ],
- cwd=tmp_path,
- capture_output=True,
- text=True,
- check=False,
- timeout=45,
+ assert powershell
+ install = tmp_path / "install with spaces"
+ package = install / "pm"
+ package.mkdir(parents=True)
+ (package / "lock.json").write_text(json.dumps({"packages": {"python": {"version": "3.12.8+fixture"}}}), encoding="utf-8")
+ (package / "__init__.py").write_text("", encoding="utf-8")
+ (package / "cli.py").write_text(
+ "import json, os, pathlib, sys\n"
+ "assert not pathlib.Path(os.environ['UV_BUSY']).exists()\n"
+ "pathlib.Path(os.environ['PM_LOG']).write_text(json.dumps(sys.argv[1:]))\n"
+ "sys.exit(int(os.environ['PROBE_EXIT']))\n", encoding="utf-8",
)
-
- assert run.returncode == 0, run.stdout + run.stderr
- manifest = json.loads(run.stdout)
- stages = [stage["name"] for stage in manifest["stages"]]
- assert (
- stages.index("repository")
- < stages.index("python")
- < stages.index("venv")
- )
- assert not install_dir.exists(), "manifest lookup must remain read-only"
-
-
-def _run_venv_stage(
- powershell: str,
- tmp_path: Path,
- hermes_home: Path,
- install_dir: Path,
- env: dict[str, str],
-) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [
- powershell,
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(_INSTALL_PS1),
- "-Stage",
- "venv",
- "-HermesHome",
- str(hermes_home),
- "-InstallDir",
- str(install_dir),
- ],
- cwd=tmp_path,
- env=env,
- capture_output=True,
- text=True,
- check=False,
- timeout=45,
- )
-
-
-def test_venv_stage_rejects_third_party_python_and_uses_managed_path(
- tmp_path: Path,
-) -> None:
- powershell = shutil.which("powershell")
- if not powershell:
- pytest.skip("Windows PowerShell is required")
-
- hermes_home = tmp_path / "hermes-home"
- install_dir = tmp_path / "install"
- managed_root = install_dir / ".hermes-runtime" / "python"
- managed_python = managed_root / "cpython-3.11" / "python.exe"
- third_party = tmp_path / "KiCad" / "bin" / "python.exe"
- log = tmp_path / "uv.log"
- uv = hermes_home / "bin" / "uv.exe"
- uv.parent.mkdir(parents=True)
- install_dir.mkdir()
- managed_python.parent.mkdir(parents=True)
- third_party.parent.mkdir(parents=True)
- third_party.write_text("fake", encoding="ascii")
- compile_fake_uv(powershell, uv)
- shutil.copy2(uv, managed_python)
-
- env = {
- **os.environ,
- "FAKE_UV_LOG": str(log),
- "FAKE_MANAGED_PYTHON": str(managed_python),
- "FAKE_THIRD_PARTY_PYTHON": str(third_party),
- "UV_PYTHON": str(third_party),
- "UV_NO_MANAGED_PYTHON": "1",
- "UV_SYSTEM_PYTHON": "1",
- }
- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)
- installer_stdout = run.stdout
- installer_stderr = run.stderr
- frames = [
- json.loads(line) for line in installer_stdout.splitlines() if line.startswith("{")
+ existing = install / "venv" / "sentinel"
+ existing.parent.mkdir()
+ existing.write_text("previous generation", encoding="utf-8")
+ log = tmp_path / "uv-calls.jsonl"
+ pm_log = tmp_path / "pm-call.json"
+ wrapper = tmp_path / "boundary.ps1"
+ wrapper.write_text(r'''
+param([string]$Installer, [string]$InstallDir, [string]$HomeDir, [string]$Log)
+$ErrorActionPreference = 'Stop'
+function uv {
+ Set-Content -Path $env:UV_BUSY -Value 'running'
+ try {
+ ConvertTo-Json -Compress -InputObject @($args) | Add-Content -Encoding UTF8 $Log
+ switch ($args[1]) {
+ 'install' { }
+ 'find' { Write-Output $env:BOOTSTRAP_PYTHON }
+ default { throw 'PM must not be a child of the bootstrap uv' }
+ }
+ $global:LASTEXITCODE = 0
+ } finally { Remove-Item $env:UV_BUSY }
+}
+function Invoke-WebRequest { throw 'network access outside test boundary' }
+. $Installer -InstallDir $InstallDir -HermesHome $HomeDir
+# Dot-sourcing defines Get-Uv, so override only that acquisition boundary.
+function Get-Uv { return 'uv' }
+Invoke-StageByName $env:PROBE_STAGE
+exit $LASTEXITCODE
+''', encoding="utf-8-sig")
+ # uv python find returns the distribution interpreter, not a venv launcher.
+ env = dict(os.environ, PROBE_STAGE=stage, PROBE_EXIT=str(exit_code), BOOTSTRAP_PYTHON=sys._base_executable,
+ PM_LOG=str(pm_log), UV_BUSY=str(tmp_path / "uv-busy"), PATHEXT=".COM;.EXE;.BAT;.CMD")
+ env.pop("PYTHONPATH", None)
+ run = subprocess.run([powershell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(wrapper),
+ "-Installer", str(INSTALLER), "-InstallDir", str(install), "-HomeDir", str(tmp_path / "home"), "-Log", str(log)],
+ cwd=tmp_path, env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, timeout=120)
+ assert (run.returncode == 0) == (exit_code == 0), run.stdout + run.stderr
+ assert [json.loads(line) for line in log.read_text(encoding="utf-8-sig").splitlines()] == [
+ ["python", "install", "--no-bin", "3.12"], ["python", "find", "--managed-python", "--no-project", "3.12"],
]
- assert run.returncode == 0, installer_stdout + installer_stderr
- assert frames[-1]["ok"] is True
- commands = log.read_text(encoding="utf-8").splitlines()
- assert any(
- command.startswith("python find 3.11") and "--managed-python" in command
- for command in commands
- )
- venv_command = next(command for command in commands if command.startswith("venv venv"))
- assert f"--python {managed_python}" in venv_command
- assert "--managed-python" in venv_command
- assert "--no-python-downloads" in venv_command
-
-
-def test_fallback_minor_is_reported_from_resolved_managed_interpreter(
- tmp_path: Path,
-) -> None:
- powershell = shutil.which("powershell")
- if not powershell:
- pytest.skip("Windows PowerShell is required")
-
- hermes_home = tmp_path / "hermes-home"
- install_dir = tmp_path / "install"
- managed_python = (
- install_dir / ".hermes-runtime" / "python" / "cpython-3.12" / "python.exe"
- )
- uv = hermes_home / "bin" / "uv.exe"
- uv.parent.mkdir(parents=True)
- managed_python.parent.mkdir(parents=True)
- install_dir.mkdir(exist_ok=True)
- compile_fake_uv(powershell, uv)
- shutil.copy2(uv, managed_python)
- env = {
- **os.environ,
- "FAKE_UV_LOG": str(tmp_path / "uv.log"),
- "FAKE_MANAGED_PYTHON": str(managed_python),
- "FAKE_MANAGED_PYTHON_VERSION": "3.12",
- "FAKE_PYTHON_VERSION": "Python 3.12.13",
- }
-
- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)
-
- assert run.returncode == 0, run.stdout + run.stderr
- assert "Creating virtual environment with Python 3.12" in run.stdout
- assert "Virtual environment ready (Python 3.12)" in run.stdout
- created_python = install_dir / "venv" / "Scripts" / "python.exe"
- version = subprocess.run(
- [str(created_python), "--version"],
- env=env,
- capture_output=True,
- text=True,
- check=True,
- )
- assert version.stdout.strip() == "Python 3.12.13"
-
-
-def test_python_find_drains_large_stderr_without_deadlock(tmp_path: Path) -> None:
- powershell = shutil.which("powershell")
- if not powershell:
- pytest.skip("Windows PowerShell is required")
-
- hermes_home = tmp_path / "hermes-home"
- install_dir = tmp_path / "install"
- managed_python = (
- install_dir / ".hermes-runtime" / "python" / "cpython-3.11" / "python.exe"
- )
- uv = hermes_home / "bin" / "uv.exe"
- uv.parent.mkdir(parents=True)
- managed_python.parent.mkdir(parents=True)
- compile_fake_uv(powershell, uv)
- shutil.copy2(uv, managed_python)
- env = {
- **os.environ,
- "FAKE_UV_LOG": str(tmp_path / "uv.log"),
- "FAKE_MANAGED_PYTHON": str(managed_python),
- "FAKE_UV_FIND_STDERR_BYTES": str(1024 * 1024),
- }
-
- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)
-
- assert run.returncode == 0, run.stdout + run.stderr
- assert "Creating virtual environment with Python 3.11" in run.stdout
-
-
-def test_python_find_timeout_kills_uv_and_fails_stage(tmp_path: Path) -> None:
- powershell = shutil.which("powershell")
- if not powershell:
- pytest.skip("Windows PowerShell is required")
-
- hermes_home = tmp_path / "hermes-home"
- install_dir = tmp_path / "install"
- uv = hermes_home / "bin" / "uv.exe"
- uv.parent.mkdir(parents=True)
- install_dir.mkdir()
- compile_fake_uv(powershell, uv)
- env = {
- **os.environ,
- "FAKE_UV_LOG": str(tmp_path / "uv.log"),
- "FAKE_UV_FIND_DELAY_MS": "60000",
- }
-
- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)
-
- assert run.returncode != 0
- assert "uv python find 3.11 timed out after 30000 ms" in (run.stdout + run.stderr)
-
-
-def test_venv_failure_fails_stage_and_restores_existing_environment(
- tmp_path: Path,
-) -> None:
- powershell = shutil.which("powershell")
- if not powershell:
- pytest.skip("Windows PowerShell is required")
-
- hermes_home = tmp_path / "hermes-home"
- install_dir = tmp_path / "install"
- managed_python = (
- install_dir / ".hermes-runtime" / "python" / "cpython-3.11" / "python.exe"
- )
- old_python = install_dir / "venv" / "Scripts" / "python.exe"
- uv = hermes_home / "bin" / "uv.exe"
- for directory in (uv.parent, managed_python.parent, old_python.parent):
- directory.mkdir(parents=True, exist_ok=True)
- old_python.write_text("previous environment", encoding="ascii")
- compile_fake_uv(powershell, uv)
- shutil.copy2(uv, managed_python)
- env = {
- **os.environ,
- "FAKE_UV_LOG": str(tmp_path / "uv.log"),
- "FAKE_MANAGED_PYTHON": str(managed_python),
- "FAKE_UV_VENV_EXIT": "37",
- }
-
- run = _run_venv_stage(powershell, tmp_path, hermes_home, install_dir, env)
-
- assert run.returncode != 0
- assert "Failed to create virtual environment (uv venv exited with 37)" in (
- run.stdout + run.stderr
- )
- assert old_python.read_text(encoding="ascii") == "previous environment"
- frames = [json.loads(line) for line in run.stdout.splitlines() if line.startswith("{")]
- assert frames[-1]["ok"] is False
+ if stage == "python-deps":
+ assert json.loads(pm_log.read_text(encoding="utf-8-sig")) == ["install"]
+ else:
+ assert not pm_log.exists()
+ assert existing.read_text(encoding="utf-8-sig") == "previous generation"
diff --cc tests/scripts/install/test_install_sh_node_tarball_without_xz.py
index a10c270680f,24c02cce79e..9d933b81d5c
--- a/tests/scripts/install/test_install_sh_node_tarball_without_xz.py
+++ b/tests/scripts/install/test_install_sh_node_tarball_without_xz.py
@@@ -12,27 -16,46 +12,30 @@@ from pathlib import Pat
import pytest
+from pm.packages import Nodejs
+from pm.store import current_target
+
+ REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
+ INDEX = "node-v26.7.0-linux-x64.tar.xz\nnode-v26.7.0-linux-x64.tar.gz\n"
+
-def _function(path: Path, name: str) -> str:
- match = re.search(rf"^{re.escape(name)}\(\) \{{\n.*?^\}}\n", path.read_text(encoding="utf-8"), re.M | re.S)
- assert match, f"{name}() not found in {path}"
- return match.group(0)
-
-
-def _selected_tarball(tmp_path: Path, *, with_xz: bool, script: Path, fn: str, call: str) -> str:
- """Run the real tarball-selection function with curl stubbed to serve INDEX; the download step
- records the chosen name and aborts, so nothing is extracted."""
- bin_dir = tmp_path / ("bin-xz" if with_xz else "bin-noxz")
- bin_dir.mkdir()
- curl = bin_dir / "curl"
- curl.write_text("#!/bin/sh\nfor a in \"$@\"; do [ \"$a\" = -o ] && { echo \"$4\" >> \"$PICKED\"; exit 1; }; done\n"
- f"printf '%s' '{INDEX}'\n", encoding="utf-8")
- curl.chmod(curl.stat().st_mode | stat.S_IXUSR)
- # PATH holds only this dir: the host's real xz must not leak into the "no xz" arm.
- for tool in ("grep", "head", "mktemp", "rm", "uname", "sh", "printf"):
- real = shutil.which(tool)
- if real:
- os.symlink(real, bin_dir / tool)
- if with_xz:
- (bin_dir / "xz").write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
- (bin_dir / "xz").chmod(0o755)
- picked = tmp_path / f"picked-{with_xz}-{fn}"
- harness = ("log_info() { :; }; log_warn() { :; }; _nb_log() { :; }; _nb_warn() { :; }\n"
- "HERMES_NODE_TARGET_MAJOR=26\n" + _function(script, fn) + call)
- env = {"PATH": str(bin_dir), "PICKED": str(picked), "HOME": str(tmp_path)}
- subprocess.run([shutil.which("bash") or "/bin/bash", "-c", harness], env=env, check=False, capture_output=True)
- return picked.read_text(encoding="utf-8").strip() if picked.exists() else ""
-
-
[email protected]("script, fn, call", [
- (REPO_ROOT / "scripts" / "install.sh", "install_node_line", "\ninstall_node_line 26 linux x64\n"),
- (REPO_ROOT / "scripts" / "lib" / "node-bootstrap.sh", "_nb_install_bundled_node", "\n_nb_install_bundled_node\n"),
-])
-def test_tarball_format_follows_xz_availability(tmp_path: Path, script: Path, fn: str, call: str) -> None:
- assert _selected_tarball(tmp_path, with_xz=True, script=script, fn=fn, call=call).endswith(".tar.xz")
- assert _selected_tarball(tmp_path, with_xz=False, script=script, fn=fn, call=call).endswith(".tar.gz")
[email protected]("linux", "macos")
+def test_node_archive_unpacks_without_host_xz(tmp_path: Path, monkeypatch) -> None:
+ package = Nodejs()
+ target = current_target()
+ version = "26.7.0"
+ archive = tmp_path / Path(package.fetch_url(version, target)).name
+ payload = b"node fixture bytes\n"
+ with tarfile.open(archive, "w:xz") as writer:
+ member = tarfile.TarInfo(f"node-v{version}/{package.binary_rel['posix']}")
+ member.size = len(payload)
+ member.mode = 0o755
+ writer.addfile(member, io.BytesIO(payload))
+
+ empty_path = tmp_path / "empty-bin"
+ empty_path.mkdir()
+ monkeypatch.setenv("PATH", str(empty_path))
+ assert shutil.which("xz") is None
+ staged = tmp_path / "staged"
+ package.unpack(archive, staged, target)
+ assert (staged / f"node-v{version}" / "bin/node").read_bytes() == payload
diff --cc tests/scripts/install/test_install_sh_reuse_supported_python.py
index e809344c763,d5f477d1fa7..f1048484ce7
--- a/tests/scripts/install/test_install_sh_reuse_supported_python.py
+++ b/tests/scripts/install/test_install_sh_reuse_supported_python.py
@@@ -16,83 -10,43 +16,83 @@@ import ven
import pytest
- ROOT = Path(__file__).resolve().parents[1]
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-
-
-def _exe(path: Path, content: str) -> Path:
- path.write_text(content, encoding="utf-8")
- path.chmod(path.stat().st_mode | stat.S_IXUSR)
- return path
++ROOT = Path(__file__).resolve().parent.parent.parent.parent
+INSTALL_SH = ROOT / "scripts/install.sh"
+pytestmark = pytest.mark.platforms("posix")
-def _run_prerequisites(tmp_path: Path, *, uv_find_script: str) -> subprocess.CompletedProcess[str]:
- """Run the real ``--stage prerequisites`` with a stub managed uv whose ``python find`` we script."""
- home = tmp_path / "home"
- hermes_home = home / ".hermes"
- (hermes_home / "bin").mkdir(parents=True)
+def _environment(tmp_path: Path) -> tuple[Path, Path, dict[str, str]]:
+ core = tmp_path / "checkout"
+ (core / "pm").mkdir(parents=True)
+ version = f"{sys.version_info.major}.{sys.version_info.minor}"
+ (core / "pm/lock.json").write_text(json.dumps(
+ {"packages": {"python": {"version": version}}}, indent=2), encoding="utf-8")
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
- _exe(bin_dir / "python3.13", "#!/bin/sh\n[ \"$1\" = --version ] && echo 'Python 3.13.12'\nexit 0\n")
- _exe(hermes_home / "bin" / "uv", "#!/bin/sh\n[ \"$1\" = --version ] && { echo 'uv 0.9.0'; exit 0; }\n"
- "if [ \"$1\" = python ] && [ \"$2\" = find ]; then\n" + uv_find_script + "fi\n"
- "if [ \"$1\" = python ] && [ \"$2\" = install ]; then echo 'DOWNLOAD ATTEMPTED' >&2; exit 1; fi\nexit 0\n")
- for tool in ("git", "node", "npm", "curl", "rg", "g++", "c++"):
- _exe(bin_dir / tool, "#!/bin/sh\ncase \"$1\" in --version|-v) echo 'v22.12.0 2.50.0';; esac\nexit 0\n")
- env = os.environ.copy()
- env.update({"HOME": str(home), "HERMES_HOME": str(hermes_home),
- "PATH": f"{bin_dir}{os.pathsep}{env.get('PATH', os.defpath)}"})
- bash = shutil.which("bash") or "/bin/bash"
- return subprocess.run([bash, str(INSTALL_SH), "--stage", "prerequisites", "--non-interactive"],
- env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False)
-
-
-def test_supported_newer_python_is_reused_instead_of_downloading_311(tmp_path: Path) -> None:
- """3.11 absent, 3.13 present: the installer must take 3.13 and never call ``uv python install``."""
- result = _run_prerequisites(tmp_path, uv_find_script=(
- # The range probe must carry --system: with the install's own venv activated, a plain
- # `uv python find` returns venv/bin/python3, which setup_venv then deletes.
- f" [ \"$3\" = 3.11 ] && exit 2\n [ \"$3\" = --system ] && [ \"$4\" = '>=3.11,<3.14' ] && {{ echo {tmp_path}/bin/python3.13; exit 0; }}\n exit 2\n"))
- assert "DOWNLOAD ATTEMPTED" not in result.stdout, result.stdout
- assert "Python found: Python 3.13.12" in result.stdout, result.stdout
+ for tool in ("awk", "cut", "uname"):
+ real = shutil.which(tool)
+ assert real, f"the shell bootstrap requires {tool}"
+ (bin_dir / tool).symlink_to(real)
+ env = {**os.environ, "HOME": str(tmp_path / "home"),
+ "HERMES_HOME": str(tmp_path / "home/.hermes"),
+ "HERMES_RUNTIME_DIR": str(tmp_path / "tools"),
+ "UV_PYTHON_INSTALL_DIR": str(tmp_path / "managed-python"),
+ "UV_CACHE_DIR": str(tmp_path / "uv-cache"), "UV_OFFLINE": "1",
+ "PATH": str(bin_dir)}
+ return core, bin_dir, env
+
+
[email protected]("activated", [False, True])
+def test_supported_base_python_is_reused_offline(tmp_path: Path, activated: bool) -> None:
+ """Use real uv discovery with no managed Python and, optionally, an active venv."""
+ uv = shutil.which("uv")
+ bash = shutil.which("bash")
+ assert uv and bash, "bootstrap integration requires uv and Bash"
+ core, bin_dir, env = _environment(tmp_path)
+ (bin_dir / "uv").symlink_to(uv)
+ (bin_dir / "python3").symlink_to(Path(sys._base_executable).resolve())
+ if activated:
+ active = core / "venv"
+ venv.EnvBuilder(with_pip=False).create(active)
+ env["VIRTUAL_ENV"] = str(active)
+ env["PATH"] = f"{active / 'bin'}{os.pathsep}{bin_dir}"
+ # Source the real helper, then inspect the selected interpreter, not argv.
+ script = ('source "$1" --manifest; INSTALL_DIR="$2"; bootstrap_python; '
+ '"$boot_py" -I -c "import sys; print(sys.prefix == sys.base_prefix)"')
+ result = subprocess.run([bash, "-c", script, "test", str(INSTALL_SH), str(core)],
+ env=env, cwd=core, capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert result.stdout.strip() == "True", result.stdout + result.stderr
+ assert not Path(env["UV_PYTHON_INSTALL_DIR"]).exists()
+ if activated:
+ assert (active / "bin/python").exists()
+
+
[email protected]("failure", ["install", "lookup", "missing", "broken"])
+def test_bootstrap_failure_has_no_success_frame(tmp_path: Path, failure: str) -> None:
+ core, bin_dir, env = _environment(tmp_path)
+ bash = shutil.which("bash")
+ assert bash
+ attempted = tmp_path / "attempted"
+ broken = bin_dir / "broken-python"
+ broken.write_text(f"#!{bash}\nexit 9\n", encoding="utf-8")
+ broken.chmod(0o755)
+ selected = broken if failure == "broken" else tmp_path / "missing-python"
+ uv = bin_dir / "uv"
+ uv.write_text(
+ f"#!{bash}\n"
+ 'if [ "$1 $2" = "python install" ]; then\n'
+ f" : > {shlex.quote(str(attempted))}\n"
+ f" exit {9 if failure == 'install' else 0}\nfi\n"
+ f"[ -f {shlex.quote(str(attempted))} ] || exit 2\n"
+ + ("exit 2\n" if failure == "lookup" else f"printf '%s\\n' {shlex.quote(str(selected))}\n"),
+ encoding="utf-8",
+ )
+ uv.chmod(0o755)
+ result = subprocess.run([bash, str(INSTALL_SH), "--dir", str(core),
+ "--stage", "venv", "--json", "--non-interactive"],
+ env=env, cwd=core, capture_output=True, text=True, timeout=30)
+ assert result.returncode != 0, result.stdout + result.stderr
+ frame = json.loads(result.stdout.splitlines()[-1])
+ assert frame["stage"] == "venv" and frame["ok"] is False, frame
+ assert "bootstrap Python ready" not in result.stdout
diff --cc tests/scripts/test_run_tests_parallel.py
index d16c999e15f,aeee6cfa0ea..e80e56ae9e8
--- a/tests/scripts/test_run_tests_parallel.py
+++ b/tests/scripts/test_run_tests_parallel.py
@@@ -32,19 -31,15 +32,19 @@@ from pathlib import Pat
import pytest
-# Both tests share the same handoff file: the leaker writes here, the
-# verifier reads here. We park it in $TMPDIR with a unique-per-run name
-# so concurrent invocations of the suite don't clobber each other.
-_HANDOFF_DIR = Path(os.environ.get("TMPDIR", "/tmp")) / "hermes-isolation-probe"
-_HANDOFF_DIR.mkdir(exist_ok=True)
[email protected](autouse=True)
+def isolated_probe_environment(monkeypatch):
+ # Probe files exercise pytest/runner mechanics, not installed third-party
+ # plugins. Autoloading the developer environment changes their startup cost.
+ monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
-def _handoff_path_for(nonce: str) -> Path:
- return _HANDOFF_DIR / f"grandchild-{nonce}.json"
+def _probe_root(tmp_path):
+ root = tmp_path / "runner-root"
+ scripts = root / "scripts"
+ scripts.mkdir(parents=True, exist_ok=True)
- shutil.copy2(Path(__file__).resolve().parents[1] / "scripts" / "run_tests_parallel.py", scripts)
++ shutil.copy2(Path(__file__).resolve().parents[2] / "scripts" / "run_tests_parallel.py", scripts)
+ return root
def _pid_alive(pid: int) -> bool:
diff --cc tests/test_managed_runtime_resolution.py
index 00000000000,410ab802550..3885a8fba12
mode 000000,100644..100644
--- a/tests/test_managed_runtime_resolution.py
+++ b/tests/test_managed_runtime_resolution.py
@@@ -1,0 -1,237 +1,240 @@@
+ """Guard: Hermes-owned subprocesses must not resolve managed runtimes by bare PATH.
+
+ Hermes installs runtimes for itself — ``uv`` at ``$HERMES_HOME/bin/uv``, Node at
+ ``$HERMES_HOME/node``. Neither directory is on the ambient PATH of an arbitrary
+ process, so ``shutil.which("uv")`` / ``shutil.which("node")`` in Hermes's own
+ code has two failure modes:
+
+ * the managed runtime is invisible, so the caller reports "not installed" or
+ degrades to a slower tier on a machine that has exactly what it needed; and
+ * when a system copy also exists, the one Hermes does not own wins — which is
+ how a generated systemd unit or launchd plist can bake a system Node in and
+ keep resolving it across reboots.
+
+ The fix per call site is one of ``find_node_executable()``,
+ ``iter_hermes_node_dirs()``, ``resolve_uv()``, or ``ensure_uv()``. This test is
+ the ratchet that stops a new bare lookup from being added back.
+
+ Reading source is normally banned (see AGENTS.md). It is the right tool here and
+ only here: the property under test is "no call site anywhere in the tree spells
+ it this way", which is a statement about the whole codebase rather than about
+ one function's behavior, and there is no runtime seam that can observe a lookup
+ that was never written. Every entry in the allow-list below names a call site
+ whose behavior is separately covered by a real test.
+ """
+
+ from __future__ import annotations
+
+ import ast
+ import functools
+ import os
+ from pathlib import Path
+
+ import pytest
+
+ REPO_ROOT = Path(__file__).resolve().parents[1]
+
+ # Runtimes Hermes provisions into HERMES_HOME and must therefore resolve
+ # through a managed-aware helper rather than PATH.
+ _MANAGED_COMMANDS = frozenset({"uv", "node", "npm", "npx"})
+
+ # Directories that are not Hermes-owned subprocess code: plugins ship their own
+ # resolution policy, tests assert against PATH deliberately, and skills/scripts/
+ # evals run as standalone user-invoked programs.
+ _EXEMPT_DIRS = (
+ "tests",
+ "plugins",
+ "skills",
+ "optional-skills",
+ "scripts",
+ "evals",
+ "website",
+ "node_modules",
+ ".git",
+ ".venv",
+ "venv",
+ ".worktrees",
+ )
+
+ # Call sites where a bare PATH lookup is the correct answer. Each entry is
+ # (path, command) -> why. Keep this list short and justified — the default
+ # answer for a new call site is a managed-aware helper, not a new exemption.
+ _ALLOWED: dict[tuple[str, str], str] = {
+ ("tools/env_probe.py", "uv"): (
+ "Reports the environment the MODEL sees in the terminal tool. The model "
+ "can only run what is on that subshell's PATH, which local.py populates "
+ "with the managed dirs — so PATH is the correct question to ask here."
+ ),
- ("hermes_cli/update_cmd_deps.py", "uv"): (
- "Termux fallback: a pkg-installed uv lands on PATH but not in the "
- "managed bin dir, and it is checked only after resolve_uv() misses."
- ),
- ("hermes_cli/update_cmd_deps.py", "npm"): (
- "WSL diagnostic: deliberately inspects what PATH resolves so it can "
- "warn that the only reachable npm is the Windows one."
- ),
+ ("tools/lazy_deps.py", "uv"): (
+ "Fallback after resolve_uv(), plus the except-branch for the "
+ "hermes_cli import guard."
+ ),
- ("tools/browser_use_cli.py", "uv"): (
- "install_cli()'s fallback after ensure_uv() misses — a user-installed "
- "uv on PATH is a legitimate last rung before giving up with install "
- "guidance."
- ),
+ ("hermes_cli/gateway.py", "node"): (
+ "Fallback rung of _append_node_dir_for_service(), after the managed "
+ "dirs from iter_hermes_node_dirs() are already appended."
+ ),
+ ("hermes_cli/main_tui_launch.py", "node"): (
+ "_ensure_tui_node()'s idempotence gate: the question really is 'is "
+ "node already discoverable on PATH', before bootstrapping one."
+ ),
+ ("hermes_cli/main_tui_launch.py", "npm"): (
+ "Same _ensure_tui_node() gate as node."
+ ),
+ ("hermes_cli/main_install_repair.py", "npm"): (
+ "_resolve_node_runtime_npm()'s WSL re-scan: PATH minus /mnt/* IS the question."
+ ),
- ("tools/browser_tool_install.py", "npx"): (
- "agent-browser runs via `npx`, resolved against the extended browser "
- "PATH that _merge_browser_path() already seeds with the managed dirs."
++ ("hermes_cli/source_build.py", "node"): (
++ "PM-composed build context: `which(node)` runs against the PATH pm's "
++ "ensure('npm')/env_for('node') just composed, not the ambient one."
++ ),
++ ("hermes_cli/source_build.py", "npm"): (
++ "Same PM-composed build context as the node lookup above."
++ ),
++ ("hermes_cli/main_desktop.py", "npm"): (
++ "Desktop build resolves npm inside the PM-prepared build_env PATH."
++ ),
++ ("pm/workspace.py", "npm"): (
++ "Plugin workspace installs resolve npm inside the PM runner env that "
++ "pm.ensure('npm') just composed."
++ ),
++ ("apps/desktop/electron/fixtures/source-backend.py", "uv"): (
++ "Test fixture drives the real uv deliberately placed on the test "
++ "runner's PATH; it is not Hermes-owned subprocess resolution."
+ ),
+ }
+
+
+ def _iter_which_calls(tree: ast.AST):
+ """Yield (command, lineno) for every ``which("<cmd>")`` call in *tree*.
+
+ AST rather than a regex so prose in docstrings and comments that mentions
+ ``shutil.which("npm")`` is not mistaken for a call site.
+ """
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or not node.args:
+ continue
+ func = node.func
+ name = (
+ func.attr
+ if isinstance(func, ast.Attribute)
+ else func.id if isinstance(func, ast.Name) else None
+ )
+ if name != "which":
+ continue
+ first = node.args[0]
+ if isinstance(first, ast.Constant) and first.value in _MANAGED_COMMANDS:
+ yield first.value, node.lineno
+
+
+ def _source_files() -> list[Path]:
+ files: list[Path] = []
+ # os.walk instead of Path.rglob: rglob raises FileNotFoundError when a
+ # directory vanishes mid-scan — a sibling CI job's sdist extraction
+ # (hermes_agent-<version>/) gets created and deleted concurrently, and
+ # that TOCTOU failed this guard on runs 33531869442/33455779041-era
+ # workspaces. os.walk tolerates vanishing dirs (onerror=None), and
+ # pruning exempt/packaging dirs at the top level also skips their
+ # subtrees entirely.
+ for dirpath, dirnames, filenames in os.walk(REPO_ROOT):
+ rel_dir = Path(dirpath).relative_to(REPO_ROOT)
+ if rel_dir == Path("."):
+ dirnames[:] = [
+ d for d in dirnames
+ if d not in _EXEMPT_DIRS and not _is_packaging_copy(d)
+ ]
+ for fname in filenames:
+ if fname.endswith(".py"):
+ files.append(Path(dirpath) / fname)
+ return files
+
+
+ @functools.lru_cache(maxsize=None)
+ def _is_packaging_copy(top_level: str) -> bool:
+ """Whether *top_level* (a dir name under REPO_ROOT) is a build artifact."""
+ if top_level in ("build", "dist") or top_level.endswith(".egg-info"):
+ return True
+ candidate = REPO_ROOT / top_level
+ if not candidate.is_dir():
+ return False
+ return (candidate / "PKG-INFO").exists()
+
+
+ def _findings() -> list[tuple[str, str, int]]:
+ """Return (relpath, command, lineno) for every bare managed lookup."""
+ found: list[tuple[str, str, int]] = []
+ for path in _source_files():
+ try:
+ source = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ continue
+ if "which(" not in source:
+ continue
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ continue
+ rel = path.relative_to(REPO_ROOT).as_posix()
+ for command, lineno in _iter_which_calls(tree):
+ found.append((rel, command, lineno))
+ return found
+
+
+ def test_no_unreviewed_bare_managed_runtime_lookups():
+ """Every bare which() for a managed runtime is a reviewed exemption."""
+ unexpected = [
+ (rel, cmd, lineno)
+ for rel, cmd, lineno in _findings()
+ if (rel, cmd) not in _ALLOWED
+ ]
+
+ assert not unexpected, (
+ "Bare PATH lookup for a Hermes-managed runtime.\n\n"
+ + "\n".join(f" {rel}:{lineno} which({cmd!r})" for rel, cmd, lineno in unexpected)
+ + "\n\n$HERMES_HOME/bin (uv) and $HERMES_HOME/node are not on an "
+ "arbitrary process's PATH, so this resolves a system copy — or nothing "
+ "— on an install that has a managed one.\n"
+ "Use instead:\n"
+ " uv -> managed_uv.resolve_uv() (lookup) or ensure_uv() (may install)\n"
+ " node/npm -> hermes_constants.find_node_executable()\n"
+ " PATH env -> hermes_constants.iter_hermes_node_dirs()\n"
+ "If PATH really is the right question, add the site to _ALLOWED with a "
+ "reason."
+ )
+
+
+ def test_allowlist_has_no_stale_entries():
+ """A fixed call site must be dropped from the allow-list, not left to rot."""
+ live = {(rel, cmd) for rel, cmd, _lineno in _findings()}
+ stale = sorted(set(_ALLOWED) - live)
+
+ assert not stale, (
+ "Allow-list entries no longer match any source line — the call site was "
+ "fixed or moved. Remove them:\n"
+ + "\n".join(f" {rel} ({cmd})" for rel, cmd in stale)
+ )
+
+
+ @pytest.mark.parametrize(
+ "helper",
+ [
+ "find_node_executable",
- "find_hermes_node_executable",
+ "iter_hermes_node_dirs",
+ "with_hermes_node_path",
+ ],
+ )
+ def test_managed_node_helpers_exist(helper):
+ """The alternatives this guard points contributors at must be importable."""
+ import hermes_constants
+
+ assert callable(getattr(hermes_constants, helper))
+
+
+ def test_managed_uv_helpers_exist():
- from hermes_cli.managed_uv import ensure_uv, managed_uv_path, resolve_uv
-
- assert callable(resolve_uv)
- assert callable(ensure_uv)
- assert managed_uv_path().parent.name == "bin"
++ """The old managed_uv module is a retirement shim on the PM branch: it
++ exists only so the frozen historical updater fixture can import it, and
++ its entry points route to relaunch instead of doing venv work. PM owns
++ real uv resolution now; the module itself must keep the names live."""
++ from hermes_cli import managed_uv
++
++ assert callable(managed_uv.resolve_uv)
++ assert callable(managed_uv.ensure_uv)
diff --cc tests/test_tests_tree_layout.py
index 00000000000,1cfd6d504e2..2e5ae3976cc
mode 000000,100644..100644
--- a/tests/test_tests_tree_layout.py
+++ b/tests/test_tests_tree_layout.py
@@@ -1,0 -1,76 +1,80 @@@
+ """The tests/ tree mirrors the source tree.
+
+ ``scripts/run_tests.sh tests/<dir>/`` is how a change gets its regression
+ coverage run, so a test filed under a directory that does not correspond to
+ the code it exercises is a test nobody runs when that code changes. Two
+ drifts had accumulated: parallel directories for one source package
+ (``tests/cli`` beside ``tests/hermes_cli``, ``tests/run_agent`` beside
+ ``tests/agent``, ``tests/state`` beside ``tests/hermes_state``) and ~250
+ loose files at ``tests/`` root that belonged to a package.
+
+ Filenames also stopped carrying issue numbers: ``test_89315_x.py`` reads as
+ noise in a directory listing and the number belongs in the docstring, where
+ ``git log -S`` and a reader can both find it with context.
+ """
+
+ from __future__ import annotations
+
+ import re
+ from pathlib import Path
+
+ REPO_ROOT = Path(__file__).resolve().parent.parent
+ TESTS_ROOT = REPO_ROOT / "tests"
+
+ # tests/<name>/ directories that do not mirror a source directory but are
+ # legitimate homes: cross-cutting suites, fixtures, and script-family tests.
++# "compat": frozen pre-PM updater import surface (tests/compat/README.md) — the
++# audited names live only in history, so there is no source package to mirror.
++# "installation": python driver for the tests/install shell e2e assets.
+ _NON_MIRROR_DIRS = {
++ "compat", "installation",
+ "ci", "conformance", "dashboard", "desktop", "docker", "e2e", "evals",
+ "fakes", "fixtures", "honcho_plugin", "install", "integration", "manual",
+ "monitoring", "openviking_plugin", "perf_guards", "scripts", "secret_sources",
+ "security", "skills", "verify", "website", "computer_use", "hermes_state",
+ }
+
+ # Root-level modules whose tests sit directly in tests/ (no package to mirror).
+ _ROOT_MODULE_STEMS = {p.stem for p in REPO_ROOT.glob("*.py")}
+
+ _ISSUE_NUMBER = re.compile(r"(^test_\d{4,6}_)|(_\d{4,6}\.py$)")
+
+
+ def _source_dirs() -> set[str]:
+ return {
+ p.name
+ for p in REPO_ROOT.iterdir()
+ if p.is_dir() and (p / "__init__.py").exists()
+ }
+
+
+ def test_every_test_directory_mirrors_a_source_directory_or_is_declared():
+ """No sibling directory for a source package that already has one."""
+ source_dirs = _source_dirs()
+ offenders = sorted(
+ d.name
+ for d in TESTS_ROOT.iterdir()
+ if d.is_dir()
+ and d.name not in ("__pycache__",)
+ and d.name not in source_dirs
+ and d.name not in _NON_MIRROR_DIRS
+ )
+ assert not offenders, (
+ "tests/ directories that mirror no source package: "
+ f"{offenders}. Put the tests under tests/<source dir>/ (tests/agent, "
+ "tests/hermes_cli, ...) or, for a genuinely cross-cutting suite, add the "
+ "name to _NON_MIRROR_DIRS in this file with a reason."
+ )
+
+
+ def test_no_issue_numbers_in_test_filenames():
+ """Issue numbers live in docstrings, where the reader gets context."""
+ offenders = sorted(
+ str(p.relative_to(REPO_ROOT))
+ for p in TESTS_ROOT.rglob("test_*.py")
+ if _ISSUE_NUMBER.search(p.name)
+ )
+ assert not offenders, (
+ f"Issue numbers in test filenames: {offenders}. Drop the number from the "
+ "name and cite the issue in the module docstring instead."
+ )
diff --cc tests/tools/test_tts_pythonpath_fallback.py
index 00000000000,6b2c1e35df1..d8ec5a710b5
mode 000000,100644..100644
--- a/tests/tools/test_tts_pythonpath_fallback.py
+++ b/tests/tools/test_tts_pythonpath_fallback.py
@@@ -1,0 -1,147 +1,143 @@@
+ """Regression tests for #53259.
+
+ When TTS/STT packages (edge-tts, elevenlabs, mistralai) installed outside
+ the venv but importable on sys.path (e.g. via PYTHONPATH, Docker layered
+ filesystems), the lazy-import helpers must fall through to the raw import
-instead of re-raising lazy_deps.ensure() failures as ImportError.
++instead of re-raising dependency-provisioning failures as ImportError.
+
-Uses sys.modules fixtures so builtins.__import__ stays intact — patching
-__import__ replaces the helper's own ``from tools.lazy_deps import ...``
-and defeats the purpose of the test.
++The PM branch provisions through pm.ensure_import (replacing the old
++pm.ensure_import provisioning); the helper must swallow its failure the
++same way. Uses sys.modules fixtures so builtins.__import__ stays intact.
+ """
+
+ import sys
+ from unittest.mock import MagicMock, patch
+
+ import pytest
+
-from tools.lazy_deps import FeatureUnavailable
++from pm.extras import ensure_import as _pm_ensure_import
+
+
+ @pytest.fixture(autouse=True)
+ def _clean_tts_modules():
+ """Remove TTS packages from sys.modules so each test starts fresh."""
+ removed = {}
+ for name in ("edge_tts", "elevenlabs", "elevenlabs.client",
+ "mistralai", "mistralai.client"):
+ if name in sys.modules:
+ removed[name] = sys.modules.pop(name)
+ yield
+ for name in ("edge_tts", "elevenlabs", "elevenlabs.client",
+ "mistralai", "mistralai.client"):
+ sys.modules.pop(name, None)
+ sys.modules.update(removed)
+
+
+ class TestEdgeTtsPythonpathFallback:
- def test_falls_through_on_lazy_deps_failure(self):
- """FeatureUnavailable from ensure() must not prevent raw import."""
++ def test_falls_through_on_provisioning_failure(self):
++ """A provisioning failure must not prevent raw import."""
+ mock_edge_tts = MagicMock()
+ with patch.dict(sys.modules, {"edge_tts": mock_edge_tts}), \
- patch("tools.lazy_deps.ensure",
- side_effect=FeatureUnavailable("tts.edge", (), "test")):
++ patch("pm.extras.ensure_import", side_effect=RuntimeError("provisioning failed")):
+ from tools.tts_tool import _import_edge_tts
+ result = _import_edge_tts()
+ assert result is mock_edge_tts
+
+ def test_raises_when_package_truly_missing(self):
+ """When the package is truly absent, ImportError must propagate."""
- with patch("tools.lazy_deps.ensure"), \
++ with patch("pm.extras.ensure_import"), \
+ patch.dict(sys.modules, {"edge_tts": None}):
+ from tools.tts_tool import _import_edge_tts
+ with pytest.raises(ImportError):
+ _import_edge_tts()
+
+
+ class TestElevenLabsPythonpathFallback:
- def test_falls_through_on_lazy_deps_failure(self):
- """FeatureUnavailable from ensure() must not prevent raw import."""
++ def test_falls_through_on_provisioning_failure(self):
++ """A provisioning failure must not prevent raw import."""
+ mock_cls = MagicMock()
+ mock_client_pkg = MagicMock()
+ mock_client_pkg.ElevenLabs = mock_cls
+ with patch.dict(sys.modules, {
+ "elevenlabs": mock_client_pkg,
+ "elevenlabs.client": mock_client_pkg,
- }), patch("tools.lazy_deps.ensure",
- side_effect=FeatureUnavailable("tts.elevenlabs", (), "test")):
++ }), patch("pm.extras.ensure_import", side_effect=RuntimeError("provisioning failed")):
+ from tools.tts_tool import _import_elevenlabs
+ result = _import_elevenlabs()
+ assert result is mock_cls
+
+ def test_raises_when_package_truly_missing(self):
+ """When the package is truly absent, ImportError must propagate."""
- with patch("tools.lazy_deps.ensure"), \
++ with patch("pm.extras.ensure_import"), \
+ patch.dict(sys.modules, {"elevenlabs": None,
+ "elevenlabs.client": None}):
+ from tools.tts_tool import _import_elevenlabs
+ with pytest.raises(ImportError):
+ _import_elevenlabs()
+
+
+ class TestMistralPythonpathFallback:
- def test_falls_through_on_lazy_deps_failure(self):
- """FeatureUnavailable from ensure() must not prevent raw import."""
++ def test_falls_through_on_provisioning_failure(self):
++ """A provisioning failure must not prevent raw import."""
+ mock_cls = MagicMock()
+ mock_mistralai = MagicMock()
+ mock_mistralai.Mistral = mock_cls
+ with patch.dict(sys.modules, {
+ "mistralai": mock_mistralai,
+ "mistralai.client": mock_mistralai,
- }), patch("tools.lazy_deps.ensure",
- side_effect=FeatureUnavailable("tts.mistral", (), "test")):
++ }), patch("pm.extras.ensure_import", side_effect=RuntimeError("provisioning failed")):
+ from tools.tts_tool import _import_mistral_client
+ result = _import_mistral_client()
+ assert result is mock_cls
+
+ def test_raises_when_package_truly_missing(self):
+ """When the package is truly absent, ImportError must propagate."""
- with patch("tools.lazy_deps.ensure"), \
++ with patch("pm.extras.ensure_import"), \
+ patch.dict(sys.modules, {"mistralai": None,
+ "mistralai.client": None}):
+ from tools.tts_tool import _import_mistral_client
+ with pytest.raises(ImportError):
+ _import_mistral_client()
+
+
+ # ── STT: _transcribe_mistral fallthrough ───────────────────────────────────
+
+
+ class TestMistralSttPythonpathFallback:
- def test_transcribe_mistral_falls_through_on_lazy_deps_failure(
++ def test_transcribe_mistral_falls_through_on_provisioning_failure(
+ self, tmp_path,
+ ):
- """FeatureUnavailable from ensure('stt.mistral') must not block
++ """A provisioning failure for stt.mistral must not block
+ transcription when mistralai is importable via PYTHONPATH."""
+ from tools.transcription_tools import _transcribe_mistral
+
+ audio_file = tmp_path / "audio.wav"
+ audio_file.write_bytes(b"fake-audio")
+
+ mock_client_cls = MagicMock()
+ mock_result = MagicMock()
+ mock_result.text = "hello world"
+ mock_client_cls.return_value.__enter__ = MagicMock(
+ return_value=MagicMock(
+ audio=MagicMock(
+ transcriptions=MagicMock(
+ complete=MagicMock(return_value=mock_result),
+ ),
+ ),
+ ),
+ )
+ mock_client_cls.return_value.__exit__ = MagicMock(return_value=False)
+
+ mock_mistralai = MagicMock()
+ mock_mistralai.Mistral = mock_client_cls
+
+ with patch.dict(sys.modules, {
+ "mistralai": mock_mistralai,
+ "mistralai.client": mock_mistralai,
- }), patch("tools.lazy_deps.ensure",
- side_effect=FeatureUnavailable("stt.mistral", (), "test")), \
++ }), patch("pm.extras.ensure_import", side_effect=RuntimeError("provisioning failed")), \
+ patch("hermes_cli.config.get_env_value",
+ return_value="test-key"):
+ result = _transcribe_mistral(str(audio_file), "mistral-large-latest")
+
+ assert result["success"] is True
+ assert result["transcript"] == "hello world"
diff --cc tests/tui_gateway/test_tui_gateway_server.py
index 263daef6a17,acc05d8f008..b67247b3979
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@@ -19852,77 -19959,6 +19959,15 @@@ def test_get_usage_safe_when_active_cou
assert usage["model"] == "x"
- def test_persist_model_switch_preserves_sibling_model_keys(tmp_path, monkeypatch):
- """#48305: switching models from the TUI must NOT destroy sibling keys under
- `model:` (model_slots, model_fallback, etc.). _persist_model_switch now uses
- targeted save_config_value writes instead of rewriting the whole block."""
- import types
- import hermes_yaml as yaml
- import cli
-
- cfg_path = tmp_path / "config.yaml"
- cfg_path.write_text(
- "model:\n"
- " default: old-model\n"
- " provider: openai\n"
- " model_slots:\n"
- " fast: gpt-5-mini\n"
- " model_fallback:\n"
- " - claude-haiku\n"
- "agent:\n"
- " system_prompt: keepme\n"
- )
- # save_config_value() resolves the config path from get_hermes_home() (live
- # env var), always targeting HERMES_HOME/config.yaml — point it at tmp_path.
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setattr(cli, "_hermes_home", tmp_path)
-
- result = types.SimpleNamespace(
- new_model="new-model", target_provider="anthropic", base_url=None
- )
- server._persist_model_switch(result)
- saved = yaml.safe_load(cfg_path.read_text())
-
- # The switched fields updated...
- assert saved["model"]["default"] == "new-model"
- assert saved["model"]["provider"] == "anthropic"
- # ...and the sibling keys SURVIVED (the bug was that they got wiped).
- assert saved["model"]["model_slots"] == {"fast": "gpt-5-mini"}
- assert saved["model"]["model_fallback"] == ["claude-haiku"]
- assert saved["agent"]["system_prompt"] == "keepme"
-
-
- def test_persist_model_switch_clears_stale_base_url(tmp_path, monkeypatch):
- """#48305: switching from a custom endpoint (which set model.base_url) to a
- provider with no base_url must CLEAR the stale base_url, not leave it
- pointing at the old host."""
- import types
- import hermes_yaml as yaml
- import cli
-
- cfg_path = tmp_path / "config.yaml"
- cfg_path.write_text(
- "model:\n"
- " default: local-model\n"
- " provider: custom:mylocal\n"
- " base_url: http://localhost:1234/v1\n"
- )
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setattr(cli, "_hermes_home", tmp_path)
-
- # Switch to a native provider with no base_url.
- result = types.SimpleNamespace(
- new_model="claude-haiku", target_provider="anthropic", base_url=None
- )
- server._persist_model_switch(result)
- saved = yaml.safe_load(cfg_path.read_text())
-
- assert saved["model"]["default"] == "claude-haiku"
- assert saved["model"]["provider"] == "anthropic"
- # Stale custom base_url must be cleared (null coalesces to absent on read).
- assert not saved["model"].get("base_url"), saved["model"].get("base_url")
++# NOTE (origin/main merge): the two _persist_model_switch tests that lived here were
++# removed. Upstream redesigned model-switch persistence (#86414): the TUI no longer has a
++# _persist_model_switch helper; persistence is opt-in (--global / persist_switch_by_default)
++# and lives in hermes_cli.model_switch.switch_model. Their invariants — sibling `model:` keys
++# survive a persisted switch, and a provider without base_url clears the stale one — are
++# covered upstream by tests/hermes_cli/test_model_persist_one_shape.py (every persist surface,
++# model_slots preserved, base_url cleared).
+
+
# ---------------------------------------------------------------------------
# _resolve_runtime_with_fallback — init-time provider fallback
# ---------------------------------------------------------------------------
diff --cc tools/environments/base.py
index b12e106d101,f9cbac4cb33..393f9a3d858
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@@ -578,16 -571,13 +587,19 @@@ class BaseEnvironment(ABC)
_on_timeout()
raise
- result = (
- {"output": f"[Command timed out after {effective_timeout}s]", "returncode": 124}
- if bounded.timed_out else bounded.value)
+ if bounded.timed_out:
+ suffix = f"\n[Command timed out after {effective_timeout}s]"
+ if output_holder:
+ collector = output_holder[0]
+ result = self._finalize_wait_result(collector, collector.render(suffix=suffix).lstrip("\n"), 124)
+ else:
+ result = {"output": suffix.lstrip(), "returncode": 124}
+ else:
+ result = bounded.value
self._update_cwd(result)
+ if getattr(self, "_recreated_notice_pending", False):
+ self._recreated_notice_pending = False
+ result["environment_recreated"] = True
return result
def _kill_spawned_tree(self, spawned) -> None:
diff --cc tools/environments/vercel_sandbox.py
index 59eb197eef3,73c88b318bf..d200adfdb34
--- a/tools/environments/vercel_sandbox.py
+++ b/tools/environments/vercel_sandbox.py
@@@ -43,47 -44,9 +43,42 @@@ def _ensure_vercel_sdk() -> None
# The SDK (>=0.7) ships default-on telemetry; Hermes policy is opt-in only, so disable it
# before the SDK is imported. setdefault: an explicit user value is never overridden.
os.environ.setdefault("VERCEL_TELEMETRY_DISABLED", "1")
- ensure_lazy_dep("terminal.vercel")
+ try:
+ from pm import ensure_import as _lazy_ensure
+ except ImportError:
+ return # pm unavailable — vercel's own import sites decide
+ try:
+ _lazy_ensure("vercel")
+ except Exception as e:
+ raise ImportError(str(e))
-
-
- _CREATE_RETRY_ATTEMPTS = 3
+_WRITE_RETRY_ATTEMPTS = 3
- _TRANSIENT_STATUS_CODES = frozenset({408, 425, 429, 500, 502, 503, 504})
+_RETRY_BACKOFF_STEP = timedelta(milliseconds=100)
+_MIN_SANDBOX_TIMEOUT = timedelta(minutes=5)
+_MIN_RUNNING_WAIT = timedelta(seconds=1)
- _RUNNING_WAIT_TIMEOUT = timedelta(seconds=30)
+_RUNNING_WAIT_POLL_INTERVAL = timedelta(milliseconds=250)
+_STOP_TIMEOUT = timedelta(seconds=15)
+_STOP_POLL_INTERVAL = timedelta(milliseconds=500)
+_SNAPSHOT_STORE_NAME = "vercel_sandbox_snapshots.json"
+def _exception_chain(exc: BaseException) -> list[BaseException]:
+ chain: list[BaseException] = []
+ current: BaseException | None = exc
+ seen: set[int] = set()
+ while current is not None and id(current) not in seen:
+ chain.append(current)
+ seen.add(id(current))
+ current = current.__cause__ or current.__context__
+ return chain
+
+
+def _extract_status_code(exc: BaseException) -> int | None:
+ response = getattr(exc, "response", None)
+ for value in (getattr(exc, "status_code", None), getattr(response, "status_code", None)):
+ if isinstance(value, int):
+ return value
+ return None
+
def _is_transient_vercel_error(exc: BaseException) -> bool:
"""True when any exception in the cause/context chain looks retryable."""
seen: set[int] = set()
diff --cc tools/skills_hub.py
index 733f058e867,6fafdddabdb..ab6e3ebba5f
--- a/tools/skills_hub.py
+++ b/tools/skills_hub.py
@@@ -75,6 -76,6 +76,17 @@@ def __getattr__(name: str)
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
++def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__
++ target = _PLUGIN_COMPAT_LAZY.get(name)
++ if target is None:
++ return _plugin_compat_prev_getattr(name)
++ import importlib
++ from hermes_cli.plugin_compat import warn_once
++ warn_once(__name__, name, *target)
++ return getattr(importlib.import_module(target[0]), target[1])
++# ---- END PLUGIN-COMPAT ----
++
++
# ---------------------------------------------------------------------------
# Install-path safety + guarded HTTP
# ---------------------------------------------------------------------------
@@@ -377,14 -441,14 +453,3 @@@ _PLUGIN_COMPAT_LAZY =
}
_plugin_compat_prev_getattr = __getattr__
--
--
--def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__
-- target = _PLUGIN_COMPAT_LAZY.get(name)
-- if target is None:
-- return _plugin_compat_prev_getattr(name)
-- import importlib
-- from hermes_cli.plugin_compat import warn_once
-- warn_once(__name__, name, *target)
-- return getattr(importlib.import_module(target[0]), target[1])
--# ---- END PLUGIN-COMPAT ----
diff --cc tools/vision_tools_image_prep.py
index 19722c776ae,dac11878c6b..9fe43e23730
--- a/tools/vision_tools_image_prep.py
+++ b/tools/vision_tools_image_prep.py
@@@ -135,7 -159,20 +159,19 @@@ def _normalize_to_supported_image
"This is an SVG, which vision models cannot read directly, and no "
"SVG rasterizer is installed (tried cairosvg, svglib, rsvg-convert, "
"inkscape). Convert the SVG to PNG first — e.g. open it in a browser "
- "and screenshot it, or install a rasterizer "
- "(`pip install cairosvg`) — then re-run vision_analyze on the PNG.")
+ "and screenshot it — then re-run vision_analyze on the PNG.")
+ # HEIF/AVIF need a codec Pillow's core doesn't always carry, served by DIFFERENT optional
+ # backends that must not be gated on one another: HEIC/HEIF (HEVC) needs the pillow-heif
+ # plugin registered; AVIF (AV1) is native in Pillow >= 11.3 while pillow-heif wheels are
+ # frequently built with NO AV1 codec at all. Register whatever backend is available, let the
+ # decode attempt be the arbiter, and only emit a codec-specific error if it really fails —
+ # same soft-dependency posture as the SVG branch.
+ if detected_mime in ("image/heic", "image/avif"):
+ try:
+ import pillow_heif # type: ignore
+ pillow_heif.register_heif_opener()
+ except Exception:
+ logger.debug("pillow-heif unavailable; relying on Pillow for %s", detected_mime)
try:
from PIL import Image as _PILImage
with _PILImage.open(image_path) as _img:
diff --cc tui_gateway/compute_host.py
index 599163901d2,ee404e98f5e..5c5f4e0283c
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@@ -546,7 -555,7 +556,6 @@@ if __name__ == "__main__": # pragma: n
# The whole block is removed by reverting the commit that added it.
from dataclasses import field # noqa: F401,E402
from dataclasses import dataclass # noqa: F401,E402
--from dataclasses import dataclass # noqa: F401,E402
from dataclasses import field # noqa: F401,E402
@dataclass
diff --cc ui-tui/src/components/messageLine.tsx
index a380ce5a566,fb64a9d6929..12b4d207499
--- a/ui-tui/src/components/messageLine.tsx
+++ b/ui-tui/src/components/messageLine.tsx
@@@ -1,6 -1,8 +1,7 @@@
import { Ansi, Box, NoSelect, Text } from '@hermes/ink'
+ import { hasAnsi, sanitizeAnsiForRender, stripAnsi } from '@hermes/shared/ansi'
import { memo, useState } from 'react'
-import { TERMUX_TUI_MODE } from '../config/env.js'
import { LONG_MSG } from '../config/limits.js'
import { hasLeadGap } from '../domain/blockLayout.js'
import { splitComposerHighlights } from '../domain/composerHighlights.js'
diff --cc ui-tui/src/gatewayClient.ts
index e4c8de8c65b,29f709453ba..e23072519f4
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@@ -72,35 -74,20 +80,12 @@@ const resolvePython = () =>
return configured
}
- const venv = process.env.VIRTUAL_ENV?.trim()
-
- const hit = [
- venv && resolve(venv, 'bin/python'),
- venv && resolve(venv, 'Scripts/python.exe'),
- resolve(root, '.venv/bin/python'),
- resolve(root, '.venv/bin/python3'),
- resolve(root, 'venv/bin/python'),
- resolve(root, 'venv/bin/python3')
- ].find(p => p && existsSync(p))
-
- return hit || (process.platform === 'win32' ? 'python' : 'python3')
+ // The one case with no launcher above it: `npm run dev` / `npm start`
+ // straight out of ui-tui/. A developer doing that runs inside their own
+ // activated environment, so PATH is the right question there.
+ return process.platform === 'win32' ? 'python' : 'python3'
}
- const asGatewayEvent = (value: unknown): GatewayEvent | null =>
- value && typeof value === 'object' && !Array.isArray(value) && typeof (value as { type?: unknown }).type === 'string'
- ? (value as GatewayEvent)
- : null
-
- // Hoisted decoder: attach mode can drive high-frequency binary frames
- // (tool deltas, reasoning streams) and constructing a fresh TextDecoder
- // per message creates avoidable GC pressure. One module-level instance
- // is fine because UTF-8 is stateless and we always pass entire frames.
- const _wireDecoder = new TextDecoder()
-
- const asWireText = (raw: unknown): string | null => {
- if (typeof raw === 'string') {
- return raw
- }
-
- if (raw instanceof ArrayBuffer || ArrayBuffer.isView(raw)) {
- return _wireDecoder.decode(raw as any as ArrayBuffer)
- }
-
- return null
- }
-
// Matches `<scheme>://user:pass@host…` style user-info segments in
// otherwise-malformed URLs that the WHATWG `URL` parser can't accept.
// Used by the `redactUrl` fallback so embedded credentials are
@@@ -471,8 -418,15 +416,15 @@@ export class GatewayClient extends Even
}
}
+ private protocolError(what: string, text: string, emptyLabel: string) {
+ const preview = text.trim().slice(0, MAX_LOG_PREVIEW) || emptyLabel
+
+ this.pushLog(`[protocol] ${what}: ${preview}`)
+ this.publish({ type: 'gateway.protocol_error', payload: { preview } })
+ }
+
private startSpawnedGateway(root: string) {
- const python = resolvePython(root)
+ const python = resolvePython()
const cwd = process.env.HERMES_CWD || root
const env = { ...process.env }
const pyPath = env.PYTHONPATH?.trim()
diff --cc website/docs/developer-guide/adding-providers.md
index 24259c7f4b4,ba8e276bd5e..48d01ed5544
--- a/website/docs/developer-guide/adding-providers.md
+++ b/website/docs/developer-guide/adding-providers.md
@@@ -343,11 -343,11 +343,12 @@@ For docs-only examples, the exact file
- provider:model parsing
- any adapter-specific message conversion
-Run the targeted tests (or use `scripts/run_tests.sh`, which runs each file in its own subprocess):
+Prepare the [independent test environment](/developer-guide/contributing#manual-development-and-test-environment),
+then use the canonical runner, which isolates each file and scrubs credentials:
```bash
- scripts/run_tests.sh tests/hermes_cli/test_runtime_provider_resolution.py tests/cli/test_cli_provider_resolution.py tests/hermes_cli/test_setup_model_provider.py tests/run_agent/test_provider_parity.py -q
-source venv/bin/activate
-python -m pytest tests/hermes_cli/test_runtime_provider_resolution.py tests/hermes_cli/test_cli_provider_resolution.py tests/hermes_cli/test_setup_model_provider.py tests/agent/test_provider_parity.py -q
++
++scripts/run_tests.sh tests/hermes_cli/test_runtime_provider_resolution.py tests/hermes_cli/test_cli_provider_resolution.py tests/hermes_cli/test_setup_model_provider.py tests/agent/test_provider_parity.py -q
```
For deeper changes, run the full suite before pushing:
diff --cc website/docs/developer-guide/macos-bundle-updates.md
index 73e3a4081c8,00000000000..73e3a4081c8
mode 100644,000000..100644
--- a/website/docs/developer-guide/macos-bundle-updates.md
+++ b/website/docs/developer-guide/macos-bundle-updates.md
diff --cc website/docs/developer-guide/pm-audit-status.md
index 1e721913a06,00000000000..1e721913a06
mode 100644,000000..100644
--- a/website/docs/developer-guide/pm-audit-status.md
+++ b/website/docs/developer-guide/pm-audit-status.md
diff --cc website/docs/developer-guide/shared-bundle-builds.md
index 2411722a86e,00000000000..2411722a86e
mode 100644,000000..100644
--- a/website/docs/developer-guide/shared-bundle-builds.md
+++ b/website/docs/developer-guide/shared-bundle-builds.md
diff --cc website/docs/developer-guide/source-update-completion.md
index 87221130b79,00000000000..87221130b79
mode 100644,000000..100644
--- a/website/docs/developer-guide/source-update-completion.md
+++ b/website/docs/developer-guide/source-update-completion.md
diff --cc website/docs/developer-guide/stable-releases.md
index 7ceea335f64,00000000000..7ceea335f64
mode 100644,000000..100644
--- a/website/docs/developer-guide/stable-releases.md
+++ b/website/docs/developer-guide/stable-releases.md