The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): Managed updates section drives per-connection SSH updates
Tekniumbc4eea77739c
diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsxindex 9381930dddb..02d04b7ec2e 100644--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx@@ -4,6 +4,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const getConnectionConfig = vi.fn()const saveConnectionConfig = vi.fn()+// This test owns the machine-level GatewaySettings contract. The managed SSH+// update section mounted below the registry has its own focused coverage+// (store/managed-updates.test.ts); keep its store subscriptions out of this+// single-purpose test.+vi.mock('./managed-updates-section', () => ({ ManagedUpdatesSection: () => null }))+const localConnection = {cloudOrg: '',envOverride: false,diff --git a/apps/desktop/src/app/settings/gateway-settings.tsx b/apps/desktop/src/app/settings/gateway-settings.tsxindex 89b533e5561..4de24c278c5 100644--- a/apps/desktop/src/app/settings/gateway-settings.tsx+++ b/apps/desktop/src/app/settings/gateway-settings.tsx@@ -28,6 +28,7 @@ import { notify, notifyError, readableError } from '@/store/notifications'import { ConnectionsRegistrySection } from './connections-registry'import { CONTROL_TEXT } from './constants'+import { ManagedUpdatesSection } from './managed-updates-section'import { EmptyState, ListRow, Pill, SettingsContent, SettingsSkeleton, ToggleRow } from './primitives'import { enrichSelectedSshHost, selectSshHost } from './ssh-host-selection'@@ -1564,7 +1565,15 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {{/* Unified Gateways page: the full connections registry (add/edit/deletenamed agent sources) lives on this page now, below the windowconnection controls. Hidden in the embedded (boot-recovery) form. */}- {embedded ? null : <ConnectionsRegistrySection />}+ {embedded ? null : (+ <>+ <ConnectionsRegistrySection />+ {/* Per-connection driver for the transactional managed SSH update+ engine (#95942). Renders only when SSH sources are registered and+ the Electron main exposes connections.updateManaged. */}+ <ManagedUpdatesSection />+ </>+ )}{/* Plain-text token opt-in: gated when secure storage is unavailable and anew token would be persisted. Confirm resumes the remembered save/apply. */}diff --git a/apps/desktop/src/app/settings/managed-updates-section.tsx b/apps/desktop/src/app/settings/managed-updates-section.tsxnew file mode 100644index 00000000000..970448ff228--- /dev/null+++ b/apps/desktop/src/app/settings/managed-updates-section.tsx@@ -0,0 +1,151 @@+import { useStore } from '@nanostores/react'++import { Button } from '@/components/ui/button'+import type { DesktopRegistryConnection } from '@/global'+import { useI18n } from '@/i18n'+import { Download, Loader2 } from '@/lib/icons'+import { $connectionsRegistry } from '@/store/connections'+import {+ $managedUpdates,+ managedUpdatesSupported,+ type ManagedUpdateState,+ runManagedUpdate+} from '@/store/managed-updates'++import { ListRow, Pill, SectionHeading } from './primitives'++function stateTone(state: ManagedUpdateState | undefined): 'muted' | 'primary' | 'warn' {+ if (!state || state.status === 'idle') {+ return 'muted'+ }++ if (state.status === 'updating' || state.status === 'updated') {+ return 'primary'+ }++ return 'warn'+}++function sshTarget(connection: DesktopRegistryConnection): string | null {+ if (!connection.host) {+ return null+ }++ return connection.user ? `${connection.user}@${connection.host}` : connection.host+}++/** Per-connection driver for #95942's transactional SSH update engine: one+ * Update button per registered Desktop-managed SSH install, a single honest+ * in-flight state (the engine exposes no streaming progress channel), and the+ * correlated receipt once it lands. */+export function ManagedUpdatesSection() {+ const { t } = useI18n()+ const m = t.settings.managedUpdates+ const registry = useStore($connectionsRegistry)+ const states = useStore($managedUpdates)+ const sshConnections = (registry?.connections ?? []).filter(connection => connection.kind === 'ssh')++ // Fail closed: no section on an Electron main without the transactional+ // bridge, and nothing to drive when no SSH install is registered.+ if (!managedUpdatesSupported() || sshConnections.length === 0) {+ return null+ }++ const statusLabel = (state: ManagedUpdateState | undefined): string | null => {+ switch (state?.status) {+ case 'failed':+ return m.failed++ case 'partial':+ return m.partial++ case 'refused':+ return state.alreadyRunning ? m.alreadyRunning : m.refused++ case 'updated':+ return m.updated++ case 'updating':+ return m.updating++ default:+ return null+ }+ }++ const receiptLine = (state: ManagedUpdateState): string | null => {+ if (!state.receipt) {+ return null+ }++ const parts = [m.receipt(state.receipt.correlationId.slice(0, 8), state.receipt.outcome)]++ if (state.receipt.preVersion && state.receipt.postVersion) {+ parts.push(m.receiptVersions(state.receipt.preVersion, state.receipt.postVersion))+ }++ if (state.receipt.stopReason) {+ parts.push(state.receipt.stopReason)+ }++ return parts.join(' · ')+ }++ return (+ <section className="mt-8">+ <SectionHeading icon={Download} title={m.title} />+ <p className="mb-1 text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">+ {m.intro}+ </p>++ <div className="grid gap-1">+ {sshConnections.map(connection => {+ const state = states[connection.id]+ const updating = state?.status === 'updating'+ const label = statusLabel(state)+ const receipt = state ? receiptLine(state) : null+ const restored = state?.scopes.filter(scope => scope.restored).map(scope => scope.profile) ?? []+ const unrestored = state?.scopes.filter(scope => !scope.restored) ?? []++ return (+ <ListRow+ action={+ updating ? (+ <Button disabled size="sm" variant="secondary">+ <Loader2 className="animate-spin" /> {m.updating}+ </Button>+ ) : (+ <Button onClick={() => void runManagedUpdate(connection.id)} size="sm">+ <Download /> {m.update}+ </Button>+ )+ }+ below={+ state && (updating || state.message || receipt || state.scopes.length > 0) ? (+ <div className="mt-1 grid gap-1 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">+ {updating ? <p>{m.progress}</p> : null}+ {!updating && state.message ? <p>{state.message}</p> : null}+ {receipt ? <p className="font-mono text-[0.68rem]">{receipt}</p> : null}+ {!updating && restored.length > 0 ? <p>{m.scopesRestored(restored.join(', '))}</p> : null}+ {!updating &&+ unrestored.map(scope => (+ <p key={scope.profile}>{m.scopeNotRestored(scope.profile, scope.error ?? m.failed)}</p>+ ))}+ </div>+ ) : null+ }+ description={sshTarget(connection) ?? m.sshConnection}+ key={connection.id}+ title={+ <span className="flex items-center gap-2">+ <span>{connection.label}</span>+ {label ? <Pill tone={stateTone(state)}>{label}</Pill> : null}+ </span>+ }+ />+ )+ })}+ </div>+ </section>+ )+}diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 71ed354c07d..b88e0e7f2b1 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -813,6 +813,24 @@ export const en: Translations = {cancel: 'Cancel',empty: 'No connections registered yet.'},+ managedUpdates: {+ title: 'Managed updates',+ intro:+ 'Update Desktop-managed SSH installs transactionally: sessions drain, the remote checkout updates, and every profile is restored with a correlated receipt.',+ sshConnection: 'Desktop-managed SSH install',+ update: 'Update',+ updating: 'Updating…',+ progress: 'Draining sessions, updating the remote install, and restoring profiles…',+ updated: 'Updated',+ partial: 'Updated — restore failed',+ refused: 'Refused',+ failed: 'Update failed',+ alreadyRunning: 'Update already in progress',+ receipt: (id: string, outcome: string) => `Receipt ${id} · ${outcome}`,+ receiptVersions: (pre: string, post: string) => `${pre} → ${post}`,+ scopesRestored: (profiles: string) => `Restored profiles: ${profiles}`,+ scopeNotRestored: (profile: string, error: string) => `Profile “${profile}” not restored: ${error}`+ },gateway: {loading: 'Loading gateway settings...',unavailableTitle: 'Gateway settings unavailable',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex fe962a860e0..839190d470e 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -689,6 +689,23 @@ export interface Translations {cancel: stringempty: string}+ managedUpdates: {+ title: string+ intro: string+ sshConnection: string+ update: string+ updating: string+ progress: string+ updated: string+ partial: string+ refused: string+ failed: string+ alreadyRunning: string+ receipt: (id: string, outcome: string) => string+ receiptVersions: (pre: string, post: string) => string+ scopesRestored: (profiles: string) => string+ scopeNotRestored: (profile: string, error: string) => string+ }gateway: {loading: stringunavailableTitle: stringdiff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex e9640609314..3ac7ca162b6 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -1013,6 +1013,23 @@ export const zh: Translations = {cancel: '取消',empty: '尚未注册任何连接。'},+ managedUpdates: {+ title: '托管更新',+ intro: '以事务方式更新由桌面端托管的 SSH 安装:先排空会话,再更新远端检出,最后恢复每个 profile,并生成关联回执。',+ sshConnection: '桌面端托管的 SSH 安装',+ update: '更新',+ updating: '更新中…',+ progress: '正在排空会话、更新远端安装并恢复 profile…',+ updated: '已更新',+ partial: '已更新 — 恢复失败',+ refused: '已拒绝',+ failed: '更新失败',+ alreadyRunning: '更新已在进行中',+ receipt: (id: string, outcome: string) => `回执 ${id} · ${outcome}`,+ receiptVersions: (pre: string, post: string) => `${pre} → ${post}`,+ scopesRestored: (profiles: string) => `已恢复的 profile:${profiles}`,+ scopeNotRestored: (profile: string, error: string) => `Profile“${profile}”未恢复:${error}`+ },gateway: {loading: '正在加载网关设置...',unavailableTitle: '网关设置不可用',diff --git a/apps/desktop/src/store/managed-updates.test.ts b/apps/desktop/src/store/managed-updates.test.tsnew file mode 100644index 00000000000..7a1ba322dc7--- /dev/null+++ b/apps/desktop/src/store/managed-updates.test.ts@@ -0,0 +1,208 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { DesktopManagedConnectionUpdateResult } from '@/global'++const {+ $managedUpdates,+ _resetManagedUpdatesForTests,+ isManagedUpdateBusyMessage,+ managedUpdatesSupported,+ runManagedUpdate+} = await import('./managed-updates')++const updateManaged = vi.fn<(id: string) => Promise<DesktopManagedConnectionUpdateResult>>()++function managedResult(over: Partial<DesktopManagedConnectionUpdateResult> = {}): DesktopManagedConnectionUpdateResult {+ return {+ connectionId: 'linux-ssh',+ correlationId: '0c44e2da-993e-4d96-ab45-2d0f73365d61',+ exitCode: 0,+ ok: true,+ outcome: 'updated',+ receipt: {+ correlationId: '0c44e2da-993e-4d96-ab45-2d0f73365d61',+ outcome: 'success',+ postVersion: '1.1.0',+ preVersion: '1.0.0'+ },+ restoreOk: true,+ scopes: [{ profile: 'default', restored: true }],+ updateOk: true,+ ...over+ }+}++beforeEach(() => {+ _resetManagedUpdatesForTests()+ updateManaged.mockReset().mockResolvedValue(managedResult())+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = {+ connections: { updateManaged }+ }+})++describe('managedUpdatesSupported', () => {+ it('is false on an older Electron main without the transactional bridge', () => {+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = { connections: {} }+ expect(managedUpdatesSupported()).toBe(false)+ })++ it('is true when the preload bridge exposes updateManaged', () => {+ expect(managedUpdatesSupported()).toBe(true)+ })+})++describe('runManagedUpdate', () => {+ it('routes through the managed drain/update/restore bridge and lands on updated with the receipt', async () => {+ const pending = runManagedUpdate('linux-ssh')++ expect($managedUpdates.get()['linux-ssh']).toMatchObject({ status: 'updating' })++ const state = await pending++ expect(updateManaged).toHaveBeenCalledWith('linux-ssh')+ expect(state).toMatchObject({ alreadyRunning: false, connectionId: 'linux-ssh', status: 'updated' })+ expect(state.receipt).toMatchObject({+ correlationId: '0c44e2da-993e-4d96-ab45-2d0f73365d61',+ outcome: 'success',+ postVersion: '1.1.0'+ })+ expect($managedUpdates.get()['linux-ssh']).toMatchObject({ status: 'updated' })+ })++ it('joins a repeat click to the in-flight promise instead of double-dispatching', async () => {+ let resolve!: (value: DesktopManagedConnectionUpdateResult) => void+ updateManaged.mockReturnValue(+ new Promise<DesktopManagedConnectionUpdateResult>(next => {+ resolve = next+ })+ )++ const first = runManagedUpdate('linux-ssh')+ const second = runManagedUpdate('linux-ssh')++ expect(second).toBe(first)+ expect(updateManaged).toHaveBeenCalledTimes(1)++ resolve(managedResult())+ await expect(first).resolves.toMatchObject({ status: 'updated' })+ })++ it('keeps updated-but-restore-failed truthful as partial', async () => {+ updateManaged.mockResolvedValue(+ managedResult({+ error: 'work profile did not come back',+ ok: false,+ outcome: 'restore-failed',+ restoreOk: false,+ scopes: [+ { profile: 'default', restored: true },+ { error: 'ssh dial timed out', profile: 'work', restored: false }+ ]+ })+ )++ const state = await runManagedUpdate('linux-ssh')++ expect(state).toMatchObject({+ message: 'work profile did not come back',+ status: 'partial'+ })+ expect(state.scopes).toHaveLength(2)+ })++ it('surfaces the managed-update-in-progress refusal as busy, not a scary failure', async () => {+ updateManaged.mockResolvedValue(+ managedResult({+ message: 'A managed update is already in progress.',+ ok: false,+ outcome: 'refused',+ receipt: null,+ scopes: [],+ updateOk: false+ })+ )++ const state = await runManagedUpdate('linux-ssh')++ expect(state).toMatchObject({+ alreadyRunning: true,+ message: 'A managed update is already in progress.',+ status: 'refused'+ })+ })++ it('maps a thrown managed-update-in-progress IPC envelope to the same busy state', async () => {+ const error: Error & { code?: string } = new Error(+ "Error invoking remote method 'hermes:connections:update-managed': " ++ 'SSH connection "linux-ssh" is paused while its managed update is in progress.'+ )++ error.code = 'managed-update-in-progress'+ updateManaged.mockRejectedValue(error)++ const state = await runManagedUpdate('linux-ssh')++ expect(state).toMatchObject({ alreadyRunning: true, status: 'refused' })+ })++ it('keeps a non-busy refusal refused with its exact message', async () => {+ updateManaged.mockResolvedValue(+ managedResult({+ message: 'Only registered Desktop-managed SSH connections can use this update lifecycle.',+ ok: false,+ outcome: 'refused',+ receipt: null,+ updateOk: false+ })+ )++ const state = await runManagedUpdate('remote-a')++ expect(state).toMatchObject({+ alreadyRunning: false,+ message: 'Only registered Desktop-managed SSH connections can use this update lifecycle.',+ status: 'refused'+ })+ })++ it('lands a failed update on failed with the stop reason as fallback message', async () => {+ updateManaged.mockResolvedValue(+ managedResult({+ error: undefined,+ exitCode: 1,+ message: undefined,+ ok: false,+ outcome: 'update-failed',+ receipt: {+ correlationId: 'run-x',+ outcome: 'failed',+ stopReason: 'launcher exited 1'+ },+ restoreOk: true,+ updateOk: false+ })+ )++ const state = await runManagedUpdate('linux-ssh')++ expect(state).toMatchObject({ message: 'launcher exited 1', status: 'failed' })+ })++ it('fails closed when the bridge is missing instead of pretending to update', async () => {+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = { connections: {} }++ const state = await runManagedUpdate('linux-ssh')++ expect(state).toMatchObject({ status: 'failed' })+ expect(updateManaged).not.toHaveBeenCalled()+ })+})++describe('isManagedUpdateBusyMessage', () => {+ it('recognizes every busy-gate phrasing and rejects unrelated failures', () => {+ expect(isManagedUpdateBusyMessage('A managed update is already in progress.')).toBe(true)+ expect(isManagedUpdateBusyMessage('code managed-update-in-progress')).toBe(true)+ expect(isManagedUpdateBusyMessage('ssh dial timed out')).toBe(false)+ expect(isManagedUpdateBusyMessage(null)).toBe(false)+ })+})diff --git a/apps/desktop/src/store/managed-updates.ts b/apps/desktop/src/store/managed-updates.tsnew file mode 100644index 00000000000..39e45a9e9e1--- /dev/null+++ b/apps/desktop/src/store/managed-updates.ts@@ -0,0 +1,157 @@+import { atom } from 'nanostores'++import type { DesktopManagedConnectionUpdateResult, DesktopManagedUpdateReceipt } from '@/global'++/** Renderer-side lifecycle of one managed SSH update (#93042 renderer unit,+ * slimmed to what #95942's engine actually exposes today: a single+ * `connections.updateManaged(id)` promise that resolves with a correlated+ * result + receipt. There is no streaming progress channel, so the in-flight+ * phase is one `updating` state and every finer-grained outcome (partial+ * restore, refusal, per-profile recovery) comes from the terminal result). */+export type ManagedUpdateStatus = 'failed' | 'idle' | 'partial' | 'refused' | 'updated' | 'updating'++export interface ManagedUpdateState {+ /** True when the refusal was the busy gate: another managed update already+ * owns this connection (the `managed-update-in-progress` envelope). */+ alreadyRunning: boolean+ connectionId: string+ finishedAt: number | null+ message: string | null+ receipt: DesktopManagedUpdateReceipt | null+ scopes: DesktopManagedConnectionUpdateResult['scopes']+ status: ManagedUpdateStatus+}++export const $managedUpdates = atom<Record<string, ManagedUpdateState>>({})++const inFlight = new Map<string, Promise<ManagedUpdateState>>()++// The main process signals the busy gate two ways: a `refused` result whose+// message says an update is already in progress, and (from sibling IPC paths+// it pauses) a thrown error carrying code `managed-update-in-progress`.+const IN_PROGRESS_PATTERN = /managed[\s-]update[\s\w]*\bin[\s-]progress|managed-update-in-progress|already in progress/i++function managedUpdater(): ((id: string) => Promise<DesktopManagedConnectionUpdateResult>) | null {+ if (typeof window === 'undefined') {+ return null+ }++ return window.hermesDesktop?.connections?.updateManaged ?? null+}++/** Whether this Electron main exposes the transactional SSH update bridge.+ * Older mains without it hide the section entirely (fail closed, no fake+ * button that could mutate a live serve process). */+export function managedUpdatesSupported(): boolean {+ return Boolean(managedUpdater())+}++export function isManagedUpdateBusyMessage(message: string | null | undefined): boolean {+ return Boolean(message && IN_PROGRESS_PATTERN.test(message))+}++function publish(state: ManagedUpdateState): void {+ $managedUpdates.set({ ...$managedUpdates.get(), [state.connectionId]: state })+}++function blankState(connectionId: string): ManagedUpdateState {+ return {+ alreadyRunning: false,+ connectionId,+ finishedAt: null,+ message: null,+ receipt: null,+ scopes: [],+ status: 'idle'+ }+}++function terminalState(connectionId: string, result: DesktopManagedConnectionUpdateResult): ManagedUpdateState {+ const message = result.message || result.error || result.receipt?.stopReason || null+ const alreadyRunning = result.outcome === 'refused' && isManagedUpdateBusyMessage(message)++ const status: ManagedUpdateStatus = result.ok+ ? 'updated'+ : result.outcome === 'refused'+ ? 'refused'+ : result.updateOk && !result.restoreOk+ ? 'partial'+ : 'failed'++ return {+ alreadyRunning,+ connectionId,+ finishedAt: Date.now(),+ message,+ receipt: result.receipt ?? null,+ scopes: result.scopes ?? [],+ status+ }+}++/** Run one managed update. A repeat click while it is in flight joins the+ * existing promise — the main process gate would refuse a second start, and+ * the UI must not turn that self-collision into a scary failure row. */+export function runManagedUpdate(connectionId: string): Promise<ManagedUpdateState> {+ const existing = inFlight.get(connectionId)++ if (existing) {+ return existing+ }++ const updateManaged = managedUpdater()++ if (!updateManaged) {+ const state: ManagedUpdateState = {+ ...blankState(connectionId),+ finishedAt: Date.now(),+ status: 'failed'+ }++ publish(state)++ return Promise.resolve(state)+ }++ publish({ ...blankState(connectionId), status: 'updating' })++ const run = (async (): Promise<ManagedUpdateState> => {+ try {+ const result = await updateManaged(connectionId)+ const state = terminalState(connectionId, result)+ publish(state)++ return state+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error)++ const alreadyRunning =+ (error as { code?: unknown } | null)?.code === 'managed-update-in-progress' ||+ isManagedUpdateBusyMessage(message)++ const state: ManagedUpdateState = {+ ...blankState(connectionId),+ alreadyRunning,+ finishedAt: Date.now(),+ message,+ status: alreadyRunning ? 'refused' : 'failed'+ }++ publish(state)++ return state+ } finally {+ inFlight.delete(connectionId)+ }+ })()++ inFlight.set(connectionId, run)++ return run+}++/** @internal */+export function _resetManagedUpdatesForTests(): void {+ inFlight.clear()+ $managedUpdates.set({})+}