Skip to content

The agent that grows with you

merge origin/main (779 commits) into ethie/pm-clean

ethernet9f2ba1b74de1
diff --cc agent/context_references.py
index b5c6d815aae,2920522d973..d574d8619d4
--- a/agent/context_references.py
+++ b/agent/context_references.py
@@@ -286,9 -300,54 +300,54 @@@ def _expand_path_reference(ref: Context
# A bare "not supported" warning was a dead end (the model gave up); the file IS
# on disk where the agent's tools run, so hand it an actionable block instead.
return None, _binary_reference_block(ref, path)
- text = path.read_text(encoding="utf-8-sig")
if ref.line_start is not None:
- text = "\n".join(text.splitlines()[max(ref.line_start - 1, 0):ref.line_end or ref.line_start])
+ # A ranged ref wants a slice, not the file: stream to the window so a GB-scale
+ # file serves :1-5 without being materialized. Lines are read in bounded pieces
+ # (budget + 1) so even a single-line giant (minified JSON, one-line logs) cannot
+ # force an unbounded string into memory; skipped lines are discarded, not kept.
+ char_budget = None if max_inline_tokens is None else max_inline_tokens * CHARS_PER_TOKEN
+ line_cap = None if char_budget is None else char_budget + 1
+
+ def _next_line(fh, collect: bool, remaining: int | None = None) -> str | None:
+ """One line ("" when skipping), None at EOF. While collecting, stop as soon as the
+ pieces exceed ``remaining``: the caller returns the oversized block and never needs
+ the rest of a giant line, so it is never materialized."""
+ pieces, seen, collected = [], False, 0
+ while True:
+ piece = fh.readline() if line_cap is None else fh.readline(line_cap)
+ if not piece:
+ break
+ seen = True
+ if collect:
+ pieces.append(piece)
+ collected += len(piece)
+ if remaining is not None and collected > remaining:
+ break
+ if piece.endswith("\n"):
+ break
+ return ("".join(pieces) if collect else "") if seen else None
+
+ parts, total_chars = [], 0
+ with path.open(encoding="utf-8") as fh:
+ for _ in range(max(ref.line_start - 1, 0)):
+ if _next_line(fh, collect=False) is None:
+ break
+ for _ in range((ref.line_end or ref.line_start) - ref.line_start + 1):
+ line = _next_line(fh, collect=True, remaining=None if char_budget is None else char_budget - total_chars)
+ if line is None:
+ break
+ total_chars += len(line)
+ if char_budget is not None and total_chars > char_budget:
+ return None, _oversized_text_reference_block(ref, path, total_chars // CHARS_PER_TOKEN)
+ parts.append(line)
+ text = "".join(parts)
+ else:
+ # estimate_tokens_rough >= bytes/CHARS_PER_TOKEN for every encoding mix, so a
+ # file past that byte ceiling is certainly oversized; refuse without reading it.
+ size = path.stat().st_size
+ if max_inline_tokens is not None and size > max_inline_tokens * CHARS_PER_TOKEN:
+ return None, _oversized_text_reference_block(ref, path, size // CHARS_PER_TOKEN)
- text = path.read_text(encoding="utf-8")
++ text = path.read_text(encoding="utf-8-sig")
lang = _FENCE_LANGUAGES.get(path.suffix.lower(), "")
text_tokens = estimate_tokens_rough(text)
# Check BEFORE building the fenced block: an oversized file is not going to be
diff --cc agent/subdirectory_hints.py
index be72c0284b3,edc1d8b4349..da267dbae8e
--- a/agent/subdirectory_hints.py
+++ b/agent/subdirectory_hints.py
@@@ -43,9 -74,11 +74,11 @@@ def _first_hint_file(directory: Path)
for filename in _HINT_FILENAMES:
candidate = directory / filename
try:
- if not candidate.is_file():
+ if not candidate.is_file() or (target := _resolved_hint_target(candidate, directory)) is None:
continue
- content = candidate.read_text(encoding="utf-8-sig").strip()
+ # Read the resolved target (not the link path) so a symlink swapped
+ # between check and read still lands on the vetted file.
- content = target.read_text(encoding="utf-8").strip()
++ content = target.read_text(encoding="utf-8-sig").strip()
except (OSError, UnicodeDecodeError):
continue
return candidate, content
diff --cc apps/desktop/electron/hardening.test.ts
index 4b8a6b6053c,78dbeb13c5c..23344dee493
--- a/apps/desktop/electron/hardening.test.ts
+++ b/apps/desktop/electron/hardening.test.ts
@@@ -381,7 -383,67 +383,67 @@@ test('resolvePersistedRemoteToken keep
assert.equal(called, false, 'an empty incoming token must not re-encrypt anything')
})
+ test('resolveRemoteTokenPlainText stays silent in the keychain-opt-out default', () => {
+ // #117269: with encryption opted out (the default), plain text is the CHOSEN
+ // mode and probeSecureTokenStorage reports availability on purpose — every
+ // saved token is plain here, so warning off the encoding alone would fire for
+ // every default user.
+ assert.equal(
+ resolveRemoteTokenPlainText({
+ envOverride: false,
+ token: { encoding: 'plain', value: 'token' },
+ secureTokenStorage: true
+ }),
+ false
+ )
+ })
+
+ test('resolveRemoteTokenPlainText warns only when the token is plain and the machine cannot secure it', () => {
+ // The genuine degraded state the banner is for: the keyring has gone away
+ // (secureTokenStorage false) while a plain token sits on disk.
+ assert.equal(
+ resolveRemoteTokenPlainText({
+ envOverride: false,
+ token: { encoding: 'plain', value: 'token' },
+ secureTokenStorage: false
+ }),
+ true
+ )
+
+ // An encrypted token never warns, whatever availability reports.
+ for (const secureTokenStorage of [true, false]) {
+ assert.equal(
+ resolveRemoteTokenPlainText({
+ envOverride: false,
+ token: { encoding: 'safeStorage', value: 'blob' },
+ secureTokenStorage
+ }),
+ false
+ )
+ }
+
+ // A missing token, or an absent availability signal, never manufactures a
+ // warning — the strict `=== false` match.
+ assert.equal(resolveRemoteTokenPlainText({ envOverride: false, token: undefined, secureTokenStorage: false }), false)
+ assert.equal(
+ resolveRemoteTokenPlainText({ envOverride: false, token: { encoding: 'plain' }, secureTokenStorage: undefined }),
+ false
+ )
+ assert.equal(resolveRemoteTokenPlainText({}), false)
+
+ // The env override supplies its token from the environment, never the saved
+ // block, so a plain stored blob must not warn while the override is active.
+ assert.equal(
+ resolveRemoteTokenPlainText({
+ envOverride: true,
+ token: { encoding: 'plain', value: 'token' },
+ secureTokenStorage: false
+ }),
+ false
+ )
+ })
+
-test('writeSecretFileAtomic does not inherit loose bits from a stale temp file', () => {
+test.runIf(process.platform !== 'win32')('writeSecretFileAtomic does not inherit loose bits from a stale temp file', () => {
// renameSync keeps the TEMP file's permissions, and writeFileSync's `mode`
// is ignored when the path already exists — so a temp left by a crashed
// earlier write would otherwise hand 0644 straight to the target.
diff --cc apps/desktop/electron/main.ts
index 9c41d26a3a7,9808fdd9048..241c95ad01c
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -42,10 -41,13 +42,11 @@@ import
withRetry
} from './api-transport'
import { appIconCandidates, resolveAppIcon } from './app-icon'
+import { stageAppInstallerFile } from './app-installer-file'
+import { appVersionInfo, type AppVersionInfo, assertSourceUpdateChannel, packagedReleaseChannel } from './app-version'
+import { runAppInstallerChecker } from './appinstaller-checker'
+ import { installApplicationMenuAfterFirstWindow } from './application-menu-startup'
-import {
- stopBackendChild as stopBackendChildImpl,
- stopBackendTreesForUpdate,
- waitForBackendExit as waitForBackendExitImpl
-} from './backend-child'
+import { stopBackendChild as stopBackendChildImpl, waitForBackendExit } from './backend-child'
import {
type BackendOutputTail,
claimDecision,
@@@ -266,9 -264,8 +275,10 @@@ import { snapHudBounds } from './hud-sn
import { createHudSnapShortcut } from './hud-snap-shortcut'
import { buildHudWindowUrl } from './hud-url'
import { resolveHudWindowing } from './hud-windowing'
+import { INSTALL_STAMP, installShape } from './install-stamp'
+import type { InstallStamp } from './install-stamp'
import { createIntroRevealWindowController } from './intro-reveal-window'
+ import { isAuthWall, resolveLinkTitle } from './link-title-wall'
import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'
import { notifyLauncherWindowRevealed } from './linux-launcher-ready'
import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'
@@@ -381,8 -369,9 +392,9 @@@ import
tagRegistrySessionResponse
} from './profile-session-routing'
import { createQuickEntryShortcut, quickEntryWindowBounds, sanitizeQuickEntrySettings } from './quick-entry'
+ import { createQuitFinalization } from './quit-finalization'
import { type ActiveWork, mergeActiveWork, normalizeActiveWork, quitPromptFor } from './quit-guard'
-import { backendQuitNeedsWait, createQuitTeardownCoordinator } from './quit-teardown'
+import { backendQuitNeedsWait, createQuitTeardownCoordinator, type QuitTeardownTask } from './quit-teardown'
import * as remoteLifecycle from './remote-lifecycle'
import {
attachPowerResumeRemoteRevalidation,
@@@ -11677,19 -12868,27 +11755,27 @@@ const backendShutdown = createBackendSh
poolIdleReaper = null
}
- await waitForTeardown([localShutdown, waitForBackendExit(primary), pooledStops], 7_000)
+ await waitForTeardown([localShutdown, primaryStop, pooledStops], 7_000)
+
+ reapInstallRootedStragglers(Number.isInteger(primary?.pid) ? [primary.pid] : [])
})
- const quitTeardown = createQuitTeardownCoordinator((): void => app.quit())
+ const quitTeardown = createQuitTeardownCoordinator(() => app.quit())
+
+ const quitFinalization = createQuitFinalization({
+ isWindows: IS_WINDOWS,
+ hardExit: code => {
+ rememberLog(`[quit] forcing Windows process exit after Electron quit finalization stalled`)
+ app.exit(code)
+ }
+ })
-async function teardownSshForQuit() {
- const scopes = [...sshConnections.keys()]
-
- for (const scope of scopes) {
- void teardownSshConnection(scope || null).catch(error => rememberLog(`SSH teardown failed: ${error.message}`))
+async function teardownSshForQuit(): Promise<void> {
+ for (const scope of sshConnections.keys()) {
+ void teardownSshConnection(scope || null).catch((error: unknown): void => rememberLog(`SSH teardown failed: ${error instanceof Error ? error.message : String(error)}`))
}
- await sshTeardowns.finish(sshBootstrapCoordinator.promises(), () => sshBootstrapCoordinator.forceCleanupAll())
+ await sshTeardowns.finish(sshBootstrapCoordinator.promises(), (): Promise<void> => sshBootstrapCoordinator.forceCleanupAll())
}
async function exitAfterBackendShutdown(code) {
diff --cc apps/desktop/electron/remote-lifecycle.test.ts
index 74158fa6e7b,e8723467115..78f31022c88
--- a/apps/desktop/electron/remote-lifecycle.test.ts
+++ b/apps/desktop/electron/remote-lifecycle.test.ts
@@@ -1506,6 -1547,53 +1553,35 @@@ test('buildSpawnCommand payload variabl
}
})
-test('buildSpawnCommand lockfile publication is POSIX sh (no bash substitution)', () => {
- const cmd = buildSpawnCommand('/x/hermes', 'work', {
- hermesHome: '~/.hermes',
- logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
- ownershipId: OWNERSHIP_ID,
- reservationNonce: SPAWN_NONCE,
- spawnNonce: SPAWN_NONCE,
- tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),
- lockMetadata: { ownershipId: OWNERSHIP_ID, pid: '__PID__' }
- })
-
- // ${var//pat/rep} is bash-only; dash aborts the payload on it AFTER the
- // serve was spawned, so the client sees an unknown failure, deletes the
- // token file, and orphans the backend.
- assert.doesNotMatch(cmd, /\$\{lock_json\/\//, 'must not use ${var//} substitution under sh')
- assert.ok(cmd.includes('sed "s/__PID__/${child}/"'), 'pid substitution must use sed')
-})
-
+ test('buildSpawnCommand scopes umask 077 to the mkdir subshell (no leak into serve)', () => {
+ const cmd = buildSpawnCommand('/x/hermes', 'work', {
+ hermesHome: '~/.hermes',
+ logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
+ ownershipId: OWNERSHIP_ID,
+ reservationNonce: SPAWN_NONCE,
+ spawnNonce: SPAWN_NONCE,
+ tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),
+ lockMetadata: { ownershipId: OWNERSHIP_ID, pid: '__PID__' }
+ })
+
+ // umask 077 must apply only to the reservation-parent mkdir. A bare
+ // umask call at the top level leaks 077 into the rest of the payload,
+ // so the detached setsid backend inherits 077 instead of the login umask.
+ assert.ok(
+ cmd.includes('(umask 077 && mkdir -p'),
+ 'umask 077 must be scoped to a mkdir subshell'
+ )
+ assert.doesNotMatch(
+ cmd,
+ /(^|[^(])umask 077/,
+ 'no bare umask 077 may leak into the spawn chain'
+ )
+ assert.ok(
+ cmd.indexOf('(umask 077') < cmd.indexOf('serve --isolated'),
+ 'scoped mkdir must still precede the serve spawn'
+ )
+ })
+
test('spawnRemoteDashboard removes a token file when upload reporting fails', async () => {
const failure = new Error('channel closed')
diff --cc apps/desktop/package.json
index 37d38d8ea2c,4aa2b391bb0..638e2938439
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@@ -168,8 -168,8 +170,9 @@@
"@types/babel__core": "7.20.5",
"@types/d3-force": "3.0.10",
"@types/hast": "3.0.5",
+ "@types/js-yaml": "4.0.9",
"@types/node": "22.20.1",
+ "@types/proxy-from-env": "1.0.4",
"@types/qrcode": "1.5.6",
"@types/react": "19.2.17",
"@types/react-dom": "19.2.3",
diff --cc apps/desktop/src/app/chat/index.tsx
index 34fa97724c1,85822116dbb..4d842b67cde
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@@ -619,7 -641,25 +644,25 @@@ const ChatViewContent = memo(function C
// Hide the composer in the exhausted error state too: there's no live runtime
// to send to until a retry rebinds one. Watch windows are pure spectators of a
// subagent run driven elsewhere — no composer, transcript is read-only.
- const showChatBar = !guideOpening && !loadingSession && !resumeExhausted && !isWatchWindow()
+ //
+ // Once this route has rendered with its composer, a later transient loader
+ // (periodic list/status refresh, hydrate through an empty frame) must not
+ // unmount it again — see composerStaysMounted (#117375).
+ const settledRoutedSessionRef = useRef<null | string>(null)
+
- if (!loadingSession && isRoutedSessionView) {
++ if (!guideOpening && !loadingSession && isRoutedSessionView) {
+ settledRoutedSessionRef.current = routedSessionId
+ } else if (!isRoutedSessionView) {
+ settledRoutedSessionRef.current = null
+ }
+
+ const showChatBar = composerStaysMounted({
+ hideComposer: resumeExhausted || isWatchWindow(),
+ loadingSession,
+ routedSessionId,
+ settledRoutedSessionId: settledRoutedSessionRef.current
+ })
+
const threadKey = selectedSessionId || activeSessionId || (isRoutedSessionView ? location.pathname : 'new')
const modelOptionsQuery = useQuery<ModelOptionsResult>({
diff --cc apps/desktop/src/app/settings/gateway-settings.tsx
index e912529b61c,c555b5f118c..107980d379c
--- a/apps/desktop/src/app/settings/gateway-settings.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.tsx
@@@ -1249,15 -1474,116 +1249,22 @@@ function GatewayConnectionSettings({ em
</div>
) : null}
- {state.mode === 'remote' && !state.envOverride ? (
+ {/* An env-pinned remote (HERMES_DESKTOP_REMOTE_URL) still renders this
+ block: the override pins the URL/mode, but the browser SESSION is not
+ env-owned — docs promise "you still sign in from the Gateway settings
+ panel" (user-guide/desktop.md). Hiding it left a lapsed session with
+ no sign-in anywhere in Settings, and the boot-recovery card routes
+ every remote failure here, so "Use local gateway" became the only way
- back in (#114856). The URL input and Save/Test stay env-gated above. */}
++ back in (#114856). The URL input and Save/Test stay env-gated. */}
+ {state.mode === 'remote' ? (
- <div className="mt-5 grid gap-1">
- <ListRow
- action={
- <Input
- className={cn('h-8', CONTROL_TEXT)}
- disabled={state.envOverride}
- onChange={event => setState(current => ({ ...current, remoteUrl: event.target.value }))}
- placeholder="https://gateway.example.com/hermes"
- value={state.remoteUrl}
- />
- }
- description={g.remoteUrlDesc}
- title={g.remoteUrlTitle}
- />
-
- {state.mode === 'remote' && probeStatus === 'probing' ? (
- <div className="flex items-center gap-2 py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
- <Loader2 className="size-4 animate-spin" />
- {g.probing}
+ <div className="mt-5">
- <RemoteSetupFields disabled={saving} setup={remote} />
++ <RemoteSetupFields disabled={saving} setup={remote} urlDisabled={state.envOverride} />
+ {remote.credentials.authMode === 'token' && state.remoteTokenPlainText ? (
+ <div className="mt-2 text-sm text-destructive">
+ <div className="font-medium">{g.plainTextStoredTitle}</div>
+ <div>{g.plainTextStoredDesc}</div>
</div>
) : null}
-
- {state.mode === 'remote' && probeStatus === 'error' ? (
- <div className="flex items-start gap-2 py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
- <AlertCircle className="mt-0.5 size-4 shrink-0" />
- {g.probeError}
- </div>
- ) : null}
-
- {/* OAuth / password gateways: present a sign-in button + connection status. */}
- {state.mode === 'remote' && authResolved && authMode === 'oauth' ? (
- <ListRow
- action={
- oauthConnected ? (
- <div className="flex items-center gap-2">
- <Pill tone="primary">
- <Check className="size-3" /> {g.signedIn}
- </Pill>
- {/* Sign-in/out are session actions, not connection edits: an
- env-pinned URL must still be able to refresh its lapsed
- session from here (#114856). */}
- <Button disabled={signingIn} onClick={() => void signOut()} variant="outline">
- {signingIn ? <Loader2 className="animate-spin" /> : null}
- {g.signOut}
- </Button>
- </div>
- ) : (
- <Button disabled={signingIn || !trimmedUrl} onClick={() => void signIn()}>
- {signingIn ? <Loader2 className="animate-spin" /> : <LogIn />}
- {isPasswordProvider ? g.signIn : g.signInWith(providerLabel)}
- </Button>
- )
- }
- description={
- oauthConnected
- ? isPasswordProvider
- ? g.authSignedInPassword
- : g.authSignedInOauth
- : isPasswordProvider
- ? g.authNeedsPassword
- : g.authNeedsOauth(providerLabel)
- }
- title={g.authTitle}
- />
- ) : null}
-
- {/* Session-token gateways: keep the existing token entry box. */}
- {state.mode === 'remote' && authResolved && authMode === 'token' ? (
- <>
- <ListRow
- action={
- <Input
- autoComplete="off"
- className={cn('h-8 font-mono', CONTROL_TEXT)}
- disabled={state.envOverride}
- onChange={event => setRemoteToken(event.target.value)}
- placeholder={
- state.remoteTokenSet
- ? g.existingToken(state.remoteTokenPreview ?? g.savedToken)
- : g.pasteSessionToken
- }
- type="password"
- value={remoteToken}
- />
- }
- description={g.tokenDesc}
- title={g.tokenTitle}
- />
-
- {/* The saved token is on disk in plain text (no OS keyring). Same
- banner idiom as envOverride so it reads as a real warning. */}
- {state.remoteTokenPlainText ? (
- <div className="mt-2 flex items-start gap-2 rounded-xl border border-destructive/30 bg-destructive/10 px-3 py-2.5 text-[length:var(--conversation-caption-font-size)] text-destructive">
- <AlertCircle className="mt-0.5 size-4 shrink-0" />
- <div>
- <div className="font-medium">{g.plainTextStoredTitle}</div>
- <div className="mt-1 leading-5">{g.plainTextStoredDesc}</div>
- </div>
- </div>
- ) : null}
- </>
- ) : null}
</div>
) : null}
diff --cc apps/desktop/src/components/remote-setup/fields.tsx
index 9ae00f239dc,00000000000..75e016ae99d
mode 100644,000000..100644
--- a/apps/desktop/src/components/remote-setup/fields.tsx
+++ b/apps/desktop/src/components/remote-setup/fields.tsx
@@@ -1,152 -1,0 +1,155 @@@
+import type { ReactElement, ReactNode } from 'react'
+
+import { ListRow, Pill } from '@/app/settings/primitives'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { useI18n } from '@/i18n'
+import { AlertCircle, Check, Loader2, LogIn } from '@/lib/icons'
+
+import type { RemoteSetup } from './use-remote-setup'
+
+interface FieldProps {
+ stacked: boolean
+ title: string
+ description?: string
+ children: ReactNode
+}
+
+function Field({ stacked, title, description, children }: FieldProps): ReactElement {
+ return stacked ? (
+ <div className="grid gap-1.5">
+ <span className="text-xs font-medium text-muted-foreground">{title}</span>
+ {children}
+ {description ? <span className="text-xs text-muted-foreground">{description}</span> : null}
+ </div>
+ ) : (
+ <ListRow action={children} description={description} title={title} />
+ )
+}
+
+interface RemoteSetupFieldsProps {
+ setup: RemoteSetup
+ disabled?: boolean
++ /** Pins only the URL input: an env-owned remote (HERMES_DESKTOP_REMOTE_URL) still signs in here. */
++ urlDisabled?: boolean
+ urlOnly?: boolean
+ onUrlChange?: () => void
+}
+
+export function RemoteSetupFields({
+ setup,
+ disabled = false,
++ urlDisabled = false,
+ urlOnly = false,
+ onUrlChange
+}: RemoteSetupFieldsProps): ReactElement {
+ const { t } = useI18n()
+ const g = t.settings.gateway
+ const firstRun = setup.host === 'first-run'
+ const registry = setup.host === 'registry'
+ const copy = firstRun ? t.install : g
+ const { credentials, isPassword, providerLabel } = setup
+ const urlTitle = registry ? t.settings.connections.urlTitle : copy.remoteUrlTitle
+
+ const authDescription = firstRun
+ ? credentials.oauthConnected
+ ? t.install.authSignedIn
+ : t.install.authNeedsOauth(providerLabel)
+ : credentials.oauthConnected
+ ? isPassword
+ ? g.authSignedInPassword
+ : g.authSignedInOauth
+ : isPassword
+ ? g.authNeedsPassword
+ : g.authNeedsOauth(providerLabel)
+
+ return (
+ <div className="grid gap-3">
+ <Field description={registry ? undefined : copy.remoteUrlDesc} stacked={firstRun} title={urlTitle}>
+ <Input
+ aria-label={urlTitle}
+ autoComplete="url"
- disabled={disabled}
++ disabled={disabled || urlDisabled}
+ onChange={event => {
+ setup.setUrl(event.target.value)
+ onUrlChange?.()
+ }}
+ placeholder={registry ? 'http://homelab.lan:9119' : t.install.remoteUrlPlaceholder}
+ value={credentials.url}
+ />
+ </Field>
+ {!registry && setup.probeStatus === 'probing' ? (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" />
+ {copy.probing}
+ </div>
+ ) : null}
+ {!registry && setup.probeStatus === 'error' ? (
+ <div className="flex items-center gap-2 text-sm text-destructive">
+ <AlertCircle className="size-4" />
+ {copy.probeError}
+ </div>
+ ) : null}
+ {registry && !urlOnly ? (
+ <Field stacked={false} title={g.authTitle}>
+ <div className="flex gap-2">
+ {(['token', 'oauth'] as const).map(mode => (
+ <Button
+ disabled={disabled}
+ key={mode}
+ onClick={() => setup.setAuthMode(mode)}
+ size="sm"
+ variant={credentials.authMode === mode ? 'default' : 'outline'}
+ >
+ {mode === 'token' ? g.tokenTitle : g.signIn}
+ </Button>
+ ))}
+ </div>
+ </Field>
+ ) : null}
+ {!urlOnly && setup.authResolved && credentials.authMode === 'oauth' ? (
+ <Field description={authDescription} stacked={firstRun} title={copy.authTitle}>
+ {credentials.oauthConnected ? (
+ <div className="flex items-center gap-2">
+ <Pill tone="primary">
+ <Check className="size-3" />
+ {firstRun ? t.install.connected : g.signedIn}
+ </Pill>
+ {setup.host === 'settings' ? (
+ <Button disabled={disabled || setup.signingIn} onClick={() => void setup.signOut()} variant="outline">
+ {g.signOut}
+ </Button>
+ ) : null}
+ </div>
+ ) : (
+ <Button
+ disabled={disabled || setup.signingIn || !setup.payload.remoteUrl}
+ onClick={() => void setup.signIn()}
+ size="sm"
+ >
+ {setup.signingIn ? <Loader2 className="animate-spin" /> : <LogIn />}
+ {isPassword ? copy.signIn : copy.signInWith(providerLabel)}
+ </Button>
+ )}
+ </Field>
+ ) : null}
+ {!urlOnly && setup.authResolved && credentials.authMode === 'token' ? (
+ <Field description={copy.tokenDesc} stacked={firstRun} title={copy.tokenTitle}>
+ <Input
+ aria-label={copy.tokenTitle}
+ autoComplete="off"
+ disabled={disabled}
+ onChange={event => setup.setToken(event.target.value)}
+ placeholder={
+ credentials.tokenSet ? g.existingToken(credentials.tokenPreview ?? g.savedToken) : copy.pasteSessionToken
+ }
+ type="password"
+ value={credentials.token}
+ />
+ </Field>
+ ) : null}
+ {setup.error ? <div className="text-sm text-destructive">{setup.error}</div> : null}
+ {setup.success ? <div className="text-sm text-primary">{setup.success}</div> : null}
+ </div>
+ )
+}
diff --cc apps/desktop/src/i18n/en.ts
index 814f4be725f,63ce4d26936..d1a82c9ccf3
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -39,8 -28,14 +34,13 @@@ export const en: Translations =
search: 'Find an app',
empty: 'No matching apps',
disclaimer: 'Connecting is optional. Only authorize the apps you want Hermes to use.',
- execution: 'Connector tools'
+ execution: 'Connector tools',
+ setup: server => `Set up ${server}`,
+ openInBrowser: 'Open in browser',
+ setupCancel: 'Cancel',
+ authorizedToolsUnavailable: 'Authorized. Tools unavailable.',
+ required: 'Required'
},
-
sessionImport: {
title: 'Continue from another app',
subtitle: 'Bring a conversation into Hermes and pick up where you left off.',
diff --cc apps/desktop/src/i18n/ru.ts
index 5e968f52041,85cc93f4021..730728e04a0
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@@ -1431,8 -1462,10 +1433,9 @@@ export const ru = defineLocale(
fallbackAdd: 'Добавить запасную',
fallbackEmpty: 'Запасных моделей нет — используется модель по умолчанию, если она не падает.',
notInCatalog: 'нет в списке моделей этого провайдера — вызовы могут уходить на запасную.',
+ moaTitle: 'Смесь агентов',
tasks: {
vision: { label: 'Зрение', hint: 'Анализ изображений' },
- web_extract: { label: 'Веб-извлечение', hint: 'Суммаризация страниц' },
compression: { label: 'Сжатие', hint: 'Компрессия контекста' },
skills_hub: { label: 'Хаб навыков', hint: 'Поиск навыков' },
approval: { label: 'Одобрение', hint: 'Умное авто-одобрение' },
diff --cc apps/desktop/src/i18n/zh.ts
index 4599ebb54d3,568e397e9f7..44692ccf75a
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@@ -34,8 -27,14 +33,13 @@@ export const zh = defineLocale(
search: '查找应用',
empty: '没有匹配的应用',
disclaimer: '连接为可选操作。请仅授权你希望 Hermes 使用的应用。',
- execution: '连接器工具'
+ execution: '连接器工具',
+ setup: server => `设置 ${server}`,
+ openInBrowser: '在浏览器中打开',
+ setupCancel: '取消',
+ authorizedToolsUnavailable: '已授权。工具不可用。',
+ required: '必填'
},
-
sessionImport: {
title: '从其他应用继续',
subtitle: '将对话导入 Hermes,接着上次的进度继续。',
diff --cc gateway/config.py
index 34236652ea7,0ff264aaf87..84c924898a4
--- a/gateway/config.py
+++ b/gateway/config.py
@@@ -170,6 -171,22 +171,22 @@@ def _getenv_str(name: str, default: st
_Platform__bundled_plugin_names: Optional[set] = None # cached outside the enum: never a member
+ _Platform__bundled_plugin_aliases: Optional[dict] = None # manifest ``name:`` (lower) -> directory name
+
+
+ def _bundled_platform_manifest_name(plugin_dir: Path) -> Optional[str]:
+ """Lowercased ``name:`` from a bundled platform's plugin manifest (None when absent/unreadable)."""
+ try:
+ import yaml
+ manifest_file = next(
+ (plugin_dir / m for m in ("plugin.yaml", "plugin.yml") if (plugin_dir / m).exists()), None)
+ if manifest_file is None:
+ return None
- data = yaml.safe_load(manifest_file.read_text(encoding="utf-8")) or {}
++ data = yaml.safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}
+ name = data.get("name") if isinstance(data, dict) else None
+ return str(name).strip().lower() or None
+ except Exception:
+ return None
class Platform(Enum):
diff --cc gateway/run.py
index d03e22da59d,e93dc6455fa..f9d9f9ca30d
--- a/gateway/run.py
+++ b/gateway/run.py
@@@ -4588,19 -4592,14 +4592,24 @@@ def _housekeeping_org_skill_sync() -> N
maybe_pull_org_skills()
+def _housekeeping_plugin_update_check() -> None:
+ """Plugin update-check cadence (plugins_cadence): due-gated by
+ plugins.auto_update_check_hours, read-only, receipt-surfaced; the
+ opt-in auto-apply rides the manual update pipeline. A network error
+ costs one warning and a stamped marker — never an apply."""
+ from hermes_cli.plugins_cadence import maybe_run_gateway_check
+
+ maybe_run_gateway_check(log=logger)
+
+
def _housekeeping_auto_archive() -> None:
"""Stale-session auto-archive on a live timer (the startup hook fires once); maybe_auto_archive()
- is gated by sessions.min_interval_hours. Opens its own SessionDB — SQLite connections are thread-bound."""
+ is gated by sessions.min_interval_hours. Opens its own SessionDB — SQLite connections are thread-bound.
+
+ Profile-scoped by its caller: ``acquire()`` and ``load_config()`` both resolve through
+ ``get_hermes_home()``, so an unscoped tick swept only the LAUNCH profile's store and a
+ multiplexed secondary was never archived by anyone — the dashboard/serve trigger defers to
+ the gateway for every profile a gateway owns (``web_server_sessions``)."""
from hermes_cli.config import load_config as _load_full_config
from hermes_state_registry import acquire, release_or_close
_sess_cfg = (_load_full_config().get("sessions") or {})
@@@ -4703,9 -4703,7 +4713,9 @@@ def _start_gateway_housekeeping
(60, "Curator tick", profile_scoped_chore(runner, _housekeeping_curator)),
(60, "Sync pull tick", profile_scoped_chore(runner, _housekeeping_skill_sync)),
(60, "Org sync pull tick", profile_scoped_chore(runner, _housekeeping_org_skill_sync)),
- (60, "Auto-archive tick", _housekeeping_auto_archive),
+ (60, "Auto-archive tick", profile_scoped_chore(runner, _housekeeping_auto_archive)),
+ # Due-gated inside: the first tick after startup runs an overdue check, not tick 60.
- (1, "Plugin update check", _housekeeping_plugin_update_check),
++ (1, "Plugin update check", profile_scoped_chore(runner, _housekeeping_plugin_update_check)),
(1, "Deferred FTS retry tick", _housekeeping_deferred_fts_retry),
(1, "gateway housekeeping memory trim", _housekeeping_memory_trim),
(1, "MCP config reconcile", _mcp_config_reconciler(runner)),
diff --cc hermes_cli/cli_config_load.py
index 00000000000,f9b368b4839..f7af2b875e7
mode 000000,100644..100644
--- a/hermes_cli/cli_config_load.py
+++ b/hermes_cli/cli_config_load.py
@@@ -1,0 -1,318 +1,318 @@@
+ """Classic-CLI config loading: prefill messages, reasoning/service-tier parsing, terminal env mirroring, CLI defaults + user YAML merge and the logging/display bootstrap.
+
+ Split out of ``cli.py``; ``cli`` re-exports every public name and moved bodies late-bind
+ cli-level names through ``from cli import ...`` at call time so facade monkeypatch seams hold.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import os
+ from pathlib import Path
+ from typing import List, Dict, Any
+ from utils import fast_safe_load
+
+ # Log-record parity with the origin module.
+ logger = logging.getLogger("cli")
+
+
+ def _cli():
+ """Late import of the ``cli`` facade: mutable CLI module state (and its test seams) lives there."""
+ import cli
+
+ return cli
+
+
+ def _load_prefill_messages(file_path: str) -> List[Dict[str, Any]]:
+ """Load prefill messages (JSON array) from *file_path*; relative to ~/.hermes/; missing/empty -> []."""
+ from cli import _hermes_home
+ if not file_path:
+ return []
+ path = Path(file_path).expanduser()
+ if not path.is_absolute():
+ path = _hermes_home / path
+ if not path.exists():
+ logger.warning("Prefill messages file not found: %s", path)
+ return []
+ try:
- with open(path, "r", encoding="utf-8") as f:
++ with open(path, "r", encoding="utf-8-sig") as f:
+ data = json.load(f)
+ if not isinstance(data, list):
+ logger.warning("Prefill messages file must contain a JSON array: %s", path)
+ return []
+ return data
+ except Exception as e:
+ logger.warning("Failed to load prefill messages from %s: %s", path, e)
+ return []
+
+
+ def _resolve_prefill_messages_file(config: Dict[str, Any]) -> str:
+ """Prefill file path: env, then top-level ``prefill_messages_file``, then legacy ``agent.*``."""
+ agent_cfg = config.get("agent", {})
+ return (
+ os.getenv("HERMES_PREFILL_MESSAGES_FILE", "").strip()
+ or str(config.get("prefill_messages_file", "") or "").strip()
+ or (str(agent_cfg.get("prefill_messages_file", "") or "").strip() if isinstance(agent_cfg, dict) else "")
+ )
+
+
+ def _parse_reasoning_config(effort) -> dict | None:
+ """Parse a reasoning effort level (string or YAML bool; ``false``/``off`` = disabled)."""
+ from hermes_constants import parse_reasoning_effort
+ result = parse_reasoning_effort(effort)
+ if effort and str(effort).strip() and result is None:
+ logger.warning("Unknown reasoning_effort '%s', using default (medium)", effort)
+ return result
+
+
+ def _parse_service_tier_config(raw: str) -> str | None:
+ """Parse a persisted fast-mode preference: None, "priority", "auto", or "cold"."""
+ value = str(raw or "").strip().lower()
+ if not value or value in {"normal", "default", "standard", "off", "none"}:
+ return None
+ if value in {"fast", "priority", "on"}:
+ return "priority"
+ if value in {"auto", "cold"}:
+ return value
+ logger.warning("Unknown service_tier '%s', ignoring", raw)
+ return None
+
+
+ # terminal.<key> -> TERMINAL_<KEY> env var. Container-resource keys apply to docker,
+ # singularity, modal, daytona and vercel_sandbox only (ignored for local/ssh).
+ _TERMINAL_ENV_MAPPINGS = {
+ key: f"TERMINAL_{key.upper()}"
+ for key in (
+ "degraded_mode", "cwd", "timeout", "home_mode", "lifetime_seconds", "docker_image",
+ "docker_forward_env", "singularity_image", "modal_image", "daytona_image", "vercel_runtime",
+ "ssh_host", "ssh_user", "ssh_port", "ssh_key", "container_cpu", "container_memory",
+ "container_disk", "container_persistent", "docker_volumes", "docker_env", "docker_extra_args",
+ "docker_shm_size", "docker_mount_cwd_to_workspace", "docker_network", "docker_run_as_host_user",
+ "docker_snap_compat",
+ "docker_persist_across_processes", "docker_shared_container_key", "docker_orphan_reaper",
+ "sandbox_dir", "persistent_shell",
+ )
+ }
+
+
+ _TERMINAL_ENV_MAPPINGS = {"env_type": "TERMINAL_ENV", **_TERMINAL_ENV_MAPPINGS, "sudo_password": "SUDO_PASSWORD"}
+
+
+ # Per-task auxiliary endpoint tuples (config key -> env var).
+ _AUXILIARY_TASK_ENV = {
+ "vision": {
+ "provider": "AUXILIARY_VISION_PROVIDER",
+ "model": "AUXILIARY_VISION_MODEL",
+ "base_url": "AUXILIARY_VISION_BASE_URL",
+ "api_key": "AUXILIARY_VISION_API_KEY",
+ },
+ "approval": {
+ "provider": "AUXILIARY_APPROVAL_PROVIDER",
+ "model": "AUXILIARY_APPROVAL_MODEL",
+ "base_url": "AUXILIARY_APPROVAL_BASE_URL",
+ "api_key": "AUXILIARY_APPROVAL_API_KEY",
+ },
+ }
+
+
+ _CWD_PLACEHOLDERS = (".", "auto", "cwd")
+
+
+ def _mirror_config_to_env(defaults, _file_has_terminal_config):
+ """Project config.yaml values into the env vars the tool modules read (terminal/browser/auxiliary/security/sessions). Env always wins when already set."""
+ from cli import _AUXILIARY_TASK_ENV, _CWD_PLACEHOLDERS, _TERMINAL_ENV_MAPPINGS
+ terminal_config = defaults.get("terminal", {})
+
+ # "backend" (documented) and legacy "env_type" are both accepted; "backend" wins.
+ if "backend" in terminal_config:
+ terminal_config["env_type"] = terminal_config["backend"]
+
+ # Local backend: cwd is always os.getcwd(). Non-local: a placeholder is popped so
+ # terminal_tool uses its per-backend default; an explicit path is kept.
+ effective_backend = terminal_config.get("env_type", "local")
+ if effective_backend == "local":
+ terminal_config["cwd"] = os.getcwd()
+ defaults["terminal"]["cwd"] = terminal_config["cwd"]
+ elif terminal_config.get("cwd") in _CWD_PLACEHOLDERS:
+ terminal_config.pop("cwd", None)
+
+ # TERMINAL_CWD is force-exported (beats stale .env) except inside a gateway process,
+ # whose config bridge already set it.
+ _is_gateway = os.environ.get("_HERMES_GATEWAY") == "1"
+ for config_key, env_var in _TERMINAL_ENV_MAPPINGS.items():
+ if config_key not in terminal_config:
+ continue
+ val = terminal_config[config_key]
+ if env_var == "TERMINAL_CWD":
+ if not _is_gateway:
+ os.environ[env_var] = str(val)
+ elif _file_has_terminal_config or env_var not in os.environ:
+ os.environ[env_var] = json.dumps(val) if isinstance(val, (list, dict)) else str(val)
+
+ browser_config = defaults.get("browser", {})
+ if "inactivity_timeout" in browser_config:
+ os.environ["BROWSER_INACTIVITY_TIMEOUT"] = str(browser_config["inactivity_timeout"])
+
+ # Only non-empty / non-"auto" auxiliary values are bridged so auto-detection still works.
+ auxiliary_config = defaults.get("auxiliary", {})
+ for task_key, env_map in _AUXILIARY_TASK_ENV.items():
+ task_cfg = auxiliary_config.get(task_key, {})
+ if not isinstance(task_cfg, dict):
+ continue
+ for field, env_var in env_map.items():
+ val = str(task_cfg.get(field, "")).strip()
+ if val and not (field == "provider" and val == "auto"):
+ os.environ[env_var] = val
+
+ security_config = defaults.get("security", {})
+ if isinstance(security_config, dict):
+ redact = security_config.get("redact_secrets")
+ if redact is not None:
+ os.environ["HERMES_REDACT_SECRETS"] = str(redact).lower()
+
+ # Session-search index knobs (hermes_state reads the env carriers).
+ sessions_config = defaults.get("sessions", {})
+ if isinstance(sessions_config, dict):
+ if "cjk_fts" in sessions_config:
+ os.environ["HERMES_CJK_FTS"] = str(sessions_config["cjk_fts"])
+ if "search_slow_ms" in sessions_config:
+ os.environ["HERMES_SEARCH_SLOW_MS"] = str(sessions_config["search_slow_ms"])
+
+
+ def _cli_config_defaults():
+ """Built-in defaults for every config key the CLI reads (the file overlays these)."""
+ img = "nikolaik/python-nodejs:python3.11-nodejs20"
+ return {
+ "model": {"default": "", "base_url": "", "provider": "auto"},
+ "terminal": {
+ "env_type": "local", "cwd": ".", "home_mode": "auto", "lifetime_seconds": 300, # cwd "." -> os.getcwd()
+ "docker_image": img, "docker_forward_env": [], "singularity_image": f"docker://{img}",
+ "modal_image": img, "daytona_image": img, "docker_volumes": [],
+ "docker_mount_cwd_to_workspace": False, # opt-in only: sandbox isolation
+ "docker_shared_container_key": "",
+ },
+ "browser": {
+ "inactivity_timeout": 120, "record_sessions": False, "engine": "auto", # auto (Chrome) | lightpanda | chrome
+ "camofox": {"rewrite_loopback_urls": False, "loopback_host_alias": "host.docker.internal"},
+ },
+ # threshold: fraction of the model's context limit; min_tail: real user messages kept in the tail
+ "compression": {"enabled": True, "threshold": 0.50, "min_tail_user_messages": 1},
+ "agent": {
+ "max_turns": 500, "verbose": False, "system_prompt": "", "prefill_messages_file": "", # max_turns shared with subagents
+ "reasoning_effort": "", "service_tier": "",
+ "personalities": {}, # user overrides merged by name over hermes_cli.personality builtins
+ },
+ "display": {
+ "compact": False,
+ # /resume recap tuning and show_reasoning: keep in sync with hermes_cli/config.py DEFAULT_CONFIG
+ "resume_display": "full", "resume_exchanges": 10, "resume_max_user_chars": 300,
+ "resume_max_assistant_chars": 200, "resume_max_assistant_lines": 3, "resume_skip_tool_only": True,
+ "show_reasoning": True, "reasoning_full": False, "streaming": True, "busy_input_mode": "interrupt",
+ "persistent_output": True, "persistent_output_max_lines": 200,
+ # Also clear scrollback on redraw/resize recovery; off because users prefer history.
+ "cli_rebuild_scrollback_on_redraw": False,
+ "persist_prompts": True, # one-line summary of resolved modal prompts into scrollback
+ "skin": "default",
+ },
+ "code_execution": {"timeout": 300, "max_tool_calls": 50},
+ "auxiliary": {"vision": {"provider": "auto", "model": "", "base_url": "", "api_key": ""}},
+ # delegation: empty model/provider = inherit parent; api_key falls back to OPENAI_API_KEY
+ "delegation": {"max_iterations": 45, "model": "", "provider": "", "base_url": "", "api_key": ""},
+ "onboarding": {"seen": {}}, # first-touch hint flags (agent/onboarding.py), latched once shown
+ }
+
+
+ def _merge_file_config(defaults: Dict[str, Any], file_config: Dict[str, Any]) -> None:
+ """Overlay a parsed config file onto *defaults* in place (model normalization, deep merge, legacy keys)."""
+ # model: string (new format) or dict (old format with default/base_url)
+ if "model" in file_config:
+ if isinstance(file_config["model"], str):
+ defaults["model"]["default"] = file_config["model"]
+ elif isinstance(file_config["model"], dict):
+ defaults["model"].update(file_config["model"])
+ # Promote model.model -> model.default (HermesCLI checks "default" first).
+ if "model" in file_config["model"] and "default" not in file_config["model"]:
+ defaults["model"]["default"] = file_config["model"]["model"]
+
+ # Deep-merge dict sections, overwrite scalars; a None section keeps the defaults;
+ # unknown keys (platform_toolsets, memory, ...) are carried over.
+ for key, value in file_config.items():
+ if key == "model":
+ continue
+ if isinstance(defaults.get(key), dict):
+ if isinstance(value, dict):
+ defaults[key].update(value)
+ elif value is not None:
+ defaults[key] = value
+ else:
+ defaults[key] = value
+
+ # Legacy root-level max_turns -> agent.max_turns whenever the nested key is missing.
+ agent_file_config = file_config.get("agent")
+ if "max_turns" in file_config and not (
+ isinstance(agent_file_config, dict) and agent_file_config.get("max_turns") is not None
+ ):
+ defaults["agent"]["max_turns"] = file_config["max_turns"]
+
+
+ def load_cli_config() -> Dict[str, Any]:
+ """~/.hermes/config.yaml (else ./cli-config.yaml) over built-in defaults; env vars win.
+
+ ``HERMES_IGNORE_USER_CONFIG=1`` skips the user config entirely (``.env`` still loads).
+ """
+ from cli import _cli_config_defaults, _hermes_home, _merge_file_config, _mirror_config_to_env
+ config_path = _hermes_home / 'config.yaml'
+ if not config_path.exists() or os.environ.get("HERMES_IGNORE_USER_CONFIG") == "1":
+ config_path = Path(__file__).parent / 'cli-config.yaml'
+
+ defaults = _cli_config_defaults()
+
+ # Only a file's terminal section may overwrite terminal env vars already set by .env.
+ _file_has_terminal_config = False
+
+ if config_path.exists():
+ try:
- with open(config_path, "r", encoding="utf-8") as f:
++ with open(config_path, "r", encoding="utf-8-sig") as f:
+ from hermes_cli.config import _normalize_root_model_keys
+
+ file_config = _normalize_root_model_keys(fast_safe_load(f) or {})
+
+ _file_has_terminal_config = "terminal" in file_config
+ _merge_file_config(defaults, file_config)
+ except Exception as e:
+ logger.warning("Failed to load cli-config.yaml: %s", e)
+
+ # Expand ${ENV_VAR} references before bridging to env vars.
+ from hermes_cli.config import _expand_env_vars
+ defaults = _expand_env_vars(defaults)
+
+ # Administrator-pinned (managed scope) values overlay LAST; cli.py builds its config
+ # independently of hermes_cli.config, so this keeps parity with `hermes config`. Fail-open.
+ from hermes_cli import managed_scope
+
+ defaults = managed_scope.apply_managed_overlay(defaults)
+
+ _mirror_config_to_env(defaults, _file_has_terminal_config)
+
+ return defaults
+
+
+ def _init_logging_and_display_from_config() -> None:
+ """Best-effort startup side effects: logging, config warnings, skin, display knobs."""
+ from importlib import import_module as _im
+
+ def _display(key, default):
+ return _cli().CLI_CONFIG.get("display", {}).get(key, default)
+
+ for step in (
+ lambda: _im("hermes_logging").setup_logging(mode="cli"),
+ lambda: _im("hermes_cli.config").print_config_warnings(),
+ lambda: _im("hermes_cli.skin_engine").init_skin_from_config(_cli().CLI_CONFIG),
+ lambda: _im("agent.display").set_tool_preview_max_len(int(_display("tool_preview_length", 0) or 0)),
+ lambda: _im("agent.display").set_friendly_tool_labels(bool(_display("friendly_tool_labels", True))),
+ ):
+ try:
+ step()
+ except Exception:
+ pass
diff --cc hermes_cli/cli_terminal_input.py
index 00000000000,ee42464a269..6eda2839541
mode 000000,100644..100644
--- a/hermes_cli/cli_terminal_input.py
+++ b/hermes_cli/cli_terminal_input.py
@@@ -1,0 -1,600 +1,600 @@@
+ """Classic-CLI terminal input helpers: file-drop/attachment path resolution, bracketed-paste patching, extended Enter-key sequences, CPR leak guards and TUI input-height estimation.
+
+ Split out of ``cli.py``; ``cli`` re-exports every public name and moved bodies late-bind
+ cli-level names through ``from cli import ...`` at call time so facade monkeypatch seams hold.
+ """
+
+ from __future__ import annotations
+
+ import logging
+ import os
+ import re
+ import shutil
+ import sys
+ import time
+ from contextlib import suppress
+ from pathlib import Path
+ from typing import Dict, Any, Optional, Mapping
+ from urllib.parse import unquote, urlparse
+
+ # Log-record parity with the origin module.
+ logger = logging.getLogger("cli")
+
+
+ def _cli():
+ """Late import of the ``cli`` facade: mutable CLI module state (and its test seams) lives there."""
+ import cli
+
+ return cli
+
+
+ _IMAGE_EXTENSIONS = frozenset({
+ '.png', '.jpg', '.jpeg', '.gif', '.webp',
+ '.bmp', '.tiff', '.tif', '.svg', '.ico',
+ })
+
+
+ def _termux_example_image_path(filename: str = "cat.png") -> str:
+ """Return a realistic example media path for the current Termux setup."""
+ candidates = [
+ os.path.expanduser("~/storage/shared"),
+ "/sdcard",
+ "/storage/emulated/0",
+ "/storage/self/primary",
+ ]
+ # Literal "/" so the Android hint is right even on Windows.
+ for root in candidates:
+ if os.path.isdir(root):
+ return f"{root}/Pictures/{filename}"
+ return f"~/storage/shared/Pictures/{filename}"
+
+
+ def _split_path_input(raw: str) -> tuple[str, str]:
+ r"""Split a leading path token (quoted or with ``\ `` escapes) from trailing free-form text."""
+ raw = str(raw or "").strip()
+ if not raw:
+ return "", ""
+
+ if raw[0] in {'"', "'"}:
+ quote = raw[0]
+ pos = 1
+ while pos < len(raw):
+ ch = raw[pos]
+ if ch == '\\' and pos + 1 < len(raw):
+ pos += 2
+ continue
+ if ch == quote:
+ return raw[1:pos], raw[pos + 1 :].strip()
+ pos += 1
+ return raw[1:], ""
+
+ pos = 0
+ while pos < len(raw):
+ ch = raw[pos]
+ if ch == '\\' and pos + 1 < len(raw) and raw[pos + 1] == ' ':
+ pos += 2
+ elif ch == ' ':
+ break
+ else:
+ pos += 1
+
+ return raw[:pos].replace('\\ ', ' '), raw[pos:].strip()
+
+
+ def _resolve_attachment_path(raw_path: str) -> Path | None:
+ """Resolve a user-supplied attachment path (quotes, ``~``, env vars, ``file://``; relative to TERMINAL_CWD).
+
+ Returns ``None`` unless it resolves to an existing file.
+ """
+ token = str(raw_path or "").strip()
+ if not token:
+ return None
+
+ if token[0] == token[-1] and token[0] in {'"', "'"}:
+ token = token[1:-1].strip()
+ token = token.replace('\\ ', ' ')
+ if not token:
+ return None
+
+ expanded = token
+ if token.startswith("file://"):
+ try:
+ parsed = urlparse(token)
+ if parsed.scheme == "file":
+ expanded = unquote(parsed.path or "")
+ if parsed.netloc and os.name == "nt":
+ expanded = f"//{parsed.netloc}{expanded}"
+ elif os.name == "nt" and len(expanded) >= 3 and expanded[0] == "/" and expanded[1].isalpha() and expanded[2] == ":":
+ # file:///C:/... parses to path "/C:/..." — drop the leading slash
+ # so it resolves as a drive-letter path.
+ expanded = expanded[1:]
+ except Exception:
+ expanded = token
+ expanded = os.path.expandvars(os.path.expanduser(expanded))
+ if os.name != "nt":
+ normalized = expanded.replace("\\", "/")
+ if len(normalized) >= 3 and normalized[1] == ":" and normalized[2] == "/" and normalized[0].isalpha():
+ expanded = f"/mnt/{normalized[0].lower()}/{normalized[3:]}"
+ path = Path(expanded)
+ if not path.is_absolute():
+ base_dir = Path(os.getenv("TERMINAL_CWD", os.getcwd()))
+ path = base_dir / path
+
+ try:
+ resolved = path.resolve()
+ except Exception:
+ resolved = path
+
+ # ENAMETOOLONG for a pasted `/goal <long prose>` that passed the `/` prefilter
+ # would otherwise reach process_loop and silently lose the input.
+ try:
+ if not resolved.exists() or not resolved.is_file():
+ return None
+ except OSError:
+ return None
+ return resolved
+
+
+ def _file_drop_result(path: Path, remainder: str) -> dict:
+ from cli import _IMAGE_EXTENSIONS
+ return {"path": path, "is_image": path.suffix.lower() in _IMAGE_EXTENSIONS, "remainder": remainder}
+
+
+ def _detect_file_drop(user_input: str) -> "dict | None":
+ """Detect a dragged/pasted file path at the start of *user_input* -> ``{path, is_image, remainder}`` or None."""
+ from cli import _file_drop_result, _resolve_attachment_path, _split_path_input
+ if not isinstance(user_input, str):
+ return None
+
+ stripped = user_input.strip()
+ if not stripped:
+ return None
+
+ # Optionally quoted; then /, ~, ./, ../, a Windows drive prefix, or (unquoted) file://.
+ quoted = stripped[:1] in {"'", '"'}
+ unquoted = stripped[1:] if quoted else stripped
+ starts_like_path = (
+ unquoted.startswith(("/", "~", "./", "../"))
+ or (not quoted and unquoted.startswith("file://"))
+ or (len(unquoted) >= 3 and unquoted[1] == ":" and unquoted[2] in {"\\", "/"} and unquoted[0].isalpha())
+ )
+ if not starts_like_path:
+ return None
+
+ direct_path = _resolve_attachment_path(stripped)
+ if direct_path is not None:
+ return _file_drop_result(direct_path, "")
+
+ first_token, remainder = _split_path_input(stripped)
+ drop_path = _resolve_attachment_path(first_token)
+ if drop_path is None and " " in stripped and not quoted:
+ for pos in reversed([idx for idx, ch in enumerate(stripped) if ch == " "]):
+ drop_path = _resolve_attachment_path(stripped[:pos].rstrip())
+ if drop_path is not None:
+ remainder = stripped[pos + 1 :].strip()
+ break
+ if drop_path is None:
+ return None
+ return _file_drop_result(drop_path, remainder)
+
+
+ def _format_image_attachment_badges(attached_images: list[Path], image_counter: int, width: int | None = None) -> str:
+ """Attached-image badge row: compact summary on narrow terminals, per-image badges otherwise."""
+ if not attached_images:
+ return ""
+
+ width = width or shutil.get_terminal_size((80, 24)).columns
+
+ def _trunc(name: str, limit: int) -> str:
+ return name if len(name) <= limit else name[: max(1, limit - 3)] + "..."
+
+ if width < 52:
+ if len(attached_images) == 1:
+ return f"[📎 {_trunc(attached_images[0].name, 20)}]"
+ return f"[📎 {len(attached_images)} images attached]"
+
+ if width < 80:
+ if len(attached_images) == 1:
+ return f"[📎 {_trunc(attached_images[0].name, 32)}]"
+ return f"[📎 {_trunc(attached_images[0].name, 20)}] [+{len(attached_images) - 1}]"
+
+ base = image_counter - len(attached_images) + 1
+ return " ".join(f"[📎 Image #{base + i}]" for i in range(len(attached_images)))
+
+
+ def _should_auto_attach_clipboard_image_on_paste(pasted_text: str) -> bool:
+ """Auto-attach clipboard images only for image-only paste gestures."""
+ return not pasted_text.strip()
+
+
+ def _hermes_call_output_screen_diff(
+ orig_osd, app, output, screen, current_pos, color_depth, previous_screen, last_style, is_done, full_screen,
+ attrs_for_style_string, style_string_has_style, size, previous_width,
+ ):
+ """prompt_toolkit ``_output_screen_diff`` with resize guards.
+
+ Inflates ``previous_screen.height`` when the new screen is taller so pt skips the
+ cursor move that stamps chrome into scrollback; on a corrupt previous paint buffer
+ (tmux re-attach) retries once as a first paint instead of crashing the loop.
+
+ 1. 2. On AttributeError/TypeError from a corrupt previous paint buffer (classic after tmux attach with
+ same width), retry once with ``previous_screen=None`` so pt first-paints cleanly instead of crashing the
+ event loop with ``'cell' object has no attribute 'char'``. See #26137.
+ """
+ try:
+ if previous_screen is not None and hasattr(previous_screen, "height") and previous_screen.height < screen.height:
+ previous_screen.height = screen.height
+ except Exception:
+ pass
+
+ common = (app, output, screen, current_pos, color_depth)
+ tail = (is_done, full_screen, attrs_for_style_string, style_string_has_style, size)
+ try:
+ return orig_osd(*common, previous_screen, last_style, *tail, previous_width)
+ except (AttributeError, TypeError):
+ # Corrupt previous_screen / row cells after client reattach: previous_screen=None
+ # takes the first-paint erase path, previous_width=0 treats the width as changed.
+ return orig_osd(*common, None, None, *tail, 0)
+
+
+ def _apply_bracketed_paste_timeout_patch() -> None:
+ """Patch ``Vt100Parser.feed`` to flush a bracketed paste whose ESC[201~ end mark never arrives.
+
+ Without it a dropped end mark (SSH glitch, sleep/wake) freezes input forever. Idempotent.
+ """
+ try:
+ import prompt_toolkit.input.vt100_parser as _vt100_mod
+ from prompt_toolkit.keys import Keys as _PtKeys
+ from prompt_toolkit.key_binding.key_processor import KeyPress as _PtKeyPress
+
+ if getattr(_vt100_mod, "_hermes_bp_timeout_patched", False):
+ return
+
+ _BP_TIMEOUT_S = 2.0
+
+ def _patched_vt100_feed(self_parser, data: str) -> None:
+ if self_parser._in_bracketed_paste:
+ self_parser._paste_buffer += data
+ end_mark = "\x1b[201~"
+
+ if end_mark in self_parser._paste_buffer:
+ end_index = self_parser._paste_buffer.index(end_mark)
+ paste_content = self_parser._paste_buffer[:end_index]
+ self_parser.feed_key_callback(_PtKeyPress(_PtKeys.BracketedPaste, paste_content))
+ self_parser._in_bracketed_paste = False
+ remaining = self_parser._paste_buffer[end_index + len(end_mark):]
+ self_parser._paste_buffer = ""
+ self_parser._hermes_bp_start = None
+ if remaining:
+ _patched_vt100_feed(self_parser, remaining)
+ else:
+ bp_start = getattr(self_parser, "_hermes_bp_start", None)
+ now = time.monotonic()
+ if bp_start is None:
+ self_parser._hermes_bp_start = now
+ elif now - bp_start > _BP_TIMEOUT_S:
+ paste_content = self_parser._paste_buffer
+ self_parser._in_bracketed_paste = False
+ self_parser._paste_buffer = ""
+ self_parser._hermes_bp_start = None
+ if paste_content:
+ self_parser.feed_key_callback(_PtKeyPress(_PtKeys.BracketedPaste, paste_content))
+ logger.warning(
+ "Bracketed-paste timeout (%.1fs) — flushed %d bytes "
+ "without end mark. Terminal may have dropped ESC[201~ "
+ "(see #16263).",
+ now - bp_start, len(paste_content),
+ )
+ else:
+ # Re-inlined: calling the original would double-buffer after entering paste mode.
+ for i, c in enumerate(data):
+ if self_parser._in_bracketed_paste:
+ _patched_vt100_feed(self_parser, data[i:])
+ break
+ self_parser._input_parser.send(c)
+
+ _vt100_mod.Vt100Parser.feed = _patched_vt100_feed
+ _vt100_mod._hermes_bp_timeout_patched = True
+ logger.debug("Applied Vt100Parser bracketed-paste timeout patch (#16263)")
+ except Exception as exc: # noqa: BLE001 — defensive: never break startup
+ logger.debug("Bracketed-paste timeout patch skipped: %s", exc)
+
+
+ # CPR replies (``ESC[<row>;<col>R``) can race past the input parser under resize storms
+ # and land as literal text; the ``^[[...R`` form appears when a filter stripped the ESC.
+ # Cursor Position Report (CPR / DSR) response, format ``ESC[<row>;<col>R``. prompt_toolkit's _on_resize() +
+ # renderer send ``ESC[6n`` queries to the terminal; under resize storms or tab switches the terminal's reply
+ # can race past the input parser and end up in the input buffer as literal text (see issue #14692). Also
+ # matches the visible-form ``^[[<row>;<col>R`` that appears when the ESC byte was stripped by a prior
+ # filter.
+ _DSR_CPR_ESC_RE = re.compile(r"\x1b\[\d+;\d+R")
+
+
+ _DSR_CPR_VISIBLE_RE = re.compile(r"\^\[\[\d+;\d+R")
+
+
+ _SGR_MOUSE_ESC_RE = re.compile(r"\x1b\[<\d+;\d+;\d+[Mm]")
+
+
+ _SGR_MOUSE_VISIBLE_RE = re.compile(r"\^\[\[<\d+;\d+;\d+[Mm]")
+
+
+ # Bare "<btn;col;rowM" fragments; deliberately broad, they are almost never intentional input.
+ _SGR_MOUSE_BARE_RE = re.compile(r"<\d+;\d+;\d+[Mm]")
+
+
+ _TERMINAL_INPUT_MODE_RESET_SEQ = (
+ "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l" # mouse: SGR, any-motion, button-motion, click
+ "\x1b[?1004l" # focus events
+ "\x1b[?2004l" # bracketed paste
+ "\x1b[?1049l" # leave alt screen
+ "\x1b[<u" # pop kitty keyboard mode
+ "\x1b[>4m" # reset modifyOtherKeys
+ "\x1b[0m\x1b[?25h" # reset attributes, show cursor
+ )
+
+
+ _KITTY_KEYBOARD_PUSH_SEQ = "\x1b[>1u"
+
+
+ _MODIFY_OTHER_KEYS_SEQ = "\x1b[>4;2m"
+
+
+ _EXTENDED_ENTER_KEYS_SEQ = _KITTY_KEYBOARD_PUSH_SEQ + _MODIFY_OTHER_KEYS_SEQ
+
+
+ _BACKSLASH_LINE_CONTINUATION_RE = re.compile(r"\\[ \t]*$")
+
+
+ def _is_ghostty_terminal(env: Optional[Mapping[str, str]] = None) -> bool:
+ """Whether the terminal is Ghostty.
+
+ Ghostty gets ONLY modifyOtherKeys: its Kitty disambiguate mode strips Alt from
+ Backspace (upstream bug), breaking backward-kill-word.
+
+ Ghostty implements modifyOtherKeys correctly (it then emits ``\\x1b[27;3;127~``, which the alias table
+ also maps). See #87630.
+ """
+ env = os.environ if env is None else env
+ return (env.get("TERM_PROGRAM") or "").strip() == "ghostty" or (env.get("TERM") or "").strip().lower() == "xterm-ghostty"
+
+
+ def _terminal_supports_extended_enter_keys(env: Optional[Mapping[str, str]] = None) -> bool:
+ """Allowlist of terminals where requesting modified-Enter reporting is safe (aligned with the Ink TUI)."""
+ env = os.environ if env is None else env
+ term_program = (env.get("TERM_PROGRAM") or "").strip()
+ term = (env.get("TERM") or "").strip().lower()
+ return bool(
+ env.get("WT_SESSION")
+ or term_program in {"iTerm.app", "WezTerm", "ghostty", "vscode"}
+ or env.get("KITTY_WINDOW_ID") or "kitty" in term
+ or term == "xterm-ghostty"
+ or term.startswith("tmux") or term_program.lower() == "tmux"
+ )
+
+
+ def _enable_extended_enter_keys(output=None, env: Optional[Mapping[str, str]] = None) -> bool:
+ """Ask allowlisted terminals to report modified keys distinctly.
+
+ Pushes BOTH kitty keyboard protocol and xterm modifyOtherKeys (kitty dropped the
+ latter; tmux/VS Code only accept it). Both re-encode modified keys as sequences
+ stock prompt_toolkit barely maps (Ctrl+C once arrived as ``ESC[99;5u``), so
+ ``install_modify_other_keys_aliases()`` must have run first. Ghostty gets only
+ modifyOtherKeys. The exit reset pops both modes.
+
+ Under either protocol the terminal re-encodes modified keys as escape sequences — Kitty disambiguate
+ mode as ``ESC[<codepoint>;<mod>u`` (plus the Esc key as ``ESC[27u``), modifyOtherKeys=2 as
+ ``ESC[27;<mod>;<codepoint>~``. Stock prompt_toolkit 3.x maps almost none of these, which is why the CSI
+ >1u push was temporarily removed in 87074 (Ctrl+C arrived as ``ESC[99;5u`` and died, #56684).
+ ``install_modify_other_keys_aliases()`` (called at CLI startup from ``hermes_cli.pt_input_extras``) now
+ populates ``ANSI_SEQUENCES`` with the full Ctrl/Alt/Shift/multi-modifier and functional-key tables under
+ BOTH formats, so every existing key binding continues to fire — including Ctrl+C, which is handled by
+ prompt_toolkit's ``c-c`` binding (raw mode clears ISIG, so the kernel INTR path was never in play for
+ the CLI).
+ See #87630.
+ """
+ from cli import _EXTENDED_ENTER_KEYS_SEQ, _MODIFY_OTHER_KEYS_SEQ, _is_ghostty_terminal, _terminal_supports_extended_enter_keys
+ if not _terminal_supports_extended_enter_keys(env):
+ return False
+ seq = _MODIFY_OTHER_KEYS_SEQ if _is_ghostty_terminal(env) else _EXTENDED_ENTER_KEYS_SEQ
+ try:
+ if output is not None and hasattr(output, "write_raw"):
+ output.write_raw(seq)
+ output.flush()
+ return True
+ if sys.stdout is not None and sys.stdout.isatty():
+ sys.stdout.write(seq)
+ sys.stdout.flush()
+ return True
+ except Exception:
+ pass
+ return False
+
+
+ def _cli_multiline_shortcuts_enabled(config: Optional[Dict[str, Any]] = None) -> bool:
+ """``display.cli_multiline_shortcuts`` (default on: Ctrl+J = newline; off restores the legacy c-j submit)."""
+ if config is None:
+ config = _cli().CLI_CONFIG
+ display = config.get("display") if isinstance(config, dict) else None
+ value = display.get("cli_multiline_shortcuts", True) if isinstance(display, dict) else True
+ if isinstance(value, bool):
+ return value
+ return not (isinstance(value, str) and value.strip().lower() in {"0", "false", "no", "off", "disabled"})
+
+
+ def _is_backslash_line_continuation(text: str) -> bool:
+ """True when Enter should turn a trailing backslash into a newline."""
+ from cli import _BACKSLASH_LINE_CONTINUATION_RE
+ return bool(_BACKSLASH_LINE_CONTINUATION_RE.search(text or ""))
+
+
+ def _apply_backslash_line_continuation(text: str) -> str:
+ """Replace a trailing ``\\`` marker with an actual newline."""
+ from cli import _BACKSLASH_LINE_CONTINUATION_RE
+ return _BACKSLASH_LINE_CONTINUATION_RE.sub("", text or "") + "\n"
+
+
+ def _preserve_ctrl_enter_newline() -> bool:
+ """Environments delivering Ctrl+Enter as bare LF (Windows Terminal, WSL, SSH, Ghostty): c-j must stay newline.
+
+ See issue #22379.
+ """
+ env = os.environ
+ if (
+ sys.platform == "win32"
+ or any(env.get(v) for v in ("SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "WT_SESSION",
+ "GHOSTTY_RESOURCES_DIR", "GHOSTTY_BIN_DIR"))
+ or env.get("TERM", "").lower() == "xterm-ghostty" or env.get("TERM_PROGRAM", "").lower() == "ghostty"
+ or "microsoft" in env.get("WSL_DISTRO_NAME", "").lower()
+ ):
+ return True
+ # WSL env vars can be scrubbed under sudo; also peek /proc.
+ for p in ("/proc/version", "/proc/sys/kernel/osrelease"):
+ try:
- with open(p, "r", encoding="utf-8", errors="ignore") as f:
++ with open(p, "r", encoding="utf-8-sig", errors="ignore") as f:
+ if "microsoft" in f.read().lower():
+ return True
+ except OSError:
+ continue
+ return False
+
+
+ def _bind_prompt_submit_keys(kb, handler, *, multiline_shortcuts_enabled: Optional[bool] = None) -> None:
+ """Enter always submits; c-j submits only with multiline shortcuts off AND where Ctrl+Enter isn't c-j.
+
+ Even when the setting is disabled, environments where Ctrl+Enter is known to arrive as c-j (Windows,
+ WSL, SSH, Windows Terminal, Ghostty) keep c-j reserved for newline; otherwise Ctrl+Enter submits instead
+ of composing. See _preserve_ctrl_enter_newline() and issue #22379.
+ """
+ from cli import _cli_multiline_shortcuts_enabled, _preserve_ctrl_enter_newline
+ if multiline_shortcuts_enabled is None:
+ multiline_shortcuts_enabled = _cli_multiline_shortcuts_enabled()
+ kb.add("enter")(handler)
+ if sys.platform != "win32" and not multiline_shortcuts_enabled and not _preserve_ctrl_enter_newline():
+ kb.add("c-j")(handler)
+
+
+ def _disable_prompt_toolkit_cpr_warning(app) -> None:
+ """Let prompt_toolkit fall back from CPR without printing into the prompt."""
+ with suppress(Exception):
+ app.renderer.cpr_not_supported_callback = None
+
+
+ def _terminal_may_leak_cpr() -> bool:
+ """Suppress prompt_toolkit CPR queries (delayed replies leak into input); Windows keeps pt's default.
+
+ Delayed CPR replies (``ESC[<row>;<col>R`` / visible ``^[[<row>;<col>R``) leak into the status line and
+ can freeze input when the reply is slow (#13870 on SSH/slow PTYs). The same race hits local POSIX TTYs
+ under heavy subagent / status-line load — see ``tests/hermes_cli/test_cpr_local_leak.py``.
+ """
+ return os.environ.get("PROMPT_TOOLKIT_NO_CPR", "") == "1" or sys.platform != "win32"
+
+
+ def _build_cpr_disabled_output(stdout):
+ """Vt100_Output with ``enable_cpr=False`` (``from_pty()`` doesn't expose it), or None on failure.
+
+ prompt_toolkit's renderer sends ``ESC[6n`` (Device Status Report) to learn the cursor row before
+ painting in non-fullscreen mode; the terminal replies ``ESC[<row>;<col>R``. When that reply is delayed
+ it races into the display as raw ``^[[39;1R`` and can stall the renderer's pending-CPR future (#13870;
+ also local POSIX under heavy subagent load).
+ """
+ try:
+ import io as _io
+ from prompt_toolkit.output.vt100 import Vt100_Output, _get_size
+ from prompt_toolkit.data_structures import Size
+
+ def _get_term_size():
+ rows = columns = None
+ try:
+ rows, columns = _get_size(stdout.fileno())
+ except (OSError, _io.UnsupportedOperation, AttributeError, ValueError):
+ pass
+ return Size(rows=rows or 24, columns=columns or 80)
+
+ return Vt100_Output(stdout, _get_term_size, enable_cpr=False)
+ except Exception:
+ return None
+
+
+ def _select_classic_cli_pt_output(stdout):
+ """CPR-disabled ``Vt100_Output`` when CPR may leak, else None (Application keeps pt's default)."""
+ from cli import _build_cpr_disabled_output, _terminal_may_leak_cpr
+ return _build_cpr_disabled_output(stdout) if _terminal_may_leak_cpr() else None
+
+
+ def _strip_leaked_terminal_responses_with_meta(text: str) -> tuple[str, bool]:
+ """Strip leaked CPR replies and mouse-report fragments -> ``(cleaned, had_mouse_reports)``."""
+ from cli import _DSR_CPR_ESC_RE, _DSR_CPR_VISIBLE_RE, _SGR_MOUSE_BARE_RE, _SGR_MOUSE_ESC_RE, _SGR_MOUSE_VISIBLE_RE
+ if not text:
+ return text, False
+
+ had_mouse_reports = False
+ for present, cpr_re, mouse_re in (
+ ("\x1b[" in text, _DSR_CPR_ESC_RE, _SGR_MOUSE_ESC_RE),
+ ("^[" in text, _DSR_CPR_VISIBLE_RE, _SGR_MOUSE_VISIBLE_RE),
+ ("<" in text and ";" in text and ("M" in text or "m" in text), None, _SGR_MOUSE_BARE_RE),
+ ):
+ if not present:
+ continue
+ if cpr_re is not None:
+ text = cpr_re.sub("", text)
+ text, count = mouse_re.subn("", text)
+ had_mouse_reports = had_mouse_reports or count > 0
+ return text, had_mouse_reports
+
+
+ def _estimate_tui_input_height(
+ lines: list[str] | tuple[str, ...], prompt_text: str, terminal_columns: int, *, max_height: int = 8,
+ ) -> int:
+ """Input rows from live terminal cells; the BeforeInput prompt consumes cells only on line 0.
+
+ Never substitute a fake wide fallback: a mis-sized TextArea leaves stale cells at the bottom.
+ """
+ from cli import _int_or
+ try:
+ from prompt_toolkit.utils import get_cwidth
+ except Exception:
+ get_cwidth = lambda value: len(value or "") # type: ignore[assignment]
+
+ columns = max(1, _int_or(terminal_columns or 0, 0))
+ prompt_width = max(0, get_cwidth(prompt_text or ""))
+
+ visual_lines = 0
+ for index, line in enumerate(lines or [""]):
+ display_width = get_cwidth(line or "") + (prompt_width if index == 0 else 0)
+ visual_lines += max(1, -(-display_width // columns))
+
+ return min(max(visual_lines, 1), max(1, int(max_height or 1)))
+
+
+ def _status_bar_visible_from_display_config(display_config: object) -> bool:
+ """Initial status-bar visibility; both YAML ``off`` (False) and strings like ``"hidden"`` mean off."""
+ if not isinstance(display_config, dict):
+ display_config = {}
+ statusbar_config = display_config.get("statusbar", display_config.get("tui_statusbar", "top"))
+ if isinstance(statusbar_config, str):
+ return statusbar_config.strip().lower() not in {"0", "false", "hidden", "no", "off"}
+ return statusbar_config is not False
+
+
+ def _collect_query_images(query: str | None, image_arg: str | None = None) -> tuple[str, list[Path]]:
+ """Collect local image attachments for single-query CLI flows."""
+ from cli import _IMAGE_EXTENSIONS, _detect_file_drop, _resolve_attachment_path
+ message = query or ""
+ images: list[Path] = []
+
+ if isinstance(message, str):
+ dropped = _detect_file_drop(message)
+ if dropped and dropped.get("is_image"):
+ images.append(dropped["path"])
+ message = dropped["remainder"] or f"[User attached image: {dropped['path'].name}]"
+
+ if image_arg:
+ explicit_path = _resolve_attachment_path(image_arg)
+ if explicit_path is None:
+ raise ValueError(f"Image file not found: {image_arg}")
+ if explicit_path.suffix.lower() not in _IMAGE_EXTENSIONS:
+ raise ValueError(f"Not a supported image file: {explicit_path}")
+ images.append(explicit_path)
+
+ return message, list(dict.fromkeys(images))
diff --cc hermes_cli/gateway_service_unit.py
index 00000000000,6d790750b6c..99527168de6
mode 000000,100644..100644
--- a/hermes_cli/gateway_service_unit.py
+++ b/hermes_cli/gateway_service_unit.py
@@@ -1,0 -1,354 +1,354 @@@
+ """Gateway service-unit definitions: systemd unit generation, staleness comparison and refresh.
+
+ Extracted from ``hermes_cli/gateway.py``. Bodies read facade helpers through ``_gw()`` (late
+ binding on ``hermes_cli.gateway``) so the seams tests and callers patch on the facade keep
+ intercepting the moved code.
+ """
+ from __future__ import annotations
+
+ import logging
+ import os
+ import shutil
+ import sys
+ from pathlib import Path
+
+ logger = logging.getLogger(__name__)
+
+
+ def _gw():
+ from hermes_cli import gateway # late: the facade imports this module
+ return gateway
+
+
+ def _systemd_env_line(name: str, value: str) -> str:
+ """One ``Environment="NAME=value"`` line: ``\\`` and ``"`` escaped for systemd's quoting, ``%``
+ doubled so specifier expansion leaves the value alone."""
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%")
+ return f'Environment="{name}={escaped}"\n'
+
+
+ def _installed_unit_ld_library_path(system: bool) -> str:
+ """``LD_LIBRARY_PATH`` baked into the installed unit; ``""`` when absent."""
+ return _gw()._unit_environment_value(_gw().get_systemd_unit_path(system=system), "LD_LIBRARY_PATH") or ""
+
+
+ def _ld_library_path_line(system: bool, target_home_dir: str | None = None) -> str:
+ """Carry the installer's LD_LIBRARY_PATH into the unit (glibc reads it only at process start, so
+ ~/.hermes/.env is too late for CUDA libs — #14613); system units remap caller-home components.
+
+ The installed unit is the fallback source: the unit is regenerated and compared on every
+ start/restart/status, and a shell without the export (ssh, cron, ``sudo`` strips ``LD_*``)
+ must not be able to "repair" the line away."""
+ raw = os.environ.get("LD_LIBRARY_PATH", "") or _gw()._installed_unit_ld_library_path(system)
+ components = [p for p in raw.split(":") if p]
+ if target_home_dir is not None:
+ components = [_gw()._remap_path_for_user(p, target_home_dir) for p in components]
+ return _gw()._systemd_env_line("LD_LIBRARY_PATH", ":".join(components)) if components else ""
+
+
+ def _hermes_home_for_target_user(target_home_dir: str) -> str:
+ """Remap the current HERMES_HOME (root's, under sudo) to the target user's equivalent:
+ ``/root/.hermes[/profiles/x]`` → ``/home/alice/.hermes[/profiles/x]``; custom paths kept as-is."""
+ current_hermes_raw = os.environ.get("HERMES_HOME", "").strip()
+ current_hermes = Path(current_hermes_raw).expanduser() if current_hermes_raw else _gw().get_hermes_home()
+ # Keep paths lexical: resolving a non-existent path can bake a different HERMES_HOME into the unit.
+ current_default = Path.home() / ".hermes"
+ target_default = Path(target_home_dir) / ".hermes"
+ try:
+ # Default ~/.hermes or a profile/subdir of it → preserve the relative structure under the target.
+ return str(target_default / current_hermes.relative_to(current_default))
+ except ValueError:
+ return str(current_hermes) # Completely custom path (not under ~/.hermes) — keep as-is
+
+
+ def _build_service_path_dirs(project_root: Path | None = None) -> list[str]:
+ """Build PATH directory list for service units, excluding non-existent dirs."""
+ if project_root is None:
+ project_root = _gw().PROJECT_ROOT
+
+ def _is_dir(path: Path) -> bool:
+ try:
+ return path.is_dir()
+ except OSError:
+ return False
+
+ candidates = []
+ venv_bin = project_root / "venv" / "bin"
+ if _is_dir(venv_bin):
+ candidates.append(str(venv_bin))
+ elif sys.prefix != sys.base_prefix:
+ candidates.append(str(Path(sys.prefix) / "bin"))
+
+ hermes_home = _gw().get_hermes_home()
+ extras = (project_root / "node_modules" / ".bin", hermes_home / "node" / "bin", hermes_home / "node_modules" / ".bin")
+ for extra in extras:
+ if _is_dir(extra):
+ candidates.append(str(extra))
+ return candidates
+
+
+ def _stable_service_working_dir() -> str:
+ """WorkingDirectory that won't disappear under systemd (HERMES_HOME, else _gw().PROJECT_ROOT). cwd is
+ irrelevant to ``-m`` resolution, and a pinned transient checkout rots: systemd fails at CHDIR
+ (status=200) before Python loads, so the unit self-heal never runs and Restart=always crash-loops."""
+ try:
+ home = _gw().get_hermes_home()
+ if home and Path(home).is_dir():
+ return str(Path(home).resolve())
+ except Exception:
+ pass
+ return str(_gw().PROJECT_ROOT)
+
+
+ def _systemd_watchdog_seconds(hermes_home: str | Path | None = None) -> int:
+ """Resolve the managed-overlay-aware watchdog setting for a service home."""
+ override_token = reset_home_override = None
+ if hermes_home is not None:
+ from hermes_constants import (reset_hermes_home_override, set_hermes_home_override)
+ override_token = set_hermes_home_override(hermes_home)
+ reset_home_override = reset_hermes_home_override
+ try:
+ config = _gw().load_gateway_config()
+ return _gw().coerce_systemd_watchdog_seconds(getattr(config, "systemd_watchdog_seconds", 0))
+ except Exception:
+ logger.debug("Could not resolve effective systemd watchdog configuration", exc_info=True)
+ return 0
+ finally:
+ if override_token is not None and reset_home_override is not None:
+ reset_home_override(override_token)
+
+
+ def _append_node_dir_for_service(path_entries: list[str], hermes_root: Path | None = None) -> None:
+ """Append the Node dir a service unit should use: managed ``<hermes_root>/node`` (profile-scoped)
+ first — a unit survives reboots, so baking a shell-PATH Node is permanent breakage — else PATH lookup."""
+ from hermes_constants import (hermes_managed_node_tree_present, iter_hermes_node_dirs)
+ managed_node_present = hermes_managed_node_tree_present(hermes_root)
+ for directory in iter_hermes_node_dirs(hermes_root) if managed_node_present else ():
+ entry = str(directory)
+ try:
+ present = directory.is_dir()
+ except OSError:
+ present = False
+ if present and entry not in path_entries:
+ path_entries.append(entry)
+
+ # With managed Node present, consulting the invoker's PATH would make a system unit depend on who ran sudo.
+ if managed_node_present:
+ return
+
+ resolved_node = shutil.which("node")
+ if not resolved_node:
+ return
+
+ # Use the dir where node is FOUND, not the symlink target (~/.local/bin/node often links into one profile).
+ resolved_node_dir = str(Path(resolved_node).parent)
+ if resolved_node_dir not in path_entries:
+ path_entries.append(resolved_node_dir)
+
+
+ def _service_venv_dir() -> str:
+ """VIRTUAL_ENV baked into service definitions: detected venv, else ``_gw().PROJECT_ROOT/venv``."""
+ detected_venv = _gw()._detect_venv_dir()
+ return str(detected_venv) if detected_venv else str(_gw().PROJECT_ROOT / "venv")
+
+
+ def generate_systemd_unit(system: bool = False, run_as_user: str | None = None) -> str:
+ python_path = _gw().get_python_path()
+ working_dir = _gw()._stable_service_working_dir()
+ venv_dir = _gw()._service_venv_dir()
+
+ path_entries = _gw()._build_service_path_dirs()
+ if not system:
+ # System units add managed Node once the TARGET user's home is known (not the sudo caller's).
+ _gw()._append_node_dir_for_service(path_entries)
+
+ # TimeoutStopSec must cover the full stop budget (cron drain + cleanup) or systemd SIGKILLs mid-drain.
+ restart_timeout = _gw().resolve_systemd_timeout_stop_sec(_gw()._get_restart_drain_timeout(), _gw()._get_cron_drain_timeout())
+
+ if system:
+ username, group_name, home_dir, uid = _gw()._system_service_identity(run_as_user)
+ hermes_home = _gw()._hermes_home_for_target_user(home_dir)
+ # Profile arg relative to the TARGET user's ~/.hermes when hermes_home lives under it.
+ target_root = Path(home_dir) / ".hermes"
+ try:
+ Path(hermes_home).resolve().relative_to(target_root.resolve())
+ profile_arg = _gw()._profile_arg(hermes_home, default_root=target_root)
+ except ValueError:
+ profile_arg = _gw()._profile_arg(hermes_home)
+ # Remap paths under the calling user's home (/root/) to the target user's so the service can read them.
+ python_path = _gw()._remap_path_for_user(python_path, home_dir)
+ working_dir = str(hermes_home) if hermes_home else _gw()._remap_path_for_user(working_dir, home_dir)
+ venv_dir = _gw()._remap_path_for_user(venv_dir, home_dir)
+ path_entries = [_gw()._remap_path_for_user(p, home_dir) for p in path_entries]
+ # Managed Node for the TARGET user's tree, prepended so it outranks remapped shell-PATH entries.
+ _target_node_entries: list[str] = []
+ _gw()._append_node_dir_for_service(_target_node_entries, Path(hermes_home) if hermes_home else None)
+ path_entries = [e for e in _target_node_entries if e not in path_entries] + path_entries
+ user_home = Path(home_dir)
+ identity_lines = f"User={username}\nGroup={group_name}\n"
+ # Restart-safe cron/Kanban workers cross `systemd-run --user`, which needs this user's manager;
+ # without the ordering the gateway and user@<uid>.service race at boot and the one-shot bus
+ # adoption in run_gateway() can miss (#104893).
+ ordering_lines = f"After=user@{uid}.service\nWants=user@{uid}.service\n"
+ env_lines = (
+ f'Environment="HOME={home_dir}"\n'
+ f'Environment="USER={username}"\n'
+ f'Environment="LOGNAME={username}"\n'
+ ) + _gw()._ld_library_path_line(system=True, target_home_dir=home_dir)
+ wanted_by = "multi-user.target"
+ else:
+ hermes_home = str(_gw().get_hermes_home().resolve())
+ profile_arg = _gw()._profile_arg(hermes_home)
+ user_home = Path.home()
+ identity_lines = ordering_lines = ""
+ env_lines = _gw()._ld_library_path_line(system=False)
+ wanted_by = "default.target"
+
+ watchdog_seconds = _gw()._systemd_watchdog_seconds(hermes_home)
+ systemd_type, systemd_watchdog_directives = "simple", ""
+ if watchdog_seconds > 0:
+ systemd_type, systemd_watchdog_directives = "notify", f"NotifyAccess=main\nWatchdogSec={watchdog_seconds}s\n"
+ path_entries.extend(_gw()._build_user_local_paths(user_home, path_entries))
+ path_entries.extend(_gw()._build_wsl_interop_paths(path_entries))
+ path_entries.extend(["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"])
+ sane_path = ":".join(path_entries)
+ return f"""[Unit]
+ Description={_gw().SERVICE_DESCRIPTION}
+ After=network-online.target
+ Wants=network-online.target
+ {ordering_lines}StartLimitIntervalSec=0
+
+ [Service]
+ Type={systemd_type}
+ {systemd_watchdog_directives}{identity_lines}ExecStart={python_path} -m hermes_cli.main{f" {profile_arg}" if profile_arg else ""} gateway run
+ WorkingDirectory={working_dir}
+ {env_lines}Environment="PATH={sane_path}"
+ Environment="VIRTUAL_ENV={venv_dir}"
+ Environment="HERMES_HOME={hermes_home}"
+ Environment="HERMES_SUPERVISED_CHILD=1"
+ Restart=always
+ RestartSec=5
+ RestartForceExitStatus={_gw().GATEWAY_SERVICE_RESTART_EXIT_CODE}
+ SuccessExitStatus={_gw().GATEWAY_SERVICE_RESTART_EXIT_CODE}
+ RestartPreventExitStatus={_gw().GATEWAY_FATAL_CONFIG_EXIT_CODE}
+ KillMode=mixed
+ KillSignal=SIGTERM
+ ExecReload=/bin/kill -USR1 $MAINPID
+ ExecStop=-{python_path} -m gateway.systemd_stop_mark
+ ExecStopPost=-{python_path} -m gateway.cgroup_cleanup
+ TimeoutStopSec={restart_timeout}
+ StandardOutput=journal
+ StandardError=journal
+
+ [Install]
+ WantedBy={wanted_by}
+ """
+
+
+ def _normalize_service_definition(text: str) -> str:
+ return "\n".join(line.rstrip() for line in text.strip().splitlines())
+
+
+ # Directives older systemd silently strips; ignored in stale-checks so such units aren't flagged forever.
+ _SYSTEMD_OPTIONAL_DIRECTIVES = ("RestartMaxDelaySec", "RestartSteps")
+
+
+ def _strip_optional_systemd_directives(text: str) -> str:
+ """Remove systemd directives that older hosts silently drop."""
+ filtered = []
+ for line in text.splitlines():
+ stripped = line.strip()
+ is_directive = stripped and not stripped.startswith("#")
+ if not (is_directive and stripped.split("=", 1)[0].strip() in _SYSTEMD_OPTIONAL_DIRECTIVES):
+ filtered.append(line)
+ return "\n".join(filtered)
+
+
+ def _normalize_launchd_plist_for_comparison(text: str) -> str:
+ """Normalize plist text for staleness checks, ignoring the PATH payload: the generated PATH is
+ captured from the invoking shell and varies across shells."""
+ import re
+ return re.sub(
+ r"(<key>PATH</key>\s*<string>)(.*?)(</string>)", r"\1__HERMES_PATH__\3",
+ _gw()._normalize_service_definition(text), flags=re.S,
+ )
+
+
+ def systemd_unit_is_current(system: bool = False) -> bool:
+ # HERMES_HOME sync chokepoint for every compare/regenerate path: under `sudo … --system` it is often
+ # stripped to /root/.hermes, so refresh would rewrite a correct unit and status warn forever.
+ # Idempotent; the os.environ mutation persists for later runtime reads (restart's PID/drain).
+ _gw()._sync_hermes_home_from_systemd_unit(system=system)
+
+ unit_path = _gw().get_systemd_unit_path(system=system)
+ if not unit_path.exists():
+ return False
+
- installed = unit_path.read_text(encoding="utf-8")
++ installed = unit_path.read_text(encoding="utf-8-sig")
+ expected_user = _gw()._read_systemd_user_from_unit(unit_path) if system else None
+ expected = _gw().generate_systemd_unit(system=system, run_as_user=expected_user)
+ # Ignore directives older systemd drops (RestartMaxDelaySec, RestartSteps) to avoid a perpetual "outdated" flag.
+ norm = lambda text: _gw()._normalize_service_definition(_gw()._strip_optional_systemd_directives(text)) # noqa: E731
+ return norm(installed) == norm(expected)
+
+
+ def _temp_home_in_service_definition(definition: str) -> str | None:
+ """Temp-dir HERMES_HOME baked into a systemd unit / launchd plist, or None. A temp home means a
+ test/E2E harness generated it; installing it leaves the gateway "running" but deaf to every platform."""
+ import re
+ import tempfile
+ candidates = re.findall(r'HERMES_HOME=([^"\n]+)', definition)
+ candidates += re.findall(r"<key>HERMES_HOME</key>\s*<string>(.*?)</string>", definition, flags=re.S)
+ temp_roots = {
+ Path(tempfile.gettempdir()).resolve(),
+ Path("/tmp"), Path("/var/tmp"), Path("/private/tmp"), Path("/private/var/tmp"), # no-tmp: ok — detects a temp HERMES_HOME in service definitions
+ }
+ for raw in candidates:
+ try:
+ resolved = Path(raw.strip().strip('"')).resolve()
+ except (OSError, ValueError):
+ continue
+ if any(resolved == root or root in resolved.parents for root in temp_roots):
+ return raw.strip()
+ return None
+
+
+ def _refuse_temp_home_service_write(definition: str, kind: str) -> bool:
+ """Refuse (with guidance) when a service definition carries a temp HERMES_HOME."""
+ temp_home = _gw()._temp_home_in_service_definition(definition)
+ if temp_home is None:
+ return False
+ print(f"✗ Refusing to write the gateway {kind}: HERMES_HOME resolves to a temporary directory ({temp_home}).")
+ print(
+ " This usually means a test/E2E environment exported HERMES_HOME. "
+ "Unset it (or run from a clean shell) and retry."
+ )
+ return True
+
+
+ def refresh_systemd_unit_if_needed(system: bool = False) -> bool:
+ """Rewrite the installed systemd unit when the generated definition has changed."""
+ unit_path = _gw().get_systemd_unit_path(system=system)
+ if not unit_path.exists():
+ return False
+
+ # _gw().systemd_unit_is_current is the HERMES_HOME-sync chokepoint; its env mutation persists for the regenerate below.
+ if _gw().systemd_unit_is_current(system=system):
+ return False
+
+ expected_user = _gw()._read_systemd_user_from_unit(unit_path) if system else None
+ new_unit = _gw().generate_systemd_unit(system=system, run_as_user=expected_user)
+
+ # Test safety belt: the user unit path is under Path.home(), which conftest does NOT sandbox, and a
+ # pytest-tmp HERMES_HOME baked into the developer's real unit breaks their gateway on next reboot.
+ if not system and any(m in new_unit for m in ("/pytest-of-", '/hermes_test"', "/hermes_test/")):
+ return False
+
+ # Structural variant: refuse ANY temp-dir HERMES_HOME (manual E2E homes lack the pytest markers).
+ if _gw()._refuse_temp_home_service_write(new_unit, "systemd unit"):
+ return False
+
+ unit_path.write_text(new_unit, encoding="utf-8")
+ _gw()._run_systemctl(["daemon-reload"], system=system, check=True, timeout=30)
+ print(f"↻ Updated gateway {_gw()._service_scope_label(system)} service definition to match the current Hermes install")
+ return True
diff --cc hermes_cli/gateway_windows_legacy.py
index 00000000000,b2b646f4d65..3b1b986a992
mode 000000,100644..100644
--- a/hermes_cli/gateway_windows_legacy.py
+++ b/hermes_cli/gateway_windows_legacy.py
@@@ -1,0 -1,95 +1,95 @@@
+ """Pre-suffix Windows gateway launchers: the objects the current per-profile names cannot reach.
+
+ Before task/launcher names carried ``_profile_suffix()``, an install wrote the Scheduled Task
+ ``Hermes_Gateway``, the Startup entry ``Hermes_Gateway.vbs``/``.cmd`` and the launcher pair
+ ``gateway-service\\Hermes_Gateway.{vbs,cmd}``. Every operation in ``gateway_windows`` is keyed on
+ ``get_task_name()`` → ``Hermes_Gateway_<suffix>``, so those strays are never queried, rewritten,
+ reported or removed: they keep launching a second gateway at logon, never pick up launcher
+ fixes, and ``hermes gateway status`` prints ✓ while they do (#116157). This module enumerates
+ them once; ``status`` warns, ``uninstall`` and ``install --force`` remove.
+ """
+
+ from __future__ import annotations
+
+ from pathlib import Path
+
+
+ def _w():
+ import hermes_cli.gateway_windows as gateway_windows # facade binding is the seam for tests
+
+ return gateway_windows
+
+
+ def _targets_this_home(text: str) -> bool:
+ """A bare-named launcher is OURS only when its action points into THIS home's ``gateway-service``
+ dir. The bare name is also the live identity of the default ``~/.hermes`` profile, so a secondary
+ profile that classified every ``Hermes_Gateway`` object as its own stray would delete the default
+ profile's gateway autostart on ``uninstall`` / ``install --force``."""
+ w = _w()
+ marker = w._normalize_windows_path(str(w._hermes_home() / "gateway-service"))
+ return marker in w._normalize_windows_path(text)
+
+
+ def legacy_launcher_artifacts() -> list[tuple[str, str, Path | str]]:
+ """``(kind, label, target)`` for every pre-suffix launcher of THIS home still present; ``kind`` is
+ ``"file"`` or ``"task"``. Empty when this home owns the bare name (its current objects ARE the bare
+ ones). Bare-named objects belonging to another home (a sibling install) are left alone."""
+ w = _w()
+ bare = w._TASK_NAME_DEFAULT
+ if w.get_task_name() == bare:
+ return []
+ found: list[tuple[str, str, Path | str]] = []
+ startup = w._startup_dir()
+ service_dir = w._hermes_home() / "gateway-service"
+ for path, label in (
+ (startup / f"{bare}.vbs", "legacy pre-suffix Windows login item"),
+ (startup / f"{bare}.cmd", "legacy pre-suffix Windows login item"),
+ ):
+ try:
- if _targets_this_home(path.read_text(encoding="utf-8", errors="replace")):
++ if _targets_this_home(path.read_text(encoding="utf-8-sig", errors="replace")):
+ found.append(("file", label, path))
+ except OSError:
+ continue
+ for path, label in (
+ (service_dir / f"{bare}.vbs", "legacy pre-suffix task launcher"),
+ (service_dir / f"{bare}.cmd", "legacy pre-suffix task script"),
+ ):
+ if path.exists(): # inside this home by construction
+ found.append(("file", label, path))
+ code, out, _err = w._exec_schtasks(["/Query", "/TN", bare, "/XML"])
+ if code == 0 and _targets_this_home(out):
+ found.append(("task", "legacy pre-suffix Scheduled Task", bare))
+ return found
+
+
+ def warn_legacy_launchers() -> bool:
+ """``hermes gateway status``: name every stray so nobody has to do file-mtime archaeology."""
+ artifacts = legacy_launcher_artifacts()
+ for _kind, label, target in artifacts:
+ print(f"⚠ {label} still installed: {target}")
+ if artifacts:
+ print(" These predate per-profile launcher names and also start the gateway at logon.")
+ print(" Remove them with: hermes gateway uninstall (then: hermes gateway install)")
+ return bool(artifacts)
+
+
+ def remove_legacy_launchers() -> None:
+ """``uninstall`` / ``install --force``: delete the strays; a task that needs elevation is named
+ with the exact elevated command instead of being silently left behind."""
+ w = _w()
+ for kind, label, target in legacy_launcher_artifacts():
+ if kind == "file":
+ try:
+ Path(target).unlink()
+ print(f"✓ Removed {label}: {target}")
+ except OSError as exc:
+ print(f"⚠ Could not remove {label} {target}: {exc}")
+ continue
+ code, _out, err = w._exec_schtasks(["/Delete", "/F", "/TN", str(target)])
+ if code == 0:
+ print(f"✓ Removed {label} {str(target)!r}")
+ elif w._is_access_denied(err.strip()):
+ print(f"⚠ {label} {str(target)!r} needs an elevated shell to remove; run as administrator:")
+ print(f" schtasks /Delete /F /TN {target}")
+ else:
+ print(f"⚠ schtasks /Delete {str(target)!r} returned code {code}: {err.strip()}")
diff --cc hermes_cli/kanban.py
index 7129305ccad,e5bd14a87fa..ace47be0f60
--- a/hermes_cli/kanban.py
+++ b/hermes_cli/kanban.py
@@@ -341,6 -341,16 +341,16 @@@ def _cmd_assignees(args: argparse.Names
def _cmd_create(args: argparse.Namespace) -> int:
from agent.delegation_context import is_dispatcher_owned_worker_context
+ body = args.body
+ body_file = getattr(args, "body_file", None)
+ if body is not None and body_file is not None:
+ return _err("kanban: --body and --body-file are mutually exclusive", 2)
+ if body_file is not None:
+ try:
- body = sys.stdin.read() if body_file == "-" else Path(body_file).read_text(encoding="utf-8")
++ body = sys.stdin.read() if body_file == "-" else Path(body_file).read_text(encoding="utf-8-sig")
+ except OSError as exc:
+ return _err(f"kanban: --body-file: {exc}", 2)
+
try:
ws_kind, ws_path = _parse_workspace_flag(args.workspace)
branch_name = _parse_branch_flag(getattr(args, "branch", None))
diff --cc hermes_cli/local_runtime/bootstrap.py
index 0a587725cf4,892e28aed7c..ac77f12adce
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@@ -195,48 -286,70 +286,54 @@@ def ensure_local_runtime(config: dict,
# download serves the new model with no policy at all (--models-autoload + stock fit). A stale
# incumbent gets stopped and replaced by a fresh boot with regenerated presets; sessions ride
# through like any other supervised restart (stable port + persisted key).
+ #
+ # The state check and the spawn below run under a cross-process lock: two backends racing
+ # to boot (#116682) must not both find no state file and both spawn a router on the stable
+ # port — the loser waits here, then re-checks state and adopts the winner's server instead.
from hermes_cli.local_runtime.endpoint import _state_endpoint
- state = _state_endpoint()
- if state is not None:
- if not _presets_stale():
- logger.info("managed llama-server already running (another process)")
- return None
- logger.info("running server's presets predate the staged models; "
- "replacing it so every model launches with a policy")
- _stop_state_server(state)
-
- try:
- from hermes_cli.local_runtime.binaries import installed_engine
- from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
-
- engine = installed_engine(section.get("backend", "auto"))
- if engine is None:
- logger.info("local runtime enabled but no PM engine installed; use the Local Models pane")
- return None
-
- mdir = models_dir()
- mdir.mkdir(parents=True, exist_ok=True)
- preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini")
+ with _cross_process_boot_lock():
+ state = _state_endpoint()
+ if state is not None:
+ if not _presets_stale():
+ logger.info("managed llama-server already running (another process)")
+ return None
+ logger.info("running server's presets predate the staged models; "
+ "replacing it so every model launches with a policy")
+ _stop_state_server(state)
- sup = LlamaServerSupervisor(engine.binary, mdir, preset_path=preset_path,
- models_max=int(section.get("models_max", 4)),
- port=int(section.get("port", 0)) or None)
try:
- sup.start()
- except Exception:
- # start() can fail after the router process exists (health timeout): leaving it
- # running unsupervised strands its VRAM behind a port nothing will clean up.
- with suppress(Exception):
- sup.stop()
- raise
- _SUPERVISOR = sup
- logger.info("managed llama-server up at %s (backend=%s tag=%s)", sup.base_url, engine.backend, engine.tag)
- _start_idle_sweeper(sup)
- return sup
- except Exception as exc: # noqa: BLE001 — never break session start
- logger.warning("managed local runtime unavailable: %s", exc)
- return None
- from hermes_cli.local_runtime.binaries import (
- default_tag, ensure_runtime_installed, installed_tags, select_backend)
++ from hermes_cli.local_runtime.binaries import installed_engine
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
- backend = section.get("backend", "auto")
- if backend == "auto":
- backend = select_backend(_detect_gpu_vendor())
- # Boot ladder: serve what is INSTALLED, never download here. The configured tag is
- # preferred; when it isn't installed yet, the newest installed tag serves and the
- # status endpoint reports the pending update — the download is a deliberate click in
- # the pane, not a boot-path surprise (a multi-minute inline download here is exactly
- # how the onboarding bounce returns).
- tag = section.get("tag") or default_tag()
- have = installed_tags()
- if tag not in have:
- if not have:
- logger.info("local runtime enabled but no build installed; "
- "install happens in the Local Models pane")
- return None
- logger.info("configured tag %s not installed; serving %s "
- "(update is a click in Local Models)", tag, have[0])
- tag = have[0]
- install_dir = ensure_runtime_installed(tag, backend)
++ engine = installed_engine(section.get("backend", "auto"))
++ if engine is None:
++ logger.info("local runtime enabled but no PM engine installed; use the Local Models pane")
++ return None
+
+ mdir = models_dir()
+ mdir.mkdir(parents=True, exist_ok=True)
+ preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini")
+
- sup = LlamaServerSupervisor(install_dir, mdir, preset_path=preset_path,
++ sup = LlamaServerSupervisor(engine.binary, mdir, preset_path=preset_path,
+ models_max=_admitted_models_max(
+ mdir, int(section.get("models_max", 4))),
+ port=int(section.get("port", 0)) or None)
+ try:
+ sup.start()
+ except Exception:
+ # start() can fail after the router process exists (health timeout): leaving it
+ # running unsupervised strands its VRAM behind a port nothing will clean up.
+ with suppress(Exception):
+ sup.stop()
+ raise
+ _SUPERVISOR = sup
- logger.info("managed llama-server up at %s (backend=%s tag=%s)", sup.base_url, backend, tag)
++ logger.info("managed llama-server up at %s (backend=%s tag=%s)", sup.base_url, engine.backend, engine.tag)
+ _start_idle_sweeper(sup)
+ return sup
+ except Exception as exc: # noqa: BLE001 — never break session start
+ logger.warning("managed local runtime unavailable: %s", exc)
+ return None
def shutdown_local_runtime() -> None:
diff --cc hermes_cli/local_runtime/supervisor.py
index 5298ffc1cdb,1cb90f7742e..a95daeb5879
--- a/hermes_cli/local_runtime/supervisor.py
+++ b/hermes_cli/local_runtime/supervisor.py
@@@ -23,8 -24,8 +24,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
+ from hermes_cli.local_runtime.processes import server_child_env, spawn_server
logger = logging.getLogger(__name__)
diff --cc hermes_cli/main.py
index 10f76f656aa,5d8ffdca864..5bdeafac9f2
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@@ -231,20 -261,18 +243,16 @@@ def _config_default_interface_early() -
"""Return the configured default interface ("cli"/"tui") via a minimal
YAML read. Best-effort: any error falls back to "cli" (legacy behavior)."""
global _EARLY_INTERFACE_CACHE
- if _EARLY_INTERFACE_CACHE is not None:
- return _EARLY_INTERFACE_CACHE[0]
+ cfg_path = _early_interface_config_path()
+ if _EARLY_INTERFACE_CACHE is not None and _EARLY_INTERFACE_CACHE[0] == cfg_path:
+ return _EARLY_INTERFACE_CACHE[1]
value = "cli"
try:
- home = os.environ.get("HERMES_HOME")
- if home:
- cfg_path = os.path.join(home, "config.yaml")
- else:
- cfg_path = os.path.join(os.path.expanduser("~"), ".hermes", "config.yaml")
if os.path.exists(cfg_path):
- import yaml as _yaml_iface
+ import hermes_yaml as _yaml_iface
- with open(cfg_path, encoding="utf-8") as _f:
- raw = _yaml_iface.load(
- _f, Loader=getattr(_yaml_iface, "CSafeLoader", None) or _yaml_iface.SafeLoader
- ) or {}
+ with open(cfg_path, encoding="utf-8-sig") as _f:
+ raw = _yaml_iface.safe_load(_f) or {}
disp = raw.get("display", {})
if isinstance(disp, dict):
iface = disp.get("interface")
diff --cc hermes_cli/main_desktop.py
index 8a43db9ea98,f02cc2956ed..8f18c917fd8
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@@ -430,11 -587,84 +434,15 @@@ def _electron_dir(project_root: Path) -
return project_root / "node_modules" / "electron"
- def _stop_desktop_processes_locking_build(desktop_dir: Path) -> list[int]:
- """Terminate a running desktop app whose exe lives INSIDE this build's ``release`` tree (Windows
- only — its lock makes the pack die with ``Access is denied``; POSIX can unlink a running
- binary). Never raises; returns the PIDs asked to stop."""
- if sys.platform != "win32":
-def _electron_dist_binary(project_root: Path) -> Path:
- """The Electron main binary inside the installed package — the exact file ``electronDist`` needs.
-
- electron-builder reads the binary from ``build.electronDist`` since #38673, so this is the exact file
- whose absence makes a pack fail with "The specified electronDist does not exist". The basename differs
- per OS (the platform Electron is named for the host the build runs on).
- """
- dist = _electron_dir(project_root) / "dist"
- if sys.platform == "darwin":
- return dist / "Electron.app" / "Contents" / "MacOS" / "Electron"
- if sys.platform == "win32":
- return dist / "electron.exe"
- return dist / "electron"
-
-
-def _electron_dist_ok(project_root: Path) -> bool:
- """True when ``node_modules/electron/dist`` holds a usable binary (a partial dir counts as NOT ok)."""
- try:
- return _electron_dist_binary(project_root).exists()
- except OSError:
- return False
-
-
-def _electron_pkg_staged_missing_dist(project_root: Path) -> bool:
- """electron staged (package.json + install.js) but dist missing — blocked postinstall."""
- electron_dir = _electron_dir(project_root)
- return (
- (electron_dir / "package.json").is_file()
- and (electron_dir / "install.js").is_file()
- and not _electron_dist_ok(project_root))
-
-
-def _redownload_electron_dist(project_root: Path, env: dict, *, mirror: Optional[str] = None) -> bool:
- """Best-effort: run electron's install.js to populate dist/ (optional mirror)."""
- if _electron_dist_ok(project_root):
- return True
-
- electron_dir = _electron_dir(project_root)
- installer = electron_dir / "install.js"
- if not installer.is_file():
- return False
- from hermes_constants import find_node_executable, with_hermes_node_path
- node = find_node_executable("node")
- if not node:
- return False
-
- shutil.rmtree(electron_dir / "dist", ignore_errors=True)
- with contextlib.suppress(OSError):
- (electron_dir / "path.txt").unlink()
-
- dl_env = with_hermes_node_path(env)
- if mirror:
- dl_env["ELECTRON_MIRROR"] = mirror
- try:
- subprocess.run([node, str(installer)], cwd=str(electron_dir), env=dl_env, check=False)
- except OSError:
- return False
- return _electron_dist_ok(project_root)
-
-
-def _try_redownload_electron_dist(project_root: Path, env: dict) -> bool:
- """Canonical download, then fallback mirror unless the user pinned one."""
- if _redownload_electron_dist(project_root, env):
- return True
- if env.get("ELECTRON_MIRROR"):
- return False
- return _redownload_electron_dist(project_root, env, mirror=_ELECTRON_FALLBACK_MIRROR)
-
-
+ def _stop_desktop_processes_locking_build(desktop_dir: Path, *, also_posix: bool = False) -> list[int]:
+ """Terminate a running desktop app whose exe lives INSIDE this build's ``release`` tree.
+
+ Windows needs it everywhere: the exe lock makes the pack die with ``Access is denied``.
+ POSIX can rename a running app's files away, so the pack itself needs no stop — but a
+ renderer left alive through the stage-and-swap promotion keeps fetching its OLD hashed
+ chunks by path after the swap and dies on the next lazy import (#109643), so the swap
+ point passes ``also_posix=True``. Never raises; returns the PIDs asked to stop."""
+ if sys.platform != "win32" and not also_posix:
return []
try:
import psutil
diff --cc hermes_cli/plugin_validate_desktop.py
index 1f690a4117a,e7c85394325..090374d61cc
--- a/hermes_cli/plugin_validate_desktop.py
+++ b/hermes_cli/plugin_validate_desktop.py
@@@ -56,19 -56,43 +56,43 @@@ def desktop_surface_findings(source: st
return sorted(findings, key=lambda f: f[1])
- def check_desktop_surface(report, plugin_dir: Path) -> None:
- """Fail the report when ``desktop/*.js`` steps outside the SDK surface; silent when there is none."""
- desktop = Path(plugin_dir) / "desktop"
+ def is_desktop_surface(rel_path: str) -> bool:
+ """Whether a file is part of the Desktop surface this lint governs: JS under ``desktop/``.
+
+ The renderer loads ``desktop/plugin.js`` (and what it imports from beside it). A Node sidecar
+ (``sidecar/*.mjs``), a build script or a ``tests/*.test.mjs`` never runs in the renderer, so a
+ lazy ``import('jszip')`` there is ordinary Node code — running the rules over every ``*.js`` /
+ ``*.mjs`` in a repository reports noise, not a surface violation. Batch tooling should scope
+ with this predicate (or call ``desktop_surface_hits``) instead of ``rglob``-ing the tree.
+ """
+ parts = Path(rel_path).parts
+ return len(parts) > 1 and parts[0] == "desktop" and Path(rel_path).suffix == ".js"
+
+
+ def desktop_surface_hits(plugin_dir: Path) -> List[str]:
+ """``["<rule> (<rel>:<line>)", ...]`` over the plugin's Desktop surface files only."""
+ plugin_dir = Path(plugin_dir)
+ desktop = plugin_dir / "desktop"
if not desktop.is_dir():
- return
+ return []
hits: List[str] = []
for js in sorted(desktop.rglob("*.js")):
+ rel = js.relative_to(plugin_dir).as_posix()
+ if not is_desktop_surface(rel):
+ continue
try:
- source = js.read_text(encoding="utf-8", errors="replace")
+ source = js.read_text(encoding="utf-8-sig", errors="replace")
except OSError:
continue
- rel = js.relative_to(plugin_dir).as_posix()
hits.extend(f"{rule} ({rel}:{line})" for rule, line in desktop_surface_findings(source))
+ return hits
+
+
+ def check_desktop_surface(report, plugin_dir: Path) -> None:
+ """Fail the report when ``desktop/*.js`` steps outside the SDK surface; silent when there is none."""
+ if not (Path(plugin_dir) / "desktop").is_dir():
+ return
+ hits = desktop_surface_hits(plugin_dir)
report.add(
"desktop surface", not hits,
"; ".join(hits[:8]) + (f" (+{len(hits) - 8} more)" if len(hits) > 8 else "")
diff --cc hermes_cli/profiles.py
index 9618eaba62d,a1db417b026..bc99eeb6c6f
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@@ -17,10 -17,9 +17,10 @@@ from pathlib import Pat
from typing import Dict, List, Optional, Tuple
from hermes_cli.archive_safe import archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targz
+from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS
from hermes_constants import (
- LOCAL_RUNTIME_ROOT_DIRS, clear_named_profile_deleted, mark_named_profile_deleted, named_profile_has_identity,
- named_profile_is_deleted, named_profile_is_live,
+ LOCAL_RUNTIME_ROOT_DIRS, PROFILE_ID_RE, clear_named_profile_deleted, mark_named_profile_deleted,
+ named_profile_has_identity, named_profile_is_deleted, named_profile_is_live,
)
logger = logging.getLogger(__name__)
diff --cc hermes_cli/subcommands/computer_use.py
index b43047f8165,76476aca7dc..31d39275a0a
--- a/hermes_cli/subcommands/computer_use.py
+++ b/hermes_cli/subcommands/computer_use.py
@@@ -39,9 -54,29 +39,18 @@@ def _cu_status(args) -> int
else:
print(" Run: hermes computer-use install")
return 1
+ rc = 0
+ if sys.platform == "linux": # hand-written daemon units: dead `serve` is invisible to the binary contract (#114748)
+ from tools.computer_use.cua_backend import cua_daemon_listening
+ from tools.computer_use.doctor import cua_daemon_units
+ for _kind, unit, _target, serve, socket in cua_daemon_units():
+ if serve and cua_daemon_listening(path, socket) is False:
+ print(f" ✗ Daemon unit {unit}: no `cua-driver serve` is listening on {socket or 'the default socket'}")
+ print(f" Check: systemctl --user status {unit} (reinstalling the driver does not start it)")
+ rc = 1
- try:
- st = cua_driver_update_check()
- if st and st.get("update_available"):
- latest = st.get("latest_version") or "?"
- print(f" ⬆ Update available: cua-driver {latest}.")
- print(" Run: hermes computer-use install --upgrade")
- elif st:
- print(" ✓ Up to date.")
- else:
- # Older driver (no check-update verb) or offline.
- print(" Refresh to latest: hermes computer-use install --upgrade")
- except Exception:
- print(" Refresh to latest: hermes computer-use install --upgrade")
+ print(" ✓ Runtime contract ready (externally managed)." if override
+ else " ✓ Runtime contract ready (Hermes PM pin).")
- return 0
+ return rc
def _cu_doctor(args) -> None:
diff --cc hermes_cli/update_cmd.py
index 5399c4536b0,be34f5bf207..73e66a7c5fd
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@@ -15,16 -15,11 +15,17 @@@ import sy
import time as _time
from dataclasses import dataclass
from pathlib import Path
+from typing import NoReturn
from hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patched via update_cmd)
+ from hermes_cli import update_handoff as _update_handoff
from hermes_cli.update_cmd_common import _best_effort
-from hermes_constants import get_default_hermes_root, project_venv_dir, venv_python_path
+# Captured BEFORE a checkout swap: parent transport/lifecycle never imports new code.
+from hermes_cli.update_completion import run_completion
+from hermes_cli.update_channel import adopt_retired_channel
+from pm.receipt import accept_worker_receipt as _accept_completion_pm_receipt
+from hermes_cli import update_receipt as _completion_receipt, update_cmd_config as _completion_config
+from hermes_cli._old_updater import stop_for_relaunch
# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.
from hermes_cli.update_abort_recovery import ( # noqa: F401
diff --cc hermes_cli/update_cmd_fleet.py
index 3a13ab33715,29e78585614..8e12953e578
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@@ -415,13 -439,214 +439,33 @@@ def _needs_sudo(scope: str) -> bool
)
-def _restart_systemd_gateway_units_best_effort(failed: list, listings) -> None:
- """Best-effort ``systemctl restart`` of every hermes-gateway/serve unit."""
- answered = set()
- for scope, scope_cmd, result in listings:
- answered.add(scope)
- if result.returncode != 0:
- failed.append(f"systemd-{scope} (listing failed)")
- continue
- def process_unit(svc_name: str, _scope=scope, _cmd=scope_cmd) -> None:
- manage_cmd = list(_cmd) + ["--no-ask-password"]
- if _needs_sudo(_scope):
- manage_cmd = ["sudo", "-n"] + manage_cmd
- result = _systemctl_reset_and_restart(manage_cmd, svc_name, scope_cmd=_cmd)
- if result.returncode != 0 or not _wait_for_service_active(_cmd, svc_name):
- failed.append(svc_name)
-
- _for_each_systemd_gateway_unit(
- result.stdout,
- process_unit=process_unit,
- on_unit_timeout=lambda svc_name, exc: failed.append(svc_name),
- )
- # A timeout or missing executable is not an empty scope.
- failed.extend(f"systemd-{scope} (listing unavailable)" for scope, _ in _SYSTEMD_SCOPES if scope not in answered)
+ def _live_fleet_current_rows() -> list[dict] | None:
+ """The fleet matrix when the probe finds at least one gateway and every row is ``current``
+ at the checkout SHA (identity known); ``None`` on any unknown/stale/down row or a failed
+ probe (restart)."""
+ checkout_sha = _current_checkout_sha()
+ if not checkout_sha:
+ return None
+ try:
+ from hermes_cli.update_receipt import collect_fleet_versions
+ fleet = collect_fleet_versions()
+ except Exception as exc:
+ logger.debug("Pending fleet restart: fleet probe failed: %s", exc)
+ return None
+ if not fleet or _fleet_covered_gateways(fleet) is None:
+ return None
+ if all(row.get("state") == "current" and str(row.get("code_sha")) == checkout_sha for row in fleet):
+ return fleet
+ return None
+
+
def _run_pending_fleet_restart() -> bool:
- """Catch-up restart for gateways left on pre-update code. Never raises.
-
- True when all discovered targets recovered (or none exist); False if incomplete.
-
- See #95294.
- """
- from hermes_cli.update_cmd import _m
- print("→ Restarting gateways left on pre-update code...")
- # Warn if legacy Hermes gateway unit files are still installed. When both hermes.service (from a
- # pre-rename install) and the current hermes-gateway.service are enabled, they SIGTERM-fight for the
- # same bot token (see PR #11909). Flagging here means every `hermes update` surfaces the issue until the
- # user migrates.
- try:
- from hermes_cli.gateway import (
- find_gateway_pids, is_macos, is_windows, kill_gateway_processes, supports_systemd_services,
- _wait_for_gateway_exit,
- )
- except Exception as exc:
- _warn_gateway_restart_phase_aborted(exc, None)
- return False
-
- try:
- pids = list(find_gateway_pids(all_profiles=True))
- except Exception as exc:
- logger.debug("Pending fleet restart: gateway probe failed: %s", exc)
- pids = None
-
- # A gateway this very update cold-started (or a manual `hermes gateway restart` seconds
- # ago) already serves the checkout code; stopping it here re-kills the fleet, and on
- # Windows the stop/start pair then reports "No gateway was running" plus a second spawn
- # (#117051). Skip when EVERY live gateway is current on the checkout SHA.
- if pids and _live_fleet_current_rows() is not None:
- print(" ✓ Every running gateway already serves the checkout code — nothing to restart.")
- return True
-
- failed: list = []
- try:
- # Snapshot before stopping: Restart=no units can disappear from list-units on a clean exit.
- systemd_listings = list(_systemd_gateway_unit_listings()) if supports_systemd_services() else None
- # Stop old processes before supervisor recovery, never its freshly verified workers.
- if pids != []:
- try:
- leftover = list(find_gateway_pids(all_profiles=True))
- except Exception:
- leftover = list(pids or [])
- if leftover:
- with _best_effort('Pending fleet restart: PID stop failed: %s'):
- kill_gateway_processes(all_profiles=True)
- _wait_for_gateway_exit(timeout=5.0, force_after=None)
- # --- Systemd services (Linux) --- Discover all hermes-gateway* units (default + profiles) plus
- # hermes-serve* units (the Desktop app's backend, #83438).
- if systemd_listings is not None:
- _restart_systemd_gateway_units_best_effort(failed, systemd_listings)
- # --- Launchd services (macOS) --- Restart EVERY ai.hermes.gateway* LaunchAgent, not only the
- # invoking profile's — parity with the systemd branch above (#41403). Per-label TimeoutExpired
- # isolation happens inside.
- if is_macos():
- try:
- _restart_macos_launchd_gateways([], failed, 45.0, require_supervision=True)
- except Exception as exc:
- logger.debug("Pending fleet restart: launchd failed: %s", exc)
- failed.append("launchd")
- if is_windows():
- try:
- from hermes_cli import gateway_windows
- if gateway_windows.is_installed():
- gateway_windows.restart()
- except Exception as exc:
- logger.debug("Pending fleet restart: Windows failed: %s", exc)
- failed.append("windows-gateway")
- if failed:
- _warn_incomplete_gateway_fleet_restart(failed)
- return False
- print(" ✓ Pending fleet restart completed.")
- return True
- except Exception as exc:
- try:
- surviving = list(find_gateway_pids(all_profiles=True))
- except Exception:
- surviving = pids
- _warn_gateway_restart_phase_aborted(exc, surviving)
- return False
-
-
-def _defer_fleet_restart_after_update(*, update_complete: bool, resume_incomplete: bool = False) -> None:
- """Record a deliberately deferred fleet restart and return/exit on outcome.
-
- ``hermes update --no-gateway-restart`` (cron running inside the gateway's
- own cgroup) updated code and dependencies but must not restart the fleet:
- the SIGUSR1 drain + systemd restart would kill the updater itself. The
- ``fleet_restart_pending`` marker written before the pull is KEPT so the
- next normal update (or ``hermes gateway restart``) catches up.
-
- Outcome contract (same success/partial meaning as the normal path):
- a STALE fleet caused only by this deliberate deferral is expected and
- does NOT make the update partial — exit 0, receipt "success". The receipt
- is "partial" (and the process exits 1, marker kept) when the update
- itself did not complete (``update_complete`` False) or the Windows
- pause/resume reconciliation reported incomplete.
-
- The live interpreter still serves pre-update code here, so callers must
- also skip stale-module purge/reload work: mutating this process's
- sys.modules graph mid-flight risks breaking the serving gateway.
- """
- print()
- print("→ Gateway restart skipped (--no-gateway-restart).")
- print(" Code and dependencies are updated; gateways still serve pre-update code.")
- print(" Restart them separately: `hermes gateway restart` or a daily-restart cron.")
- print(" (fleet restart deferred — marker kept for catch-up)")
- with suppress(Exception):
- from hermes_cli.update_receipt import record_skip
- record_skip("gateway_restart", "--no-gateway-restart: deferred, marker kept")
- partial = (not update_complete) or resume_incomplete
- with suppress(Exception):
- from hermes_cli.update_receipt import finalize_update_receipt
- finalize_update_receipt("partial" if partial else "success")
- if partial:
- sys.exit(1)
-
-
-def _apply_pending_fleet_restart_catchup(*, defer: bool = False) -> None:
- """On an already-up-to-date ``hermes update``, finish a skipped restart.
-
- No-op when nothing is pending; exits 1 on incomplete catch-up so automation
- does not treat the fleet as healthy. ``defer`` (``--no-gateway-restart``) keeps
- the marker and warns instead: running the restart from inside the gateway's own
- cgroup would kill the caller.
- """
- from hermes_cli.update_cmd import _run_pending_fleet_restart
- if not _pending_fleet_restart_needed():
- return
- if defer:
- print()
- _warn_pending_fleet_restart()
- print(" (fleet restart deferred — --no-gateway-restart; marker kept)")
- print(" Restart separately: `hermes gateway restart` or next non-cron update.")
- return
- print()
- _warn_pending_fleet_restart()
- print("→ Running the pending fleet restart...")
- if not _run_pending_fleet_restart():
- print(" ⚠ Fleet restart incomplete. Recover with: hermes gateway restart")
- sys.exit(1)
- if not _pending_fleet_restart_needed():
- return
- # The restart itself succeeded, but the receipt still owes gateways it cannot match to a
- # live row (unknown identity, pre-pull plan SHAs). When every live gateway serves the
- # checkout code, that matrix is the recovery evidence: settle the receipt with it instead of
- # failing this run — an exit 1 here writes another failed receipt and the warning never
- # clears, even after a successful manual `hermes gateway restart` (#117051).
- fleet = _live_fleet_current_rows()
- if fleet is not None:
- from hermes_cli.update_receipt import settle_latest_receipt_fleet
- settled = settle_latest_receipt_fleet(
- fleet, discharges=lambda receipt: not _pending_fleet_restart_needed(receipt=receipt)
- )
- if settled:
- print(f" ✓ Update receipt settled: {len(fleet)} gateway(s) serve the checkout code.")
- return
- print(" ⚠ Fleet restart ran, but gateways are still off the checkout code. Recover with: hermes gateway restart")
- sys.exit(1)
+ """Historical retry hook; new retries use the ordinary completion owner."""
+ from hermes_cli._old_updater import stop_for_relaunch
+ stop_for_relaunch(incomplete=True)
def _systemctl(cmd: list, *, timeout: float):
diff --cc hermes_cli/update_receipt.py
index 403d5220d7e,b2efdf2e237..eecb4f0ebfb
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@@ -356,6 -246,40 +356,40 @@@ def _prune_old_receipts(directory: Path
stale.unlink()
+ def settle_latest_receipt_fleet(fleet: list[dict[str, Any]], *, discharges) -> bool:
+ """Record on ``latest.json`` that the fleet it still reports as owed now serves the checkout.
+
+ A failed receipt whose plan rows cannot be matched to a live gateway (unknown identity,
+ pre-pull SHAs) keeps ``hermes update`` exiting 1 and every CLI start warning about mixed
+ modules, long after the operator's ``hermes gateway restart`` fixed the fleet (#117051). The
+ caller has just verified every live row is current at the checkout SHA; persisting that
+ matrix as the receipt's post-restart ``fleet`` (and un-flagging ``gateway_restart``) is what
+ lets the stale-runtime readers see the recovery. ``discharges(settled_receipt)`` decides on
+ the in-memory copy; ``latest.json`` is rewritten only when it answers True, so a catch-up
+ that still exits 1 leaves the receipt byte-identical. Only the ``latest.json`` pointer is
+ rewritten; the archived per-run file keeps the original outcome. Never raises.
+ """
+ try:
+ path = _receipt_dir() / "latest.json"
- receipt = json.loads(path.read_text(encoding="utf-8"))
++ receipt = json.loads(path.read_text(encoding="utf-8-sig"))
+ if not isinstance(receipt, dict):
+ return False
+ receipt["fleet"] = list(fleet)
+ gateway_restart = receipt.get("gateway_restart")
+ if not isinstance(gateway_restart, dict):
+ gateway_restart = {}
+ gateway_restart.update({"incomplete": False, "phase_error": ""})
+ gateway_restart["settled_from_live_fleet_at"] = _utc_now_iso()
+ receipt["gateway_restart"] = gateway_restart
+ if not discharges(receipt):
+ return False
+ path.write_text(json.dumps(receipt, indent=2, default=str), encoding="utf-8")
+ return True
+ except Exception as exc:
+ logger.debug("Could not settle latest update receipt from the live fleet: %s", exc)
+ return False
+
+
def read_latest_receipt() -> Optional[dict[str, Any]]:
"""Read the most recent update receipt, or None. Never raises."""
with suppress(Exception):
diff --cc package-lock.json
index f5f5e377e15,be7de895da7..1e10b7fd442
--- a/package-lock.json
+++ b/package-lock.json
@@@ -156,8 -153,8 +158,9 @@@
"@types/babel__core": "7.20.5",
"@types/d3-force": "3.0.10",
"@types/hast": "3.0.5",
+ "@types/js-yaml": "4.0.9",
"@types/node": "22.20.1",
+ "@types/proxy-from-env": "1.0.4",
"@types/qrcode": "1.5.6",
"@types/react": "19.2.17",
"@types/react-dom": "19.2.3",
diff --cc pyproject.toml
index 2e6702d92a8,f487128d79e..37f9edb9455
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -115,19 -119,21 +114,25 @@@ dependencies =
# macOS and Windows. It replaces POSIX-only idioms like `os.kill(pid, 0)`
# (which is a silent killer on Windows — see CONTRIBUTING.md) and
# `os.killpg` (which doesn't exist on Windows).
- "psutil==7.2.2",
+ "psutil==7.2.2; sys_platform != 'android' and python_version >= '3.14'",
+ # Android Python 3.13+ needs upstream #2891 for platform recognition and
+ # disk_partitions(). The fix is not in a published psutil release yet.
+ # Keep this commit until a release includes it, then remove the source pin.
+ "psutil @ git+https://github.com/giampaolo/psutil.git@380bd2b59c67b0e1b04bbf3a90b11744f4f96644 ; sys_platform == 'android' and python_version >= '3.14'",
# Browser CDP supervisor + browser_dialog import this directly. Keep core
# so browser tool discovery doesn't fail on lean installs.
- "websockets==15.0.1",
+ "websockets==15.0.1; python_version >= '3.14'",
# .gitignore-aware file matching for desktop build stamp.
- "pathspec==1.1.1",
- "fastapi>=0.104.0,<1",
+ "pathspec==1.1.1; python_version >= '3.14'",
+ "fastapi>=0.104.0,<1; python_version >= '3.14'",
# CIDR-aware forwarded_allow_ips requires uvicorn >=0.31.0.
- "uvicorn[standard]>=0.31.0,<1; python_version >= '3.14'",
+ # uvicorn's [standard] extra bundles uvloop, httptools, and watchfiles.
+ # uvloop cannot build on Android/Termux (libuv's ./configure fails), so
+ # we declare the working components inline and gate uvloop behind the
+ # [uvloop] optional extra — desktop/server profiles pull it via [all].
- "uvicorn>=0.31.0,<1",
- "httptools>=0.6.3,<0.9",
- "watchfiles>=0.20,<2",
++ "uvicorn>=0.31.0,<1; python_version >= '3.14'",
++ "httptools>=0.6.3,<0.9; python_version >= '3.14'",
++ "watchfiles>=0.20,<2; python_version >= '3.14'",
# Streaming multipart uploads for the dashboard file manager (NS-501).
# FastAPI's UploadFile/Form depend on python-multipart; it is NOT pulled in
# by fastapi itself, so the dashboard's multipart upload endpoint would 500
@@@ -192,12 -189,21 +197,20 @@@
# 738 CPython reports sys_platform == 'android' and never matched.) Pre-GKI
# devices can still slip through; they get the same resolution failure as
# before, worked around by installing with `--no-deps` or an older release.
- "nemo-relay>=0.8.3,<0.9; (sys_platform == 'darwin' and platform_machine == 'arm64') or (sys_platform == 'linux' and platform_machine == 'x86_64' and 'android' not in platform_release) or (sys_platform == 'linux' and platform_machine == 'aarch64' and 'android' not in platform_release) or (sys_platform == 'win32' and platform_machine == 'AMD64') or (sys_platform == 'win32' and platform_machine == 'ARM64')",
-]
+ "nemo-relay>=0.8.3,<0.9; ((sys_platform == 'darwin' and platform_machine == 'arm64') or (sys_platform == 'linux' and platform_machine == 'x86_64' and 'android' not in platform_release) or (sys_platform == 'linux' and platform_machine == 'aarch64' and 'android' not in platform_release) or (sys_platform == 'win32' and platform_machine == 'AMD64') or (sys_platform == 'win32' and platform_machine == 'ARM64')) and python_version >= '3.14'",]
[project.optional-dependencies]
+ # High-performance event loop — uvloop replaces the stdlib asyncio loop with
+ # a libuv-backed implementation for ~2-4x throughput on uvicorn. Gated as an
+ # optional extra because libuv's ./configure does not run on Android/Termux
+ # (bionic libc, non-FHS layout). Desktop and server installs pull this via
+ # [all]; the [termux] / [termux-all] profiles intentionally omit it.
+ uvloop = [
+ "uvloop>=0.15.1,<0.24; sys_platform != 'win32' and sys_platform != 'cygwin' and sys_platform != 'android' and platform_python_implementation != 'PyPy'",
+ ]
# Native Anthropic provider — only needed when provider=anthropic (not via
# OpenRouter or other aggregators).
-anthropic = ["anthropic==0.87.0"] # CVE-2026-34450, CVE-2026-34452
+anthropic = ["anthropic==0.87.0"] # CVE-2026-34450, CVE-2026-34452
# Web search backends — each only loaded when the user picks it as their
# search provider (configured via `hermes tools` or config.yaml).
exa = ["exa-py==2.10.2"]
@@@ -473,15 -381,13 +486,18 @@@ youtube =
# `hermes dashboard` (localhost SPA + API). Not in core to keep the default install lean.
# starlette==1.3.1 pinned for CVE-2026-48710 (BadHost) — fastapi pulls Starlette
# transitively and pre-1.0.1 is the vulnerable range. See the mcp extra above.
+ # uvicorn pin without [standard] — httptools / watchfiles are now core deps,
+ # and uvloop is gated behind the [uvloop] extra. This keeps [web] safe for
+ # termux-all which includes it.
-web = ["fastapi==0.133.1", "uvicorn==0.41.0", "starlette==1.3.1", "python-multipart==0.0.32"]
+web = [
+ "fastapi==0.133.1",
- "uvicorn[standard]==0.41.0",
++ "uvicorn==0.41.0",
+ "starlette==1.3.1",
+ "python-multipart==0.0.32",
+]
all = [
# Policy (2026-05-12): `[all]` includes only extras that genuinely
- # CAN'T be lazy-installed via `tools/lazy_deps.py` — i.e. things every
+ # CAN'T be prepared on demand by PM — i.e. things every
# session can use, things needed before the agent loop is alive
# (terminal/CLI), and skill deps that dev environments need.
# Anything an opt-in backend (provider, search, TTS, image, memory,
@@@ -532,38 -432,7 +549,39 @@@ hermes = "hermes_cli.main:main
hermes-agent = "run_agent:main"
hermes-acp = "acp_adapter.entry:main"
+# Per-extra platform gates (settled 2026-09-02): an extra listed here is
+# only installable on platforms matching the marker. pm consults this
+# table (pm.extras.extra_supported) — ensure_import/sync_venv refuse a
+# gated-off extra with a clear message instead of resolving it to an
+# empty set. The per-package markers inside the extra stay (uv's
+# resolver needs them for --all-extras); this table is the readable
+# single-authority for WHICH extra is supported WHERE.
++
+[tool.hermes.extras-platforms]
+# mautrix[encryption] → python-olm: linux-only wheels, no win/darwin build.
+matrix = "sys_platform == 'linux'"
+# grpcio (via google-cloud-pubsub) has no win_arm64 wheel.
+google-chat = "platform_machine != 'ARM64' or sys_platform != 'win32'"
+# qdrant-client → grpcio (via mem0ai) has no win_arm64 wheel.
+mem0 = "platform_machine != 'ARM64' or sys_platform != 'win32'"
+# Match the engine dependency markers so PM refuses an unsupported install.
+wake-openwakeword = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or sys_platform != 'darwin')"
+# faster-whisper's closure is prebuilt-only: ctranslate2 has no win_arm64 wheel and onnxruntime
+# none for darwin-x64. Its ANCHOR is faster_whisper, so an unsupported machine could install the
+# extra, rebuild the whole dependency environment and still fail the anchor on every retry.
+# Gate the extra that carries only faster-whisper; [voice] also has ungated deps (sounddevice,
+# numpy) and stays installable, see test_declared_extra_gates_match_dependency_selection.
+stt-whisper = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or platform_system != 'Darwin')"
+# NeuTTS excludes Python 3.14. KittenTTS's misaki dependency excludes 3.13+.
+neutts = "python_version < '3.14'"
+kittentts = "python_version < '3.13'"
+piper = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or sys_platform != 'darwin')"
+
[tool.uv]
+# 3.11 is an install bridge for pre-PM updaters, never a runtime, so the lock
+# covers 3.14 only. Without this the lock must resolve every supported version,
+# where extras that only ever coexist on 3.14 (kittentts vs neutts) conflict.
+environments = ["python_version >= '3.14'"]
override-dependencies = [
# discord.py's latest published version, 2.7.1, pins pynacl at <1.6. however, pynacl 1.5.0 has known vulnerabilities.
# discord.py has updated pynacl to 1.6 on `main`, but has not yet published a patch release.
@@@ -628,12 -495,9 +646,13 @@@ exclude-newer = "14 days
# (Termux/Android) it must build from sdist, and the isolated build
# environment resolves under the same cutoff ("Failed to resolve
# requirements from build-system.requires ... maturin>=1.9,<2").
+#
+# google-cloud-pubsub: same exact-pin shape (==2.39.2, google-chat adapter).
+# The pin bump WAS the review; exclude-newer only filters it because the
+# 14-day window is younger than the reviewed release.
++
[tool.uv.exclude-newer-package]
agent-client-protocol = false
-ai-edge-litert = false
aiohttp = false
aiohttp-socks = false
aiosqlite = false
diff --cc scripts/desktop-update/posix.sh
index 7865a7b9835,b343cc17875..a69fb61927e
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@@ -36,9 -36,9 +36,10 @@@
set -u
ORIGINAL_ARGS=("$@")
-INSTALL_ROOT="" BRANCH="main" DESKTOP_PID=0 RELAUNCH_TARGET=""
+INSTALL_ROOT="" BRANCH="main" CHANNEL="" DESKTOP_PID=0 RELAUNCH_TARGET=""
+BRANCH_EXPLICIT=0
RELAUNCH_CWD="" SANDBOX_FALLBACK=0 RELAUNCH_ARGS=()
+ NO_GATEWAY=0
NO_UI=0 NO_MARKER_CLEANUP=0 SELF_TEST_UI=0 SELF_TEST_GATE=0 SELF_TEST_MARKER=0
SELF_TEST_TCC_HEAL=0
HANDOFF_DAEMONIZED=0
@@@ -833,9 -773,19 +835,19 @@@ if "${UPDATE_INVOKE[@]}" update --help
else
log "installed hermes predates --keep-stash; running without it"
fi
- log "running: ${UPDATE_INVOKE[*]} update --yes --gateway $KEEP_STASH ${TARGET_ARGS[*]}"
+ # --gateway restarts the local messaging gateway after the update. The
+ # Desktop omits it (--no-gateway) when it is served by a remote gateway
+ # (#117529): restarting a local one there is never wanted, and with the same
+ # channel credentials as the remote host it becomes a competing long-poll
+ # consumer (e.g. Telegram rejects one of the two getUpdates callers).
+ GATEWAY_FLAG="--gateway"
+ if [ "$NO_GATEWAY" -eq 1 ]; then
+ GATEWAY_FLAG=""
+ log "update requested without --gateway (remote-served Desktop)"
+ fi
-log "running: ${UPDATE_INVOKE[*]} update --yes $GATEWAY_FLAG $KEEP_STASH --branch $BRANCH"
++log "running: ${UPDATE_INVOKE[*]} update --yes $GATEWAY_FLAG $KEEP_STASH ${TARGET_ARGS[*]}"
publish_stage "Updating code and dependencies"
- OUT="$("${UPDATE_INVOKE[@]}" update --yes --gateway $KEEP_STASH "${TARGET_ARGS[@]}" 2>&1)"; CODE=$?
-OUT="$("${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH --branch "$BRANCH" 2>&1)"; CODE=$?
++OUT="$("${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH "${TARGET_ARGS[@]}" 2>&1)"; CODE=$?
printf '%s\n' "$OUT" >> "$LOG" 2>/dev/null
log "hermes update exit code: $CODE"
@@@ -857,8 -807,7 +869,8 @@@ if [ "$LEGACY_INSTALL" -eq 1 ] && [ "$C
fi
log "retrying once (freshly pulled fix loads on the second run)"
publish_stage "Retrying update"
- OUT="$("${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH --branch "$BRANCH" 2>&1)"; CODE=$?
+ select_update_invoke || { FINAL_CODE=3 FINAL_MSG="Updated installation launcher is missing; repair this installation."; exit 3; }
- OUT="$("${UPDATE_INVOKE[@]}" update --yes --gateway $KEEP_STASH "${TARGET_ARGS[@]}" 2>&1)"; CODE=$?
++ OUT="$("${UPDATE_INVOKE[@]}" update --yes $GATEWAY_FLAG $KEEP_STASH "${TARGET_ARGS[@]}" 2>&1)"; CODE=$?
printf '%s\n' "$OUT" >> "$LOG" 2>/dev/null
log "retry exit code: $CODE"
fi
diff --cc scripts/desktop-update/windows.ps1
index 85d0c74082f,17bb6b32355..07195318766
--- a/scripts/desktop-update/windows.ps1
+++ b/scripts/desktop-update/windows.ps1
@@@ -17,10 -17,10 +17,10 @@@
# OS component -- is "frozen".
#
# CONTRACT (keep in sync with apps/desktop/electron/main.ts):
- # cmd /d /s /c start "" /min powershell -NoProfile -ExecutionPolicy Bypass
+ # cmd /d /s /c start "" /b powershell -NoProfile -ExecutionPolicy Bypass
# -File scripts\desktop-update\windows.ps1
# -InstallRoot <path> repo checkout (HERMES_HOME\hermes-agent)
-# -Branch <ref> branch to update against
+# [-Branch <ref> | -Channel stable|canary|main] default: branch main
# -DesktopPid <pid> the Electron main process to wait out
# [-RelaunchExe <path>] Hermes.exe to start when done (omit = no relaunch)
# [-NoUi] headless (tests); default shows a progress window
@@@ -1540,12 -1526,90 +1542,23 @@@ try
Write-HandoffLog "desktop exited"
}
- # -- 2. Wait for the venv shim to unlock (FAIL CLOSED) ------------------
- Publish-UiProgress "Preparing Hermes files"
- $shim = Join-Path $VenvDir "Scripts\hermes.exe"
- if (Test-Path -LiteralPath $shim) {
- $unlocked = $false
- $deadline = (Get-Date).AddSeconds(20)
- while ((Get-Date) -lt $deadline) {
- try {
- $fs = [System.IO.File]::Open($shim, 'Open', 'ReadWrite', 'None')
- $fs.Close()
- $unlocked = $true
- break
- } catch {
- Start-Sleep -Milliseconds 400
- if ($script:Ui) { [System.Windows.Forms.Application]::DoEvents() }
- }
- }
- if (-not $unlocked) {
- # Something still maps the venv. --force-ing past it guarantees a
- # half-updated venv (the exact 2026-08-09 Access-denied brick).
- $finalCode = 5
- $finalMsg = "Update aborted: another process is still holding the Hermes install open ($shim locked after 20s). Nothing was changed. Close other Hermes windows/terminals and try again."
- Write-HandoffLog $finalMsg
- exit $finalCode
- }
- Write-HandoffLog "venv shim unlocked"
- }
-
- # -- 3. Run the update from the CURRENT checkout ------------------------
- # --force skips only the hermes.exe shim guard, which step 2 just PROVED
- # is unlocked; the venv-python holder guard (orphan reap included) stays
- # active. Our marker claim is adopted by the child via update_lock.py's
- # process-ancestry rule.
- #
- # DRIVE THE UPDATE THROUGH venv\Scripts\python.exe, NOT venv\Scripts\hermes.exe.
- # `uv pip install -e .` has to replace the console-script shims, so
- # _quarantine_running_hermes_exe must first rename the running hermes.exe
- # out of the way. On Windows that rename fails whenever ANY child process
- # spawned from that hermes.exe is still alive: a child inherits a handle on
- # the parent image, and the resulting sharing violation is indistinguishable
- # from a user leaving a second Hermes window open. It is the inherited
- # handle, not the trampoline itself, that pins the file -- killing the child
- # makes the same rename succeed immediately, and the shim flavour (uv
- # trampoline vs distlib launcher) makes no difference.
- #
- # The updater reliably spawns such children itself (npx cache warm, memory
- # provider refresh -- hindsight-api runs as a daemon with --idle-timeout
- # 300 and outlives the step that started it), so this is a race, not a
- # deterministic failure: the same hand-off succeeds on one run and dies on
- # the next. Step 2's preflight cannot catch it, because the shim genuinely
- # IS unlocked at that moment.
- #
- # When the rename loses that race there is no recovery: `uv pip install -e .`
- # exits 2 and the ZIP fallback repeats the identical sequence, so the desktop
- # build stage is never reached and apps/desktop/release is left missing -- an
- # install whose Start Menu shortcut points at a Hermes.exe that no longer
- # exists. (A reboot-deferred rename was the old last resort here; it needed
- # elevation a Desktop-driven update does not have, and freed nothing for the
- # install already in flight.)
- #
- # Running the same code as `python.exe -m hermes_cli.main update` puts the
- # inherited handles on python.exe, which uv never has to replace.
- #
- # posix.sh is deliberately left alone: unlinking a running executable is
- # legal there, so the equivalent call is harmless.
- $pythonExe = Join-Path $VenvDir "Scripts\python.exe"
- if (-not (Test-Path -LiteralPath $pythonExe)) {
- $finalCode = 3
- $finalMsg = "Update aborted: $pythonExe is missing. The install needs repair (run the Hermes installer or `hermes doctor`)."
- Write-HandoffLog $finalMsg
- exit $finalCode
- }
+ # PM creates a new dependency generation. Live old Python readers do not
+ # block it; Desktop exit above protects the application output replacement.
+ $pythonExe = $runtimeCommand[0]
+ $runtimeArgs = @($runtimeCommand | Select-Object -Skip 1)
- $updateArgs = $runtimeArgs + @('update', '--yes', '--gateway') + $targetArgs
+ # --gateway restarts the local messaging gateway after the update. The
+ # Desktop passes -NoGateway when it is served by a remote gateway
+ # (#117529): restarting a local one there is never wanted, and with the
+ # same channel credentials as the remote host it becomes a competing
+ # long-poll consumer (e.g. Telegram rejects one of the two getUpdates
+ # callers).
- $gatewayArg = @("--gateway")
++ $gatewayArg = @('--gateway')
+ if ($NoGateway) {
+ $gatewayArg = @()
+ Write-HandoffLog "update requested without --gateway (remote-served Desktop)"
+ }
- $updateArgs = @("-m", "hermes_cli.main", "update", "--yes") + $gatewayArg + @("--force", "--branch", $Branch)
++ $updateArgs = $runtimeArgs + @('update', '--yes') + $gatewayArg + $targetArgs
+ if ($legacyInstall) { $updateArgs += '--force' }
# --keep-stash: never re-apply local source edits after the update (they
# stay parked in git stash). Probe --help first: the flag ships with newer
# backends and an unknown flag would abort argparse with exit 2, which
@@@ -1565,27 -1629,40 +1578,27 @@@
$res = Invoke-HermesStep $pythonExe $updateArgs "update"
Write-HandoffLog "hermes update exit code: $($res.Code)"
- $retryPolicyPath = Join-Path $PSScriptRoot "retry-policy.ps1"
- if (Test-Path -LiteralPath $retryPolicyPath) {
- . $retryPolicyPath
- $shouldRetry = Test-HermesUpdateShouldRetry -ExitCode $res.Code -InstallRoot $InstallRoot
- } else {
- # The child may have swapped to a checkout without the companion policy
- # while this older script is still running in memory. Preserve the
- # previous fail-closed behavior instead of calling an undefined function.
- Write-HandoffLog "retry policy is unavailable after checkout swap; using legacy retry rules"
- $shouldRetry = $res.Code -ne 0 -and $res.Code -ne 2
- }
- if ($shouldRetry) {
- # One retry for update-boundary failures. Most exit-2 safety refusals
- # remain terminal, but self-lock deferral also uses exit 2 and writes
- # .update-incomplete after the code swap. That marker is only a retry
- # signal here: the fresh process's early-recovery pass finishes core
- # dependency sync before native modules load, then `update` continues
- # the remaining Desktop/skills stages of the full pipeline.
- Write-HandoffLog "first attempt left retryable update state; retrying once in a fresh process"
+ # Retry only the identified pre-PM update-boundary transition. Current
+ # update/build failures propagate and must not trigger another owner.
+ if ($legacyInstall -and $res.Code -ne 0 -and $res.Code -ne 2) {
+ Write-HandoffLog "legacy update failed; retrying once from the updated installation"
Publish-UiProgress "Retrying update"
- $res = Invoke-HermesStep $pythonExe $updateArgs "update"
- Write-HandoffLog "retry exit code: $($res.Code)"
+ $runtimeCommand = @(Get-HermesRuntimeCommand -InstallRoot $InstallRoot)
+ $pythonExe = $runtimeCommand[0]
+ $runtimeArgs = @($runtimeCommand | Select-Object -Skip 1)
- $updateArgs = $runtimeArgs + @('update', '--yes', '--gateway') + $targetArgs
++ $updateArgs = $runtimeArgs + @('update', '--yes') + $gatewayArg + $targetArgs
+ $res = Invoke-HermesStep $pythonExe $updateArgs 'update'
}
- # -- 4. Truthful completion: don't trust exit 0 -------------------------
- # `hermes update` treats a Desktop GUI build failure as NON-fatal (prints
- # a one-line warning, exits 0). For a Desktop-DRIVEN update that warning
- # is fatal: we would relaunch the old exe and call it success. Detect it,
- # retry the build once, and propagate honestly.
+ # Pre-PM updates reported a successful exit with a failed build warning.
+ # Keep that historical transition here only; current failures propagate.
$desktopBuildFailed = $false
- if ($res.Code -eq 0 -and $res.Output -match "Desktop build failed") {
+ if ($legacyInstall -and $res.Code -eq 0 -and $res.Output -match "Desktop build failed") {
Write-HandoffLog "hermes update reported a desktop build failure (non-fatal there, fatal here); retrying build"
Publish-UiProgress "Rebuilding Desktop"
- $rebuild = Invoke-HermesStep $pythonExe @("-m", "hermes_cli.main", "desktop", "--force-build", "--build-only") "rebuild"
+ $runtimeCommand = @(Get-HermesRuntimeCommand -InstallRoot $InstallRoot)
+ $rebuildArgs = @($runtimeCommand | Select-Object -Skip 1) + @('desktop', '--force-build', '--build-only')
+ $rebuild = Invoke-HermesStep $runtimeCommand[0] $rebuildArgs 'rebuild'
Write-HandoffLog "desktop rebuild exit code: $($rebuild.Code)"
if ($rebuild.Code -ne 0) { $desktopBuildFailed = $true }
}
diff --cc scripts/run_tests_parallel.py
index a0b9ac044f0,5fbc91de55b..4d2b0c86a2e
mode 100644,100755..100644
--- a/scripts/run_tests_parallel.py
+++ b/scripts/run_tests_parallel.py
@@@ -162,10 -162,33 +162,33 @@@ def _split_pathspec(value: str) -> List
# this runner never executes them, by construction. The summary calls that
# out explicitly so a local run isn't misread as covering macOS/Windows
# behaviour, and names the CI lane where those tests actually execute.
+
+
+ def _read_files_from(spec: str) -> List[str]:
+ """Read an explicit test-file list from *spec* - a path, or ``-`` for stdin.
+
+ One path per line, blank lines ignored. This is the file-backed
+ counterpart of ``--files`` for lists that exceed the kernel's
+ per-argument cap (``MAX_ARG_STRLEN``, 128 KiB on Linux): the
+ whole-suite list is already ~210 KB, so passing it as one ``--files``
+ argv element dies with ``E2BIG`` in ``execve`` before the runner's
+ first line can even run.
+ """
+ if spec == "-":
+ text = sys.stdin.read()
+ else:
+ try:
- text = Path(spec).read_text(encoding="utf-8")
++ text = Path(spec).read_text(encoding="utf-8-sig")
+ except OSError as exc:
+ print(f"error: --files-from: cannot read {spec!r}: {exc}", file=sys.stderr)
+ sys.exit(2)
+ return [line.strip() for line in text.splitlines() if line.strip()]
+
+
_OS_MARKERS = {
"linux_only": ("linux", "the main Linux CI lane"),
- "macos_only": ("darwin", "the tests-os CI lane (macos-latest)"),
- "windows_only": ("win32", "the tests-os CI lane (windows-latest)"),
+ "macos_only": ("darwin", "the macOS Python-tests lane"),
+ "windows_only": ("win32", "the Windows Python-tests lane"),
}
diff --cc tests/gateway/test_status.py
index dbe876e8d29,ef94bb6c824..c0d663b2e7c
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@@ -597,8 -633,42 +634,42 @@@ class TestTerminatePid
assert calls == []
+ class TestPidExistsZombieProbe:
+ """#115578: the psutil ``status()`` zombie probe is POSIX-only. On Windows it costs ~7 ms per
+ pid, runs once per registry entry inside the session-registry file lock, and can never
+ report a zombie (Windows has no such state), so pollers starve at a handful of leases."""
+
+ @staticmethod
+ def _spy_status(monkeypatch):
+ psutil = pytest.importorskip("psutil")
+ calls = []
+ real_status = psutil.Process.status
+
+ def spy(self):
+ calls.append(self.pid)
+ return real_status(self)
+
+ monkeypatch.setattr(psutil.Process, "status", spy)
+ return calls
+
+ @pytest.mark.windows_only
+ def test_windows_skips_zombie_status_probe(self, monkeypatch):
+ # Faking os.name on POSIX proves nothing about the cost on the real host; the wine2e
+ # runner receipt (red on main, green on the fix) is the live repro for this test.
+ calls = self._spy_status(monkeypatch)
+ assert status._pid_exists(os.getpid()) is True
+ assert calls == []
+
+ @pytest.mark.linux_only
+ def test_posix_still_probes_zombie_status(self, monkeypatch):
+ # Control: on POSIX a zombie still answers pid_exists(), so the probe must survive.
+ calls = self._spy_status(monkeypatch)
+ assert status._pid_exists(os.getpid()) is True
+ assert calls == [os.getpid()]
+
+
class TestScopedLocks:
- @pytest.mark.windows_only
+ @pytest.mark.platforms("windows")
def test_windows_file_lock_uses_high_offset(self, tmp_path, monkeypatch):
# Faking _IS_WINDOWS on POSIX could not reproduce the msvcrt
# byte-range locking path at all: msvcrt does not exist off Windows,
diff --cc tests/hermes_cli/test_install_cua_driver.py
index 01230a02723,f53e8c14a5e..b48b98f579f
--- a/tests/hermes_cli/test_install_cua_driver.py
+++ b/tests/hermes_cli/test_install_cua_driver.py
@@@ -46,135 -110,1722 +46,135 @@@ def test_runtime_contract(version, omit
assert "serve --approve-capability-manifest" in state["reason"]
-class TestInstallCuaDriverUpgrade:
- # ``install_cua_driver`` supports macOS, Windows AND Linux. For everything
- # below except the two unsupported-platform cases, the Linux host takes a
- # byte-identical path to macOS — same ``fetch_tool`` ("curl"), same
- # ``_cua_install_target_writable()`` verdict, same branch — so the old
- # ``patch("platform.system", return_value="Darwin")`` bought nothing but a
- # fake host. Dropped, and the names no longer claim macOS.
-
- def test_upgrade_on_unsupported_platform_is_silent_noop(self):
- """The one branch no CI runner can reach for real.
-
- ``platform.system`` is still faked here, deliberately and narrowly: we
- run Linux/macOS/Windows lanes, and every one of them is a *supported*
- platform, so the refusal path is unreachable on all three. The fake is
- sound because the function returns before touching any OS facility —
- no subprocess, no path handling, no import — so there is nothing
- underneath the branch for a real host to falsify.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config, "_print_warning") as warn, \
- patch("platform.system", return_value="FreeBSD"):
- assert tools_config.install_cua_driver(upgrade=True) is False
- warn.assert_not_called()
-
- def test_non_upgrade_on_unsupported_platform_warns(self):
- """Same narrow exception as above — see that test's docstring."""
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config, "_print_warning") as warn, \
- patch("platform.system", return_value="FreeBSD"):
- assert tools_config.install_cua_driver(upgrade=False) is False
- warn.assert_called()
-
- def test_upgrade_with_binary_present_runs_installer(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/local/bin/" + n
- if n in {"cua-driver", "curl"} else None), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""},
- ), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner, \
- patch("subprocess.run"):
- assert tools_config.install_cua_driver(upgrade=True) is True
- runner.assert_called_once()
- kwargs = runner.call_args.kwargs
- assert kwargs.get("verbose") is False
-
- def test_upgrade_without_binary_runs_installer(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/bin/curl" if n == "curl" else None), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner:
- assert tools_config.install_cua_driver(upgrade=True) is True
- runner.assert_called_once()
-
- @pytest.mark.linux_only
- def test_quiet_refresh_prints_single_contextual_progress_line(self):
- """``linux_only``: reaches Popen through the POSIX download-then-exec
- branch, which this lane takes for real."""
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- with patch(
- "subprocess.run",
- return_value=MagicMock(returncode=0, stderr=""),
- ), \
- patch("subprocess.Popen", return_value=fake_proc), \
- patch.object(
- tools_config.shutil,
- "which",
- return_value="/usr/local/bin/cua-driver",
- ), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_info") as info:
- assert tools_config._run_cua_driver_installer(
- label="Refreshing",
- verbose=False,
- ) is True
-
- info.assert_called_once_with(
- "→ Refreshing cua-driver (Computer Use)..."
- )
-
- @pytest.mark.linux_only
- def test_quiet_refresh_can_suppress_progress_line(self):
- """``linux_only``: same POSIX Popen path as the test above."""
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- with patch(
- "subprocess.run",
- return_value=MagicMock(returncode=0, stderr=""),
- ), \
- patch("subprocess.Popen", return_value=fake_proc), \
- patch.object(
- tools_config.shutil,
- "which",
- return_value="/usr/local/bin/cua-driver",
- ), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_info") as info:
- assert tools_config._run_cua_driver_installer(
- label="Refreshing",
- verbose=False,
- show_progress=False,
- ) is True
-
- info.assert_not_called()
-
- def test_quiet_refresh_closes_stdin_and_honors_custom_timeout(self):
- """A background refresh must neither wait on a hidden prompt nor
- inherit the explicit install command's 11-minute ceiling."""
- import subprocess
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- with patch(
- "subprocess.run",
- return_value=MagicMock(returncode=0, stderr=""),
- ), \
- patch("subprocess.Popen", return_value=fake_proc) as popen, \
- patch.object(
- tools_config.shutil,
- "which",
- return_value="/usr/local/bin/cua-driver",
- ), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(
- tools_config,
- "_repair_cua_driver_autostart_windows",
- return_value=True,
- ), \
- patch.object(tools_config, "_print_info"), \
- patch.object(tools_config, "_print_success"):
- assert tools_config._run_cua_driver_installer(
- label="Refreshing",
- verbose=False,
- installer_timeout=120,
- ) is True
-
- assert popen.call_args.kwargs["stdin"] is subprocess.DEVNULL
- fake_proc.communicate.assert_called_once_with(timeout=120)
-
- def test_upgrade_can_suppress_installer_progress(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(
- tools_config.shutil,
- "which",
- side_effect=lambda name: (
- f"/usr/local/bin/{name}"
- if name in {"cua-driver", "curl"}
- else None
- ),
- ), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""},
- ), \
- patch.object(
- tools_config,
- "_run_cua_driver_installer",
- return_value=True,
- ) as runner, \
- patch("subprocess.run"):
- assert tools_config.install_cua_driver(
- upgrade=True,
- show_installer_progress=False,
- ) is True
-
- assert runner.call_args.kwargs["show_progress"] is False
-
- def test_upgrade_non_writable_install_target_skips_refresh(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/local/bin/" + n
- if n in {"cua-driver", "curl"} else None), \
- patch.object(tools_config, "_cua_install_target_writable",
- return_value=False), \
- patch.object(tools_config, "_run_cua_driver_installer") as runner, \
- patch.object(tools_config, "_print_info") as info:
- assert tools_config.install_cua_driver(upgrade=True) is True
- runner.assert_not_called()
- assert any(
- "/Applications is not writable" in call.args[0]
- for call in info.call_args_list
- )
-
- def test_fresh_install_non_writable_install_target_skips_install(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/bin/curl" if n == "curl" else None), \
- patch.object(tools_config, "_cua_install_target_writable",
- return_value=False), \
- patch.object(tools_config, "_run_cua_driver_installer") as runner, \
- patch.object(tools_config, "_print_info") as info:
- assert tools_config.install_cua_driver(upgrade=False) is False
- runner.assert_not_called()
- assert any(
- "/Applications is not writable" in call.args[0]
- for call in info.call_args_list
- )
-
- @pytest.mark.macos_only
- def test_install_target_writability_is_probed_for_real_on_macos(self):
- """The ``_cua_install_target_writable`` seam the two tests above patch.
-
- ``macos_only``: ``/Applications`` is the only install target Hermes
- checks, and the probe short-circuits to True on every other platform —
- so this is the one host where the real filesystem answer means
- anything.
- """
- import os
-
- from hermes_cli import tools_config_cua as tools_config
-
- writable = tools_config._cua_install_target_writable()
- if os.path.isdir("/Applications"):
- assert writable is os.access("/Applications", os.W_OK)
- else:
- assert writable is True
-
- def test_non_upgrade_with_binary_skips_install(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/local/bin/" + n
- if n in {"cua-driver", "curl"} else None), \
- patch.object(tools_config, "_run_cua_driver_installer") as runner, \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""},
- ), \
- patch.object(
- tools_config,
- "_repair_cua_driver_autostart_windows",
- return_value=True,
- ), \
- patch("subprocess.run"):
- assert tools_config.install_cua_driver(upgrade=False) is True
- runner.assert_not_called()
-
- def test_non_upgrade_repairs_incompatible_existing_driver(self):
- from hermes_cli import tools_config_cua as tools_config
-
- incompatible = {
- "ready": False,
- "version": "0.19.4",
- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",
- }
- repaired = {"ready": True, "version": "0.20.0", "reason": ""}
- with patch.object(
- tools_config.shutil,
- "which",
- side_effect=lambda name: f"/usr/bin/{name}",
- ), \
- patch.object(
- tools_config,
- "_resolved_cua_driver_cmd",
- return_value="/usr/bin/cua-driver",
- ), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- side_effect=[incompatible, repaired],
- ), \
- patch.object(
- tools_config,
- "_run_cua_driver_installer",
- return_value=True,
- ) as runner:
- assert tools_config.install_cua_driver(upgrade=False) is True
-
- assert runner.call_args.kwargs["label"] == "Repairing"
-
- def test_incompatible_explicit_override_is_not_replaced(self, monkeypatch):
- from hermes_cli import tools_config_cua as tools_config
-
- monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", "/opt/custom/cua-driver")
- incompatible = {
- "ready": False,
- "version": "0.19.4",
- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",
- }
- with patch.object(
- tools_config,
- "_resolved_cua_driver_cmd",
- return_value="/opt/custom/cua-driver",
- ), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value=incompatible,
- ), \
- patch.object(tools_config, "_run_cua_driver_installer") as runner:
- assert tools_config.install_cua_driver(upgrade=False) is False
-
- runner.assert_not_called()
-
- @pytest.mark.parametrize("upgrade", [False, True])
- def test_missing_explicit_override_does_not_install_standard_driver(
- self, monkeypatch, upgrade
- ):
- from hermes_cli import tools_config_cua as tools_config
-
- monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", "/missing/custom/cua-driver")
- with patch.object(
- tools_config,
- "_resolved_cua_driver_cmd",
- return_value=None,
- ), \
- patch.object(tools_config, "_run_cua_driver_installer") as runner:
- assert tools_config.install_cua_driver(upgrade=upgrade) is False
-
- runner.assert_not_called()
-
- def test_non_upgrade_without_binary_runs_installer(self):
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/bin/curl" if n == "curl" else None), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner:
- assert tools_config.install_cua_driver(upgrade=False) is True
- runner.assert_called_once()
-
-
-class TestRequireConfirmedUpdate:
- """`hermes update` passes require_confirmed_update=True: the full
- upstream installer (multi-minute, output captured, plus install.ps1's
- 600s lock window on Windows) may only run when the driver's native
- ``check-update`` verb positively confirms a newer release. An
- indeterminate check (old driver, offline, GitHub rate-limited, probe
- timeout) keeps the installed version and returns fast.
-
- Explicit `hermes computer-use install --upgrade` keeps the old
- fall-through (require_confirmed_update=False): a force-refresh should
- still reinstall when the check can't answer.
- """
-
- def _install(self, check_state, require_confirmed, contract_status=None,
- binary_missing=False):
- """Drive ``install_cua_driver`` on the host, whatever it is.
-
- The old signature took a ``system`` string and faked
- ``platform.system`` with it, so callers picked "Windows"/"Darwin"
- arbitrarily. Nothing in the confirmed-update gate is
- platform-dependent — it's ``check-update`` state plus a flag — so the
- fake only decided which lie the test told itself. ``which`` answers
- for every fetch tool so the host's own branch resolves cleanly.
- """
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- _which_names = {"curl", "powershell"}
- if not binary_missing:
- _which_names.add("cua-driver")
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/x/" + n
- if n in _which_names else None), \
- patch.object(tools_config, "_resolved_cua_driver_cmd",
- return_value=None if binary_missing
- else "/x/cua-driver"), \
- patch.object(tools_config, "_cua_install_target_writable",
- return_value=True), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value=contract_status or {
- "ready": True,
- "version": "0.20.0",
- "reason": "",
- },
- ), \
- patch("tools.computer_use.cua_backend_driver.cua_driver_update_check",
- return_value=check_state), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner, \
- patch("subprocess.run",
- return_value=MagicMock(stdout="cua-driver 0.5.0", returncode=0)), \
- patch.object(tools_config, "_print_success"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info") as info:
- ok = tools_config.install_cua_driver(
- upgrade=True, require_confirmed_update=require_confirmed
- )
- return ok, runner, info
-
- def test_indeterminate_check_keeps_installed_version(self):
- ok, runner, info = self._install(None, require_confirmed=True)
- assert ok is True
- runner.assert_not_called()
- assert any(
- "keeping the installed version" in call.args[0]
- for call in info.call_args_list
- )
-
- def test_indeterminate_check_points_at_force_path(self):
- ok, runner, info = self._install(None, require_confirmed=True)
- assert ok is True
- runner.assert_not_called()
- assert any(
- "computer-use install --upgrade" in call.args[0]
- for call in info.call_args_list
- )
-
- def test_confirmed_update_runs_installer_bounded(self):
- """Every platform: a positively confirmed newer release runs the
- installer in unattended-safe mode (background ceiling). On Windows
- the actual command adds -NoAutoStart and the preflights guard the
- launch (covered by their own test classes below)."""
- state = {"current_version": "0.5.0", "latest_version": "0.6.0",
- "update_available": True}
- ok, runner, _ = self._install(state, require_confirmed=True)
- assert ok is True
- runner.assert_called_once()
- assert runner.call_args.kwargs["installer_timeout"] == 120
-
- @pytest.mark.windows_only
- def test_windows_incompatible_driver_defers_interactive_repair(self):
- incompatible = {
- "ready": False,
- "version": "0.19.3",
- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",
- }
- ok, runner, info = self._install(
- None,
- require_confirmed=True,
- contract_status=incompatible,
- )
-
- assert ok is False
- runner.assert_not_called()
- assert any(
- "computer-use install --upgrade" in call.args[0]
- for call in info.call_args_list
- )
-
- @pytest.mark.windows_only
- def test_windows_missing_binary_defers_interactive_install(self):
- """Driver enabled but never installed (or wiped by a failed install):
- the automatic update must not launch install.ps1 either — this path
- reached the installer before the top-level guard (#94296 review)."""
- ok, runner, info = self._install(
- None,
- require_confirmed=True,
- binary_missing=True,
- )
-
- assert ok is False
- runner.assert_not_called()
- assert any(
- "computer-use install --upgrade" in call.args[0]
- for call in info.call_args_list
- )
-
- @pytest.mark.skipif(
- sys.platform == "win32",
- reason="POSIX installers are non-interactive; missing binary installs",
- )
- def test_posix_missing_binary_still_installs(self):
- ok, runner, _ = self._install(
- None,
- require_confirmed=True,
- binary_missing=True,
- )
-
- assert ok is True
- runner.assert_called_once()
-
- def test_up_to_date_short_circuits(self):
- state = {"current_version": "0.6.0", "latest_version": "0.6.0",
- "update_available": False}
- ok, runner, _ = self._install(state, require_confirmed=True)
- assert ok is True
- runner.assert_not_called()
-
- def test_explicit_upgrade_still_falls_through_on_indeterminate(self):
- # `hermes computer-use install --upgrade` (default flag): the old
- # behaviour — indeterminate check re-runs the installer.
- ok, runner, _ = self._install(None, require_confirmed=False)
- assert ok is True
- runner.assert_called_once()
-
- @pytest.mark.skipif(
- sys.platform == "win32",
- reason="automatic Windows updates must not launch an interactive repair",
- )
- def test_incompatible_driver_repairs_on_posix_despite_indeterminate_check(self):
- """Hermes' own version floor is the confirmation. When the installed
- driver fails the runtime contract, the `hermes update` refresh must
- repair it even though ``check-update`` can't confirm a newer release
- (its ~20h cache routinely lags a same-day floor bump — the 0.19.3
- wedge)."""
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- incompatible = {
- "ready": False,
- "version": "0.19.3",
- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",
- }
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/x/" + n
- if n in {"cua-driver", "curl", "powershell"} else None), \
- patch.object(tools_config, "_resolved_cua_driver_cmd",
- return_value="/x/cua-driver"), \
- patch.object(tools_config, "_cua_install_target_writable",
- return_value=True), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- side_effect=[incompatible,
- {"ready": True, "version": "0.20.0", "reason": ""}],
- ), \
- patch("tools.computer_use.cua_backend_driver.cua_driver_update_check",
- return_value=None) as check, \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner, \
- patch("subprocess.run",
- return_value=MagicMock(stdout="cua-driver 0.19.3",
- returncode=0)), \
- patch.object(tools_config, "_print_success"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config.install_cua_driver(
- upgrade=True, require_confirmed_update=True
- )
-
- assert ok is True
- runner.assert_called_once()
- assert runner.call_args.kwargs["label"] == "Repairing"
- # The confirmed-update gate must not even consult check-update:
- # the contract failure already confirmed the need.
- check.assert_not_called()
-
-
-class TestUpdateCheckTimeoutDefaults:
- """cua_driver_update_check: platform-sensitive default timeout.
-
- 8s is fine on POSIX but too tight for Windows first-spawn (Defender /
- SmartScreen scanning), and a false timeout is what used to trigger the
- full reinstall fall-through during `hermes update`.
- """
-
- def _captured_timeout(self):
- from unittest.mock import MagicMock
- from tools.computer_use import cua_backend_driver
-
- captured = {}
-
- def fake_run(cmd, **kw):
- captured["timeout"] = kw.get("timeout")
- m = MagicMock()
- m.stdout = '{"update_available": false, "current_version": "1.0"}'
- return m
-
- with patch("tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd",
- return_value="/x/cua-driver"), \
- patch("tools.computer_use.cua_backend.subprocess.run",
- side_effect=fake_run):
- cua_backend_driver.cua_driver_update_check()
- return captured.get("timeout")
-
- @pytest.mark.windows_only
- def test_windows_default_is_generous(self):
- """``windows_only``: the 25s default exists because a real Windows
- first-spawn is delayed by Defender/SmartScreen scanning — a faked
- platform asserted the constant, never the host it is chosen for.
- """
- assert self._captured_timeout() == 25.0
-
- def test_posix_default_unchanged(self):
- # Unmarked: the POSIX default is what this (Linux) host already picks,
- # so no platform faking is involved.
- assert self._captured_timeout() == 8.0
-
- def test_explicit_timeout_wins(self):
- from unittest.mock import MagicMock
- from tools.computer_use import cua_backend_driver
-
- captured = {}
-
- def fake_run(cmd, **kw):
- captured["timeout"] = kw.get("timeout")
- m = MagicMock()
- m.stdout = "{}"
- return m
-
- with patch("tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd",
- return_value="/x/cua-driver"), \
- patch("tools.computer_use.cua_backend.subprocess.run",
- side_effect=fake_run):
- cua_backend_driver.cua_driver_update_check(timeout=3.0)
- assert captured.get("timeout") == 3.0
-
-
-class TestArchProbeRemoval:
- """Regression tests for the deletion of `_check_cua_driver_asset_for_arch`.
-
- The old probe queried ``/releases/latest`` on trycua/cua and inspected
- asset names. That was wrong in two ways:
-
- 1. cua-driver-rs releases are marked **prerelease** on every cut, so
- ``/releases/latest`` returns the Python ``cua-agent`` / ``cua-computer``
- package instead — a release with zero binary assets. The probe then
- reported "no asset for $arch" on Linux x86_64, Windows, macOS Intel,
- Linux arm64 — every non-Apple-Silicon host.
- 2. Even with the right endpoint, it duplicated tag-resolution the upstream
- installer already does correctly via ``CUA_DRIVER_RS_BAKED_VERSION``
- (auto-baked by CD on every release).
-
- The fix: stop probing. Trust the upstream installer for fresh installs
- (it has the baked version + correct API fallback) and the
- ``cua-driver check-update --json`` MCP-binary native command for the
- upgrade path.
- """
-
- def test_probe_function_is_gone(self):
- from hermes_cli import tools_config_cua as tools_config
- assert not hasattr(tools_config, "_check_cua_driver_asset_for_arch")
- assert not hasattr(tools_config, "_latest_cua_driver_rs_release")
-
- def test_fresh_install_does_not_call_github_api(self):
- """Pre-install no longer probes the GitHub API — the upstream
- ``install.sh`` resolves the tag from its baked CUA_DRIVER_RS_BAKED_VERSION
- line. install.sh errors cleanly when the arch has no asset, so the
- probe was duplicate gatekeeping.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- # No platform fake: "does Python hit the GitHub API?" is host-agnostic,
- # and ``which`` is stubbed so the host's own fetch tool resolves.
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/bin/" + n
- if n in ("curl", "powershell") else None), \
- patch("urllib.request.urlopen") as urlopen, \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner:
- assert tools_config.install_cua_driver(upgrade=False) is True
- runner.assert_called_once()
- urlopen.assert_not_called()
-
- def test_upgrade_with_binary_does_not_call_github_api_directly(self):
- """The upgrade path no longer hits GitHub from Python — it delegates
- to the upstream ``install.sh`` (which has the baked release tag and
- the proper API fallback). When cua-driver is already installed,
- ``cua_driver_update_check()`` (added in a separate change) further
- short-circuits the network re-install via the binary's native
- ``check-update --json`` verb.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/usr/local/bin/" + n
- if n in ("cua-driver", "curl", "powershell") else None), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""},
- ), \
- patch("urllib.request.urlopen") as urlopen, \
- patch("subprocess.run"), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner:
- assert tools_config.install_cua_driver(upgrade=True) is True
- runner.assert_called_once()
- # Probe deleted — no direct GitHub API call from Python.
- urlopen.assert_not_called()
-
-
- sys.platform == "win32",
- reason="POSIX installer uses the .install.lock.d directory protocol",
-)
-class TestPosixStaleInstallLockClear:
- """_clear_stale_cua_install_lock: pre-clears the upstream installer's
- concurrent-install lock only when the holder is provably dead (or the
- lock is old and pid-less). Issue #58762."""
-
- def _make_lock(self, tmp_path, pid=None):
- import os
- home = tmp_path / ".cua-driver"
- lock = home / "packages" / ".install.lock.d"
- lock.mkdir(parents=True)
- if pid is not None:
- (lock / "info").write_text(f"pid={pid}\n")
- os.environ["CUA_DRIVER_RS_HOME"] = str(home)
- return lock
-
- def teardown_method(self):
- import os
- os.environ.pop("CUA_DRIVER_RS_HOME", None)
-
- def test_dead_holder_lock_is_cleared(self, tmp_path):
- from hermes_cli import tools_config_cua as tools_config
-
- dead_pid = 4194000 # above default pid_max on most systems
- lock = self._make_lock(tmp_path, pid=dead_pid)
- with patch.object(tools_config, "_print_info"):
- tools_config._clear_stale_cua_install_lock()
- assert not lock.exists()
-
- def test_live_holder_lock_is_kept(self, tmp_path):
- import os
- from hermes_cli import tools_config_cua as tools_config
-
- lock = self._make_lock(tmp_path, pid=os.getpid())
- tools_config._clear_stale_cua_install_lock()
- assert lock.exists()
-
- def test_pidless_fresh_lock_is_kept(self, tmp_path):
- from hermes_cli import tools_config_cua as tools_config
-
- lock = self._make_lock(tmp_path, pid=None)
- tools_config._clear_stale_cua_install_lock()
- assert lock.exists()
-
- def test_pidless_old_lock_is_cleared(self, tmp_path):
- import os
- import time
- from hermes_cli import tools_config_cua as tools_config
-
- lock = self._make_lock(tmp_path, pid=None)
- old = time.time() - (tools_config._CUA_LOCK_STALE_AFTER + 60)
- os.utime(lock, (old, old))
- with patch.object(tools_config, "_print_info"):
- tools_config._clear_stale_cua_install_lock()
- assert not lock.exists()
-
- def test_no_lock_is_noop(self, tmp_path):
- import os
- os.environ["CUA_DRIVER_RS_HOME"] = str(tmp_path / ".cua-driver")
- from hermes_cli import tools_config_cua as tools_config
- tools_config._clear_stale_cua_install_lock() # must not raise
-
-
-class TestWindowsStaleInstallLockClearDispatch:
- @pytest.mark.windows_only
- def test_windows_branch_uses_file_lock_probe(self):
- """``windows_only``: which lock protocol applies IS the host fact under
- test — on Linux the faked platform asserted the dispatch and skipped
- the ``.install.lock.d`` directory that really exists here.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(
- tools_config, "_clear_stale_windows_cua_install_lock"
- ) as clear_windows:
- tools_config._clear_stale_cua_install_lock()
-
- clear_windows.assert_called_once_with()
-
-
-# ``windows_only`` rather than ``skipif(sys.platform != "win32")``: the
-# dedicated Windows CI job selects ``-m windows_only``, so a bare skipif left
-# these real-CreateFileW tests running on no host at all.
-class TestWindowsStaleInstallLockClear:
- def _make_lock(self, tmp_path):
- import os
-
- home = tmp_path / ".cua-driver"
- home.mkdir()
- lock = home / "install.lock"
- lock.write_text("pid=stale\n", encoding="utf-8")
- os.environ["CUA_DRIVER_RS_HOME"] = str(home)
- return lock
-
- def teardown_method(self):
- import os
-
- os.environ.pop("CUA_DRIVER_RS_HOME", None)
-
- def test_unlocked_lock_file_is_cleared(self, tmp_path):
- from hermes_cli import tools_config_cua as tools_config
-
- lock = self._make_lock(tmp_path)
- with patch.object(tools_config, "_print_info"):
- tools_config._clear_stale_cua_install_lock()
-
- assert not lock.exists()
-
- def test_lock_held_with_file_share_none_is_kept(self, tmp_path):
- import ctypes
- from ctypes import wintypes
- from hermes_cli import tools_config_cua as tools_config
-
- lock = self._make_lock(tmp_path)
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- create_file = kernel32.CreateFileW
- create_file.argtypes = [
- wintypes.LPCWSTR,
- wintypes.DWORD,
- wintypes.DWORD,
- wintypes.LPVOID,
- wintypes.DWORD,
- wintypes.DWORD,
- wintypes.HANDLE,
- ]
- create_file.restype = wintypes.HANDLE
- close_handle = kernel32.CloseHandle
- close_handle.argtypes = [wintypes.HANDLE]
- close_handle.restype = wintypes.BOOL
- handle = create_file(
- str(lock),
- 0x80000000 | 0x40000000, # GENERIC_READ | GENERIC_WRITE
- 0, # FileShare::None, matching install.ps1
- None,
- 3, # OPEN_EXISTING
- 0x00000080, # FILE_ATTRIBUTE_NORMAL
- None,
- )
- assert handle != wintypes.HANDLE(-1).value
-
- try:
- tools_config._clear_stale_cua_install_lock()
- assert lock.exists()
- finally:
- assert close_handle(handle)
-
-
-class TestInstallerTimeoutKillsProcessGroup:
- """On timeout the whole installer process group must be killed, so the
- `curl | bash` grandchildren can't survive holding the install lock.
-
- The POSIX cases drop the old ``platform.system`` → "Linux" fake: this lane
- IS Linux, so the branch is selected for real. The Windows cases are
- ``windows_only`` — the psutil tree-kill only runs when ``is_windows``, and
- on Linux the fake picked that branch on a host with no such process model.
- """
-
- @pytest.mark.linux_only
- def test_timeout_kills_process_group_and_returns_false(self):
- import signal
- import subprocess
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- killed = {}
- sigkill = getattr(signal, "SIGKILL", signal.SIGTERM)
-
- fake_proc = MagicMock()
- fake_proc.pid = 12345
- # First communicate() raises TimeoutExpired, second (post-kill) returns.
- fake_proc.communicate.side_effect = [
- subprocess.TimeoutExpired(cmd="x", timeout=1),
- ("", None),
- ]
-
- def fake_killpg(pgid, sig):
- killed["pgid"] = pgid
- killed["sig"] = sig
-
- with patch("subprocess.run", return_value=MagicMock(returncode=0, stderr="")), \
- patch("subprocess.Popen", return_value=fake_proc), \
- patch.object(
- tools_config.os, "getpgid", return_value=99999, create=True
- ), \
- patch.object(
- tools_config.os, "killpg", side_effect=fake_killpg, create=True
- ), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config._run_cua_driver_installer(label="Refreshing", verbose=False)
-
- assert ok is False
- assert killed.get("pgid") == 99999
- assert killed.get("sig") == sigkill
- # Post-kill reap happened.
- assert fake_proc.communicate.call_count == 2
-
- def test_timeout_ceiling_exceeds_upstream_lock_window(self):
- from hermes_cli import tools_config_cua as tools_config
- # The upstream installer waits up to 600s before reclaiming a stale
- # lock; our ceiling must give that window room to complete.
- assert tools_config._CUA_INSTALLER_TIMEOUT > tools_config._CUA_LOCK_STALE_AFTER
-
- @pytest.mark.linux_only
- def test_installer_runs_in_new_session_on_posix(self):
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- captured = {}
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 1
- fake_proc.communicate.return_value = ("", None)
-
- def fake_popen(*args, **kwargs):
- captured.update(kwargs)
- return fake_proc
-
- with patch("subprocess.run", return_value=MagicMock(returncode=0, stderr="")), \
- patch("subprocess.Popen", side_effect=fake_popen), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- tools_config._run_cua_driver_installer(label="Refreshing", verbose=False)
-
- assert captured.get("start_new_session") is True
-
- @pytest.mark.windows_only
- def test_windows_timeout_kills_descendants_and_parent(self):
- import subprocess
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- child = MagicMock()
- parent = MagicMock()
- parent.children.return_value = [child]
-
- fake_proc = MagicMock()
- fake_proc.pid = 12345
- fake_proc.communicate.side_effect = [
- subprocess.TimeoutExpired(cmd="powershell", timeout=1),
- ("", None),
- ]
-
- with patch("subprocess.Popen", return_value=fake_proc), \
- patch("psutil.Process", return_value=parent), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config._run_cua_driver_installer(
- label="Refreshing", verbose=False
- )
-
- assert ok is False
- parent.children.assert_called_once_with(recursive=True)
- child.kill.assert_called_once_with()
- parent.kill.assert_called_once_with()
- fake_proc.kill.assert_not_called()
- assert fake_proc.communicate.call_count == 2
- assert (
- fake_proc.communicate.call_args_list[1].kwargs["timeout"]
- == tools_config._CUA_INSTALLER_DRAIN_GRACE
- )
-
- @pytest.mark.windows_only
- def test_windows_tree_enumeration_failure_falls_back_to_direct_kill(self):
- import psutil
- import subprocess
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- parent = MagicMock()
- parent.children.side_effect = psutil.AccessDenied(pid=12345)
-
- fake_proc = MagicMock()
- fake_proc.pid = 12345
- fake_proc.communicate.side_effect = [
- subprocess.TimeoutExpired(cmd="powershell", timeout=1),
- ("", None),
- ]
-
- with patch("subprocess.Popen", return_value=fake_proc), \
- patch("psutil.Process", return_value=parent), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config._run_cua_driver_installer(
- label="Refreshing", verbose=False
- )
-
- assert ok is False
- fake_proc.kill.assert_called_once_with()
- assert fake_proc.communicate.call_count == 2
-
-
-class TestInstallerTimeoutDrainIsBounded:
- """The drain that follows the timeout kill must carry its own deadline.
-
- ``_kill_installer_tree`` is best-effort: every ``psutil.Error`` it can hit
- is logged at debug level and stepped over, so the tree it leaves behind
- can still contain a live process — on Windows, most concretely, an
- ``install.ps1`` that self-elevated through ``Start-Process -Verb RunAs``
- and cannot be killed from a medium-integrity parent. That survivor holds
- the ``stdout=PIPE`` write handle it inherited, so reading to EOF is
- reading for something that will not happen, and ``_CUA_INSTALLER_TIMEOUT``
- stops being a ceiling (#87703).
-
- Asserted through the ``timeout`` kwarg rather than by timing: a test that
- proved the hang by hanging would be the same defect wearing a test's name.
- """
-
- def test_drain_grace_is_short_relative_to_the_run_ceiling(self):
- from hermes_cli import tools_config_cua as tools_config
-
- # This is a grace period for a pipe that a live process is holding
- # open, not a second budget for the install itself — the install is
- # already over by the time it is used.
- assert 0 < tools_config._CUA_INSTALLER_DRAIN_GRACE
- assert (
- tools_config._CUA_INSTALLER_DRAIN_GRACE
- < tools_config._CUA_INSTALLER_TIMEOUT / 10
- )
-
- @pytest.mark.linux_only
- def test_post_kill_drain_passes_a_deadline(self):
- """``linux_only``: reaches the timeout handler through the real POSIX
- ``killpg`` branch, so the drain under test is the one this lane runs.
- """
- import subprocess
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 12345
- fake_proc.communicate.side_effect = [
- subprocess.TimeoutExpired(cmd="x", timeout=1),
- ("", None),
- ]
-
- with patch("subprocess.run", return_value=MagicMock(returncode=0, stderr="")), \
- patch("subprocess.Popen", return_value=fake_proc), \
- patch.object(tools_config.os, "getpgid", return_value=99999, create=True), \
- patch.object(tools_config.os, "killpg", create=True), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config._run_cua_driver_installer(label="Refreshing", verbose=False)
-
- assert ok is False
- assert fake_proc.communicate.call_count == 2
- drain_timeout = fake_proc.communicate.call_args_list[1].kwargs.get("timeout")
- assert drain_timeout is not None, (
- "the post-kill drain was issued without a deadline, so a survivor "
- "of the kill can hold it open indefinitely"
- )
- assert drain_timeout == tools_config._CUA_INSTALLER_DRAIN_GRACE
-
- @pytest.mark.linux_only
- def test_verbose_path_drains_under_the_same_deadline(self):
- """The streaming install has the same handler and had the same hole.
-
- Its child inherits the console rather than a pipe, so the stall is
- harder to hit there, but the two branches should not be allowed to
- drift on a rule this small.
- """
- import subprocess
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 12345
- fake_proc.communicate.side_effect = [
- subprocess.TimeoutExpired(cmd="x", timeout=1),
- ("", None),
- ]
-
- with patch("subprocess.run", return_value=MagicMock(returncode=0, stderr="")), \
- patch("subprocess.Popen", return_value=fake_proc), \
- patch.object(tools_config.os, "getpgid", return_value=99999, create=True), \
- patch.object(tools_config.os, "killpg", create=True), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"), \
- patch.object(tools_config, "_print_success"):
- ok = tools_config._run_cua_driver_installer(label="Installing", verbose=True)
-
- assert ok is False
- assert fake_proc.communicate.call_count == 2
- drain_timeout = fake_proc.communicate.call_args_list[1].kwargs.get("timeout")
- assert drain_timeout is not None, (
- "the streaming path's drain was issued without a deadline"
- )
- assert drain_timeout == tools_config._CUA_INSTALLER_DRAIN_GRACE
-
- @pytest.mark.windows_only
- def test_unkillable_elevated_descendant_does_not_stall_the_drain(self):
- """The reported scenario, with the kill refused exactly where it is.
-
- ``install.ps1`` self-elevates, so the descendant is High-IL and
- ``child.kill()`` raises ``AccessDenied`` — which the tree-kill catches
- and logs, by design. The survivor is then still holding the pipe, and
- the drain is the only thing standing between that and an indefinite
- hang.
- """
- import psutil
- import subprocess
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- child = MagicMock()
- child.kill.side_effect = psutil.AccessDenied(pid=999)
- parent = MagicMock()
- parent.children.return_value = [child]
-
- fake_proc = MagicMock()
- fake_proc.pid = 12345
- fake_proc.communicate.side_effect = [
- subprocess.TimeoutExpired(cmd="powershell", timeout=1),
- ("", None),
- ]
-
- with patch("subprocess.Popen", return_value=fake_proc), \
- patch("psutil.Process", return_value=parent), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config._run_cua_driver_installer(
- label="Refreshing", verbose=False
- )
-
- assert ok is False
- # The refused child kill must not abort the rest of the sweep.
- parent.kill.assert_called_once_with()
- drain_timeout = fake_proc.communicate.call_args_list[1].kwargs.get("timeout")
- assert drain_timeout is not None, (
- "a High-IL descendant survived the kill and the drain was issued "
- "without a deadline, which is the reported hang"
- )
- assert drain_timeout == tools_config._CUA_INSTALLER_DRAIN_GRACE
-
- @pytest.mark.windows_only
- def test_drain_that_times_out_still_surfaces_the_run_timeout(self):
- """A guardrail, not a regression test — it passes without the fix too.
-
- What it pins is that the drain's own ``TimeoutExpired`` must not be
- the one that escapes: the caller has to see the original run timeout
- so the existing manual re-run hint prints and ``hermes update``
- unwinds. That is the behaviour a future refactor of the drain is most
- likely to break silently.
- """
- import subprocess
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- parent = MagicMock()
- parent.children.return_value = []
-
- fake_proc = MagicMock()
- fake_proc.pid = 12345
- fake_proc.communicate.side_effect = [
- subprocess.TimeoutExpired(cmd="powershell", timeout=660),
- subprocess.TimeoutExpired(cmd="powershell", timeout=15),
- ]
-
- with patch("subprocess.Popen", return_value=fake_proc), \
- patch("psutil.Process", return_value=parent), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning") as warn, \
- patch.object(tools_config, "_print_info"):
- ok = tools_config._run_cua_driver_installer(
- label="Refreshing", verbose=False
- )
-
- assert ok is False
- warned = " ".join(str(c.args[0]) for c in warn.call_args_list if c.args)
- assert "timed out after" in warned
-
-
-class TestInstallerNoShell:
- """The POSIX installer path must not use shell=True or command
- substitution: the script is downloaded to a mkstemp file and exec'd
- as a plain argv list (salvage of #34974's intent, without the fixed
- /tmp path TOCTOU that PR introduced).
-
- ``linux_only``: the download-then-exec argv IS the POSIX branch, and this
- lane already takes it — the old ``platform.system`` → "Linux" fake was
- asserting a branch the host had already selected.
- """
-
- def _run(self, download_rc=0):
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- calls = []
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- def fake_run(cmd, **kw):
- calls.append(("run", cmd, kw))
- m = MagicMock()
- m.returncode = download_rc
- m.stderr = "curl: (6) could not resolve" if download_rc else ""
- return m
-
- def fake_popen(cmd, **kw):
- calls.append(("popen", cmd, kw))
- return fake_proc
-
- with patch("subprocess.run", side_effect=fake_run), \
- patch("subprocess.Popen", side_effect=fake_popen), \
- patch.object(tools_config.shutil, "which", return_value="/usr/local/bin/cua-driver"), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"), \
- patch.object(tools_config, "_print_success"):
- ok = tools_config._run_cua_driver_installer(label="Refreshing", verbose=False)
- return ok, calls
-
- def test_posix_path_downloads_then_execs_argv_list(self):
- ok, calls = self._run()
- assert ok is True
- run_calls = [c for c in calls if c[0] == "run"]
- popen_calls = [c for c in calls if c[0] == "popen"]
- assert len(run_calls) == 1 and len(popen_calls) == 1
- # Download: plain argv curl, no shell.
- dl_cmd = run_calls[0][1]
- assert isinstance(dl_cmd, list) and dl_cmd[0] == "curl"
- # Exec: argv list ["/bin/bash", <mkstemp path>], shell=False.
- exec_cmd, exec_kw = popen_calls[0][1], popen_calls[0][2]
- assert isinstance(exec_cmd, list) and exec_cmd[0] == "/bin/bash"
- assert "cua-driver-install-" in exec_cmd[1]
- assert exec_kw.get("shell") is False
-
- def test_download_failure_returns_false_without_exec(self):
- ok, calls = self._run(download_rc=6)
- assert ok is False
- assert not [c for c in calls if c[0] == "popen"]
-
- def test_temp_script_removed_after_run(self):
- import os
- captured = {}
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- def fake_run(cmd, **kw):
- m = MagicMock(); m.returncode = 0; m.stderr = ""
- return m
-
- def fake_popen(cmd, **kw):
- captured["script"] = cmd[1]
- return fake_proc
-
- with patch("subprocess.run", side_effect=fake_run), \
- patch("subprocess.Popen", side_effect=fake_popen), \
- patch.object(tools_config.shutil, "which", return_value="/usr/local/bin/cua-driver"), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"), \
- patch.object(tools_config, "_print_success"):
- tools_config._run_cua_driver_installer(label="Refreshing", verbose=False)
-
- assert "script" in captured
- assert not os.path.exists(captured["script"])
-
-
-class TestConfirmedVersionPinning:
- """When check-update confirms a newer release, the installer run must be
- pinned to that exact version via CUA_DRIVER_RS_VERSION.
-
- The upstream installer scripts on `main` carry a baked version that
- Release Please bumps in the release PR *before* the release assets are
- published. An unpinned install inside that window 404s (observed
- 2026-07-29: baked 0.14.0 vs latest published release 0.13.1). Pinning to
- check-update's `latest_version` — which comes from the Releases API and
- therefore has published assets — sidesteps the race.
- """
-
- def _install(self, check_state):
- """Version pinning also applies to explicit installer runs."""
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- with patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/x/" + n
- if n in {"cua-driver", "curl", "powershell"} else None), \
- patch.object(tools_config, "_resolved_cua_driver_cmd",
- return_value="/x/cua-driver"), \
- patch.object(tools_config, "_cua_install_target_writable",
- return_value=True), \
- patch.object(
- tools_config,
- "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""},
- ), \
- patch("tools.computer_use.cua_backend_driver.cua_driver_update_check",
- return_value=check_state), \
- patch.object(tools_config, "_run_cua_driver_installer",
- return_value=True) as runner, \
- patch("subprocess.run",
- return_value=MagicMock(stdout="cua-driver 0.5.0", returncode=0)), \
- patch.object(tools_config, "_print_success"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config.install_cua_driver(
- upgrade=True, require_confirmed_update=False
- )
- return ok, runner
-
- def test_confirmed_update_pins_latest_version(self):
- state = {"current_version": "0.12.6", "latest_version": "0.13.1",
- "update_available": True}
- ok, runner = self._install(state)
- assert ok is True
- assert runner.call_args.kwargs.get("pin_version") == "0.13.1"
-
- def test_v_prefixed_latest_version_is_normalized(self):
- state = {"current_version": "0.12.6", "latest_version": "v0.13.1",
- "update_available": True}
- ok, runner = self._install(state)
- assert ok is True
- assert runner.call_args.kwargs.get("pin_version") == "0.13.1"
-
- def test_malformed_latest_version_falls_back_unpinned(self):
- state = {"current_version": "0.12.6", "latest_version": "not a version",
- "update_available": True}
- ok, runner = self._install(state)
- assert ok is True
- assert runner.call_args.kwargs.get("pin_version") is None
-
- def test_missing_latest_version_falls_back_unpinned(self):
- state = {"current_version": "0.12.6", "update_available": True}
- ok, runner = self._install(state)
- assert ok is True
- assert runner.call_args.kwargs.get("pin_version") is None
-
-
-class TestRunInstallerPinEnv:
- """_run_cua_driver_installer(pin_version=...) exports CUA_DRIVER_RS_VERSION
- into the installer child env; unpinned runs leave it untouched.
-
- ``linux_only``: the helper reaches Popen through the POSIX
- download-then-exec branch, which this lane takes for real — no
- ``platform.system`` fake needed. The pin itself is host-agnostic
- (``TestConfirmedVersionPinning`` covers the caller side unmarked).
- """
-
- def _run(self, pin_version):
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- captured = {}
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 1
- fake_proc.communicate.return_value = ("", None)
-
- def fake_popen(cmd, **kw):
- captured["env"] = kw.get("env")
- return fake_proc
-
- def fake_run(cmd, **kw):
- m = MagicMock(); m.returncode = 0; m.stderr = ""
- return m
-
- with patch("subprocess.run", side_effect=fake_run), \
- patch("subprocess.Popen", side_effect=fake_popen), \
- patch.object(tools_config, "_cua_driver_env",
- return_value={"PATH": "/usr/bin"}), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- tools_config._run_cua_driver_installer(
- label="Refreshing", verbose=False, pin_version=pin_version
- )
- return captured.get("env") or {}
-
- def test_pin_version_exported_to_installer_env(self):
- env = self._run("0.13.1")
- assert env.get("CUA_DRIVER_RS_VERSION") == "0.13.1"
-
- def test_no_pin_leaves_env_untouched(self):
- env = self._run(None)
- assert "CUA_DRIVER_RS_VERSION" not in env
-
-
-class TestWindowsAutostartRepair:
- @pytest.mark.windows_only
- def test_existing_task_skips_elevated_powershell_repair(self):
- """``windows_only``: ``_repair_cua_driver_autostart_windows`` returns
- True unconditionally off Windows, so only the fake made the schtasks
- probe run at all.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- calls = []
-
- def fake_run(cmd, **kwargs):
- calls.append((cmd, kwargs))
- return SimpleNamespace(returncode=0)
-
- with patch("subprocess.run", side_effect=fake_run), \
- patch.object(tools_config.shutil, "which") as which:
- ok = tools_config._repair_cua_driver_autostart_windows(
- "cua-driver", verbose=False
- )
-
- assert ok is True
- assert [cmd for cmd, _kwargs in calls] == [
- ["schtasks.exe", "/Query", "/TN", "cua-driver-serve"]
- ]
- which.assert_not_called()
-
- @pytest.mark.windows_only
- def test_windows_installer_runs_autostart_repair_after_success(self):
- """``windows_only``: the PowerShell install argv and the autostart
- repair hook are both inside the ``is_windows`` branch, so on Linux the
- fake selected a branch whose `powershell` doesn't exist on PATH."""
- from unittest.mock import MagicMock
- from hermes_cli import tools_config_cua as tools_config
-
- captured = {}
- fake_proc = MagicMock()
- fake_proc.pid = 1
- fake_proc.returncode = 0
- fake_proc.communicate.return_value = ("", None)
-
- def fake_popen(cmd, **kwargs):
- captured["cmd"] = cmd
- captured["kwargs"] = kwargs
- return fake_proc
-
- def fake_which(name: str):
- if name == "cua-driver":
- return r"C:\Users\Ha Trung\AppData\Local\Programs\Cua\cua-driver\bin\cua-driver.exe"
- return None
-
- with patch.object(tools_config.shutil, "which", side_effect=fake_which), \
- patch("subprocess.Popen", side_effect=fake_popen), \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config, "_repair_cua_driver_autostart_windows", return_value=True) as repair, \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"), \
- patch.object(tools_config, "_print_success"):
- ok = tools_config._run_cua_driver_installer(label="Refreshing", verbose=False)
-
- assert ok is True
- assert captured["kwargs"].get("shell") is False
- assert isinstance(captured["cmd"], list)
- assert captured["cmd"][:4] == [
- "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass",
- ]
- repair.assert_called_once_with(
- r"C:\Users\Ha Trung\AppData\Local\Programs\Cua\cua-driver\bin\cua-driver.exe",
- verbose=False,
- )
-
- @pytest.mark.windows_only
- def test_autostart_repair_quotes_username_space_path_via_file_path(self):
- """``windows_only``: same early return off Windows — the elevated
- PowerShell command string is only built on a real Windows host.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- calls = []
- driver = (
- r"C:\Users\Ha Trung\AppData\Local\Programs\Cua"
- r"\cua-driver\bin\cua-driver.exe"
- )
-
- def fake_which(name: str):
- if name == "cua-driver":
- return driver
- if name == "powershell":
- return r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
- return None
-
- def fake_run(cmd, **kwargs):
- calls.append((cmd, kwargs))
- if cmd[0] == "schtasks.exe":
- return SimpleNamespace(returncode=1)
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- with patch.object(tools_config.shutil, "which", side_effect=fake_which), \
- patch("subprocess.run", side_effect=fake_run), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info"):
- ok = tools_config._repair_cua_driver_autostart_windows(
- "cua-driver", verbose=False
- )
-
- assert ok is True
- ps_calls = [cmd for cmd, _kwargs in calls if cmd[0].endswith("powershell.exe")]
- assert len(ps_calls) == 1
- ps_command = ps_calls[0][-1]
- assert "-FilePath $exe" in ps_command
- assert "-ArgumentList @('autostart','enable')" in ps_command
- assert f"$exe = '{driver}'" in ps_command
- assert f"& {driver}" not in ps_command
-
- @pytest.mark.windows_only
- def test_repair_spawns_no_console_window_and_failure_degrades(self):
- """``windows_only``: issue #115017 — the auto-start repair must not park a blank PowerShell
- window on the desktop, and a failed repair must not fail the install.
-
- This repair is reached from the shared install/refresh path, which a windowless parent
- drives (Desktop backend, detached gateway, a logon task). A ``powershell.exe`` spawned
- there WITHOUT ``CREATE_NO_WINDOW`` allocates its own console: a blank PowerShell window that
- stays on screen for as long as the elevated ``-Verb RunAs -Wait`` child lives (verified live
- on Windows 11: the window appears, and with ``CREATE_NO_WINDOW`` it never does). Without
- ``-NonInteractive`` that shell can also sit on an interactive prompt instead of unwinding.
- """
- from hermes_cli import tools_config_cua as tools_config
-
- create_no_window = 0x08000000
- calls = []
- driver = (
- r"C:\Users\Ha Trung\AppData\Local\Programs\Cua"
- r"\cua-driver\bin\cua-driver.exe"
- )
-
- def fake_which(name: str):
- if name == "cua-driver":
- return driver
- if name == "powershell":
- return r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
- return None
-
- def fake_run(cmd, **kwargs):
- calls.append((cmd, kwargs))
- if cmd[0] == "schtasks.exe": # task absent -> the repair branch runs
- return SimpleNamespace(returncode=1, stdout="", stderr="")
- return SimpleNamespace(returncode=1, stdout="", stderr="denied") # repair itself fails
-
- with patch.object(tools_config.shutil, "which", side_effect=fake_which), \
- patch("subprocess.run", side_effect=fake_run), \
- patch.object(tools_config, "_post_setup_no_window_flags",
- side_effect=lambda **kw: create_no_window), \
- patch.object(tools_config, "_print_warning") as warn, \
- patch.object(tools_config, "_print_info"):
- assert tools_config._repair_cua_driver_autostart_windows(
- "cua-driver", verbose=False
- ) is False
-
- ps_cmd, ps_kwargs = next(
- (cmd, kwargs) for cmd, kwargs in calls
- if str(cmd[0]).lower().endswith("powershell.exe")
- )
- assert ps_kwargs.get("creationflags") == create_no_window, (
- "windowless spawn is the fix: without CREATE_NO_WINDOW the child allocates its own "
- "visible console window on the user's desktop"
- )
- assert "-NonInteractive" in ps_cmd, "no interactive prompt may be presented"
- assert ps_cmd[-2:] == ["-Command", ps_cmd[-1]], "script stays the -Command argument"
- assert ps_kwargs.get("timeout"), "the repair must stay bounded, never block the caller"
-
- # Degrade, do not fail: the driver is installed and compatible, only its logon task is
- # missing — install_cua_driver must not report the whole toolset as broken.
- with patch.object(tools_config, "_resolved_cua_driver_cmd", return_value=driver), \
- patch.object(tools_config, "_cua_driver_contract_status",
- return_value={"ready": True, "version": "0.20.0", "reason": ""}), \
- patch.object(tools_config, "_cua_driver_version", return_value="0.20.0"), \
- patch.object(tools_config, "_repair_cua_driver_autostart_windows",
- return_value=False), \
- patch.object(tools_config, "_print_success"):
- assert tools_config.install_cua_driver(
- upgrade=False, show_installer_progress=False
- ) is True
-
- assert any("auto-start" in str(call) for call in warn.call_args_list)
-
-
-class TestCuaVersionSummary:
- """`hermes computer-use status` prints one line, whatever the binary says.
-
- A binary chosen by HERMES_CUA_DRIVER_CMD is under no obligation to answer
- `--version` the way cua-driver does, and its output used to be spliced
- verbatim into the status line.
- """
-
- @staticmethod
- def _summary(raw, **kw):
- from hermes_cli import tools_config_cua as tools_config
-
- return tools_config._cua_version_summary(raw, **kw)
-
- def test_plain_version_passes_through(self):
- assert self._summary("cua-driver 0.20.0") == "cua-driver 0.20.0"
-
- def test_multiline_banner_collapses_to_first_line(self):
- banner = (
- "Microsoft Windows [Version 10.0.26200.9168]\n"
- "(c) Microsoft Corporation. All rights reserved.\n"
- "\n"
- "C:\\Users\\demo>"
- )
- summary = self._summary(banner)
- assert summary == "Microsoft Windows [Version 10.0.26200.9168]"
- assert "\n" not in summary
-
- def test_leading_blank_lines_skipped(self):
- assert self._summary("\n\n cua-driver 0.20.0 ") == "cua-driver 0.20.0"
-
- def test_long_line_is_bounded(self):
- assert len(self._summary("x" * 500)) == 120
-
- def test_empty_output_stays_empty(self):
- assert self._summary("") == ""
- assert self._summary(" \n \n") == ""
-
-
-class TestUnattendedRefreshPreflights:
- """Unattended refreshes (installer_timeout set) fail FAST instead of
- eating the ceiling: a held install lock or an unreachable release host
- skips the run in seconds. Explicit installs (installer_timeout=None)
- bypass both preflights — a human is watching upstream's own recovery.
- """
-
- def _run(self, installer_timeout, lock_held=False, reachable=True,
- system="Linux"):
- from unittest.mock import MagicMock
-
- from hermes_cli import tools_config_cua as tools_config
-
- proc = MagicMock()
- proc.communicate.return_value = ("ok", None)
- proc.returncode = 0
-
- with patch("platform.system", return_value=system), \
- patch.object(tools_config, "_cua_install_lock_held",
- return_value=lock_held) as lock_probe, \
- patch.object(tools_config, "_cua_release_endpoint_reachable",
- return_value=reachable) as net_probe, \
- patch.object(tools_config, "_clear_stale_cua_install_lock"), \
- patch.object(tools_config.shutil, "which",
- side_effect=lambda n: "/x/" + n), \
- patch.object(tools_config.subprocess, "run",
- return_value=SimpleNamespace(
- returncode=0, stdout="", stderr="")), \
- patch.object(tools_config.subprocess, "Popen",
- return_value=proc) as popen, \
- patch.object(tools_config, "_print_success"), \
- patch.object(tools_config, "_print_warning"), \
- patch.object(tools_config, "_print_info") as info:
- ok = tools_config._run_cua_driver_installer(
- label="Refreshing",
- verbose=False,
- show_progress=False,
- installer_timeout=installer_timeout,
- )
- return ok, popen, info, lock_probe, net_probe
-
- def test_held_lock_skips_unattended_run(self):
- ok, popen, info, _, _ = self._run(120, lock_held=True)
- assert ok is False
- popen.assert_not_called()
- assert any("install lock is held" in c.args[0]
- for c in info.call_args_list)
-
- def test_unreachable_host_skips_unattended_run(self):
- ok, popen, info, _, _ = self._run(120, reachable=False)
- assert ok is False
- popen.assert_not_called()
- assert any("unreachable" in c.args[0] for c in info.call_args_list)
-
- def test_explicit_install_bypasses_preflights(self):
- """installer_timeout=None (explicit `computer-use install --upgrade`):
- neither probe runs; upstream's own lock recovery stays in charge."""
- ok, popen, _, lock_probe, net_probe = self._run(None)
- lock_probe.assert_not_called()
- net_probe.assert_not_called()
- popen.assert_called_once()
- assert ok is True
-
- def test_clean_preflights_run_installer(self):
- ok, popen, _, lock_probe, net_probe = self._run(120)
- lock_probe.assert_called_once()
- net_probe.assert_called_once()
- popen.assert_called_once()
- assert ok is True
-
- def test_windows_unattended_command_passes_noautostart(self):
- """The unattended Windows command must invoke install.ps1 with
- -NoAutoStart — Register-CuaDriverAutostart is the only branch that
- self-elevates (UAC)."""
- ok, popen, _, _, _ = self._run(120, system="Windows")
- assert ok is True
- cmd = popen.call_args.args[0]
- joined = " ".join(cmd)
- assert "-NoAutoStart" in joined
- assert "scriptblock" in joined
-
- def test_windows_explicit_command_keeps_plain_oneliner(self):
- """Explicit installs keep upstream's documented `irm | iex` shape
- (autostart re-registration included — human present for UAC)."""
- ok, popen, _, _, _ = self._run(None, system="Windows")
- assert ok is True
- cmd = popen.call_args.args[0]
- joined = " ".join(cmd)
- assert "-NoAutoStart" not in joined
- assert "| iex" in joined
[email protected]("upgrade", [False, True])
+def test_pm_failure_is_reported_without_vendor_fallback(monkeypatch, capsys, upgrade):
+ import pm
+ from hermes_cli import tools_config_cua as cua
+
+ monkeypatch.delenv("HERMES_CUA_DRIVER_CMD", raising=False)
+ monkeypatch.setattr(cua, "_resolved_cua_driver_cmd", lambda: None)
+ with patch.object(pm, "ensure", side_effect=pm.InstallError("cua-driver", "offline")) as ensure, \
+ patch.object(cua.subprocess, "Popen", side_effect=AssertionError("vendor installer")):
+ assert not cua.install_cua_driver(upgrade=upgrade)
+ ensure.assert_called_once_with("cua-driver", explicit=True)
+ assert "offline" in capsys.readouterr().out
+
+
[email protected]("upgrade", [False, True])
+def test_broken_override_never_acquires_standard_driver(tmp_path, monkeypatch, upgrade):
+ import pm
+ from hermes_cli import tools_config_cua as cua
+
+ monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(tmp_path / "missing-driver"))
+ with patch.object(pm, "ensure", side_effect=AssertionError("override was replaced")):
+ assert not cua.install_cua_driver(upgrade=upgrade)
+
+
[email protected]("windows")
[email protected]("old_target", [False, True])
+def test_autostart_uses_selected_binary_and_verifies_registration(tmp_path, monkeypatch, old_target):
+ from hermes_cli import tools_config_cua as cua
+
+ binary = str(tmp_path / "User's driver directory" / "cua-driver.exe")
+ selected = str(tmp_path / "old-cua-driver.exe") if old_target else binary
+ calls = []
+
+ def run(cmd, **kwargs):
+ nonlocal selected
+ calls.append(cmd)
+ if cmd[0] == "schtasks.exe":
+ xml = ('<?xml version="1.0" encoding="UTF-16"?>'
+ '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'
+ f'<Actions><Exec><Command>{escape(selected)}</Command></Exec></Actions></Task>')
+ return SimpleNamespace(returncode=0, stdout=xml.encode("utf-16"), stderr=b"")
+ assert "-FilePath $exe" in cmd[-1]
+ assert "-ArgumentList @('autostart','enable')" in cmd[-1]
+ assert cua._ps_single_quote(binary) in cmd[-1]
+ selected = binary
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(cua.subprocess, "run", run)
+ monkeypatch.setattr(cua.shutil, "which", lambda command: command)
+ assert cua._repair_cua_driver_autostart_windows(binary, verbose=False)
+ assert len([cmd for cmd in calls if cmd[0] != "schtasks.exe"]) == int(old_target)
+ assert all("/XML" in cmd for cmd in calls if cmd[0] == "schtasks.exe")
+
+
[email protected]("windows")
+def test_autostart_does_not_claim_success_without_registered_task(monkeypatch):
+ from hermes_cli import tools_config_cua as cua
+
+ monkeypatch.setattr(cua, "_cua_driver_autostart_registered_windows", lambda binary=None: False)
+ monkeypatch.setattr(cua.shutil, "which", lambda command: command)
+ monkeypatch.setattr(cua, "_run_text", lambda *a, **kw: SimpleNamespace(returncode=0))
+ assert not cua._repair_cua_driver_autostart_windows("cua-driver.exe", verbose=False)
+
+
[email protected]("windows")
[email protected]("registered", [False, True])
+def test_setup_preserves_host_registration_failure(monkeypatch, registered):
+ import pm
+ from hermes_cli import tools_config_cua as cua
+
+ monkeypatch.delenv("HERMES_CUA_DRIVER_CMD", raising=False)
+ monkeypatch.setattr(pm, "ensure", lambda *a, **kw: None)
+ monkeypatch.setattr(cua, "_resolved_cua_driver_cmd", lambda: "cua-driver.exe")
+ monkeypatch.setattr(cua, "_cua_driver_contract_status", lambda *a: {"ready": True})
+ with patch.object(cua, "_repair_cua_driver_autostart_windows", return_value=registered) as repair:
+ assert cua.install_cua_driver(show_installer_progress=False) is registered
+ repair.assert_called_once_with("cua-driver.exe", verbose=False)
+
+
+def test_setup_refuses_bare_binary_without_required_signed_app(monkeypatch, tmp_path):
+ from hermes_cli import tools_config_cua as cua
+
+ driver = tmp_path / "cua-driver"
+ driver.write_text("#!/bin/sh\nexit 0\n")
+ driver.chmod(0o755)
+ monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(driver))
+ monkeypatch.setattr(cua, "_cua_driver_contract_status", lambda *a: {"ready": True})
+ assert not cua.install_cua_driver(show_installer_progress=False)
+
+
+def test_setup_registers_only_the_validated_selected_app(monkeypatch, tmp_path):
+ from hermes_cli import tools_config_cua as cua
+ from tools.computer_use import cua_backend_daemon as daemon
+
+ app = tmp_path / "CuaDriver.app"
+ driver = app / "Contents" / "MacOS" / "cua-driver"
+ driver.parent.mkdir(parents=True)
+ driver.write_text("#!/bin/sh\nexit 0\n")
+ driver.chmod(0o755)
+ monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(driver))
+ monkeypatch.setattr(cua, "_cua_driver_contract_status", lambda *a: {"ready": True})
+ with patch.object(daemon, "_validate_cua_driver_app_signature") as validate, \
+ patch.object(cua, "_run_text", return_value=SimpleNamespace(returncode=0)) as register:
+ assert cua.install_cua_driver(show_installer_progress=False)
+ validate.assert_called_once_with(str(app))
+ assert register.call_args.args[0][-2:] == ["-f", str(app)]
+
+
+def test_setup_keeps_permission_guidance(capsys):
+ from hermes_cli.tools_config_cua import _print_cua_platform_notes
+
+ _print_cua_platform_notes(False, False, fresh_install=True)
+ output = capsys.readouterr().out
+ assert "Accessibility" in output
+ assert "Screen Recording" in output
+
+
[email protected]("raw,expected", [
+ ("cua-driver 0.20.0", "cua-driver 0.20.0"),
+ ("banner\nsecond line", "banner"),
+ ("\n\n cua-driver 0.20.0 ", "cua-driver 0.20.0"),
+ ("x" * 500, "x" * 120),
+ ("", ""),
+ (" \n \n", ""),
+])
+def test_version_summary(raw, expected):
+ from hermes_cli.tools_config_cua import _cua_version_summary
+
- assert _cua_version_summary(raw) == expected
++ assert _cua_version_summary(raw) == expected
diff --cc tests/hermes_cli/test_local_runtime.py
index 0694d11db43,d5580fa62c7..4c97a4ae13d
--- a/tests/hermes_cli/test_local_runtime.py
+++ b/tests/hermes_cli/test_local_runtime.py
@@@ -795,6 -955,107 +883,93 @@@ def test_bootstrap_failure_never_raises
raise RuntimeError("no network")
monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.ensure_runtime_installed", boom)
+ "hermes_cli.local_runtime.binaries.installed_engine", boom)
result = bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}})
assert result is None # no exception escaped
+
+
+ def test_ensure_local_runtime_serializes_racing_callers(tmp_path, monkeypatch):
+ """Cross-process boot race (#116682): two backends starting in the same second must not
+ both spawn a router on the stable port. Neither caller here ever sees the other's
+ in-process ``_SUPERVISOR`` (each opens its own fd for the boot lock, exactly like two
+ separate OS processes would) — only the cross-process file lock can serialize them."""
+ import time as _time
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import bootstrap
+ from hermes_cli.local_runtime import supervisor as sup_mod
+
+ monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)
+ mdir = bootstrap.models_dir()
+ mdir.mkdir(parents=True, exist_ok=True)
+ (mdir / "stub-Q4_K_M.gguf").touch()
+
+ monkeypatch.setattr(bootstrap, "_generate_presets", lambda *a, **k: None)
+ monkeypatch.setattr(bootstrap, "_presets_stale", lambda: False)
+ monkeypatch.setattr(bootstrap, "_detect_gpu_vendor", lambda: None)
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_tags", lambda: ["b1"])
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.default_tag", lambda: "b1")
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.ensure_runtime_installed",
- lambda tag, backend: tmp_path / "install")
++ from hermes_cli.local_runtime.binaries import Engine
++ monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_engine",
++ lambda backend="auto", **k: Engine("cpu", "b1", tmp_path / "install" / "llama-server"))
+
+ spawns = []
+
+ class _FakeSupervisor:
+ def __init__(self, *a, **k):
+ self.port = 18434
+ self.api_key = "k"
+ self.proc = None
+
+ @property
+ def base_url(self):
+ return f"http://127.0.0.1:{self.port}/v1"
+
+ def start(self, timeout_s=120):
+ spawns.append(1)
+ _time.sleep(0.3) # widen the window the other caller races into
+ path = sup_mod.state_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({
+ "base_url": self.base_url, "api_key": self.api_key, "pid": os.getpid(),
+ }), encoding="utf-8")
+
+ monkeypatch.setattr(sup_mod, "LlamaServerSupervisor", _FakeSupervisor)
+
+ barrier = threading.Barrier(2)
+ results = []
+
+ def _boot():
+ barrier.wait()
+ results.append(bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}}))
+
+ threads = [threading.Thread(target=_boot) for _ in range(2)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10)
+
+ assert len(spawns) == 1, (
+ "both racing callers spawned a router instead of the second adopting the "
+ "first's published state (#116682)")
+
+
+ def test_ensure_local_runtime_proceeds_when_boot_lock_is_unwritable(tmp_path, monkeypatch, caplog):
+ """The boot lock lives outside the body's ``try/except``: an unwritable runtimes dir must
+ degrade to a warning and an unlocked boot, never an OSError out of session start."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import bootstrap
+
+ monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)
+ mdir = bootstrap.models_dir()
+ mdir.mkdir(parents=True, exist_ok=True)
+ (mdir / "stub-Q4_K_M.gguf").touch()
+ blocker = tmp_path / "not-a-dir"
+ blocker.write_text("", encoding="utf-8")
+ monkeypatch.setattr(bootstrap, "runtimes_root", lambda: blocker / "runtimes") # mkdir -> OSError
+ monkeypatch.setattr("hermes_cli.local_runtime.endpoint._state_endpoint", lambda: None)
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_tags", lambda: [])
++ monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_engine", lambda backend="auto", **k: None)
+
+ with caplog.at_level(logging.WARNING, logger=bootstrap.logger.name):
+ result = bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}})
+
+ assert result is None # no exception escaped
+ assert any("boot lock unavailable" in rec.getMessage() for rec in caplog.records)
-
-
-def test_manifest_verified_tolerates_non_dict_manifest(tmp_path):
- """A parseable-but-non-object manifest used to raise AttributeError out of
- manifest_verified (the .get ran inside a try that only caught decode/OSError),
- breaking any() scans over install dirs."""
- from hermes_cli.local_runtime.binaries import manifest_verified
-
- m = tmp_path / "manifest.json"
- m.write_text('"oops"', encoding="utf-8")
- assert manifest_verified(m) is False
- m.write_text(json.dumps({"verified_version": "5015 (abc)"}), encoding="utf-8")
- assert manifest_verified(m) is True
diff --cc tests/hermes_cli/test_plugin_catalog.py
index d2a971acf85,38a7bc15cdb..4f8683d16af
--- a/tests/hermes_cli/test_plugin_catalog.py
+++ b/tests/hermes_cli/test_plugin_catalog.py
@@@ -58,8 -55,18 +58,18 @@@ def test_version_and_image_are_cosmetic
assert entries["labelled"].to_dict()["version"] == "1.4.0"
+ def test_screenshots_and_readme_are_parsed_and_default_off(tmp_path):
+ shot = "https://raw.githubusercontent.com/owner/repo/38fe0fb53eff98d477f807432e965429e665ca33/docs/1.png"
+ (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("paged", screenshots=[shot, "https://evil.example/x.png"], readme=True)))
+ (tmp_path / "b.yaml").write_text(yaml.safe_dump(_entry("plain", readme="yes")))
+ entries = {e.name: e for e in pc.load_catalog(tmp_path)}
+ assert entries["paged"].screenshots == [shot] and entries["paged"].readme is True
+ assert entries["plain"].screenshots == [] and entries["plain"].readme is False
+ assert entries["paged"].to_dict()["screenshots"] == [shot] and entries["paged"].to_dict()["readme"] is True
+
+
def test_invalid_entries_are_skipped_not_raised(tmp_path):
- (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("ok")))
+ (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("ok", description="café")), encoding="utf-8-sig")
(tmp_path / "b.yaml").write_text(yaml.safe_dump(_entry("short-sha", sha="abc123")))
(tmp_path / "c.yaml").write_text(yaml.safe_dump(_entry("http-repo", repo="http://x/y")))
(tmp_path / "d.yaml").write_text(yaml.safe_dump(_entry("Bad Name")))
diff --cc tests/hermes_cli/test_plugin_validate.py
index 53fe0564980,5954819c155..2003843536b
--- a/tests/hermes_cli/test_plugin_validate.py
+++ b/tests/hermes_cli/test_plugin_validate.py
@@@ -8,9 -8,10 +8,10 @@@ from __future__ import annotation
from pathlib import Path
-import yaml
+import hermes_yaml as yaml
from hermes_cli.plugin_validate import validate_plugin_dir
+ from hermes_cli.plugin_validate_desktop import desktop_surface_hits, is_desktop_surface
def _make_plugin(
diff --cc tests/hermes_cli/test_update_import_guard.py
index 2a760a5ab8b,699804ef11a..29bd5f7e0c9
--- a/tests/hermes_cli/test_update_import_guard.py
+++ b/tests/hermes_cli/test_update_import_guard.py
@@@ -281,20 -332,70 +281,68 @@@ def test_import_guard_ignores_missing_t
that adds a dependency would otherwise look like breakage and trigger a
spurious `git reset --hard` rollback of a perfectly good update.
"""
- (tmp_path / "consumer.py").write_text("import totally_not_installed_pkg\n")
+ (probe_root / "consumer.py").write_text("import totally_not_installed_pkg\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)
+ assert update_cmd._validate_critical_modules_import(probe_root) == (True, None, None)
+ def test_import_guard_rejects_module_satisfied_only_by_inherited_pythonpath(
+ monkeypatch, tmp_path
+ ):
+ """A stale checkout on PYTHONPATH must not stand in for a candidate module.
+
+ The probe child used to inherit the updater's environment wholesale, so
+ with PYTHONPATH pointing at an older tree the critical module imported
+ fine from there and a candidate lacking it entirely read as healthy
+ (#115032).
+ """
+ stale = tmp_path / "stale"
+ stale.mkdir()
+ (stale / "hermes_stale_supply.py").write_text("VALUE = 'from the stale tree'\n")
+
+ monkeypatch.setattr(
+ update_cmd, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)
+ )
+ monkeypatch.setattr(
+ update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)
+ )
+ monkeypatch.setenv("PYTHONPATH", str(stale))
+
+ ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+
+ assert ok is False
+ assert module == "hermes_stale_supply"
+ assert error is not None and "hermes_stale_supply" in error
+
+
+ def test_import_guard_accepts_candidate_with_foreign_pythonpath(monkeypatch, tmp_path):
+ """The env scrub must not overreach: a candidate that carries the module
+ still passes while a foreign PYTHONPATH is set (#115032)."""
+ stale = tmp_path / "stale"
+ stale.mkdir()
+ (stale / "hermes_stale_supply.py").write_text("VALUE = 'stale'\n")
+ (tmp_path / "hermes_stale_supply.py").write_text("VALUE = 'candidate'\n")
+
+ monkeypatch.setattr(
+ update_cmd, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)
+ )
+ monkeypatch.setattr(
+ update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)
+ )
+ monkeypatch.setenv("PYTHONPATH", str(stale))
+
+ assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)
+
+
-def test_import_guard_flags_missing_first_party_module(monkeypatch, tmp_path):
+def test_import_guard_flags_missing_first_party_module(monkeypatch, probe_root):
"""A missing *first-party* module IS skew — the update dropped a file."""
- (tmp_path / "tools").mkdir()
- (tmp_path / "tools" / "__init__.py").write_text("")
- (tmp_path / "consumer.py").write_text("import tools.nonexistent_module\n")
+ (probe_root / "tools").mkdir()
+ (probe_root / "tools" / "__init__.py").write_text("")
+ (probe_root / "consumer.py").write_text("import tools.nonexistent_module\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "consumer"
assert error is not None and "tools.nonexistent_module" in error
diff --cc tests/test_managed_runtime_resolution.py
index 2b88650a773,47c0e91de8c..9aa009fa9da
--- a/tests/test_managed_runtime_resolution.py
+++ b/tests/test_managed_runtime_resolution.py
@@@ -65,7 -65,24 +65,7 @@@ _ALLOWED: dict[tuple[str, str], str] =
"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/gateway.py", "node"): (
- ("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_service_unit.py", "node"): (
"Fallback rung of _append_node_dir_for_service(), after the managed "
"dirs from iter_hermes_node_dirs() are already appended."
),
diff --cc tests/tools/test_checkpoint_manager.py
index 72d4a825f90,4fb2efb6f1c..8e7454bfbc9
--- a/tests/tools/test_checkpoint_manager.py
+++ b/tests/tools/test_checkpoint_manager.py
@@@ -1069,6 -1071,88 +1069,37 @@@ class TestPruneCheckpointsOrphanAllowli
assert second_repo.exists()
-class TestGcOnlyAfterStoreMutation:
- """``git gc`` rewrites the whole pack (tens of seconds on a GB store). A checkpoint never runs
- it — it rewrites refs and marks the store gc-pending — and the periodic prune runs it only when
- a ref actually moved. A store over the cap with every ref at its one-snapshot floor used to gc on
- every checkpoint AND on every daily prune, stalling tool calls and gateway startup."""
-
- def test_checkpoint_never_gcs_and_hands_the_reclaim_to_prune(self, checkpoint_base, tmp_path, monkeypatch):
- import tools.checkpoint_manager as cm
- monkeypatch.setattr(cm, "CHECKPOINT_BASE", checkpoint_base)
- gc_calls = []
- real_gc = cm._gc_store
- monkeypatch.setattr(cm, "_gc_store", lambda store, wd: gc_calls.append(store) or real_gc(store, wd))
- work = tmp_path / "big"
- work.mkdir()
- (work / "blob.bin").write_bytes(os.urandom(2 * 1024 * 1024)) # incompressible → store > 1 MB cap
- m = CheckpointManager(enabled=True, max_snapshots=50, max_total_size_mb=1)
- store = checkpoint_base / "store"
-
- assert m.ensure_checkpoint(str(work), "first") is True
- assert gc_calls == [] and not (store / ".gc-pending").exists() # at the floor: nothing to drop
-
- (work / "blob.bin").write_bytes(os.urandom(2 * 1024 * 1024))
- m.new_turn()
- assert m.ensure_checkpoint(str(work), "second") is True
- assert gc_calls == [] # the oldest snapshot was dropped, but the repack is not the tool call's
- assert (store / ".gc-pending").exists()
-
- prune_checkpoints(retention_days=30, delete_orphans=False, checkpoint_base=checkpoint_base)
- assert len(gc_calls) == 1 and not (store / ".gc-pending").exists()
-
- def test_prune_gcs_only_when_a_project_was_deleted(self, checkpoint_base, tmp_path, monkeypatch):
- import tools.checkpoint_manager as cm
- monkeypatch.setattr(cm, "CHECKPOINT_BASE", checkpoint_base)
- gc_calls = []
- monkeypatch.setattr(cm, "_gc_store", lambda store, working_dir: gc_calls.append(store))
- work = tmp_path / "proj"
- work.mkdir()
- (work / "f").write_text("f")
- CheckpointManager(enabled=True).ensure_checkpoint(str(work), "seed")
-
- assert prune_checkpoints(retention_days=30, delete_orphans=False, checkpoint_base=checkpoint_base)["deleted_stale"] == 0
- assert gc_calls == []
-
- meta_path = checkpoint_base / "store" / "projects" / f"{_project_hash(str(work))}.json"
- meta = json.loads(meta_path.read_text())
- meta["last_touch"] = time.time() - 60 * 86400
- meta_path.write_text(json.dumps(meta))
- assert prune_checkpoints(retention_days=30, delete_orphans=False, checkpoint_base=checkpoint_base)["deleted_stale"] == 1
- assert len(gc_calls) == 1
-
-
+ class TestPruneSweepsTmpPackDebris:
+ """A ``git gc`` killed by the store timeout strands ``tmp_pack_*`` files in
+ ``objects/pack/``; ``gc.auto=0`` means git itself never reclaims them and the gc
+ only runs when a ref moved — so the prune sweeps the debris unconditionally (#115410)."""
+
+ def test_sweeps_debris_even_when_no_ref_moved(self, checkpoint_base, tmp_path, monkeypatch):
+ import tools.checkpoint_manager as cm
+ monkeypatch.setattr(cm, "CHECKPOINT_BASE", checkpoint_base)
+ monkeypatch.setattr("hermes_cli.gitlock._git_proc_running", lambda: False)
+ work = tmp_path / "proj"
+ work.mkdir()
+ (work / "f").write_text("f")
+ CheckpointManager(enabled=True).ensure_checkpoint(str(work), "seed")
+
+ pack = checkpoint_base / "store" / "objects" / "pack"
+ pack.mkdir(parents=True, exist_ok=True)
+ debris = pack / "tmp_pack_killedGc"
+ debris.write_bytes(b"x" * 512)
+ stamp = time.time() - 11 * 60 # past the sweep's 10-minute age floor
+ os.utime(debris, (stamp, stamp))
+ fresh = pack / "tmp_pack_inFlight"
+ fresh.write_bytes(b"y")
+
+ result = prune_checkpoints(retention_days=30, delete_orphans=False, checkpoint_base=checkpoint_base)
+
+ assert result["deleted_stale"] == 0 # no ref moved: the expensive gc never ran…
+ assert not debris.exists() # …but the debris is still swept
+ assert fresh.exists() # a pack possibly being written NOW is spared
+ assert result["bytes_freed"] >= 512
+
+
class TestMaybeAutoPruneCheckpoints:
def test_prunes_once_then_skips_within_interval(self, tmp_path):
base = tmp_path / "checkpoints"
diff --cc tests/tools/test_local_env_blocklist.py
index 78db26cb1b9,2f544c0a1be..4047b9df8dd
--- a/tests/tools/test_local_env_blocklist.py
+++ b/tests/tools/test_local_env_blocklist.py
@@@ -4,8 -11,9 +4,9 @@@ import jso
import os
import subprocess
import sys
+ import threading
from pathlib import Path
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
diff --cc tests/tools/test_zombie_process_cleanup.py
index 71a47726e9c,312ce26c4bf..c09bf78fbcb
--- a/tests/tools/test_zombie_process_cleanup.py
+++ b/tests/tools/test_zombie_process_cleanup.py
@@@ -419,8 -479,27 +419,27 @@@ class TestDelegationCleanup
parent._active_children.append(child)
relay_host = MagicMock()
monkeypatch.setattr(relay_runtime, "get_runtime", lambda **_kwargs: relay_host)
- monkeypatch.setattr("tools.delegate_tool._get_child_timeout", lambda: 0.1)
+ monkeypatch.setattr("tools.delegate_tool._get_child_timeout", lambda: 2)
+ # The parent's cap must not elapse before the worker thread has opened the child's turn, or
+ # the "late result" scenario degrades into "child never started" on a loaded runner. Gate the
+ # settle wait the timeout rides on (``_ChildRun.run`` waits on ``heartbeat.settled``).
+ class _GatedSettle(threading.Event):
+ def wait(self, timeout=None):
+ child_started.wait(timeout=5)
+ return super().wait(timeout)
+
+ import tools.delegate_tool as delegate_tool
+
+ real_start_heartbeat = delegate_tool._start_heartbeat
+
+ def start_gated_heartbeat(*args, **kwargs):
+ heartbeat = real_start_heartbeat(*args, **kwargs)
+ heartbeat.settled = _GatedSettle()
+ return heartbeat
+
+ monkeypatch.setattr(delegate_tool, "_start_heartbeat", start_gated_heartbeat)
+
def run_conversation(**kwargs):
lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation(
profile_key=relay_runtime.current_profile_key(),
diff --cc tools/bot_relay.py
index 732361be31c,689effed530..3f20af91d5f
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@@ -290,16 -363,71 +364,71 @@@ def claim_pending_envelopes(root: Path
claimed = base / CLAIMED_DIR / path.name
with contextlib.suppress(OSError, ValueError):
os.replace(path, claimed) # atomic claim
+ os.utime(claimed, (now, now)) # the re-offer window counts from the claim, not the enqueue
- envelope = json.loads(claimed.read_text(encoding="utf-8"))
+ envelope = json.loads(claimed.read_text(encoding="utf-8-sig"))
if not isinstance(envelope, dict):
raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")
out.append(envelope)
return out
+ def _reoffer_unanswered(root: Path | str, base: Path, ttl: float, now: float) -> list[dict]:
+ """``claimed/`` envelopes unanswered ``REOFFER_AFTER_SECONDS`` after their claim, at most once each.
+
+ The claim is the Desktop's: one that disconnects between ``outbox.drain`` and ``bot_relay.deliver``
+ leaves the envelope here with no reply, silent until the waiter's deadline and then swept, while
+ the reconnected Desktop's drains see an empty outbox (#111021, #111207). Bounds, in check order:
+
+ * ``created_at + REPLY_WAIT_SECONDS`` passed with no reply — the waiter is gone (or about to be);
+ a ``delivery_timeout`` reply is written so it learns, and the envelope is never handed out again.
+ * already re-offered (``reoffered_at`` stamped on the envelope) — one extra delivery per message,
+ never a turn loop against a target nobody is listening for.
+ * ``bot_mode.envelope_ttl_seconds`` applies to the re-offer leg exactly as to the outbox: the
+ message is back in the queue from ``claim + REOFFER_AFTER_SECONDS``; a drain that comes ``ttl``
+ later than that refuses it with ``queued_expired``.
+ """
+ out: list[dict] = []
+ for path in sorted((base / CLAIMED_DIR).glob("*.json"), key=_queued_at):
+ if (base / REPLIES_DIR / path.name).exists():
+ continue
+ with contextlib.suppress(OSError, ValueError):
+ claimed_at = path.stat().st_mtime
- envelope = json.loads(path.read_text(encoding="utf-8"))
++ envelope = json.loads(path.read_text(encoding="utf-8-sig"))
+ if not isinstance(envelope, dict):
+ raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")
+ env_id = str(envelope.get("id") or "")
+ label = f"@{envelope.get('target_handle') or '?'} on {envelope.get('target_connection') or '?'}"
+ created = float(envelope.get("created_at") or claimed_at)
+ if now - created > REPLY_WAIT_SECONDS:
+ write_reply(root, env_id, reason="delivery_timeout", error=(
+ f"no reply from {label} within {REPLY_WAIT_SECONDS}s of sending — the Desktop picked "
+ "the message up but never reported a delivery. It will not be retried; resend if it matters."))
+ continue
+ if envelope.get("reoffered_at"):
+ continue
+ queued_for = now - claimed_at - REOFFER_AFTER_SECONDS
+ if queued_for < 0:
+ continue
+ if ttl > 0 and queued_for > ttl:
+ write_reply(root, env_id, reason="queued_expired", error=(
+ f"re-queued message to {label} expired after {ttl}s waiting for the Desktop to drain it "
+ "again — it was NOT delivered. Resend once the Desktop reconnects."))
+ continue
+ envelope["reoffered_at"] = int(now)
+ _atomic_write_json(path, envelope)
+ out.append(envelope)
+ return out
+
+
def write_reply(root: Path | str, envelope_id: str, *, reply: str = "", error: str = "", reason: str = "") -> Path:
"""Persist the relayed reply (or delivery error) for the waiter. ``reason`` (typed
- code, ``tools.bot_failure_reasons``) is classified from ``error`` when omitted."""
+ code, ``tools.bot_failure_reasons``) is classified from ``error`` when omitted.
+
+ Idempotent by envelope id — the first settled reply stands, error or not. That is safe because
+ two deliveries of one envelope never overlap: ``_reoffer_unanswered`` waits past the Desktop's own
+ deliver deadline (``REOFFER_AFTER_SECONDS``), so by the time a second delivery can start, the first
+ has either replied (and the waiter may already have read it) or provably died without one. A
+ later write is therefore a duplicate or a bookkeeping timeout, never a truer answer."""
base = _ensure_dirs(root)
safe = str(envelope_id or "").strip()
if not re.match(r"^[0-9a-f]{32}$", safe):
diff --cc tools/checkpoint_manager.py
index c36fbffab27,9f3e9178d82..07921c88fce
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@@ -54,13 -17,16 +54,14 @@@ import loggin
import os
import re
import shutil
-import stat as stat_mod
import subprocess
import time
-from dataclasses import dataclass, field
from pathlib import Path
-from typing import Dict, Iterator, List, NamedTuple, Optional, Set, Tuple
-
from hermes_constants import get_hermes_home
-from hermes_cli._subprocess_compat import windows_hide_flags
+from hermes_cli._subprocess_compat import selected_git_env, windows_hide_flags
+ from hermes_cli.gitlock import clear_stale_tmp_packs
+from typing import Dict, List, Optional, Set, Tuple
+
from utils import env_int
logger = logging.getLogger(__name__)
@@@ -1623,260 -1023,124 +1624,264 @@@ def _workdir_is_observably_gone
if parent_dev is not None and parent_ino is not None:
st = parent.stat()
if (st.st_dev, st.st_ino) != (parent_dev, parent_ino):
+ # A different directory is visible at the parent's path than
+ # the one the project lived in — the volume is detached (its
+ # underlay showing through) or was swapped. Not a deletion.
return False
elif require_parent_identity:
+ # No recorded identity to check against — we cannot tell the
+ # project's real parent from an underlay directory exposed by an
+ # unmount. Unsure never deletes; retention still reclaims.
return False
- with os.scandir(parent) as entries:
- return next(entries, None) is not None or os.path.ismount(parent)
+ if _dir_has_any_entry(parent):
+ return True
+ # Empty parent: only evidence if that directory is a mount point, i.e.
+ # the volume is attached right now and simply does not hold the
+ # project. An empty plain directory is an unmounted mount point as
+ # readily as an emptied project root.
+ return os.path.ismount(parent)
except OSError:
- return False # probe failed (permission, I/O error) — not evidence of deletion
+ # Probe failed (permission, I/O error) — not evidence of deletion.
+ return False
-def _int_or_none(value) -> Optional[int]:
- return value if isinstance(value, int) and not isinstance(value, bool) else None
+def _dir_has_any_entry(directory: Path) -> bool:
+ """True when ``directory`` contains at least one entry.
+ Stops after the first entry rather than materializing the listing; a
+ project root can hold a large tree.
+ """
+ with os.scandir(directory) as entries:
+ for _ in entries:
+ return True
+ return False
-def _sweep(entries, result: Dict[str, int], delete) -> None:
- """Shared orphan/stale sweep. ``entries`` yields ``(item, gone, allowed, is_stale)`` where
- ``is_stale`` is a thunk (may do I/O, so only evaluated for non-orphans); "orphan" wins."""
- for item, gone, allowed, is_stale in entries:
- result["scanned"] += 1
- reason = "orphan" if gone and allowed else "stale" if is_stale() else None
- if reason is not None:
- delete(item, reason)
+def prune_checkpoints(
+ retention_days: int = 7,
+ delete_orphans: bool = True,
+ checkpoint_base: Optional[Path] = None,
+ max_total_size_mb: int = 0,
+ orphan_allowlist: Optional[set] = None,
+) -> Dict[str, int]:
+ """Delete stale/orphan checkpoints and reclaim store space.
-def _rmtree_counted(child: Path, result: Dict[str, int], key: str, fail_fmt: str, label) -> None:
- """rmtree ``child``, crediting bytes + ``result[key]``; failures count as ``errors`` when tracked."""
- try:
- size = _dir_size_bytes(child)
- shutil.rmtree(child)
- result["bytes_freed"] += size
- result[key] += 1
- except OSError as exc:
- if "errors" in result:
- result["errors"] += 1
- logger.warning(fail_fmt, label, exc)
-
-
-def _prune_legacy_archives(base: Path, cutoff: float, result: Dict[str, int]) -> None:
- """Delete ``legacy-*`` archives whose mtime predates ``cutoff`` (skipped when retention is off)."""
- for child in _legacy_archives(base) if cutoff > 0 else ():
- mtime = _mtime_or_none(child)
- if mtime is not None and mtime < cutoff:
- _rmtree_counted(child, result, "deleted_stale", "Failed to delete legacy archive %s: %s", child)
-
-
-def _prune_pre_v2_repos(base: Path, cutoff: float, delete_orphans: bool,
- orphan_allowlist: Optional[set], result: Dict[str, int]) -> None:
- """Sweep pre-v2 per-project shadow repos exactly as the v1 pruner did (scan shared with
- ``store_status``; the frozen layout has no recorded parent identity, so orphan detection
- uses the structural checks only)."""
- def entries():
- for repo in _pre_v2_shadow_repos(base):
- child = repo["path"]
- gone = delete_orphans and not repo["marker_unreadable"] and (
- repo["workdir"] is None
- or _workdir_is_observably_gone(repo["workdir"], require_parent_identity=False))
- yield (child, gone, orphan_allowlist is None or str(child) in orphan_allowlist,
- lambda c=child: cutoff > 0 and 0 < _newest_mtime(c) < cutoff)
+ A project entry is deleted when either:
- _sweep(entries(), result, lambda child, reason: _rmtree_counted(
- child, result, f"deleted_{reason}", "Failed to prune checkpoint repo %s: %s", child.name))
+ * ``delete_orphans=True`` and its ``workdir`` no longer exists on disk
+ (the original project was deleted / moved); OR
+ * its ``last_touch`` is older than ``retention_days`` days.
+ ``orphan_allowlist``, when not ``None``, restricts orphan deletion to
+ the given identities (v2 project ``_hash`` strings and/or pre-v2 shadow
+ repo paths as ``str``). This lets a caller that showed the user a
+ confirmation preview (built from ``store_status()``) bind the resulting
+ deletion to exactly what was displayed — a project that only becomes
+ orphaned *after* the preview (e.g. its workdir vanishes while the human
+ is answering the prompt) is skipped rather than swept up under the
+ earlier confirmation. Pass ``None`` (the default) to delete every
+ currently-orphaned project, e.g. for ``--force`` or unattended callers
+ that never show a preview.
-def _prune_v2_projects(store: Path, cutoff: float, delete_orphans: bool,
- orphan_allowlist: Optional[set], result: Dict[str, int]) -> None:
- """Drop the ref, index and metadata of orphan/stale projects in the shared store."""
- def entries():
- for meta in _list_projects(store):
- dir_hash = meta.get("_hash") or ""
- workdir = meta.get("workdir") or ""
- if not dir_hash:
- continue
- gone = delete_orphans and (not workdir or _workdir_is_observably_gone(
- workdir, parent_dev=_int_or_none(meta.get("workdir_parent_dev")),
- parent_ino=_int_or_none(meta.get("workdir_parent_ino"))))
- yield (dir_hash, gone, orphan_allowlist is None or dir_hash in orphan_allowlist,
- lambda m=meta: cutoff > 0 and 0 < float(m.get("last_touch", 0) or 0) < cutoff)
-
- def delete(dir_hash: str, reason: str) -> None:
- _delete_ref(store, _ref_name(dir_hash))
- _unlink_quiet(_index_path(store, dir_hash))
- _unlink_quiet(_project_meta_path(store, dir_hash))
- result[f"deleted_{reason}"] += 1
-
- _sweep(entries(), result, delete)
-
-
-def prune_checkpoints(retention_days: int = 7, delete_orphans: bool = True, checkpoint_base: Optional[Path] = None,
- max_total_size_mb: int = 0, orphan_allowlist: Optional[set] = None) -> Dict[str, int]:
- """Delete stale/orphan checkpoints and reclaim store space. Never raises. Deleted when
- ``delete_orphans`` and the workdir is observably gone, OR last touch predates ``retention_days``
- (``<= 0`` disables). ``orphan_allowlist`` (v2 ``_hash`` strings and/or pre-v2 repo paths as
- ``str``) binds orphan deletion to exactly what a ``store_status()`` preview showed — a project
- orphaned after the preview is skipped; ``None`` deletes every current orphan (``--force``,
- unattended). ``max_total_size_mb > 0`` drops the oldest commit per project until the store fits."""
+ Additionally, if ``max_total_size_mb > 0`` and the store exceeds that
+ after orphan/stale pruning, the oldest commit per remaining project is
+ dropped until the store is under the cap.
+
+ Legacy-archive dirs (``legacy-*``) older than ``retention_days`` are
+ also deleted.
+
+ Returns a dict with counts ``{"scanned", "deleted_orphan",
+ "deleted_stale", "errors", "bytes_freed"}``.
+
+ Never raises — maintenance must never block interactive startup.
+ """
base = checkpoint_base or _resolve_checkpoint_base()
- result = _empty_prune_result()
+ result = {
+ "scanned": 0,
+ "deleted_orphan": 0,
+ "deleted_stale": 0,
+ "errors": 0,
+ "bytes_freed": 0,
+ }
if not base.exists():
return result
+
+ from tools.checkpoint_pruning import PruneError, store_lock
+
+ try:
+ with store_lock(base):
+ return _prune_checkpoints(base, result, retention_days, delete_orphans, max_total_size_mb, orphan_allowlist)
+ except (PruneError, OSError) as exc:
+ result["errors"] += 1
+ logger.warning("Checkpoint maintenance stopped: %s", exc)
+ return result
+
+
+def _prune_checkpoints(
+ base: Path, result: Dict[str, int], retention_days: int, delete_orphans: bool,
+ max_total_size_mb: int, orphan_allowlist: Optional[set],
+) -> Dict[str, int]:
size_before = _dir_size_bytes(base)
- cutoff = time.time() - retention_days * 86400 if retention_days > 0 else 0.0
- _prune_legacy_archives(base, cutoff, result)
- _prune_pre_v2_repos(base, cutoff, delete_orphans, orphan_allowlist, result)
+
+ # --- Legacy pre-v2 per-project shadow repos (kept directly under base) ---
+ # Pre-v2 layout: ``base/<hash>/HEAD`` etc. We treat these exactly as the
+ # v1 pruner did so behaviour is unchanged for anyone still on that layout
+ # or sitting on a mid-migration system.
+ cutoff = 0.0
+ if retention_days > 0:
+ cutoff = time.time() - retention_days * 86400
+
+ for child in base.iterdir():
+ if not child.is_dir():
+ continue
+ if child.name == _STORE_DIRNAME:
+ continue
+ if child.name.startswith(_LEGACY_PREFIX):
+ # Legacy archive: prune by dir mtime using same retention rule.
+ if retention_days <= 0:
+ continue
+ try:
+ m = child.stat().st_mtime
+ except OSError:
+ continue
+ if m >= cutoff:
+ continue
+ try:
+ size = _dir_size_bytes(child)
+ shutil.rmtree(child)
+ result["bytes_freed"] += size
+ result["deleted_stale"] += 1
+ except OSError as exc:
+ result["errors"] += 1
+ logger.warning("Failed to delete legacy archive %s: %s", child, exc)
+
+ # Pre-v2 per-project shadow repos. Scanned via the same helper
+ # `store_status()` uses for its orphan preview, so a confirmation prompt
+ # built from that preview always matches what gets deleted here.
+ for repo in _pre_v2_shadow_repos(base):
+ child = repo["path"]
+ result["scanned"] += 1
+ reason: Optional[str] = None
+ if (
+ delete_orphans
+ and not repo["marker_unreadable"]
+ and (
+ repo["workdir"] is None
+ # The frozen pre-v2 layout has no metadata channel to carry a
+ # recorded parent identity, so only the structural checks
+ # (parent present + populated / live mount point) apply here.
+ or _workdir_is_observably_gone(
+ repo["workdir"], require_parent_identity=False,
+ )
+ )
+ and (orphan_allowlist is None or str(child) in orphan_allowlist)
+ ):
+ reason = "orphan"
+ if reason is None and retention_days > 0:
+ newest = 0.0
+ try:
+ for p in child.rglob("*"):
+ try:
+ mt = p.stat().st_mtime
+ newest = max(newest, mt)
+ except OSError:
+ continue
+ except OSError:
+ pass
+ if newest > 0 and newest < cutoff:
+ reason = "stale"
+ if reason is None:
+ continue
+ try:
+ size = _dir_size_bytes(child)
+ shutil.rmtree(child)
+ result["bytes_freed"] += size
+ if reason == "orphan":
+ result["deleted_orphan"] += 1
+ else:
+ result["deleted_stale"] += 1
+ except OSError as exc:
+ result["errors"] += 1
+ logger.warning("Failed to prune checkpoint repo %s: %s", child.name, exc)
+
+ # --- v2 shared store: per-project ref pruning via metadata ---
store = _store_path(base)
- if _store_has_head(store):
+ if (store / "HEAD").exists():
+ # A gc killed by the store timeout strands tmp_pack_* files that gc.auto=0 means git
+ # itself never reclaims; sweep them even when no ref moved (a sweep is a directory
+ # listing, unlike the pack-rewriting gc gated on refs below).
+ clear_stale_tmp_packs(store)
- # gc rewrites the whole pack — the entire cost of a prune on a large store — so it runs
- # only when a ref moved: deleted here, or rewritten by a checkpoint that left it pending.
- deleted_before = result["deleted_orphan"] + result["deleted_stale"]
- _prune_v2_projects(store, cutoff, delete_orphans, orphan_allowlist, result)
- if result["deleted_orphan"] + result["deleted_stale"] > deleted_before or (store / _GC_PENDING_NAME).exists():
- _gc_store(store, str(base))
- if max_total_size_mb > 0:
- _shrink_store_to_cap(store, str(base), max_total_size_mb * _MB)
-
- result["bytes_freed"] = max(result["bytes_freed"], size_before - _dir_size_bytes(base))
+ for meta in _list_projects(store):
+ dir_hash = meta.get("_hash") or ""
+ workdir = meta.get("workdir") or ""
+ if not dir_hash:
+ continue
+ result["scanned"] += 1
+ reason = None
+ parent_dev = meta.get("workdir_parent_dev")
+ parent_ino = meta.get("workdir_parent_ino")
+ if not isinstance(parent_dev, int) or isinstance(parent_dev, bool):
+ parent_dev = None
+ if not isinstance(parent_ino, int) or isinstance(parent_ino, bool):
+ parent_ino = None
+ if (
+ delete_orphans
+ and (
+ not workdir
+ or _workdir_is_observably_gone(
+ workdir,
+ parent_dev=parent_dev,
+ parent_ino=parent_ino,
+ )
+ )
+ and (orphan_allowlist is None or dir_hash in orphan_allowlist)
+ ):
+ reason = "orphan"
+ elif retention_days > 0:
+ last_touch = float(meta.get("last_touch", 0) or 0)
+ if last_touch > 0 and last_touch < cutoff:
+ reason = "stale"
+ if reason is None:
+ continue
+ ref = _ref_name(dir_hash)
+ if not _delete_ref(store, ref):
+ result["errors"] += 1
+ return result
+ # Drop per-project index and metadata.
+ try:
+ idx = _index_path(store, dir_hash)
+ if idx.exists():
+ idx.unlink()
+ except OSError:
+ pass
+ try:
+ mp = _project_meta_path(store, dir_hash)
+ if mp.exists():
+ mp.unlink()
+ except OSError:
+ pass
+ if reason == "orphan":
+ result["deleted_orphan"] += 1
+ else:
+ result["deleted_stale"] += 1
+
+ from tools.checkpoint_pruning import Pruner, PruneError
+
+ pruner = Pruner(_run_git, store, str(base), _GIT_TIMEOUT, _dir_size_bytes, _REFS_PREFIX)
+ try:
+ if result["deleted_orphan"] + result["deleted_stale"] or pruner.gc_pending():
+ pruner.reclaim()
+ if not pruner.enforce_size(max_total_size_mb * 1024 * 1024):
+ result["errors"] += 1
+ logger.warning("Checkpoint store remains over its size cap; minimum history retained")
+ except (PruneError, OSError) as exc:
+ result["errors"] += 1
+ logger.warning("Checkpoint pruning stopped: %s", exc)
+
+ size_after = _dir_size_bytes(base)
+ delta = size_before - size_after
+ result["bytes_freed"] = max(result["bytes_freed"], delta)
+
return result
diff --cc tools/computer_use/doctor.py
index 6c2fa7ddcc6,66d2832d4fd..646c66080a3
--- a/tools/computer_use/doctor.py
+++ b/tools/computer_use/doctor.py
@@@ -281,6 -288,88 +288,88 @@@ def _apply_display_count_guard(report:
report["overall"] = "degraded"
return report
+ def cua_daemon_units(config_dir: Optional[str] = None) -> List[Tuple[str, str, str, bool, Optional[str]]]:
+ """(kind, unit, exec_target, runs_serve, --socket path or None) for every systemd user unit / XDG autostart
+ entry whose Exec runs cua-driver — the hand-written daemon units Linux relies on (there is no managed
+ autostart). ``%h`` is expanded in the socket path so it can be probed; the exec target is left as written."""
+ home = os.path.expanduser("~")
+ # systemd --user and XDG autostart both honour $XDG_CONFIG_HOME; a host that sets it keeps its units there.
+ base = config_dir or os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
+ units: List[Tuple[str, str, str, bool, Optional[str]]] = []
+ sources = (("systemd user unit", os.path.join(base, "systemd", "user"), ".service", "ExecStart"),
+ ("XDG autostart entry", os.path.join(base, "autostart"), ".desktop", "Exec"))
+ for kind, directory, suffix, key in sources:
+ try:
+ names = sorted(e.name for e in os.scandir(directory) if e.name.endswith(suffix) and e.is_file())
+ except OSError:
+ continue
+ for name in names:
+ try:
- with open(os.path.join(directory, name), encoding="utf-8", errors="replace") as fh:
++ with open(os.path.join(directory, name), encoding="utf-8-sig", errors="replace") as fh:
+ text = fh.read()
+ except OSError:
+ continue
+ for line in text.splitlines():
+ stripped = line.strip()
+ tokens = stripped.split("=", 1)[1].split() if stripped.startswith(key + "=") else []
+ # first token = executable; systemd's prefix modifiers (-, +, !, :) never start a path
+ if not tokens or "cua-driver" not in tokens[0]:
+ continue
+ socket = next((tokens[i + 1] for i, t in enumerate(tokens[:-1]) if t == "--socket"), None)
+ units.append((kind, name, tokens[0].lstrip("-+:!"), "serve" in tokens[1:],
+ os.path.expanduser(socket.replace("%h", home)) if socket else None))
+ return units
+
+ def _stale_cua_exec_references(config_dir: Optional[str] = None) -> List[Tuple[str, str, str]]:
+ """(kind, unit, target) for daemon units whose cua-driver Exec points at a pruned ``packages/releases/<version>/``
+ directory. The installer prunes all but the last five, so a versioned reference crash-loops with 203/EXEC after
+ every upgrade while every binary-level check stays green (#114748). ``packages/current`` and still-present
+ release dirs are healthy by construction and never reported."""
+ home = os.path.expanduser("~")
+ findings: List[Tuple[str, str, str]] = []
+ for kind, unit, target, _serve, _socket in cua_daemon_units(config_dir):
+ resolved = os.path.expanduser(target.replace("%h", home))
+ if "/packages/releases/" in resolved and not os.path.exists(resolved):
+ findings.append((kind, unit, target))
+ return findings
+
+ def _apply_daemon_liveness_guard(report: Report, binary: str) -> Report:
+ """Append one check per configured daemon unit whose ``cua-driver serve`` is not answering on its socket
+ (pass when it is). Only configured daemons are probed: on Linux the MCP runtime needs no daemon, so an
+ unconfigured, silent socket is not a finding. Unknown probe results add nothing (#114748)."""
+ from tools.computer_use.cua_backend import cua_daemon_listening
+
+ checks = report.get("checks")
+ if sys.platform != "linux" or not isinstance(checks, list):
+ return report
+ for _kind, unit, _target, serve, socket in cua_daemon_units():
+ listening = cua_daemon_listening(binary, socket) if serve else None
+ if listening is None:
+ continue
+ shown = socket or "the default socket"
+ if listening:
+ checks.append({"name": f"daemon ({unit})", "status": "pass", "message": f"cua-driver serve is listening on {shown}"})
+ continue
+ checks.append({"name": f"daemon ({unit})", "status": "fail", "message": _DEAD_DAEMON_MSG.format(unit=unit, socket=shown),
+ "hint": _DEAD_DAEMON_HINT.format(unit=unit)})
+ if report.get("overall") == "ok":
+ report["overall"] = "degraded"
+ return report
+
+ def _apply_stale_unit_guard(report: Report) -> Report:
+ """Append a fail check per hand-written unit/autostart entry whose cua-driver Exec target was pruned — the
+ daemon can crash-loop (203/EXEC) for days while every binary-level check stays green (#114748). Binary-level
+ repair (`install`) cannot fix a stale unit reference, so doctor is the only surface that can name it."""
+ for kind, unit, target in _stale_cua_exec_references() if sys.platform == "linux" else ():
+ checks = report.get("checks")
+ if isinstance(checks, list):
+ checks.append({"name": f"daemon unit ({unit})", "status": "fail",
+ "message": _PRUNED_UNIT_MSG.format(target=target),
+ "hint": _PRUNED_UNIT_HINT.format(kind=kind)})
+ if report.get("overall") == "ok": # fail-worse overalls are never softened
+ report["overall"] = "degraded"
+ return report
+
def _wayland_environment_context(report: Report) -> Optional[Report]:
"""Linux+Wayland only: doctor probes the CLI process's environment, not the gateway's."""
if report.get("platform") != "linux" or not os.environ.get("WAYLAND_DISPLAY"):
diff --cc tools/environments/local.py
index 69910e8c8ec,3cdeb36f287..e811c09cde7
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@@ -20,10 -20,13 +20,10 @@@ from hermes_constants import get_proces
from tools.environments.base import BaseEnvironment
from tools.environments.base_output import _pipe_stdin
from hermes_cli._subprocess_compat import windows_hide_flags
- from tools.environments.local_env_policy import (
+ from tools.environments.local_env_policy import ( # noqa: F401 — _HERMES_PROVIDER_ENV_BLOCKLIST stays importable from here
_ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,
- _is_hermes_internal_secret, _is_terminal_first_party_env,
+ _is_hermes_internal_secret, _is_provider_env_blocklisted, _is_terminal_first_party_env,
_matches_terminal_first_party_prefix, _plugin_terminal_env_strip_keys, strip_profile_gate_env)
-from tools.environments.local_gitbash_probe import (
- _bash_probe_details_cache, _bash_starts, _git_bash_aslr_help,
- _looks_like_msys_spawn_failure, _mandatory_aslr_enabled)
from tools.environments.local_pythonpath import (
_build_hermes_repo_root_aliases, _strip_hermes_owned_pythonpath_and_runtime_markers)
@@@ -463,19 -444,62 +473,47 @@@ def strip_launch_profile_env(env: dict
# --- Shell discovery ---
+ def _windows_bash_candidates(custom: "str | None") -> list[str]:
+ """Ordered bash.exe candidates on Windows: HERMES_GIT_BASH_PATH, our portable Git
+ under %LOCALAPPDATA%\\hermes\\git (PortableGit ``bin`` and MinGit ``usr\\bin``),
+ known Git-for-Windows dirs, then PATH last — ``shutil.which`` may return WSL's
+ bash, which fails silently on Windows paths."""
+ getenv = os.environ.get
+ lad = getenv("LOCALAPPDATA", "")
+ roots = [
+ lad and os.path.join(lad, "hermes", "git", "bin"),
+ lad and os.path.join(lad, "hermes", "git", "usr", "bin"),
+ os.path.join(getenv("ProgramFiles", r"C:\Program Files"), "Git", "bin"),
+ os.path.join(getenv("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Git", "bin"),
+ lad and os.path.join(lad, "Programs", "Git", "bin"),
+ ]
+ raw = [custom or "", *(os.path.join(r, "bash.exe") for r in roots if r)]
+ candidates = list(dict.fromkeys(c for c in raw if c and os.path.isfile(c)))
+ found = shutil.which("bash")
+ if found and found not in candidates:
+ # Skip WSL/system bash.exe (C:\Windows\System32\bash.exe or
+ # WindowsApps bash.exe) — it is a stub launcher, not a usable shell.
+ norm = os.path.normpath(found).lower()
+ if "system32" in norm or "windowsapps" in norm:
+ logger.debug("Skipping WSL/system bash.exe at %s", found)
+ else:
+ candidates.append(found)
+ return candidates
+
+
def _find_bash() -> str:
- """Find bash for command execution."""
- if not _IS_WINDOWS:
- return (shutil.which("bash")
- or next((p for p in ("/usr/bin/bash", "/bin/bash") if os.path.isfile(p)), None)
- or os.environ.get("SHELL") or "/bin/sh")
- custom = os.environ.get("HERMES_GIT_BASH_PATH")
- candidates = _windows_bash_candidates(custom)
- # First candidate that can actually start wins: a stale HERMES_GIT_BASH_PATH
- # pointing at a broken install must not beat a healthy portable Git.
- for candidate in candidates:
- if _bash_starts(candidate):
- if candidate != custom and custom and os.path.isfile(custom):
- logger.warning(
- "HERMES_GIT_BASH_PATH=%s fails to start; using %s instead", custom, candidate)
- return candidate
- if candidates:
- probe_details = "\n".join(
- detail for c in candidates if (detail := _bash_probe_details_cache.get(c)))
- if _mandatory_aslr_enabled() is True or _looks_like_msys_spawn_failure(probe_details):
- raise RuntimeError(_git_bash_aslr_help(candidates[0], probe_details))
- # Unknown failure class: return the first path so the caller sees the
- # real bash error instead of a less useful "not found".
- return candidates[0]
+ """Resolve the shell Hermes runs commands with. Owned by pm (the store
+ is the authority on bundled bash); this is a thin wrapper over
+ pm.shell() for callers that need a bash binary."""
+ import pm.shell
+
+ bash = pm.shell.bash()
+ if bash:
+ return bash
raise RuntimeError(
- "Git Bash not found. Hermes Agent requires Git for Windows on Windows.\n"
- "Install it from: https://git-scm.com/download/win\n"
- "Or set HERMES_GIT_BASH_PATH to your bash.exe location.")
+ "No shell found. Hermes needs bash (Git for Windows on Windows). "
+ "Run `hermes pm install` or reinstall the bundle."
+ )
_git_bash_bin_dirs_cache: "list[str] | None" = None
diff --cc uv.lock
index 18ff725e9e2,41b83576c45..89482e2d668
--- a/uv.lock
+++ b/uv.lock
@@@ -2043,16 -1765,11 +2044,17 @@@ dependencies =
{ name = "ruamel-yaml" },
{ name = "snowballstemmer" },
{ name = "tenacity" },
+ { name = "tomli-w" },
+ { name = "truststore" },
{ name = "tzdata", marker = "sys_platform == 'win32'" },
{ name = "urllib3" },
- { name = "uvicorn", extra = ["standard"] },
+ { name = "uvicorn" },
+ { name = "watchfiles" },
{ name = "websockets" },
+ { name = "winrt-windows-applicationmodel", marker = "sys_platform == 'win32'" },
+ { name = "winrt-windows-foundation", marker = "sys_platform == 'win32'" },
+ { name = "winrt-windows-foundation-collections", marker = "sys_platform == 'win32'" },
+ { name = "winrt-windows-services-store", marker = "sys_platform == 'win32'" },
]
[package.optional-dependencies]
@@@ -2253,11 -1945,8 +2256,11 @@@ termux-all =
{ name = "python-multipart" },
{ name = "python-telegram-bot", extra = ["webhooks"] },
{ name = "starlette" },
- { name = "uvicorn", extra = ["standard"] },
+ { name = "uvicorn" },
]
+trace-upload = [
+ { name = "huggingface-hub" },
+]
tts-premium = [
{ name = "elevenlabs" },
]
@@@ -2384,7 -2057,9 +2391,8 @@@ requires-dist =
{ name = "hindsight-client", marker = "extra == 'hindsight'", specifier = "==0.6.1" },
{ name = "honcho-ai", marker = "extra == 'honcho'", specifier = "==2.2.0" },
{ name = "httplib2", marker = "extra == 'google'", specifier = "==0.32.0" },
- { name = "httplib2", marker = "extra == 'google-chat'", specifier = "==0.32.0" },
- { name = "httptools", specifier = ">=0.6.3,<0.9" },
- { name = "httpx", extras = ["socks"], specifier = "==0.28.1" },
++ { name = "httptools", marker = "python_full_version >= '3.14'", specifier = ">=0.6.3,<0.9" },
+ { name = "httpx", extras = ["socks"], marker = "python_full_version >= '3.14'", specifier = "==0.28.1" },
{ name = "httpx2", marker = "extra == 'computer-use'", specifier = "==2.7.0" },
{ name = "httpx2", marker = "extra == 'dev'", specifier = "==2.7.0" },
{ name = "httpx2", marker = "extra == 'mcp'", specifier = "==2.7.0" },
@@@ -2469,31 -2127,19 +2477,33 @@@
{ name = "starlette", marker = "extra == 'mcp'", specifier = "==1.3.1" },
{ name = "starlette", marker = "extra == 'web'", specifier = "==1.3.1" },
{ name = "supermemory", marker = "extra == 'supermemory'", specifier = "==3.50.0" },
- { name = "tenacity", specifier = "==9.1.4" },
+ { name = "tenacity", marker = "python_full_version >= '3.14'", specifier = "==9.1.4" },
+ { name = "tomli-w", marker = "python_full_version >= '3.14'", specifier = "==1.2.0" },
+ { name = "truststore", marker = "python_full_version >= '3.14'", specifier = ">=0.10.4,<0.11" },
{ name = "ty", marker = "extra == 'dev'", specifier = "==0.0.21" },
- { name = "tzdata", marker = "sys_platform == 'win32'", specifier = "==2025.3" },
- { name = "urllib3", specifier = ">=2.7.0,<3" },
- { name = "uvicorn", specifier = ">=0.31.0,<1" },
+ { name = "tzdata", marker = "python_full_version >= '3.14' and sys_platform == 'win32'", specifier = "==2025.3" },
+ { name = "urllib3", marker = "python_full_version >= '3.14'", specifier = ">=2.7.0,<3" },
- { name = "uvicorn", extras = ["standard"], marker = "python_full_version >= '3.14'", specifier = ">=0.31.0,<1" },
- { name = "uvicorn", extras = ["standard"], marker = "extra == 'web'", specifier = "==0.41.0" },
++ { name = "uvicorn", marker = "python_full_version >= '3.14'", specifier = ">=0.31.0,<1" },
+ { name = "uvicorn", marker = "extra == 'web'", specifier = "==0.41.0" },
+ { name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'android' and sys_platform != 'cygwin' and sys_platform != 'win32' and extra == 'uvloop'", specifier = ">=0.15.1,<0.24" },
{ name = "vercel", marker = "extra == 'vercel'", specifier = "==0.7.2" },
- { name = "watchfiles", specifier = ">=0.20,<2" },
- { name = "websockets", specifier = "==15.0.1" },
++ { name = "watchfiles", marker = "python_full_version >= '3.14'", specifier = ">=0.20,<2" },
+ { name = "websockets", marker = "python_full_version >= '3.14'", specifier = "==15.0.1" },
+ { name = "websockets", marker = "extra == 'google-meet'", specifier = "==15.0.1" },
+ { name = "winrt-windows-applicationmodel", marker = "python_full_version >= '3.14' and sys_platform == 'win32'", specifier = ">=3.2.1,<4" },
+ { name = "winrt-windows-foundation", marker = "python_full_version >= '3.14' and sys_platform == 'win32'", specifier = ">=3.2.1,<4" },
+ { name = "winrt-windows-foundation-collections", marker = "python_full_version >= '3.14' and sys_platform == 'win32'", specifier = ">=3.2.1,<4" },
+ { name = "winrt-windows-services-store", marker = "python_full_version >= '3.14' and sys_platform == 'win32'", specifier = ">=3.2.1,<4" },
{ name = "youtube-transcript-api", marker = "extra == 'youtube'", specifier = "==1.2.4" },
]
- provides-extras = ["anthropic", "exa", "firecrawl", "parallel-web", "ddgs", "fal", "edge-tts", "neutts", "kittentts", "piper", "modal", "daytona", "vercel", "hindsight", "google-meet", "dev", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "honcho", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "google-chat", "doc-extract", "trace-upload", "supermemory", "mem0", "vision", "pty", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "langfuse", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"]
-provides-extras = ["uvloop", "anthropic", "exa", "firecrawl", "parallel-web", "fal", "edge-tts", "modal", "daytona", "vercel", "hindsight", "dev", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "honcho", "supermemory", "mem0", "vision", "pty", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "google-chat", "youtube", "web", "all"]
++provides-extras = ["uvloop", "anthropic", "exa", "firecrawl", "parallel-web", "ddgs", "fal", "edge-tts", "neutts", "kittentts", "piper", "modal", "daytona", "vercel", "hindsight", "google-meet", "dev", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "honcho", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "google-chat", "doc-extract", "trace-upload", "supermemory", "mem0", "vision", "pty", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "langfuse", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"]
+
+[package.metadata.requires-dev]
+icon-build = [
+ { name = "pillow", specifier = "==12.3.0" },
+ { name = "resvg-py", specifier = "==0.4.0" },
+]
+test = [{ name = "distlib", marker = "sys_platform == 'win32'", specifier = "==0.4.3" }]
[[package]]
name = "hf-xet"
diff --cc website/docs/user-guide/local-models.md
index 7fb1c07f9dd,1783667e6c1..7519399caad
--- a/website/docs/user-guide/local-models.md
+++ b/website/docs/user-guide/local-models.md
@@@ -143,16 -121,33 +143,35 @@@ local_runtime
enabled: false # true = start the managed server with Hermes.
# The desktop "Use" button sets this automatically.
backend: auto # auto | cuda | metal | vulkan | hip | cpu
- tag: b10362 # pinned llama.cpp release; Hermes updates it with
- # each release after re-validation
+ detect_ports: [8081] # extra ports to probe for a llama-server you run
+ # yourself (the default probe is :8080 only)
```
+ Running `llama-server` yourself on a fixed port works with the same
+ `model.provider: llamacpp` selection — either list the port in
+ `local_runtime.detect_ports`, or define the endpoint explicitly under
+ `providers:` (an explicit entry wins over server detection):
+
+ ```yaml
+ providers:
+ llamacpp:
+ base_url: http://127.0.0.1:8081/v1
+ model: my-model
+ ```
+
+ The `/model` → **Local** picker row and `provider: llamacpp` resolve to that
+ server; with no server reachable the error names the local runtime ("the local
+ model server isn't running") instead of an unknown-provider or missing-API-key
+ message.
+
-Models and runtime builds live under the Hermes home directory
-(`models/` and `runtimes/llamacpp/`). Selecting a local model as your
-main model uses the standard `model.provider: llamacpp` +
-`model.default` settings — the same shape as every other provider.
+Engine versions come only from PM's lockfile, not a `local_runtime.tag`
+override. Boot uses an installed PM engine without downloading. When a new
+pin is available, install it with the desktop update button.
+
+Models live in the machine-shared `models/` directory. Engine binaries live
+in PM's store; `runtimes/llamacpp/` holds mutable presets and server state.
+Selecting a local model as your main model uses the standard
+`model.provider: llamacpp` + `model.default` settings.
## Requirements and limits
diff --cc website/scripts/generate-skill-docs.py
index d1f78113c9b,dc5f8954994..f8ffb88d171
--- a/website/scripts/generate-skill-docs.py
+++ b/website/scripts/generate-skill-docs.py
@@@ -19,12 -18,12 +19,13 @@@ from collections import defaultdic
from pathlib import Path
from typing import Any
-import yaml
-
REPO = Path(__file__).resolve().parent.parent.parent
+sys.path.insert(0, str(REPO))
+import hermes_yaml as yaml
+
DOCS = REPO / "website" / "docs"
SKILLS_PAGES = DOCS / "user-guide" / "skills"
+ ZH_HANS_DOCS = REPO / "website" / "i18n" / "zh-Hans" / "docusaurus-plugin-content-docs" / "current"
SKILL_SOURCES = [
("bundled", REPO / "skills"),