Skip to content

The agent that grows with you

fix: register CLI profile use and localize shared-profile warnings

ethernete59ef4a4f6aa
diff --git a/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts b/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts
index 08cb2edbbbc..461a619dd30 100644
--- a/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts
+++ b/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts
@@ -1,9 +1,10 @@
import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'
-import { createElement } from 'react'
+import { createElement, type ReactElement, type ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { NotificationStack } from '@/components/notifications'
import { getStatus } from '@/hermes'
+import { I18nProvider, type Locale, TRANSLATIONS, type Translations } from '@/i18n'
import { $setupReadyTick, notifySetupReady } from '@/store/live-sync'
import { clearNotifications } from '@/store/notifications'
@@ -40,44 +41,58 @@ afterEach(() => {
})
describe('useStatusSnapshot', () => {
- it('shows a dismissible shared-profile warning on the existing status refresh', async (): Promise<void> => {
- const warning: string = 'Another installation is using this profile.'
- const requestGateway: GatewayRequester = vi.fn().mockResolvedValue({}) as unknown as GatewayRequester
-
- render(createElement(NotificationStack))
-
- const { rerender }: { rerender: (props: { scope: string }) => void } = renderHook(({ scope }: { scope: string }): ReturnType<typeof useStatusSnapshot> => useStatusSnapshot('open', requestGateway, scope), {
- initialProps: { scope: 'local-default' }
- })
-
- await flushAsync()
- expect(screen.queryByText(warning)).toBeNull()
- vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: warning } as never)
- await act(async () => {
- await vi.advanceTimersByTimeAsync(60_000)
- })
- expect(screen.getByText(warning)).toBeTruthy()
- fireEvent.click(screen.getByRole('button', { name: /dismiss/i }))
- expect(screen.queryByText(warning)).toBeNull()
- await act(async () => {
- await vi.advanceTimersByTimeAsync(60_000)
- })
- expect(screen.queryByText(warning)).toBeNull()
-
- vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: '' } as never)
- await act(async () => {
- await vi.advanceTimersByTimeAsync(60_000)
- })
- vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: warning } as never)
- await act(async () => {
- await vi.advanceTimersByTimeAsync(60_000)
- })
- expect(screen.getByText(warning)).toBeTruthy()
- vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: '' } as never)
- rerender({ scope: 'local-work' })
- await flushAsync()
- expect(screen.queryByText(warning)).toBeNull()
- })
+ it.each(Object.entries(TRANSLATIONS) as [Locale, Translations][])(
+ 'localizes and deduplicates shared-profile warnings in %s',
+ async (locale: Locale, copy: Translations): Promise<void> => {
+ const warning: string = copy.notifications.sharedProfileWarning
+
+ expect(warning).toBeTypeOf('string')
+
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement =>
+ createElement(I18nProvider, { configClient: null, initialLocale: locale, children })
+
+ const requestGateway: GatewayRequester = vi.fn().mockResolvedValue({}) as unknown as GatewayRequester
+
+ render(createElement(NotificationStack), { wrapper })
+
+ const { rerender }: { rerender: (props: { scope: string }) => void } = renderHook(
+ ({ scope }: { scope: string }): ReturnType<typeof useStatusSnapshot> =>
+ useStatusSnapshot('open', requestGateway, scope),
+ {
+ initialProps: { scope: 'local-default' },
+ wrapper
+ }
+ )
+
+ await flushAsync()
+ expect(screen.queryByText(warning)).toBeNull()
+ vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: true } as never)
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ expect(screen.getByText(warning)).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: copy.notifications.dismiss }))
+ expect(screen.queryByText(warning)).toBeNull()
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ expect(screen.queryByText(warning)).toBeNull()
+
+ vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: false } as never)
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: true } as never)
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(60_000)
+ })
+ expect(screen.getByText(warning)).toBeTruthy()
+ vi.mocked(getStatus).mockResolvedValue({ shared_profile_warning: false } as never)
+ rerender({ scope: 'local-work' })
+ await flushAsync()
+ expect(screen.queryByText(warning)).toBeNull()
+ }
+ )
it('pauses status RPCs while visible but unfocused, then catches up on focus', async () => {
vi.mocked(document.hasFocus).mockReturnValue(false)
diff --git a/apps/desktop/src/app/shell/hooks/use-status-snapshot.ts b/apps/desktop/src/app/shell/hooks/use-status-snapshot.ts
index 3f9c1e79118..65aae4b0822 100644
--- a/apps/desktop/src/app/shell/hooks/use-status-snapshot.ts
+++ b/apps/desktop/src/app/shell/hooks/use-status-snapshot.ts
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'
import { getStatus } from '@/hermes'
+import { type I18nContextValue, useI18n } from '@/i18n'
import { evaluateRuntimeReadiness, type RuntimeReadinessResult } from '@/lib/runtime-readiness'
import { refreshFreeTierStatus, setFreeTierRoute } from '@/store/free-tier'
import { $setupReadyTick } from '@/store/live-sync'
@@ -17,15 +18,17 @@ type GatewayRequester = <T = unknown>(method: string, params?: Record<string, un
export function useStatusSnapshot(
gatewayState: string | undefined,
requestGateway: GatewayRequester,
- gatewayScope = ''
-) {
+ gatewayScope: string = ''
+): { inferenceStatus: RuntimeReadinessResult | null; statusSnapshot: StatusResponse | null } {
+ const { t }: I18nContextValue = useI18n()
+ const warningMessage: string = t.notifications.sharedProfileWarning
const [statusSnapshot, setStatusSnapshot] = useState<StatusResponse | null>(null)
const [inferenceStatus, setInferenceStatus] = useState<RuntimeReadinessResult | null>(null)
useEffect(() => {
let cancelled = false
let timer: number | undefined
- let sharedProfileWarning: string = ''
+ let sharedProfileWarning: boolean = false
let sharedProfileNoticeId: string | undefined
// Status and inference readiness belong to one backend. A source switch
@@ -110,7 +113,7 @@ export function useStatusSnapshot(
if (statusResult.status === 'fulfilled') {
setStatusSnapshot(statusResult.value)
- const warning: string = statusResult.value.shared_profile_warning || ''
+ const warning: boolean = Boolean(statusResult.value.shared_profile_warning)
// Keep dismissal until the conflict clears. A new overlap can warn again.
if (warning !== sharedProfileWarning) {
@@ -119,7 +122,7 @@ export function useStatusSnapshot(
}
sharedProfileWarning = warning
- sharedProfileNoticeId = warning ? notify({ kind: 'warning', message: warning }) : undefined
+ sharedProfileNoticeId = warning ? notify({ kind: 'warning', message: warningMessage }) : undefined
}
}
} finally {
@@ -161,7 +164,7 @@ export function useStatusSnapshot(
window.clearTimeout(timer)
}
}
- }, [gatewayScope, gatewayState, requestGateway])
+ }, [gatewayScope, gatewayState, requestGateway, warningMessage])
return { inferenceStatus, statusSnapshot }
}
diff --git a/apps/desktop/src/components/update-status.test.tsx b/apps/desktop/src/components/update-status.test.tsx
index 4e8ebd7c999..b6afc83dbb3 100644
--- a/apps/desktop/src/components/update-status.test.tsx
+++ b/apps/desktop/src/components/update-status.test.tsx
@@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { DesktopUpdateStatus, DesktopVersionInfo } from '@/global'
+import { I18nProvider, type Locale, TRANSLATIONS, type Translations } from '@/i18n'
import { en } from '@/i18n/en'
import type { UpdateApplyState } from '@/store/updates'
@@ -137,6 +138,26 @@ describe('VersionHero bundle banners', () => {
return relaunchApp
}
+ it.each(Object.entries(TRANSLATIONS) as [Locale, Translations][])(
+ 'localizes version channels in %s',
+ (locale: Locale, copy: Translations): void => {
+ for (const channel of ['stable', 'canary'] as const) {
+ const label: string = copy.updates.channels[channel]
+
+ expect(label).toBeTypeOf('string')
+
+ const { unmount }: { unmount: () => void } = render(
+ <I18nProvider configClient={null} initialLocale={locale}>
+ <VersionHero version={version({ channel })} />
+ </I18nProvider>
+ )
+
+ expect(screen.getByText(`${copy.updates.version('0.19.0')} · ${label}`)).toBeTruthy()
+ unmount()
+ }
+ }
+ )
+
// FAIL-BEFORE (C19): the shared About extraction dropped the swap-pending
// restart affordance even though main still produces bundleSwapPending and
// exposes the relaunchApp IPC — users could no longer finish an applied
diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsx
index 6c7a85dd8ae..3a2aefe09f2 100644
--- a/apps/desktop/src/components/update-status.tsx
+++ b/apps/desktop/src/components/update-status.tsx
@@ -152,7 +152,7 @@ export function VersionHero({
)}
<p className="mt-1 text-xs text-muted-foreground">
{version?.appVersion ? u.version(version.appVersion) : u.versionUnavailable}
- {version?.channel ? ` · ${version.channel}` : ''}
+ {version?.channel ? ` · ${u.channels[version.channel]}` : ''}
</p>
</div>
{(version?.bundleSwapPending || version?.bundleOutOfSync) && (
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 41328f21f76..129d3a82af4 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -173,6 +173,7 @@ export const ar = defineLocale({
}
},
notifications: {
+ sharedProfileWarning: 'تستخدم نسخة أخرى من Hermes هذا الملف الشخصي. تتشارك النسختان إعداداته وبياناته، لذا قد تتعارض التغييرات. يمكنك المتابعة أو إغلاق النسخة الأخرى قبل إجراء تغييرات.',
region: 'الإشعارات',
hide: 'إخفاء',
show: 'إظهار',
@@ -2406,6 +2407,7 @@ export const ar = defineLocale({
}
},
updates: {
+ channels: { stable: 'مستقر', canary: 'تجريبي' },
bundleSwapPending: 'أعد التشغيل لإكمال التحديث',
bundleSwapPendingDesc: 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',
bundleSwapPendingAction: 'إعادة تشغيل Hermes',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 17b7eae3be6..978121062a2 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -197,6 +197,7 @@ export const en: Translations = {
},
notifications: {
+ sharedProfileWarning: 'Another Hermes installation is using this profile. Both installations share its settings and data, so changes can conflict. You can continue, or close the other installation before making changes.',
region: 'Notifications',
hide: 'Hide',
show: 'Show',
@@ -3254,6 +3255,7 @@ export const en: Translations = {
},
updates: {
+ channels: { stable: 'Stable', canary: 'Canary' },
bundleSwapPending: 'Restart to finish the update',
bundleSwapPendingDesc: 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',
bundleSwapPendingAction: 'Restart Hermes',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 5fdfbefa53f..b2f4acae0ea 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -165,6 +165,7 @@ export const ja = defineLocale({
},
notifications: {
+ sharedProfileWarning: '別の Hermes インストールがこのプロファイルを使用しています。両方が設定とデータを共有しているため、変更が競合する可能性があります。このまま続けるか、変更する前にもう一方を終了してください。',
region: '通知',
hide: '非表示',
show: '表示',
@@ -2797,6 +2798,7 @@ export const ja = defineLocale({
},
updates: {
+ channels: { stable: '安定版', canary: '先行版' },
bundleSwapPending: '再起動して更新を完了',
bundleSwapPendingDesc: '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',
bundleSwapPendingAction: 'Hermes を再起動',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 892eae01225..da3da3709bc 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -168,6 +168,7 @@ export const ru = defineLocale({
}
},
notifications: {
+ sharedProfileWarning: 'Другая установка Hermes использует этот профиль. Обе установки используют общие настройки и данные, поэтому изменения могут конфликтовать. Можно продолжить работу или закрыть другую установку перед внесением изменений.',
region: 'Уведомления',
hide: 'Скрыть',
show: 'Показать',
@@ -2948,6 +2949,7 @@ export const ru = defineLocale({
}
},
updates: {
+ channels: { stable: 'Стабильный', canary: 'Тестовый' },
bundleSwapPending: 'Перезапустите, чтобы завершить обновление',
bundleSwapPendingDesc: 'Обновлённое приложение уже установлено — достаточно перезапустить Hermes, чтобы загрузить его. Чаты и настройки не пострадают.',
bundleSwapPendingAction: 'Перезапустить Hermes',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 4fa28dd7b13..e99ca0100a2 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -405,6 +405,7 @@ export interface Translations {
}
notifications: {
+ sharedProfileWarning: string
region: string
hide: string
show: string
@@ -2800,6 +2801,7 @@ export interface Translations {
}
updates: {
+ channels: { stable: string; canary: string }
bundleSwapPending: string
bundleSwapPendingDesc: string
bundleSwapPendingAction: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index c8afb19bbe0..27039d145e9 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -161,6 +161,7 @@ export const zhHant = defineLocale({
},
notifications: {
+ sharedProfileWarning: '另一個 Hermes 安裝實例正在使用此設定檔。兩個實例共用此設定檔的設定和資料,因此變更可能發生衝突。你可以繼續使用,也可以在變更前關閉另一個實例。',
region: '通知',
hide: '隱藏',
show: '顯示',
@@ -2701,6 +2702,7 @@ export const zhHant = defineLocale({
},
updates: {
+ channels: { stable: '穩定版', canary: '預覽版' },
bundleSwapPending: '重新啟動以完成更新',
bundleSwapPendingDesc: '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',
bundleSwapPendingAction: '重新啟動 Hermes',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index e72c7782713..7ac4d7b0219 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -193,6 +193,7 @@ export const zh: Translations = {
},
notifications: {
+ sharedProfileWarning: '另一个 Hermes 安装实例正在使用此配置。两个实例共享此配置的设置和数据,因此更改可能发生冲突。你可以继续使用,也可以在更改前关闭另一个实例。',
region: '通知',
hide: '隐藏',
show: '显示',
@@ -3399,6 +3400,7 @@ export const zh: Translations = {
},
updates: {
+ channels: { stable: '稳定版', canary: '预览版' },
bundleSwapPending: '重启以完成更新',
bundleSwapPendingDesc: '更新后的应用已安装完成,只需重启 Hermes 即可加载新版本。聊天记录和设置不会受到影响。',
bundleSwapPendingAction: '重启 Hermes',
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index c4913f9052f..ac53ec2c811 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -1328,7 +1328,7 @@ export interface PlatformStatus {
}
export interface StatusResponse {
- shared_profile_warning?: string
+ shared_profile_warning?: boolean
active_sessions: number
config_path: string
config_version: number
diff --git a/cli.py b/cli.py
index 24f98dff86c..682249fdfd2 100644
--- a/cli.py
+++ b/cli.py
@@ -4517,6 +4517,15 @@ def main(
_run_legacy_gateway()
return
+ if not (list_tools or list_toolsets):
+ from hermes_cli.process_identity import register_self
+ from hermes_cli.shared_profile_warning import shared_profile_warning
+
+ register_self("cli")
+ warning = shared_profile_warning()
+ if warning:
+ print(f"Warning: {warning}", file=sys.stderr)
+
_join_worktree = _start_worktree_setup(list_tools, list_toolsets, worktree, w)
query = query or q
cli = _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget,
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.py
index 5e3ced90854..3dae667c15e 100644
--- a/hermes_cli/process_identity.py
+++ b/hermes_cli/process_identity.py
@@ -146,7 +146,7 @@ def _read_ledger(path: Path) -> Optional[list[dict]]:
text = path.read_text(encoding="utf-8-sig")
except FileNotFoundError:
return []
- except OSError:
+ except (OSError, UnicodeError):
return None
if not text.strip():
return []
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 663cf87ed78..9298e95c267 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -439,9 +439,9 @@ async def get_status(profile: Optional[str] = None):
if install_id:
status["install_id"] = install_id
- # Advisory only. The message exposes no paths or process identities on this public probe.
+ # Advisory only. Expose no paths or process identities on this public probe.
from hermes_cli.shared_profile_warning import shared_profile_warning
- status["shared_profile_warning"] = await run_in_threadpool(shared_profile_warning)
+ status["shared_profile_warning"] = bool(await run_in_threadpool(shared_profile_warning))
components = await _component_health(gateway)
status["components"] = components
diff --git a/tests/hermes_cli/test_shared_profile_warning.py b/tests/hermes_cli/test_shared_profile_warning.py
index 5e68d6e8836..413d2a1ef85 100644
--- a/tests/hermes_cli/test_shared_profile_warning.py
+++ b/tests/hermes_cli/test_shared_profile_warning.py
@@ -72,29 +72,120 @@ def test_warning_tracks_live_other_install_in_same_home(homes, tmp_path):
assert shared_profile_warning(home=work, project_root=current)
+@contextmanager
+def running_cli(home: Path, install: Path):
+ """Run the real CLI constructor and entrypoint; stop at terminal interaction."""
+ env = dict(os.environ, HERMES_HOME=str(home), HOME=str(home.parent), USERPROFILE=str(home.parent))
+ for key in ("HERMES_SPAWN", "HERMES_PARENT_PID", "HERMES_PARENT_START_MARKER"):
+ env.pop(key, None)
+ script = """
+import sys
+from pathlib import Path
+import hermes_constants
+# Model two installed runtime roots without copying the source tree.
+hermes_constants.PROJECT_ROOT = Path(sys.argv[1])
+import cli
+
+def terminal_boundary(self):
+ print('cli-ready', flush=True)
+ sys.stdin.readline()
+
+cli.HermesCLI.run = terminal_boundary
+cli.main(model='test-model', provider='openai', api_key='test-only',
+ base_url='http://127.0.0.1:1/v1', toolsets='none', ignore_rules=True)
+"""
+ output = {}
+ child = subprocess.Popen(
+ [sys.executable, "-u", "-c", script, str(install)],
+ env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True,
+ )
+ try:
+ assert child.stdout is not None and child.stderr is not None
+ for line in child.stdout:
+ if line.strip() == "cli-ready":
+ break
+ else:
+ raise AssertionError(child.stderr.read())
+ yield child, output
+ finally:
+ _, output["stderr"] = child.communicate("exit\n", timeout=15)
+ assert child.returncode == 0, output["stderr"]
+
+
[email protected]("other_surface", ["serve", "cli"])
+def test_cli_entrypoint_registers_and_warns_once_for_live_shared_home(homes, tmp_path, monkeypatch, other_surface):
+ from hermes_cli.shared_profile_warning import shared_profile_warning
+
+ stable = tmp_path / "stable"
+ canary = tmp_path / "canary"
+ start_other = running_install if other_surface == "serve" else running_cli
+ with start_other(homes, stable):
+ with running_cli(homes, canary) as (child, output):
+ entries = process_identity.ledger_entries(project_root=canary, verified_only=True)
+ own = [entry for entry in entries if entry["pid"] == child.pid]
+ assert len(own) == 1
+ assert own[0]["purpose"] == "cli"
+ assert own[0]["hermes_home"] == hermes_home_key(homes)
+ assert shared_profile_warning(project_root=stable)
+ # A CLI record must not make a terminal process an update-owned backend.
+ import hermes_constants
+ from hermes_cli.update_cmd_windows import _ledger_manual_serve_holders, _ledger_reapable_backend_pids
+ from hermes_cli.update_inventory import UpdatePlan, _collect_ledger_runtimes
+
+ with monkeypatch.context() as patcher:
+ patcher.setattr(hermes_constants, "PROJECT_ROOT", canary, raising=False)
+ assert own == process_identity.ledger_entries(verified_only=True)
+ matches = [(child.pid, "python", own[0]["argv"])]
+ assert own[0]["purpose"] not in process_identity.REAPABLE_PURPOSES
+ assert _ledger_manual_serve_holders(matches) == []
+ assert _ledger_reapable_backend_pids(matches) == []
+ plan = UpdatePlan()
+ _collect_ledger_runtimes(plan, set())
+ assert plan.runtimes == []
+ assert child.poll() is None
+ assert output["stderr"].count("Another Hermes installation") == 1
+ assert shared_profile_warning(project_root=stable) == ""
+
+ work = homes / "profiles" / "work"
+ work.mkdir(parents=True)
+ with running_install(homes, stable), running_cli(work, canary) as (_, output):
+ assert shared_profile_warning(project_root=stable) == ""
+ assert "Another Hermes installation" not in output["stderr"]
+
+
[email protected]("corrupt", [b"{broken", b"\xff"])
+def test_cli_startup_quarantines_corrupt_ledger(homes, tmp_path, corrupt):
+ ledger = process_identity._ledger_path()
+ ledger.write_bytes(corrupt)
+ install = tmp_path / "cli-install"
+ with running_cli(homes, install) as (child, _):
+ assert ledger.with_suffix(".json.corrupt").read_bytes() == corrupt
+ entries = process_identity.ledger_entries(project_root=install, verified_only=True)
+ assert [entry["pid"] for entry in entries] == [child.pid]
+ assert entries[0]["hermes_home"] == hermes_home_key(homes)
+
+
def test_status_surfaces_live_warning_without_host_details(homes, tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from hermes_cli import web_server
monkeypatch.setattr(web_server.app.state, "auth_required", True, raising=False)
client = TestClient(web_server.app)
- assert client.get("/api/status").json().get("shared_profile_warning", "") == ""
- with running_install(homes, tmp_path / "canary"):
+ assert client.get("/api/status").json()["shared_profile_warning"] is False
+ with running_cli(homes, tmp_path / "canary"):
response = client.get("/api/status")
assert response.status_code == 200
- warning = response.json().get("shared_profile_warning", "")
- assert warning
- assert str(homes) not in warning
- assert str(tmp_path / "canary") not in warning
- assert client.get("/api/status").json().get("shared_profile_warning", "") == ""
+ assert response.json()["shared_profile_warning"] is True
+ assert client.get("/api/status").json()["shared_profile_warning"] is False
work = homes / "profiles" / "work"
work.mkdir(parents=True)
(work / "config.yaml").write_text("{}")
with running_install(work, tmp_path / "canary"):
- assert client.get("/api/status").json().get("shared_profile_warning", "") == ""
+ assert client.get("/api/status").json()["shared_profile_warning"] is False
response = client.get("/api/status?profile=work")
assert response.status_code == 200
- assert response.json().get("shared_profile_warning")
+ assert response.json()["shared_profile_warning"] is True
def test_warning_rejects_reused_or_unverifiable_process_identity(homes, tmp_path):