The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): close safe preview blockers before update
Ryan Hart7af27c65ab73
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex e47797b90d0..e43ba19f288 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -268,7 +268,12 @@ import {stagedUpdaterSupportsPrewrittenMarker,wrapHandoffForDetachedConsole} from './updater-process'-import { formatBlockerMessage, formatProbeFailedMessage, scanVenvBlockers } from './venv-blocker-scan'+import {+ formatBlockerMessage,+ formatProbeFailedMessage,+ scanVenvBlockers,+ stopSafeVenvBlockers+} from './venv-blocker-scan'import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace'import { createWakeIndicatorWindowController } from './wake-indicator-window'import { readWindowBelow } from './window-below'@@ -3287,7 +3292,7 @@ async function releaseBackendLock(updateRoot, tag) {//// Detection (checkUpdates / commit changelog / "N behind") stays in the UI;// only this apply action changed.-async function applyUpdates(opts = {}) {+async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {if (updateInFlight) {throw new Error('An update is already in progress.')}@@ -3424,7 +3429,18 @@ async function applyUpdates(opts = {}) {// malformed output, missing psutil) abort the handoff — never proceed// to the detached updater when the venv state is unknown.if (IS_WINDOWS) {- const scanOutcome = await scanVenvBlockers(updateRoot)+ let scanOutcome = await scanVenvBlockers(updateRoot)++ if (scanOutcome.kind === 'blocked' && opts.stopSafeBlockers) {+ const stopResult = await stopSafeVenvBlockers(updateRoot, scanOutcome.result)+ rememberLog(+ `[updates] user-approved blocker cleanup: stopped=${stopResult.stopped.join(',') || 'none'} failed=${stopResult.failed.join(',') || 'none'}`+ )+ // Let verified process-tree termination finish unwinding wrapper shells,+ // then make the scanner — not the stale renderer payload — authoritative.+ await new Promise(resolve => setTimeout(resolve, 300))+ scanOutcome = await scanVenvBlockers(updateRoot)+ }if (scanOutcome.kind === 'blocked') {const message = formatBlockerMessage(scanOutcome.result)@@ -3433,7 +3449,7 @@ async function applyUpdates(opts = {}) {emitUpdateProgress({ stage: 'error', message, percent: null })startHermes().catch(() => {})- return { ok: false, error: 'venv-blocked', message }+ return { ok: false, error: 'venv-blocked', message, blockers: scanOutcome.result.processes }}if (scanOutcome.kind === 'probe-failure') {diff --git a/apps/desktop/electron/venv-blocker-scan.test.ts b/apps/desktop/electron/venv-blocker-scan.test.tsindex 161f308d3f9..a74a309696e 100644--- a/apps/desktop/electron/venv-blocker-scan.test.ts+++ b/apps/desktop/electron/venv-blocker-scan.test.ts@@ -19,7 +19,8 @@ import {formatProbeFailedMessage,parseVenvBlockerScanOutput,resolveVenvPython,- scanVenvBlockers+ scanVenvBlockers,+ stopSafeVenvBlockers} from './venv-blocker-scan'// ---------------------------------------------------------------------------@@ -56,7 +57,9 @@ describe('formatBlockerMessage', () => {it('includes PID, name, cmdline, remote-client warning, and retry suggestion', () => {const msg = formatBlockerMessage({blocked: true,- processes: [{ pid: 101, name: 'python.exe', cmdline: 'serve --host 10.0.0.1' }]+ processes: [+ { pid: 101, name: 'python.exe', cmdline: 'serve --host 10.0.0.1', kind: 'other', safeToStop: false }+ ]})assert.ok(msg.includes('PID 101'))@@ -99,6 +102,85 @@ describe('parseVenvBlockerScanOutput', () => {assert.equal(o.kind, 'blocked')})+ it('classifies Python http.server blockers as safe local previews with a human label', () => {+ const o = parseVenvBlockerScanOutput(+ ok({+ blocked: true,+ processes: [+ {+ pid: 47484,+ name: 'python.exe',+ cmdline: 'C:\\Hermes\\venv\\Scripts\\python.exe -m http.server 8766 --directory C',+ kind: 'local-preview',+ safeToStop: true,+ label: 'Example Preview',+ port: 8766,+ createTime: 1722798000.25+ }+ ]+ })+ )++ assert.equal(o.kind, 'blocked')++ if (o.kind !== 'blocked') {+ return+ }++ assert.deepEqual(o.result.processes[0], {+ pid: 47484,+ name: 'python.exe',+ cmdline: 'C:\\Hermes\\venv\\Scripts\\python.exe -m http.server 8766 --directory C',+ kind: 'local-preview',+ safeToStop: true,+ label: 'Example Preview',+ port: 8766,+ createTime: 1722798000.25+ })+ })++ it('does not trust a truncated http.server command line without scanner identity metadata', () => {+ const o = parseVenvBlockerScanOutput(+ ok({+ blocked: true,+ processes: [+ {+ pid: 47484,+ name: 'python.exe',+ cmdline: 'python.exe -m http.server 8766 --directory C'+ }+ ]+ })+ )++ assert.equal(o.kind, 'blocked')++ if (o.kind !== 'blocked') {+ return+ }++ assert.equal(o.result.processes[0]?.kind, 'other')+ assert.equal(o.result.processes[0]?.safeToStop, false)+ })++ it('never marks an arbitrary Python process safe to stop', () => {+ const o = parseVenvBlockerScanOutput(+ ok({+ blocked: true,+ processes: [{ pid: 9, name: 'python.exe', cmdline: 'python.exe important-script.py' }]+ })+ )++ assert.equal(o.kind, 'blocked')++ if (o.kind !== 'blocked') {+ return+ }++ assert.equal(o.result.processes[0]?.kind, 'other')+ assert.equal(o.result.processes[0]?.safeToStop, false)+ })+it('malformed JSON', () => {assert.equal(parseVenvBlockerScanOutput('not json').kind, 'probe-failure')})@@ -216,3 +298,57 @@ describe('scanVenvBlockers', () => {assert.ok(c.timeout > 0)})})++describe('stopSafeVenvBlockers', () => {+ it('stops only blockers explicitly classified as safe local previews', async () => {+ const calls: Array<{ command: string; args: string[] }> = []++ const exec = (async (command: string, args: string[]) => {+ calls.push({ command, args })++ return { stdout: '', stderr: '' }+ }) as any++ const outcome = await stopSafeVenvBlockers(+ '/update/root',+ {+ blocked: true,+ processes: [+ {+ pid: 47484,+ name: 'python.exe',+ cmdline: 'python.exe -m http.server 8766 --directory C:\\preview',+ kind: 'local-preview',+ safeToStop: true,+ label: 'preview',+ port: 8766,+ createTime: 1722798000.25+ },+ {+ pid: 99,+ name: 'python.exe',+ cmdline: 'python.exe important-script.py',+ kind: 'other',+ safeToStop: false+ }+ ]+ },+ exec,+ () => 'C:\\Hermes\\venv\\Scripts\\python.exe'+ )++ assert.deepEqual(calls, [+ {+ command: 'C:\\Hermes\\venv\\Scripts\\python.exe',+ args: [+ '-m',+ 'hermes_cli._scan_venv_blockers',+ '--terminate-safe',+ '47484',+ '1722798000.25'+ ]+ }+ ])+ assert.deepEqual(outcome, { stopped: [47484], failed: [] })+ })+})diff --git a/apps/desktop/electron/venv-blocker-scan.ts b/apps/desktop/electron/venv-blocker-scan.tsindex 18c93e16fbe..aaea9bec73b 100644--- a/apps/desktop/electron/venv-blocker-scan.ts+++ b/apps/desktop/electron/venv-blocker-scan.ts@@ -18,10 +18,17 @@ const execFileAsync = promisify(execFile)// Types// ---------------------------------------------------------------------------+export type VenvBlockerKind = 'local-preview' | 'other'+export interface VenvBlockerProcess {pid: numbername: stringcmdline: string+ kind: VenvBlockerKind+ safeToStop: boolean+ label?: string+ port?: number+ createTime?: number}export interface VenvBlockerScanResult {@@ -45,6 +52,99 @@ const SCAN_MODULE = 'hermes_cli._scan_venv_blockers'// Public API// ---------------------------------------------------------------------------+function classifyVenvBlocker(+ process: Pick<VenvBlockerProcess, 'pid' | 'name' | 'cmdline'>,+ hints?: Record<string, unknown>+): VenvBlockerProcess {+ const moduleMatch = process.cmdline.match(/(?:^|\s)-m\s+http\.server(?:\s+(\d{1,5}))?(?:\s|$)/i)+ const isPython = /^python(?:w)?(?:\.exe)?$/i.test(process.name)+ const hintedCreateTime = typeof hints?.createTime === 'number' ? hints.createTime : undefined++ const trustedScannerIdentity =+ hints?.kind === 'local-preview' &&+ hints.safeToStop === true &&+ hintedCreateTime !== undefined &&+ Number.isFinite(hintedCreateTime) &&+ hintedCreateTime > 0++ if (!isPython || !moduleMatch || !trustedScannerIdentity) {+ return { ...process, kind: 'other', safeToStop: false }+ }++ const parsedPort = moduleMatch[1] ? Number(moduleMatch[1]) : 8000+ const hintedPort = trustedScannerIdentity && typeof hints?.port === 'number' ? hints.port : undefined+ const candidatePort = hintedPort ?? parsedPort++ const port =+ Number.isInteger(candidatePort) && candidatePort > 0 && candidatePort <= 65535 ? candidatePort : undefined++ const directoryMatch = process.cmdline.match(/(?:^|\s)--directory\s+(?:"([^"]+)"|'([^']+)'|(.+))$/i)+ const directory = (directoryMatch?.[1] || directoryMatch?.[2] || directoryMatch?.[3] || '').trim()+ const parsedLabel = directory ? path.win32.basename(directory.replace(/["']$/, '')) : undefined+ const hintedLabel = trustedScannerIdentity && typeof hints?.label === 'string' ? hints.label.trim() : ''+ const label = hintedLabel || parsedLabel++ return {+ ...process,+ kind: 'local-preview',+ safeToStop: true,+ ...(label ? { label } : {}),+ ...(port ? { port } : {}),+ createTime: hintedCreateTime+ }+}++/**+ * Stop only blockers that the fresh scanner identified as Python static-file+ * preview servers. Unknown Python/Hermes processes are deliberately ignored.+ */+export async function stopSafeVenvBlockers(+ updateRoot: string,+ result: VenvBlockerScanResult,+ execOverride?: typeof execFileAsync,+ resolvePython: typeof resolveVenvPython = resolveVenvPython+): Promise<{ stopped: number[]; failed: number[] }> {+ const execFn = execOverride || execFileAsync+ const stopped: number[] = []+ const failed: number[] = []+ const pythonPath = resolvePython(updateRoot)++ for (const process of result.processes) {+ if (+ !pythonPath ||+ !process.safeToStop ||+ process.kind !== 'local-preview' ||+ !process.createTime ||+ !Number.isFinite(process.createTime)+ ) {+ if (process.safeToStop && process.kind === 'local-preview') {+ failed.push(process.pid)+ }++ continue+ }++ try {+ await execFn(+ pythonPath,+ [+ '-m',+ 'hermes_cli._scan_venv_blockers',+ '--terminate-safe',+ String(process.pid),+ String(process.createTime)+ ],+ { cwd: updateRoot, windowsHide: true, timeout: 10_000, maxBuffer: 256 * 1024 }+ )+ stopped.push(process.pid)+ } catch {+ failed.push(process.pid)+ }+ }++ return { stopped, failed }+}+/*** Strictly validate and parse the JSON output from the venv-blocker scan.* Pure function — no side effects.@@ -91,7 +191,7 @@ export function parseVenvBlockerScanOutput(raw: string): ScanOutcome {return { kind: 'probe-failure', error: 'process cmdline must be a string' }}- processes.push({ pid, name, cmdline })+ processes.push(classifyVenvBlocker({ pid, name, cmdline }, entry))}// Reject inconsistent combinationsdiff --git a/apps/desktop/src/app/updates-overlay.blockers.test.tsx b/apps/desktop/src/app/updates-overlay.blockers.test.tsxnew file mode 100644index 00000000000..edf2a11910f--- /dev/null+++ b/apps/desktop/src/app/updates-overlay.blockers.test.tsx@@ -0,0 +1,53 @@+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { Dialog, DialogContent } from '@/components/ui/dialog'+import { I18nProvider } from '@/i18n/context'++import { BlockerView } from './updates-overlay'++async function renderWithI18n(ui: React.ReactNode) {+ await act(async () => {+ render(+ <I18nProvider configClient={{ getConfig: async () => ({}), saveConfig: async () => ({ ok: true }) }}>+ <Dialog open>+ <DialogContent>{ui}</DialogContent>+ </Dialog>+ </I18nProvider>+ )+ })+}++describe('BlockerView', () => {+ afterEach(cleanup)++ it('explains safe local previews and offers one-click close-and-update', async () => {+ const onStopAndUpdate = vi.fn()++ await renderWithI18n(+ <BlockerView+ blockers={[+ {+ pid: 47484,+ name: 'python.exe',+ cmdline: 'python.exe -m http.server 8766',+ kind: 'local-preview',+ safeToStop: true,+ label: 'Example Preview',+ port: 8766+ }+ ]}+ onDismiss={() => {}}+ onStopAndUpdate={onStopAndUpdate}+ />+ )++ expect(screen.getByText('Close local previews to update Hermes?')).toBeTruthy()+ expect(screen.getByText('Example Preview')).toBeTruthy()+ expect(screen.getByText('Port 8766')).toBeTruthy()+ expect(screen.getByText(/will not modify or delete your files/i)).toBeTruthy()++ fireEvent.click(screen.getByRole('button', { name: 'Close previews and update' }))+ expect(onStopAndUpdate).toHaveBeenCalledTimes(1)+ })+})diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsxindex 14339f03736..c616c642ad1 100644--- a/apps/desktop/src/app/updates-overlay.tsx+++ b/apps/desktop/src/app/updates-overlay.tsx@@ -14,7 +14,12 @@ import {import { ErrorIcon, ErrorState } from '@/components/ui/error-state'import { Loader } from '@/components/ui/loader'import { Progress } from '@/components/ui/progress'-import type { DesktopUpdateCommit, DesktopUpdateStage, DesktopUpdateStatus } from '@/global'+import type {+ DesktopUpdateBlocker,+ DesktopUpdateCommit,+ DesktopUpdateStage,+ DesktopUpdateStatus+} from '@/global'import { useI18n } from '@/i18n'import { buildCommitChangelog, type CommitGroup } from '@/lib/commit-changelog'import { AlertCircle, Check, Copy, Terminal } from '@/lib/icons'@@ -80,6 +85,14 @@ export function UpdatesOverlay() {? 'error': 'idle'+ const safeBlockers =+ !isBackend &&+ apply.error === 'venv-blocked' &&+ apply.blockers?.length &&+ apply.blockers.every(blocker => blocker.kind === 'local-preview' && blocker.safeToStop)+ ? apply.blockers+ : null+const handleClose = (next: boolean) => {if (phase === 'applying') {return@@ -117,9 +130,17 @@ export function UpdatesOverlay() {{phase === 'guiSkew' && <GuiSkewView message={apply.message} onDone={() => handleClose(false)} />}- {phase === 'error' && (+ {phase === 'error' && safeBlockers ? (+ <BlockerView+ blockers={safeBlockers}+ onDismiss={() => handleClose(false)}+ onStopAndUpdate={() => void applyUpdates({ stopSafeBlockers: true })}+ />+ ) : null}++ {phase === 'error' && !safeBlockers ? (<ErrorView message={apply.message} onDismiss={() => handleClose(false)} onRetry={handleInstall} />- )}+ ) : null}{phase === 'idle' && (<IdleView@@ -420,6 +441,62 @@ function ApplyingView({ apply, isBackend }: { apply: UpdateApplyState; isBackend)}+export function BlockerView({+ blockers,+ onDismiss,+ onStopAndUpdate+}: {+ blockers: readonly DesktopUpdateBlocker[]+ onDismiss: () => void+ onStopAndUpdate: () => void+}) {+ const { t } = useI18n()+ const u = t.updates++ return (+ <div className="grid gap-5 px-6 pb-6 pt-7 pr-8">+ <div className="flex flex-col items-center gap-3 text-center">+ <div className="grid size-12 place-items-center rounded-full bg-warning/15 text-warning">+ <AlertCircle aria-hidden className="size-6" />+ </div>+ <DialogTitle className="text-center text-xl font-semibold tracking-tight">{u.blockerTitle}</DialogTitle>+ <DialogDescription className="max-w-prose text-center text-sm leading-5 text-muted-foreground">+ {u.blockerBody}+ </DialogDescription>+ </div>++ <div className="grid gap-2">+ {blockers.map(blocker => (+ <div className="rounded-lg border border-border/70 bg-muted/35 px-3 py-2.5" key={blocker.pid}>+ <div className="text-sm font-medium">{blocker.label || u.localPreview}</div>+ {blocker.port ? <div className="text-xs text-muted-foreground">{u.portLabel(blocker.port)}</div> : null}+ </div>+ ))}+ </div>++ <details className="rounded-md border border-border/60 px-3 py-2 text-xs text-muted-foreground">+ <summary className="cursor-pointer select-none font-medium">{u.technicalDetails}</summary>+ <div className="mt-2 grid gap-2 font-mono text-[11px] leading-4">+ {blockers.map(blocker => (+ <div className="break-all" key={blocker.pid}>+ PID {blocker.pid} · {blocker.cmdline}+ </div>+ ))}+ </div>+ </details>++ <div className="grid gap-1">+ <Button className="font-semibold" onClick={onStopAndUpdate} size="lg">+ {u.closePreviewsAndUpdate}+ </Button>+ <Button onClick={onDismiss} variant="text">+ {u.notNow}+ </Button>+ </div>+ </div>+ )+}+function ErrorView({ message, onDismiss, onRetry }: { message: string; onDismiss: () => void; onRetry: () => void }) {const { t } = useI18n()const u = t.updatesdiff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 81aeadb2353..14f73a061e0 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -497,8 +497,21 @@ export interface DesktopUpdateStatus {export type DesktopUpdateDirtyStrategy = 'abort' | 'stash' | 'force'+export interface DesktopUpdateBlocker {+ pid: number+ name: string+ cmdline: string+ kind: 'local-preview' | 'other'+ safeToStop: boolean+ label?: string+ port?: number+ createTime?: number+}+export interface DesktopUpdateApplyOptions {dirtyStrategy?: DesktopUpdateDirtyStrategy+ /** User confirmed that Desktop may stop freshly re-scanned safe local preview servers. */+ stopSafeBlockers?: boolean}export interface DesktopUpdateApplyResult {@@ -506,6 +519,7 @@ export interface DesktopUpdateApplyResult {branch?: stringerror?: stringmessage?: string+ blockers?: DesktopUpdateBlocker[]/** True when no staged updater exists (CLI install) and the user should run* `hermes update` themselves. `command` is the exact line to run. */manual?: booleandiff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 91d6c16314a..7b06448c4f6 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -1901,6 +1901,12 @@ export const ar = defineLocale({applyingClose: 'ستُغلق هذه النافذة أثناء تشغيل التحديث، ثم يعيد Hermes فتح نفسه تلقائيا.',errorTitle: 'لم يكتمل التحديث',errorBody: 'لا داعي للقلق — لم يُفقد شيء. يمكنك إعادة المحاولة الآن.',+ blockerTitle: 'إغلاق المعاينات المحلية لتحديث Hermes؟',+ blockerBody: 'يحتاج Hermes إلى إيقاف هذه المعاينات المحلية قبل التحديث. لن يؤدي ذلك إلى تعديل ملفاتك أو حذفها.',+ closePreviewsAndUpdate: 'إغلاق المعاينات والتحديث',+ localPreview: 'معاينة محلية',+ portLabel: port => `المنفذ ${port}`,+ technicalDetails: 'التفاصيل التقنية',notNow: 'ليس الآن',applyStatus: {preparing: 'جار تحديث الواجهة الخلفية...',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 0b7f57d461e..7169ad85b79 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -2376,6 +2376,13 @@ export const en: Translations = {applyingClose: 'This window will close while the update runs, then Hermes reopens on its own.',errorTitle: 'Update didn’t finish',errorBody: 'No worries — nothing was lost. You can try again now.',+ blockerTitle: 'Close local previews to update Hermes?',+ blockerBody:+ 'Hermes needs to stop these local previews before updating. This will not modify or delete your files.',+ closePreviewsAndUpdate: 'Close previews and update',+ localPreview: 'Local preview',+ portLabel: port => `Port ${port}`,+ technicalDetails: 'Technical details',notNow: 'Not now',applyStatus: {preparing: 'Updating backend…',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex a3674007fda..a6a075bb1c2 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2096,6 +2096,12 @@ export const ja = defineLocale({applyingClose: 'このウィンドウは更新中に閉じ、その後 Hermes が自動的に再度開きます。',errorTitle: '更新が完了しませんでした',errorBody: 'ご安心ください。何も失われていません。今すぐ再試行できます。',+ blockerTitle: 'Hermes を更新するためにローカルプレビューを閉じますか?',+ blockerBody: '更新する前に、これらのローカルプレビューを停止する必要があります。ファイルが変更または削除されることはありません。',+ closePreviewsAndUpdate: 'プレビューを閉じて更新',+ localPreview: 'ローカルプレビュー',+ portLabel: port => `ポート ${port}`,+ technicalDetails: '技術的な詳細',notNow: '今は後で',applyStatus: {preparing: 'バックエンドを更新しています…',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 5ab74d2fa3c..d4c7dfbbf87 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1995,6 +1995,12 @@ export interface Translations {applyingClose: stringerrorTitle: stringerrorBody: string+ blockerTitle: string+ blockerBody: string+ closePreviewsAndUpdate: string+ localPreview: string+ portLabel: (port: number) => string+ technicalDetails: stringnotNow: stringapplyStatus: {preparing: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 5d5abe0e074..e25d5268bd4 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2034,6 +2034,12 @@ export const zhHant = defineLocale({applyingClose: '此視窗會在更新期間關閉,隨後 Hermes 會自動重新開啟。',errorTitle: '更新未完成',errorBody: '沒有資料遺失。您可以現在重試。',+ blockerTitle: '關閉本機預覽以更新 Hermes?',+ blockerBody: 'Hermes 需要在更新前停止這些本機預覽。這不會修改或刪除您的檔案。',+ closePreviewsAndUpdate: '關閉預覽並更新',+ localPreview: '本機預覽',+ portLabel: port => `連接埠 ${port}`,+ technicalDetails: '技術詳細資料',notNow: '暫不',applyStatus: {preparing: '正在更新後端…',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 42deb03e522..a270e68f9df 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -2561,6 +2561,12 @@ export const zh: Translations = {applyingClose: '此窗口会在更新期间关闭,随后 Hermes 会自动重新打开。',errorTitle: '更新未完成',errorBody: '没有数据丢失。你可以现在重试。',+ blockerTitle: '关闭本地预览以更新 Hermes?',+ blockerBody: 'Hermes 需要在更新前停止这些本地预览。这不会修改或删除你的文件。',+ closePreviewsAndUpdate: '关闭预览并更新',+ localPreview: '本地预览',+ portLabel: port => `端口 ${port}`,+ technicalDetails: '技术详情',notNow: '暂不',applyStatus: {preparing: '正在更新后端…',diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.tsindex 55a9391a1a6..f91a686b882 100644--- a/apps/desktop/src/store/updates.test.ts+++ b/apps/desktop/src/store/updates.test.ts@@ -415,6 +415,27 @@ describe('applyUpdates terminal state', () => {expect($updateApply.get().error).toBe('rebuild-failed')})+ it('preserves structured safe blockers for the close-and-update prompt', async () => {+ const blockers = [+ {+ pid: 47484,+ name: 'python.exe',+ cmdline: 'python.exe -m http.server 8766',+ kind: 'local-preview' as const,+ safeToStop: true,+ label: 'Example Preview',+ port: 8766+ }+ ]++ applyMock.mockResolvedValue({ ok: false, error: 'venv-blocked', message: 'blocked', blockers })++ await applyUpdates()++ expect($updateApply.get().error).toBe('venv-blocked')+ expect($updateApply.get().blockers).toEqual(blockers)+ })+it('keeps the manual command state for CLI installs with no staged updater', async () => {applyMock.mockResolvedValue({ ok: true, manual: true, command: 'hermes update' })diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.tsindex 3d234e0d4fb..02f2a40903c 100644--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@ -8,6 +8,7 @@ import { atom } from 'nanostores'import type {DesktopUpdateApplyOptions,DesktopUpdateApplyResult,+ DesktopUpdateBlocker,DesktopUpdateProgress,DesktopUpdateStage,DesktopUpdateStatus,@@ -29,6 +30,8 @@ export interface UpdateApplyState {/** When the stage is 'manual': the exact command the user should run* (CLI install with no staged updater). */command: string | null+ /** Structured update blockers used by the safe close-and-update confirmation. */+ blockers?: readonly DesktopUpdateBlocker[] | nulllog: readonly { stage: DesktopUpdateStage; message: string; at: number }[]}@@ -480,7 +483,8 @@ export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promisapplying: false,stage: 'error',error: result?.error ?? 'apply-failed',- message: result?.message ?? translateNow('updates.errorBody')+ message: result?.message ?? translateNow('updates.errorBody'),+ blockers: result?.blockers ?? null})}}diff --git a/hermes_cli/_scan_venv_blockers.py b/hermes_cli/_scan_venv_blockers.pyindex e25a465567a..8ebbb216a2d 100644--- a/hermes_cli/_scan_venv_blockers.py+++ b/hermes_cli/_scan_venv_blockers.py@@ -12,7 +12,9 @@ one JSON document on stdout; diagnostics on stderr only.from __future__ import annotationsimport json+import mathimport sys+from pathlib import PureWindowsPathfrom typing import NoReturn# Long CLI flags whose argument value must be redacted from the cmdline.@@ -106,6 +108,98 @@ def _redact_sensitive_cmdline(cmdline: str) -> str:return cmdline+def _classify_local_preview_args(args: object) -> dict[str, object]:+ """Return safe UI metadata for an exact ``python -m http.server`` argv.++ The general holder detector intentionally truncates its diagnostic command+ line. Reading argv separately preserves a useful directory label without+ exposing an unbounded command line to the renderer.+ """+ if not isinstance(args, (list, tuple)) or not all(isinstance(arg, str) for arg in args):+ return {}++ # For a real interpreter module invocation, ``-m`` is the first argument+ # after the executable. A later ``-m http.server`` can merely be data passed+ # to an unrelated script and must never authorize termination.+ if len(args) < 3 or args[1] != "-m" or args[2].lower() != "http.server":+ return {}+ module_index = 1++ port = 8000+ if module_index + 2 < len(args):+ candidate = args[module_index + 2]+ if candidate.isdigit() and 0 < int(candidate) <= 65535:+ port = int(candidate)++ label = ""+ try:+ directory_index = args.index("--directory")+ if directory_index + 1 < len(args):+ label = PureWindowsPath(args[directory_index + 1]).name+ except ValueError:+ pass++ metadata: dict[str, object] = {+ "kind": "local-preview",+ "safeToStop": True,+ "port": port,+ }+ if label:+ metadata["label"] = label+ return metadata+++def _local_preview_metadata(pid: int, name: str) -> dict[str, object]:+ if name.lower() not in {"python.exe", "pythonw.exe", "python", "pythonw"}:+ return {}+ try:+ import psutil # noqa: PLC0415++ process = psutil.Process(pid)+ metadata = _classify_local_preview_args(process.cmdline())+ if metadata:+ metadata["createTime"] = process.create_time()+ return metadata+ except Exception:+ return {}+++def _terminate_safe_preview(+ pid: int,+ expected_create_time: float,+ *,+ psutil_module: object | None = None,+) -> tuple[bool, str | None]:+ """Terminate one verified local preview process tree.++ A fresh ``psutil.Process`` identity check and exact argv classification occur+ immediately before termination. psutil guards mutating Process methods+ against PID reuse, avoiding taskkill's stale-PID race.+ """+ try:+ if psutil_module is None:+ import psutil as psutil_module # type: ignore[no-redef] # noqa: PLC0415++ process = psutil_module.Process(pid) # type: ignore[attr-defined]+ if abs(process.create_time() - expected_create_time) > 0.001:+ return False, "process identity changed"+ if not _classify_local_preview_args(process.cmdline()):+ return False, "process is no longer a local preview"++ children = process.children(recursive=True)+ targets = [*reversed(children), process]+ for target in targets:+ target.terminate()+ _gone, alive = psutil_module.wait_procs(targets, timeout=3) # type: ignore[attr-defined]+ for target in alive:+ target.kill()+ if alive:+ psutil_module.wait_procs(alive, timeout=2) # type: ignore[attr-defined]+ return True, None+ except Exception as exc:+ return False, f"termination failed: {type(exc).__name__}"++def _is_pausable_gateway(cmdline: str) -> bool:"""Return True when *cmdline* is a gateway process the updater can pause.@@ -154,8 +248,11 @@ def main() -> None:except Exception as exc:_emit_probe_fail(f"scan aborted: {exc}")- processes = [- {+ processes = []+ for pid, name, cmdline in matches:+ if _is_pausable_gateway(cmdline):+ continue+ process = {"pid": pid,"name": name,# Truncate for display AFTER the gateway exemption has seen the@@ -163,9 +260,9 @@ def main() -> None:# otherwise swallow the `gateway run` argv)."cmdline": _redact_sensitive_cmdline(cmdline)[:120],}- for pid, name, cmdline in matches- if not _is_pausable_gateway(cmdline)- ]+ process.update(_local_preview_metadata(pid, name))+ processes.append(process)+exempted = sum(1 for _pid, _name, cmdline in matches if _is_pausable_gateway(cmdline))data = {"ok": True,@@ -179,5 +276,25 @@ def main() -> None:sys.exit(0)+def _terminate_safe_main(argv: list[str]) -> NoReturn:+ if len(argv) != 2:+ print(json.dumps({"ok": False, "error": "expected pid and create time"}))+ raise SystemExit(2)+ try:+ pid = int(argv[0])+ create_time = float(argv[1])+ if pid <= 0 or not math.isfinite(create_time) or create_time <= 0:+ raise ValueError+ except ValueError:+ print(json.dumps({"ok": False, "error": "invalid process identity"}))+ raise SystemExit(2)++ stopped, error = _terminate_safe_preview(pid, create_time)+ print(json.dumps({"ok": stopped, "pid": pid, "error": error}))+ raise SystemExit(0 if stopped else 1)++if __name__ == "__main__":+ if len(sys.argv) > 1 and sys.argv[1] == "--terminate-safe":+ _terminate_safe_main(sys.argv[2:])main()\ No newline at end of filediff --git a/tests/hermes_cli/test_scan_venv_blockers.py b/tests/hermes_cli/test_scan_venv_blockers.pyindex 2082d082c58..def834960b6 100644--- a/tests/hermes_cli/test_scan_venv_blockers.py+++ b/tests/hermes_cli/test_scan_venv_blockers.py@@ -17,9 +17,11 @@ import pytestimport agent.redact as redact_modulefrom hermes_cli._scan_venv_blockers import (+ _classify_local_preview_args,_is_pausable_gateway,_probe_fail_json,_redact_sensitive_cmdline,+ _terminate_safe_preview,main,)@@ -97,6 +99,91 @@ def test_redact_short_flags_not_redacted() -> None:assert result == raw # short flags pass through unchanged+def test_classify_local_preview_args_preserves_full_directory_label_and_port() -> None:+ args = [+ r"C:\Hermes\venv\Scripts\python.exe",+ "-m",+ "http.server",+ "8766",+ "--bind",+ "0.0.0.0",+ "--directory",+ r"C:\Projects\Example Preview",+ ]++ assert _classify_local_preview_args(args) == {+ "kind": "local-preview",+ "safeToStop": True,+ "label": "Example Preview",+ "port": 8766,+ }+++def test_classify_local_preview_args_rejects_arbitrary_python_process() -> None:+ assert _classify_local_preview_args(["python.exe", "important-script.py"]) == {}+++def test_classify_local_preview_args_rejects_module_flags_passed_to_a_script() -> None:+ assert _classify_local_preview_args(+ ["python.exe", "important-script.py", "-m", "http.server", "8765"]+ ) == {}+++def test_terminate_safe_preview_revalidates_identity_and_exact_argv() -> None:+ class FakeProcess:+ def __init__(self, pid: int, *, created: float, args: list[str]) -> None:+ self.pid = pid+ self._created = created+ self._args = args+ self.terminated = False+ self.killed = False+ self._children: list[FakeProcess] = []++ def create_time(self) -> float:+ return self._created++ def cmdline(self) -> list[str]:+ return self._args++ def children(self, *, recursive: bool) -> list[FakeProcess]:+ assert recursive is True+ return self._children++ def terminate(self) -> None:+ self.terminated = True++ def kill(self) -> None:+ self.killed = True++ child = FakeProcess(200, created=10.0, args=["child.exe"])+ parent = FakeProcess(100, created=1722798000.25, args=["python.exe", "-m", "http.server", "8766"])+ parent._children = [child]+ fake_psutil = types.SimpleNamespace(+ Process=lambda pid: parent if pid == 100 else child,+ wait_procs=lambda processes, timeout: (processes, []),+ )++ stopped, error = _terminate_safe_preview(100, 1722798000.25, psutil_module=fake_psutil)++ assert stopped is True+ assert error is None+ assert parent.terminated is True+ assert child.terminated is True+++def test_terminate_safe_preview_refuses_reused_pid() -> None:+ process = MagicMock()+ process.create_time.return_value = 1722798999.0+ fake_psutil = types.SimpleNamespace(Process=lambda _pid: process)++ stopped, error = _terminate_safe_preview(100, 1722798000.25, psutil_module=fake_psutil)++ assert stopped is False+ assert error == "process identity changed"+ process.cmdline.assert_not_called()+ process.terminate.assert_not_called()++# ---------------------------------------------------------------------------# _is_pausable_gateway — the gateway exemption#