The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): respect package ownership before uninstalling
ethernet32db27d63fb2
diff --git a/apps/desktop/electron/desktop-uninstall-ipc.test.ts b/apps/desktop/electron/desktop-uninstall-ipc.test.tsnew file mode 100644index 00000000000..79fee6235d0--- /dev/null+++ b/apps/desktop/electron/desktop-uninstall-ipc.test.ts@@ -0,0 +1,134 @@+import { expect, type Mock, test, vi } from 'vitest'++import { registerDesktopUninstallIpc } from './desktop-uninstall'+import type { DesktopUninstallIpcDeps, DesktopUninstallSummary } from './desktop-uninstall'+import type { InstallStamp } from './install-stamp'++const fallbackSummary: Omit<DesktopUninstallSummary, 'code_removal_allowed'> = {+ hermes_home: '/test/.hermes',+ agent_installed: true,+ gui_installed: true,+ source_built_artifacts: [],+ packaged_app_paths: [],+ userdata_dir: '/test/desktop',+ userdata_exists: true,+ platform: process.platform,+ probe: 'fallback'+}++interface CapturedIpc {+ probeSummary: Mock<() => Promise<DesktopUninstallSummary>>+ runUninstall: Mock<DesktopUninstallIpcDeps['runUninstall']>+ localSummary: Mock<DesktopUninstallIpcDeps['fallbackSummary']>+ invoke: (channel: string, payload?: unknown) => Promise<unknown>+}++function captureIpc(stamp: DesktopUninstallIpcDeps['stamp']): CapturedIpc {+ type Handler = Parameters<DesktopUninstallIpcDeps['ipcMain']['handle']>[1]++ const handlers: Map<string, Handler> = new Map()++ const probeSummary: CapturedIpc['probeSummary'] = vi.fn(async (): Promise<DesktopUninstallSummary> => ({+ ...fallbackSummary,+ probe: 'python',+ code_removal_allowed: true+ }))++ const runUninstall: CapturedIpc['runUninstall'] = vi.fn<DesktopUninstallIpcDeps['runUninstall']>(+ async (mode: string): ReturnType<DesktopUninstallIpcDeps['runUninstall']> => ({ ok: true, mode })+ )++ const localSummary: CapturedIpc['localSummary'] = vi.fn(+ (): ReturnType<DesktopUninstallIpcDeps['fallbackSummary']> => fallbackSummary+ )++ const ipcMain: DesktopUninstallIpcDeps['ipcMain'] = {+ handle: (channel: string, handler: Handler): void => {+ handlers.set(channel, handler)+ }+ }++ registerDesktopUninstallIpc({ ipcMain, stamp, fallbackSummary: localSummary, probeSummary, runUninstall })++ return {+ probeSummary,+ runUninstall,+ localSummary,+ invoke: async (channel: string, payload?: unknown): Promise<unknown> => {+ const handler: Handler | undefined = handlers.get(channel)++ if (!handler) {+ throw new Error(`Missing IPC handler: ${channel}`)+ }++ return handler(undefined, payload)+ }+ }+}++test('excluded artifact owners block every uninstall IPC before a Python probe or destructive callback', async (): Promise<void> => {+ const stamps: Array<Partial<InstallStamp>> = [+ { distribution: 'nix' },+ { source: 'nix' },+ { payload: 'bundled', updateMechanism: 'electron-updater' },+ { payload: 'light', updateMechanism: 'app-installer' },+ { payload: 'bootstrap', distribution: 'package-manager', updateMechanism: 'external' }+ ]++ for (const stamp of stamps) {+ const ipc: CapturedIpc = captureIpc(stamp)++ expect(await ipc.invoke('hermes:uninstall:summary')).toEqual({+ ...fallbackSummary,+ code_removal_allowed: false+ })+ expect(ipc.probeSummary).not.toHaveBeenCalled()++ for (const mode of ['gui', 'lite', 'full', 'data']) {+ for (const payload of [mode, { mode }]) {+ expect(await ipc.invoke('hermes:uninstall:run', payload)).toMatchObject({+ ok: false,+ error: 'externally-managed'+ })+ }+ }++ expect(ipc.runUninstall).not.toHaveBeenCalled()+ }+})++test('self-managed installs retain summary and uninstall IPC behavior under Electron policy', async (): Promise<void> => {+ for (const stamp of [null, { payload: 'bootstrap', updateMechanism: 'self' }] as const) {+ const ipc: CapturedIpc = captureIpc(stamp)++ ipc.probeSummary.mockResolvedValue({ ...fallbackSummary, probe: 'python', code_removal_allowed: false })+ expect(await ipc.invoke('hermes:uninstall:summary')).toEqual({+ ...fallbackSummary,+ probe: 'python',+ code_removal_allowed: true+ })+ expect(ipc.probeSummary).toHaveBeenCalledOnce()+ expect(ipc.localSummary).not.toHaveBeenCalled()++ ipc.probeSummary.mockResolvedValue({ ...fallbackSummary, code_removal_allowed: false })+ expect(await ipc.invoke('hermes:uninstall:summary')).toMatchObject({+ probe: 'fallback',+ code_removal_allowed: true+ })++ for (const mode of ['gui', 'lite', 'full']) {+ for (const payload of [mode, { mode }]) {+ expect(await ipc.invoke('hermes:uninstall:run', payload)).toEqual({ ok: true, mode })+ expect(ipc.runUninstall).toHaveBeenLastCalledWith(mode)+ }+ }++ ipc.runUninstall.mockClear()++ for (const payload of ['unknown', 'data', undefined, { mode: 'unknown' }]) {+ expect(await ipc.invoke('hermes:uninstall:run', payload)).toMatchObject({ ok: false, error: 'invalid-mode' })+ }++ expect(ipc.runUninstall).not.toHaveBeenCalled()+ }+})diff --git a/apps/desktop/electron/desktop-uninstall.test.ts b/apps/desktop/electron/desktop-uninstall.test.tsindex 23ece67cd5a..a7a6186c941 100644--- a/apps/desktop/electron/desktop-uninstall.test.ts+++ b/apps/desktop/electron/desktop-uninstall.test.ts@@ -51,14 +51,14 @@ test('resolveInstallKind reads the stamp: distribution nix wins, payload kind meassert.equal(resolveInstallKind(), 'standard')})-test('only standard installs may remove code; managed kinds get data-only', () => {+test('only standard installs allow desktop uninstall; managed kinds have no safe mode', (): void => {assert.equal(installKindAllowsCodeRemoval('standard'), true)assert.equal(installKindAllowsCodeRemoval('nix'), false)assert.equal(installKindAllowsCodeRemoval('bundled'), false)assert.deepEqual(allowedUninstallModes('standard'), ['gui', 'lite', 'full'])- assert.deepEqual(allowedUninstallModes('nix'), ['data'])- assert.deepEqual(allowedUninstallModes('bundled'), ['data'])+ assert.deepEqual(allowedUninstallModes('nix'), [])+ assert.deepEqual(allowedUninstallModes('bundled'), [])})test('nativeRemovalInstructions names the steward per kind and OS', () => {@@ -161,7 +161,7 @@ test('shouldRemoveAppBundle requires packaged AND a resolved path', () => {// --- buildPosixCleanupScript ----test('buildPosixCleanupScript waits for the PID, runs the uninstall module, removes bundle', () => {+test('buildPosixCleanupScript waits for the PID, runs the uninstall module, removes bundle', (): void => {const script = buildPosixCleanupScript({desktopPid: 4321,pythonExe: '/home/x/.hermes/hermes-agent/venv/bin/python',@@ -172,7 +172,7 @@ test('buildPosixCleanupScript waits for the PID, runs the uninstall module, remohermesHome: '/home/x/.hermes'})- assert.match(script, /^#!\/bin\/bash/)+ assert.match(script, /^#!\/usr\/bin\/env bash\n/)assert.match(script, /pid=4321/)assert.match(script, /kill -0 "\$pid"/)// bounded wait (~30s), not unboundeddiff --git a/apps/desktop/electron/desktop-uninstall.ts b/apps/desktop/electron/desktop-uninstall.tsindex d1d9686e1f7..ae51e549b02 100644--- a/apps/desktop/electron/desktop-uninstall.ts+++ b/apps/desktop/electron/desktop-uninstall.ts@@ -6,9 +6,8 @@* resolve the running app bundle/exe so a detached cleanup script can remove* it after the app quits, and build that cleanup script for each OS.*- * Kept standalone (no ` import 'electron'`) so it can be unit-tested with- * `node --test` — same pattern as connection-config.ts / backend-probes.ts.- * main.ts requires these and wires them into the electron-coupled IPC layer.+ * Kept electron-free so Vitest can exercise the registered IPC handlers.+ * main.ts supplies the local install stamp and process callbacks.** The three modes mirror the CLI's options exactly:* - 'gui' → remove ONLY the Chat GUI, keep the agent + all user data.@@ -28,31 +27,103 @@import path from 'node:path'-import type { ArtifactKind } from './install-stamp'+import type { InstallStamp } from './install-stamp'++export interface UninstallSummaryDetails {+ hermes_home: string+ agent_installed: boolean+ gui_installed: boolean+ source_built_artifacts: string[]+ packaged_app_paths: string[]+ userdata_dir: string+ userdata_exists: boolean+ platform: string+ running_app_path?: string | null+ probe?: string+}++export interface DesktopUninstallSummary extends UninstallSummaryDetails {+ code_removal_allowed: boolean+}++export interface DesktopUninstallResult {+ ok: boolean+ mode?: string+ willRemoveAppBundle?: boolean+ scriptPath?: string+ error?: string+ message?: string+}++export interface DesktopUninstallIpcDeps {+ ipcMain: {+ handle: (channel: string, handler: (event: unknown, payload?: unknown) => Promise<unknown>) => void+ }+ stamp: Readonly<Partial<Pick<InstallStamp, 'distribution' | 'source' | 'payload' | 'updateMechanism'>>> | null+ fallbackSummary: () => UninstallSummaryDetails+ probeSummary: () => Promise<UninstallSummaryDetails>+ runUninstall: (mode: string) => Promise<DesktopUninstallResult>+}-const UNINSTALL_MODES = ['gui', 'lite', 'full', 'data']+export function registerDesktopUninstallIpc({+ ipcMain,+ stamp,+ fallbackSummary,+ probeSummary,+ runUninstall+}: DesktopUninstallIpcDeps): void {+ const kind: InstallKind = resolveInstallKind(stamp ?? {})+ const codeRemovalAllowed: boolean = installKindAllowsCodeRemoval(kind)++ ipcMain.handle('hermes:uninstall:summary', async (): Promise<DesktopUninstallSummary> => {+ const summary: UninstallSummaryDetails = codeRemovalAllowed ? await probeSummary() : fallbackSummary()++ // The local artifact owns this decision, not the Python summary.+ return { ...summary, code_removal_allowed: codeRemovalAllowed }+ })+ ipcMain.handle(+ 'hermes:uninstall:run',+ async (_event: unknown, payload?: unknown): Promise<DesktopUninstallResult> => {+ // Every cleanup mode can remove the bundle, including a hidden data request.+ if (!codeRemovalAllowed) {+ return {+ ok: false,+ error: 'externally-managed',+ message: 'This desktop install must be removed through its installer or package manager.'+ }+ }++ const mode: unknown = payload && typeof payload === 'object' && 'mode' in payload ? payload.mode : payload+ const requestedMode: string = String(mode || '')++ if (!allowedUninstallModes(kind).includes(requestedMode)) {+ return { ok: false, error: 'invalid-mode', message: `Unknown uninstall mode: ${requestedMode}` }+ }++ return runUninstall(requestedMode)+ }+ )+}-// How this desktop app got onto the machine, read from the install stamp-// (install-stamp.json) that every packager writes:+const UNINSTALL_MODES: string[] = ['gui', 'lite', 'full', 'data']++// The baked install stamp determines who owns removal:// 'nix' — a Nix build (stamp distribution 'nix'). The store is// immutable and the install is owned by Nix tooling, so the// app must not remove any code, its own bundle included.-// 'bundled' — an embedded artifact (agent payload in resources; the-// stamp has payload:true). There is no agent venv under-// HERMES_HOME, and the OS owns app removal (Apps & Features-// / Trash / delete the AppImage).+// 'bundled' — a bundled or light artifact. The OS owns app removal.+// 'external' — another package manager owns updates and removal.// 'standard' — everything else: the git-clone install the desktop// installer bootstraps, or a `hermes desktop` source build.// The classic script flow (venv python + rm the bundle) works.//-// Only 'standard' installs may remove code. 'nix' and 'bundled' installs-// may only remove user data (mode 'data') — the app itself is removed the-// native way, per nativeRemovalInstructions().-const INSTALL_KINDS = ['nix', 'bundled', 'standard']+// Only 'standard' installs may use the desktop cleanup script.+const INSTALL_KINDS = ['nix', 'bundled', 'external', 'standard'] as const+type InstallKind = (typeof INSTALL_KINDS)[number]/*** Classify the install from the stamp. Pure so it can be unit-tested:- * callers pass the stamp fields (`distribution`, `source`, `payload`).+ * callers pass the baked stamp, never the connected backend's install facts.* `distribution` is authoritative; `source` is the schema-1 fallback.* The 'bundled' and 'light' artifact kinds both classify as the managed* 'bundled' flow — neither has agent code the app may remove, and the OS@@ -61,8 +132,9 @@ const INSTALL_KINDS = ['nix', 'bundled', 'standard']function resolveInstallKind({distribution,source,- payload = 'bootstrap'-}: { distribution?: string | null; source?: string | null; payload?: ArtifactKind } = {}) {+ payload = 'bootstrap',+ updateMechanism+}: NonNullable<DesktopUninstallIpcDeps['stamp']> = {}): InstallKind {if (distribution === 'nix' || source === 'nix') {return 'nix'}@@ -71,23 +143,24 @@ function resolveInstallKind({return 'bundled'}+ if (updateMechanism === 'external') {+ return 'external'+ }+return 'standard'}/** True when this install kind lets the app remove code (agent / bundle). */-function installKindAllowsCodeRemoval(kind) {+function installKindAllowsCodeRemoval(kind: InstallKind): boolean {return kind === 'standard'}/**- * The modes the uninstall UI may offer for an install kind. Every kind can- * remove user data. Only 'standard' may also remove code — there the 'full'- * mode already covers data, so 'data' alone is not offered. Managed installs- * (nix, bundled) get exactly one destructive action — remove user data —- * with app removal handed to the steward via nativeRemovalInstructions().+ * Desktop cleanup always removes the bundle. No mode is safe for an install+ * owned by another installer, including the CLI's data-only mode.*/-function allowedUninstallModes(kind) {- return installKindAllowsCodeRemoval(kind) ? ['gui', 'lite', 'full'] : ['data']+function allowedUninstallModes(kind: InstallKind): string[] {+ return installKindAllowsCodeRemoval(kind) ? ['gui', 'lite', 'full'] : []}/**diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 225e233e1b3..be2fdf4b0ce 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -170,11 +170,14 @@ import { resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remotimport {buildPosixCleanupScript,buildWindowsCleanupScript,+ type DesktopUninstallResult,modeRemovesAgent,modeRemovesUserData,+ registerDesktopUninstallIpc,resolveRemovableAppPath,shouldRemoveAppBundle,- uninstallArgsForMode+ uninstallArgsForMode,+ type UninstallSummaryDetails} from './desktop-uninstall'import { describeDevCdpDecision, resolveDevCdpPort } from './dev-cdp'import { installEmbedReferer } from './embed-referer'@@ -17346,24 +17349,17 @@ function resolveHermesRuntime() {// registry / service / node-symlink cleanup all lives in one place// (hermes_cli/uninstall.py + hermes_cli/gui_uninstall.py).//-// getUninstallSummary() shells out to `--gui-summary` (a fast, no-side-effect-// JSON probe) so the UI can gate options on what's actually installed — and-// detect a missing agent (a future "lite client" that ships without the-// bundled agent), hiding the agent/full options when there's nothing to remove.+// The IPC boundary applies the baked install policy before either callback.+// Only self-managed installs use the Python summary or the cleanup script.-function uninstallVenvPython() {+function uninstallVenvPython(): string {return getVenvPython(VENV_ROOT)}-async function getUninstallSummary() {- const py = uninstallVenvPython()- const agentRoot = ACTIVE_HERMES_ROOT-- // Fast JS-side fallback used when the agent venv is gone (lite client) or the- // probe fails — the renderer still needs *something* to render options from.- const fallback = () => ({+function fallbackUninstallSummary(): UninstallSummaryDetails {+ return {hermes_home: HERMES_HOME,- agent_installed: isHermesSourceRoot(agentRoot) && fileExists(py),+ agent_installed: isHermesSourceRoot(ACTIVE_HERMES_ROOT) && fileExists(uninstallVenvPython()),gui_installed: true,source_built_artifacts: [],packaged_app_paths: [],@@ -17371,17 +17367,22 @@ async function getUninstallSummary() {userdata_exists: true,platform: process.platform,probe: 'fallback'- })+ }+}++async function probeUninstallSummary(): Promise<UninstallSummaryDetails> {+ const py: string = uninstallVenvPython()+ const agentRoot: string = ACTIVE_HERMES_ROOTif (!fileExists(py)) {- return fallback()+ return fallbackUninstallSummary()}- return new Promise(resolve => {- let stdout = ''- let settled = false+ return new Promise<UninstallSummaryDetails>((resolve: (value: UninstallSummaryDetails) => void): void => {+ let stdout: string = ''+ let settled: boolean = false- const done = value => {+ const done = (value: UninstallSummaryDetails): void => {if (settled) {return}@@ -17391,7 +17392,7 @@ async function getUninstallSummary() {}try {- const child = spawn(+ const child: ChildProcess = spawn(py,['-m', 'hermes_cli.main', 'uninstall', '--gui-summary'],hiddenWindowsChildOptions({@@ -17401,36 +17402,36 @@ async function getUninstallSummary() {}))- child.stdout.on('data', chunk => {+ child.stdout.on('data', (chunk: Buffer): void => {stdout += chunk.toString()})- child.on('error', () => done(fallback()))- child.on('exit', code => {+ child.on('error', (): void => done(fallbackUninstallSummary()))+ child.on('exit', (code: number | null): void => {if (code !== 0) {- return done(fallback())+ return done(fallbackUninstallSummary())}try {- const line = stdout.trim().split('\n').filter(Boolean).pop() || '{}'- const parsed = JSON.parse(line)+ const line: string = stdout.trim().split('\n').filter(Boolean).pop() || '{}'+ const parsed: UninstallSummaryDetails = JSON.parse(line)// The app bundle the renderer would be removing on *this* machine,// resolved from the running exe (the Python probe only knows the// standard locations, not where THIS build actually runs from).parsed.running_app_path = resolveRemovableAppPath(process.execPath, process.platform, process.env)done(parsed)} catch {- done(fallback())+ done(fallbackUninstallSummary())}})- setTimeout(() => done(fallback()), 8000)+ setTimeout((): void => done(fallbackUninstallSummary()), 8000)} catch {- done(fallback())+ done(fallbackUninstallSummary())}})}-async function runDesktopUninstall(mode) {- let uninstallArgs+async function runDesktopUninstall(mode: string): Promise<DesktopUninstallResult> {+ let uninstallArgs: string[]try {uninstallArgs = uninstallArgsForMode(mode)@@ -17544,11 +17545,12 @@ async function runDesktopUninstall(mode) {return { ok: true, mode, willRemoveAppBundle: Boolean(removeBundle), scriptPath }}-ipcMain.handle('hermes:uninstall:summary', async () => getUninstallSummary())-ipcMain.handle('hermes:uninstall:run', async (_event, payload) => {- const mode = payload && typeof payload === 'object' ? payload.mode : payload-- return runDesktopUninstall(String(mode || ''))+registerDesktopUninstallIpc({+ ipcMain,+ stamp: INSTALL_STAMP,+ fallbackSummary: fallbackUninstallSummary,+ probeSummary: probeUninstallSummary,+ runUninstall: runDesktopUninstall})// Download a VS Code Marketplace extension and return the raw color-theme JSONdiff --git a/apps/desktop/src/app/settings/uninstall-section.test.tsx b/apps/desktop/src/app/settings/uninstall-section.test.tsxnew file mode 100644index 00000000000..9d6a8cd7fbf--- /dev/null+++ b/apps/desktop/src/app/settings/uninstall-section.test.tsx@@ -0,0 +1,66 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'++import type { DesktopUninstallSummary } from '@/global'++import { UninstallSection } from './uninstall-section'++function summary(allowed: boolean): DesktopUninstallSummary {+ return {+ code_removal_allowed: allowed,+ hermes_home: '/test/home',+ agent_installed: true,+ gui_installed: true,+ source_built_artifacts: [],+ packaged_app_paths: [],+ userdata_dir: '/test/desktop',+ userdata_exists: true,+ platform: 'linux'+ }+}++afterEach((): void => {+ cleanup()+ vi.unstubAllGlobals()+})++it.each(['external', 'missing-policy', 'probe-failed', 'loading'] as const)(+ 'does not offer uninstall actions when ownership is %s',+ async (state: 'external' | 'missing-policy' | 'probe-failed' | 'loading'): Promise<void> => {+ const getSummary: ReturnType<typeof vi.fn> = vi.fn(async (): Promise<DesktopUninstallSummary> => {+ if (state === 'probe-failed') { throw new Error('IPC unavailable') }++ if (state === 'loading') { return new Promise<DesktopUninstallSummary>((): void => {}) }++ if (state === 'missing-policy') {+ const { code_removal_allowed: _ignored, ...oldSummary }: ReturnType<typeof summary> = summary(true)++ return oldSummary as DesktopUninstallSummary+ }++ return summary(false)+ })++ const run: ReturnType<typeof vi.fn> = vi.fn()++ vi.stubGlobal('hermesDesktop', { uninstall: { summary: getSummary, run } })+ await act(async (): Promise<void> => { render(<UninstallSection />) })+ expect(getSummary).toHaveBeenCalledOnce()+ expect(screen.queryByText('Uninstall Hermes')).toBeNull()+ expect(screen.queryByRole('button', { name: /Uninstall/ })).toBeNull()+ expect(screen.queryByText('Danger zone')).toBeNull()+ expect(run).not.toHaveBeenCalled()+ }+)++it('keeps owned-install removal modes and confirms the selected mode', async (): Promise<void> => {+ const run: ReturnType<typeof vi.fn> = vi.fn().mockResolvedValue({ ok: true })+ vi.stubGlobal('hermesDesktop', {+ uninstall: { summary: async (): Promise<DesktopUninstallSummary> => summary(true), run }+ })+ render(<UninstallSection />)+ fireEvent.click(await screen.findByRole('button', { name: /Uninstall Chat GUI only/ }))+ expect(run).not.toHaveBeenCalled()+ fireEvent.click(screen.getByRole('button', { name: 'Yes, uninstall' }))+ await waitFor((): void => { expect(run).toHaveBeenCalledWith('gui') })+})diff --git a/apps/desktop/src/app/settings/uninstall-section.tsx b/apps/desktop/src/app/settings/uninstall-section.tsxindex 5ac21ac80e7..8ae2a188771 100644--- a/apps/desktop/src/app/settings/uninstall-section.tsx+++ b/apps/desktop/src/app/settings/uninstall-section.tsx@@ -1,7 +1,7 @@-import { useEffect, useState } from 'react'+import { type ReactElement, useEffect, useState } from 'react'import { Button } from '@/components/ui/button'-import type { DesktopUninstallMode, DesktopUninstallSummary } from '@/global'+import type { DesktopUninstallMode, DesktopUninstallResult, DesktopUninstallSummary } from '@/global'import { AlertTriangle, Loader2, Trash2 } from '@/lib/icons'import { cn } from '@/lib/utils'@@ -45,56 +45,50 @@ const OPTIONS: ModeOption[] = [}]-export function UninstallSection() {+export function UninstallSection(): ReactElement | null {const [summary, setSummary] = useState<DesktopUninstallSummary | null>(null)- const [loading, setLoading] = useState(true)const [pending, setPending] = useState<DesktopUninstallMode | null>(null)- const [running, setRunning] = useState(false)+ const [running, setRunning] = useState<boolean>(false)const [error, setError] = useState<string | null>(null)- useEffect(() => {- let alive = true- const bridge = window.hermesDesktop?.uninstall+ useEffect((): (() => void) | undefined => {+ let alive: boolean = true+ const bridge: Window['hermesDesktop']['uninstall'] | undefined = window.hermesDesktop?.uninstallif (!bridge) {- setLoading(false)-return}void bridge.summary()- .then(result => {+ .then((result: DesktopUninstallSummary): void => {if (alive) {setSummary(result)}})- .catch(() => {- // Non-fatal — we degrade to offering the GUI-only option.- })- .finally(() => {+ .catch((): void => {+ // A failed ownership probe must not offer a destructive fallback.if (alive) {- setLoading(false)+ setSummary(null)}})- return () => {+ return (): void => {alive = false}}, [])- const bridge = window.hermesDesktop?.uninstall+ const bridge: Window['hermesDesktop']['uninstall'] | undefined = window.hermesDesktop?.uninstall- if (!bridge) {+ if (!bridge || summary?.code_removal_allowed !== true) {return null}- // Gate the agent-removing options on whether an agent is actually present.- // A future lite client that ships without the bundled agent shows GUI-only.- const agentInstalled = summary?.agent_installed ?? false- const visibleOptions = OPTIONS.filter(opt => agentInstalled || !opt.needsAgent)+ // An owned GUI can remain after its local agent has been removed.+ const agentInstalled: boolean = summary.agent_installed+ const visibleOptions: ModeOption[] = OPTIONS.filter((opt: ModeOption): boolean => agentInstalled || !opt.needsAgent)- const handleConfirm = async () => {+ const handleConfirm = async (): Promise<void> => {if (!pending) {return}@@ -103,7 +97,7 @@ export function UninstallSection() {setError(null)try {- const result = await bridge.run(pending)+ const result: DesktopUninstallResult = await bridge.run(pending)if (!result.ok) {setError(result.message || result.error || 'Uninstall could not start.')@@ -118,19 +112,14 @@ export function UninstallSection() {}}- const pendingOption = OPTIONS.find(opt => opt.mode === pending) ?? null+ const pendingOption: ModeOption | null = OPTIONS.find((opt: ModeOption): boolean => opt.mode === pending) ?? nullreturn (<div className="mx-auto mt-8 w-full max-w-2xl"><SectionHeading icon={AlertTriangle} title="Danger zone" /><div className="rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3">- {loading ? (- <div className="flex items-center gap-2 py-2 text-sm text-muted-foreground">- <Loader2 className="size-3.5 animate-spin" />- Checking what's installed…- </div>- ) : pendingOption ? (+ {pendingOption ? (<div><p className="text-sm font-medium text-destructive">Confirm uninstall</p><p className="mt-1 text-xs text-muted-foreground">@@ -141,11 +130,11 @@ export function UninstallSection() {)}{error && <p className="mt-2 text-xs text-destructive">{error}</p>}<div className="mt-3 flex flex-wrap items-center gap-3">- <Button disabled={running} onClick={() => void handleConfirm()} size="sm" variant="destructive">+ <Button disabled={running} onClick={(): void => void handleConfirm()} size="sm" variant="destructive">{running && <Loader2 className="size-3 animate-spin" />}{running ? 'Uninstalling…' : 'Yes, uninstall'}</Button>- <Button disabled={running} onClick={() => setPending(null)} size="sm" variant="text">+ <Button disabled={running} onClick={(): void => setPending(null)} size="sm" variant="text">Cancel</Button></div>@@ -157,14 +146,14 @@ export function UninstallSection() {Choose how much to remove. The app closes to finish the job; reopen the installer any time to come back.</p><div className="mt-1 flex flex-col gap-2">- {visibleOptions.map(opt => (+ {visibleOptions.map((opt: ModeOption): ReactElement => (<buttonclassName={cn('flex items-start gap-3 rounded-lg border border-border/60 bg-background/40 px-3 py-2.5 text-left transition','hover:border-destructive/40 hover:bg-destructive/5')}key={opt.mode}- onClick={() => {+ onClick={(): void => {setError(null)setPending(opt.mode)}}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 7e5ea3a0a76..f2f7b750d75 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -711,6 +711,8 @@ export type RuntimeSource =export type DesktopUninstallMode = 'full' | 'gui' | 'lite'export interface DesktopUninstallSummary {+ /** Local package ownership, resolved by Electron before offering removal. */+ code_removal_allowed: booleanhermes_home: stringagent_installed: booleangui_installed: booleandiff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex 14e7c7f456e..a5025a94c8b 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -300,15 +300,17 @@ The [manual update process](https://hermes-agent.nousresearch.com/docs/getting-s## Uninstalling-Open **Settings → About → Danger zone** and pick how much to remove:+For installations managed by the app, open **Settings → About → Danger zone** and pick how much to remove:- **Uninstall Chat GUI only** — removes the desktop app and its data; the Hermes agent, your config, and your chats stay. (Same as `hermes uninstall --gui`.)- **Uninstall GUI + agent, keep my data** — removes the app and the agent but keeps config, chats, and secrets for a future reinstall. (Same as `hermes uninstall`.)- **Uninstall everything** — removes the app, the agent, and all user data. (Same as `hermes uninstall --full`.)-The app closes to finish the job (the cleanup runs after it exits so it can remove the running app bundle and its own venv). The agent-removing options are hidden automatically when no local agent is installed (for example, a GUI-only "lite" client connected to a remote backend).+The app closes to finish the job (the cleanup runs after it exits so it can remove the running app bundle and its own venv). The agent-removing options are hidden automatically when no local agent is installed.-You can do the same from the terminal — `hermes uninstall --gui` for the GUI alone, or `hermes uninstall` / `hermes uninstall --full` for the agent too.+These controls are hidden for Nix, bundled/Light packages, and other externally owned installations. Remove those through their package manager or the operating system instead. The app checks its own local package ownership, independently of a remote backend's update status. If ownership cannot be confirmed, no uninstall actions are offered.++For self-managed installations, you can do the same from the terminal — `hermes uninstall --gui` for the GUI alone, or `hermes uninstall` / `hermes uninstall --full` for the agent too.:::noteRunning `hermes uninstall --gui` from a **source checkout** (a `hermes desktop` dev build) also removes the workspace `node_modules` and `apps/desktop/{dist,release}` build output, since those are GUI build artifacts. They're recoverable with `hermes desktop` (or `npm install` + a rebuild) — but if you're actively hacking on the desktop app, expect to reinstall dependencies afterward.