Skip to content

The agent that grows with you

fix(plugins): catalog installs keep the inspected commit; older backends ask; partial installs need Force

Tekniume0c52c4fbf39
diff --git a/apps/desktop/electron/desktop-plugin-install.test.ts b/apps/desktop/electron/desktop-plugin-install.test.ts
index f2dbfa304e5..d5dd660dcab 100644
--- a/apps/desktop/electron/desktop-plugin-install.test.ts
+++ b/apps/desktop/electron/desktop-plugin-install.test.ts
@@ -152,7 +152,10 @@ interface DetectionCase {
// Shared with the gateway's detector (tests/hermes_cli/test_plugins_cmd_inspect.py).
const DETECTION_CASES = (
JSON.parse(
- fs.readFileSync(path.resolve(here, '..', '..', '..', 'tests', 'fixtures', 'plugin_component_detection.json'), 'utf8')
+ fs.readFileSync(
+ path.resolve(here, '..', '..', '..', 'tests', 'fixtures', 'plugin_component_detection.json'),
+ 'utf8'
+ )
) as { cases: DetectionCase[] }
).cases
@@ -267,6 +270,24 @@ describe('installDesktopPluginFromGit', () => {
expect(fs.readFileSync(path.join(appRoot, result.pluginName!, 'panel.js'), 'utf8')).toBe('reviewed\n')
})
+ it('installs a reviewed catalog pin that names an annotated tag at the commit it points at', async () => {
+ const repo = pluginRepo(null, { 'panel.js': 'reviewed\n' })
+ const git = (...args: string[]) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' }).toString().trim()
+ const ident = ['-c', '[email protected]', '-c', 'user.name=Fixture']
+ git(...ident, 'tag', '-a', 'v1.0', '-m', 'v1.0')
+ fs.writeFileSync(path.join(repo, 'desktop', 'panel.js'), 'moved\n')
+ git(...ident, 'commit', '-qam', 'moved')
+ const tagObject = git('rev-parse', 'v1.0')
+ expect(tagObject).not.toBe(git('rev-parse', 'v1.0^{commit}'))
+ const appRoot = mkdtemp('hermes-plugin-root-')
+ roots.push(appRoot)
+
+ const result = await installDesktopPluginFromGit('git', pathToFileURL(repo).href, appRoot, false, tagObject)
+
+ expect(result).toMatchObject({ ok: true })
+ expect(fs.readFileSync(path.join(appRoot, result.pluginName!, 'panel.js'), 'utf8')).toBe('reviewed\n')
+ })
+
it('stamps the package marker on a unified package half and names the folder after the agent package', async () => {
// Without the marker the Plugins page has no evidence that this copy is the
// agent row's desktop half: the row sits on "copying…" while the copy shows
diff --git a/apps/desktop/electron/desktop-plugin-install.ts b/apps/desktop/electron/desktop-plugin-install.ts
index 526436f0aed..01fe28b0f3d 100644
--- a/apps/desktop/electron/desktop-plugin-install.ts
+++ b/apps/desktop/electron/desktop-plugin-install.ts
@@ -380,8 +380,8 @@ async function cloneToTemp(gitBin: string, gitUrl: string, subdir: string | null
const COMMIT_SHA = /^[0-9a-f]{40}$/
-async function headSha(gitBin: string, cloneRoot: string): Promise<string> {
- const { code, stdout, stderr } = await execGit(gitBin, ['rev-parse', 'HEAD'], {
+async function headSha(gitBin: string, cloneRoot: string, revision = 'HEAD'): Promise<string> {
+ const { code, stdout, stderr } = await execGit(gitBin, ['rev-parse', revision], {
cwd: cloneRoot,
env: noninteractiveGitEnv(),
timeoutMs: GIT_TIMEOUT_MS
@@ -409,7 +409,8 @@ async function checkoutReviewedCommit(gitBin: string, cloneRoot: string, sha: st
await runGitOrThrow(gitBin, ['checkout', '--detach', reviewed], cloneRoot)
}
- if ((await headSha(gitBin, cloneRoot)) !== reviewed) {
+ // A catalog pin may name an annotated tag: HEAD is the commit it peels to.
+ if ((await headSha(gitBin, cloneRoot)) !== (await headSha(gitBin, cloneRoot, `${reviewed}^{commit}`))) {
throw new Error(`HEAD is not ${reviewed}.`)
}
} catch (err) {
diff --git a/apps/desktop/src/app/settings/plugin-install-details.tsx b/apps/desktop/src/app/settings/plugin-install-details.tsx
index 18df5d52f0b..cce0c09aef2 100644
--- a/apps/desktop/src/app/settings/plugin-install-details.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-details.tsx
@@ -43,6 +43,8 @@ interface PluginInstallDetailsProps {
pin: PinState
force: boolean
onForceChange: (value: boolean) => void
+ /** Offer Force for a catalog pick too: a partial install proceeds only by replacing both halves. */
+ offerForce?: boolean
}
function Row({ label, children }: { label: string; children: ReactNode }) {
@@ -178,7 +180,7 @@ export function PluginInstallDetails(props: PluginInstallDetailsProps) {
</SelectContent>
</Select>
</Row>
- {!request.catalogName && (
+ {(!request.catalogName || props.offerForce) && (
<div>
<label className={cn(CAPTION, 'flex items-center justify-between gap-3 text-foreground')}>
<span>{copy.forceReinstall}</span>
diff --git a/apps/desktop/src/app/settings/plugin-install-modal.tsx b/apps/desktop/src/app/settings/plugin-install-modal.tsx
index 4b35c1ee3b0..c7e5cdb2eb3 100644
--- a/apps/desktop/src/app/settings/plugin-install-modal.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-modal.tsx
@@ -20,6 +20,7 @@ import { DisclosureCaret } from '@/components/ui/disclosure-caret'
import { Input } from '@/components/ui/input'
import { useI18n } from '@/i18n'
import { AlertTriangle, Loader2 } from '@/lib/icons'
+import { lookupPluginCatalogEntry } from '@/lib/plugin-catalog'
import { cn } from '@/lib/utils'
import { COMMIT_SHA_RE, inspectAgentPlugin } from '@/store/agent-plugins'
import {
@@ -37,6 +38,7 @@ import {
type InstallModalCopy,
type InstallOutcome,
type ProbeResult,
+ reviewedCommit,
runPluginInstall
} from './plugin-install-run'
import { usePluginProbe } from './use-plugin-probe'
@@ -274,15 +276,27 @@ function Disclosure({
interface InstallFooterProps {
canInstall: boolean
+ /** An older backend cannot hold the install to the reviewed commit: Install becomes "Install anyway". */
+ confirmUnreviewed: boolean
failed: boolean
installing: boolean
onInstall: () => void
+ onInstallAnyway: () => void
onRetry: () => void
retryable: boolean
}
/** Cancel, then Install (one loader while it runs) or, after a failure, Retry — unless retrying cannot help. */
-function InstallFooter({ canInstall, failed, installing, onInstall, onRetry, retryable }: InstallFooterProps) {
+function InstallFooter({
+ canInstall,
+ confirmUnreviewed,
+ failed,
+ installing,
+ onInstall,
+ onInstallAnyway,
+ onRetry,
+ retryable
+}: InstallFooterProps) {
const { t } = useI18n()
const m = t.settings.plugins.installModal
@@ -291,7 +305,9 @@ function InstallFooter({ canInstall, failed, installing, onInstall, onRetry, ret
<Button disabled={installing} onClick={closePluginInstallRequest} variant="outline">
{t.common.cancel}
</Button>
- {failed ? (
+ {confirmUnreviewed && !installing ? (
+ <Button onClick={onInstallAnyway}>{m.installAnyway}</Button>
+ ) : failed ? (
retryable && <Button onClick={onRetry}>{t.common.retry}</Button>
) : (
<Button disabled={!canInstall} onClick={onInstall}>
@@ -308,22 +324,97 @@ interface SourceMovedNoticeProps {
/** A failure on screen replaces the notice. */
failure: null | string
probe: null | ProbeResult
+ request: PluginInstallRequest
shown: boolean
}
-/** The source moved past the commit the user reviewed: name the commit the fresh inspection read. */
-function SourceMovedNotice({ copy, failure, probe, shown }: SourceMovedNoticeProps) {
+/** The source moved past the commit the user reviewed: name the commit the fresh review holds the install to. */
+function SourceMovedNotice({ copy, failure, probe, request, shown }: SourceMovedNoticeProps) {
if (!shown || failure) {
return null
}
return (
<p className={cn(CAPTION, 'text-(--ui-text-secondary)')} role="status">
- {copy.sourceMoved(probe?.ok ? (probe.sha?.slice(0, 12) ?? '') : '')}
+ {copy.sourceMoved(probe?.ok ? (reviewedCommit({ probe, request })?.slice(0, 12) ?? '') : '')}
</p>
)
}
+/** Read the source again after a refusal. A catalog pick whose pin the backend did not read (native Desktop
+ * inspects the branch tip in Electron) also takes the catalog's current pin, or every Install would resend
+ * the one the catalog left; `repin` is that lookup, which Install waits on. */
+function useReviewAgain(request: PluginInstallRequest, start: (repo: string) => void) {
+ const [repin, setRepin] = useState<Promise<void>>(() => Promise.resolve())
+
+ const reviewAgain = (current: ProbeResult) => {
+ start(request.repo)
+ const name = request.catalogName
+
+ if (name && !current.catalogPin) {
+ setRepin(
+ lookupPluginCatalogEntry(name).then(found => {
+ const open = $pluginInstallRequest.get()
+
+ if (found.ok && open?.catalogName === name) {
+ openPluginInstallRequest({ ...open, sha: found.entry.sha })
+ }
+ })
+ )
+ }
+ }
+
+ return { repin, reviewAgain }
+}
+
+interface InstallNoticesProps {
+ confirmUnreviewed: boolean
+ copy: InstallModalCopy
+ /** A failure on screen replaces the partial-install notice. */
+ failure: null | string
+ partial: null | string
+ uncertain: boolean
+}
+
+/** What the last Install left: only the agent half in, an older backend's missing guarantee, or no answer. */
+function InstallNotices({ confirmUnreviewed, copy, failure, partial, uncertain }: InstallNoticesProps) {
+ return (
+ <>
+ {partial && !failure && (
+ <p className={cn(CAPTION, 'text-destructive')} role="alert">
+ {partial}
+ </p>
+ )}
+ {confirmUnreviewed && (
+ <p className={cn(CAPTION, 'text-foreground')} role="alert">
+ {copy.legacyBackendConfirm}
+ </p>
+ )}
+ {uncertain && (
+ <p className={cn(CAPTION, 'text-(--ui-text-secondary)')} role="status">
+ {copy.installUncertain}
+ </p>
+ )}
+ </>
+ )
+}
+
+interface InstallGate {
+ force: boolean
+ installing: boolean
+ partial: null | string
+ pinInvalid: boolean
+ probe: null | ProbeResult
+ uncertain: boolean
+ verified: boolean
+}
+
+/** An unverified repository installs only once its contents are on screen; a reviewed pick may start at once.
+ * After a partial install only Force (a replacement of both halves) may proceed. */
+function installEnabled({ force, installing, partial, pinInvalid, probe, uncertain, verified }: InstallGate): boolean {
+ return !installing && !uncertain && !pinInvalid && (!partial || force) && (verified || Boolean(probe?.ok))
+}
+
interface InstallViewProps {
request: PluginInstallRequest
installing: boolean
@@ -358,6 +449,11 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
const [installUncertain, setInstallUncertain] = useState(false)
// The source moved past the commit on screen: the dialog read it again and shows the new one for review.
const [sourceMoved, setSourceMoved] = useState(false)
+ // The backend predates `inspected_sha` and installed nothing: Install waits for an explicit "Install anyway".
+ const [confirmUnreviewed, setConfirmUnreviewed] = useState(false)
+ // The agent half installed and the desktop half could not follow it: only a replacement of both proceeds.
+ const [partial, setPartial] = useState<null | string>(null)
+ const { repin, reviewAgain } = useReviewAgain(request, start)
useEffect(() => {
start(request.repo)
@@ -380,21 +476,31 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
const retryable = Boolean(installError) || !(probe?.unavailable || nothing)
const line = `${verified ? m.reviewedByNous : m.securityIntro} ${(enable ? m.installsAndEnables : m.installsOnly)(targetLabel)}`
- const install = async () => {
+ const install = async (withoutReviewedCommit = false) => {
onInstallingChange(true)
setInstallError(null)
setSourceMoved(false)
+ setConfirmUnreviewed(false)
try {
// A catalog pick may click Install while the inspection is still running: wait for it under the loader.
- const detected = await settled()
+ const [detected] = await Promise.all([settled(), repin])
if (!detected?.ok) {
return
}
const outcome = await runPluginInstall(
- { request, probe: detected, profile: targetProfile, enable, force, ref: pin || undefined, remote },
+ {
+ request: $pluginInstallRequest.get() ?? request,
+ probe: detected,
+ profile: targetProfile,
+ enable,
+ force,
+ ref: pin || undefined,
+ remote,
+ withoutReviewedCommit
+ },
{ copy: m, navigate, requestGateway }
)
@@ -405,8 +511,16 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
// Install waits on the new commit being on screen.
stale: () => {
setSourceMoved(true)
- start(request.repo)
+ reviewAgain(detected)
},
+ // Never install the desktop half beside it at another commit: show the source as it is now, and
+ // Install waits for Force reinstall, which replaces both halves with that version.
+ partial: () => {
+ setPartial((outcome as Extract<InstallOutcome, { status: 'partial' }>).error)
+ setAdvancedOpen(true)
+ reviewAgain(detected)
+ },
+ needsConfirm: () => setConfirmUnreviewed(true),
failed: () => setInstallError((outcome as Extract<InstallOutcome, { status: 'failed' }>).error)
}
@@ -424,8 +538,15 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
}
}
- // An unverified repository installs only once its contents are on screen; a reviewed pick may start at once.
- const canInstall = !installing && !installUncertain && !pinInvalid && (verified || Boolean(probe?.ok))
+ const canInstall = installEnabled({
+ force,
+ installing,
+ partial,
+ pinInvalid,
+ probe,
+ uncertain: installUncertain,
+ verified
+ })
return (
<>
@@ -439,6 +560,7 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
busy={installing}
copy={m}
force={force}
+ offerForce={Boolean(partial)}
onForceChange={setForce}
pin={{ value: pinRef, invalid: pinInvalid, onChange: setPinRef }}
probe={probe}
@@ -458,19 +580,23 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
{failure}
</p>
)}
- <SourceMovedNotice copy={m} failure={failure} probe={probe} shown={sourceMoved} />
- {installUncertain && (
- <p className={cn(CAPTION, 'text-(--ui-text-secondary)')} role="status">
- {m.installUncertain}
- </p>
- )}
+ <SourceMovedNotice copy={m} failure={failure} probe={probe} request={request} shown={sourceMoved} />
+ <InstallNotices
+ confirmUnreviewed={confirmUnreviewed}
+ copy={m}
+ failure={failure}
+ partial={partial}
+ uncertain={installUncertain}
+ />
</div>
<InstallFooter
canInstall={canInstall}
+ confirmUnreviewed={confirmUnreviewed}
failed={Boolean(failure)}
installing={installing}
onInstall={() => void install()}
+ onInstallAnyway={() => void install(true)}
onRetry={retry}
retryable={retryable}
/>
diff --git a/apps/desktop/src/app/settings/plugin-install-review-guards.test.tsx b/apps/desktop/src/app/settings/plugin-install-review-guards.test.tsx
new file mode 100644
index 00000000000..195d926d0be
--- /dev/null
+++ b/apps/desktop/src/app/settings/plugin-install-review-guards.test.tsx
@@ -0,0 +1,277 @@
+import { JsonRpcGatewayError } from '@hermes/shared'
+import { QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { MemoryRouter } from 'react-router'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// What an install dialog may put down besides the commit it showed: only what the user explicitly chose.
+// An older backend that cannot hold the install to that commit asks first; a catalog pick is held to the
+// pin the backend read; a package whose desktop half could not follow its agent half never gets that half
+// at another commit without a replacement of both.
+const { requestGateway } = vi.hoisted(() => ({
+ requestGateway: vi.fn(async (_method: string, _params?: Record<string, unknown>): Promise<unknown> => ({
+ plugins: []
+ }))
+}))
+
+vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({
+ useGatewayRequest: () => ({ requestGateway })
+}))
+const { lookupPluginCatalogEntry } = vi.hoisted(() => ({ lookupPluginCatalogEntry: vi.fn() }))
+
+vi.mock('@/lib/plugin-catalog', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ lookupPluginCatalogEntry
+}))
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getProfiles: async () => ({ profiles: [] })
+}))
+
+import { queryClient } from '@/lib/query-client'
+import { $notifications } from '@/store/notifications'
+import {
+ $pluginInstallRequest,
+ closePluginInstallRequest,
+ openPluginInstallRequest
+} from '@/store/plugin-install-request'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection, $gatewayState } from '@/store/session'
+
+import { PluginInstallModal } from './plugin-install-modal'
+
+const V1 = 'e404b6816b20237a82f6fbe2749b5a576cf75dba'
+const V2 = '0a415bc5c1d2e3f405162738495a6b7c8d9e0f1a'
+const REPO = 'https://github.com/example/pkg'
+
+const ADMISSION_REFUSAL =
+ 'invalid params for plugins.manage: inspected_sha: Extra inputs are not permitted — the client and the ' +
+ 'Hermes backend are out of sync (different versions); run `hermes update` and restart both'
+
+const callsFor = (action: string) =>
+ requestGateway.mock.calls.filter(([method, params]) => method === 'plugins.manage' && params?.action === action)
+
+const installButton = () => screen.queryByRole('button', { name: /^Install$|^Installing/ }) as HTMLButtonElement | null
+
+const renderModal = () =>
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <QueryClientProvider client={queryClient}>
+ <PluginInstallModal />
+ </QueryClientProvider>
+ </MemoryRouter>
+ )
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ queryClient.clear()
+ closePluginInstallRequest()
+ $notifications.set([])
+ $gatewayState.set('idle')
+ $connection.set({ mode: 'remote' } as NonNullable<ReturnType<typeof $connection.get>>)
+ $activeGatewayProfile.set('default')
+})
+afterEach(() => {
+ cleanup()
+ closePluginInstallRequest()
+ vi.unstubAllGlobals()
+ delete window.document.documentElement.dataset.hermesDesktopHost
+})
+
+describe('a backend that predates inspected_sha', () => {
+ const olderBackend = () =>
+ requestGateway.mockImplementation(async (method, params) => {
+ if (method !== 'plugins.manage') {
+ return { plugins: [] }
+ }
+
+ if (params?.action === 'inspect') {
+ return { ok: true, agent: true, agent_name: 'pkg', desktop: false, sha: V1, warnings: [] }
+ }
+
+ if (params?.action === 'install') {
+ if ('inspected_sha' in params) {
+ throw new JsonRpcGatewayError(ADMISSION_REFUSAL, { code: 4000 })
+ }
+
+ return { ok: true, plugin_name: 'pkg' }
+ }
+
+ return { plugins: [] }
+ })
+
+ it('explains the missing guarantee and installs nothing until the user confirms', async () => {
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ olderBackend()
+
+ renderModal()
+ act(() => openPluginInstallRequest({ profile: 'research', repo: REPO }))
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+
+ expect(await screen.findByText(/cannot guarantee that the version you reviewed/)).toBeTruthy()
+ expect(screen.getByText(/Update the backend to get that guarantee/)).toBeTruthy()
+ expect(callsFor('install')).toHaveLength(1)
+ expect($pluginInstallRequest.get()).not.toBeNull()
+ expect($notifications.get().filter(n => n.kind === 'success')).toEqual([])
+
+ fireEvent.click(screen.getByRole('button', { name: 'Install anyway' }))
+
+ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())
+ const [, anyway] = callsFor('install')[1]
+ expect(anyway).not.toHaveProperty('inspected_sha')
+ expect(anyway).toMatchObject({ identifier: REPO, profile: 'research' })
+ })
+
+ it('Cancel leaves nothing installed', async () => {
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ olderBackend()
+
+ renderModal()
+ act(() => openPluginInstallRequest({ repo: REPO }))
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+ await screen.findByRole('button', { name: 'Install anyway' })
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ expect($pluginInstallRequest.get()).toBeNull()
+ expect(callsFor('install')).toHaveLength(1)
+ })
+})
+
+describe('native Desktop on a remote backend: the desktop half cannot follow the agent half', () => {
+ it('reports a partial install and replaces both halves only once Force is on', async () => {
+ let tip = V1
+
+ requestGateway.mockImplementation(async (method, params) => {
+ if (method === 'plugins.manage' && params?.action === 'install') {
+ return params.force || !callsFor('install').slice(0, -1).length
+ ? { ok: true, plugin_name: 'pkg' }
+ : { ok: false, error: "Plugin 'pkg' already exists." }
+ }
+
+ return { plugins: [] }
+ })
+
+ const probePluginRepo = vi.fn(async () => ({
+ ok: true,
+ agent: true,
+ agentName: 'pkg',
+ desktop: true,
+ desktopName: 'pkg',
+ sha: tip,
+ warnings: []
+ }))
+
+ const installDesktopPlugin = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: false,
+ sourceMoved: true,
+ error: 'The commit you reviewed could not be checked out.'
+ })
+ .mockResolvedValue({ ok: true, pluginName: 'pkg' })
+
+ vi.stubGlobal('hermesDesktop', { installDesktopPlugin, probePluginRepo })
+
+ renderModal()
+ act(() => openPluginInstallRequest({ repo: REPO }))
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ tip = V2
+ fireEvent.click(installButton()!)
+
+ // The agent half is in at V1, the desktop half is not: said so, never a clean "review again".
+ expect(await screen.findByText(new RegExp(`agent half is in at commit ${V1.slice(0, 12)}`))).toBeTruthy()
+ await waitFor(() => expect(probePluginRepo).toHaveBeenCalledTimes(2))
+ expect(installButton()?.disabled).toBe(true)
+ fireEvent.click(installButton()!)
+ expect(installDesktopPlugin).toHaveBeenCalledTimes(1)
+
+ fireEvent.click(screen.getByRole('switch'))
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+
+ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())
+ expect(callsFor('install').map(([, params]) => [params?.inspected_sha, params?.force])).toEqual([
+ [V1, false],
+ [V2, true]
+ ])
+ expect(installDesktopPlugin.mock.calls.map(([payload]) => [payload.sha, payload.force])).toEqual([
+ [V1, false],
+ [V2, true]
+ ])
+ })
+})
+
+describe('a catalog pick is held to the pin the dialog showed', () => {
+ const catalogBackend = (refuseUnless?: () => string) =>
+ requestGateway.mockImplementation(async (method, params) => {
+ if (method === 'plugins.manage' && params?.action === 'inspect') {
+ return { ok: true, agent: true, agent_name: 'pkg', desktop: false, sha: V1, warnings: [] }
+ }
+
+ if (method === 'plugins.manage' && params?.action === 'install') {
+ if (refuseUnless && params.inspected_sha !== refuseUnless()) {
+ throw new JsonRpcGatewayError('The source changed since you reviewed it.', {
+ code: 5026,
+ data: { reason: 'source_moved' }
+ })
+ }
+
+ return { ok: true, plugin_name: 'pkg' }
+ }
+
+ return { plugins: [] }
+ })
+
+ const openCatalog = () => act(() => openPluginInstallRequest({ catalogName: 'pkg', repo: REPO, sha: V1 }))
+
+ it('browser-hosted: the commit the backend read at the catalog pin', async () => {
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ catalogBackend()
+
+ renderModal()
+ openCatalog()
+ await waitFor(() => expect(callsFor('inspect')).toHaveLength(1))
+ fireEvent.click(installButton()!)
+
+ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())
+ expect(callsFor('install')[0][1]).toMatchObject({ catalog_name: 'pkg', inspected_sha: V1 })
+ })
+
+ it("native Desktop: the reviewed pin, never the branch tip Electron's probe read", async () => {
+ catalogBackend()
+ const probePluginRepo = vi.fn(async () => ({ ok: true, agent: true, desktop: false, sha: V2, warnings: [] }))
+ vi.stubGlobal('hermesDesktop', { probePluginRepo })
+
+ renderModal()
+ openCatalog()
+ await waitFor(() => expect(probePluginRepo).toHaveBeenCalledTimes(1))
+ fireEvent.click(installButton()!)
+
+ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())
+ expect(callsFor('install')[0][1]).toMatchObject({ catalog_name: 'pkg', inspected_sha: V1 })
+ })
+
+ it('native Desktop: a re-pin since the dialog opened is refused, and the next Install holds the new pin', async () => {
+ const pin = { current: V1 }
+ catalogBackend(() => pin.current)
+ lookupPluginCatalogEntry.mockImplementation(async () => ({ ok: true, entry: { name: 'pkg', sha: pin.current } }))
+ const probePluginRepo = vi.fn(async () => ({ ok: true, agent: true, desktop: false, sha: V2, warnings: [] }))
+ vi.stubGlobal('hermesDesktop', { probePluginRepo })
+
+ renderModal()
+ openCatalog()
+ await waitFor(() => expect(probePluginRepo).toHaveBeenCalledTimes(1))
+ pin.current = V2 // the catalog re-pins while the dialog is open
+ fireEvent.click(installButton()!)
+
+ expect(await screen.findByText(new RegExp(`Review the new version \\(commit ${V2.slice(0, 12)}\\)`))).toBeTruthy()
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+
+ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())
+ expect(callsFor('install').map(([, params]) => params?.inspected_sha)).toEqual([V1, V2])
+ })
+})
diff --git a/apps/desktop/src/app/settings/plugin-install-run.ts b/apps/desktop/src/app/settings/plugin-install-run.ts
index aadb03898e4..5d4531c2428 100644
--- a/apps/desktop/src/app/settings/plugin-install-run.ts
+++ b/apps/desktop/src/app/settings/plugin-install-run.ts
@@ -69,6 +69,8 @@ export interface InstallPlan {
force: boolean
ref?: string
remote: boolean
+ /** The user chose "Install anyway" on a backend that cannot hold the agent half to the reviewed commit. */
+ withoutReviewedCommit?: boolean
}
export interface InstallDeps {
@@ -78,11 +80,16 @@ export interface InstallDeps {
}
/** `stale`: a half was refused because the source left the commit the dialog showed. Retrying would resend
- * that commit and fail forever, so the dialog reads the source again and shows the new commit first. */
+ * that commit and fail forever, so the dialog reads the source again and shows the new commit first.
+ * `partial`: the agent half installed at the reviewed commit, then the desktop half was refused because the
+ * source left it; only a replacement of both halves may follow. `needsConfirm`: the backend cannot hold the
+ * install to the reviewed commit and installed nothing; the user decides whether to install anyway. */
export type InstallOutcome =
| { error: string; status: 'failed' }
+ | { error: string; status: 'partial' }
| { error: string; status: 'stale' }
| { status: 'done' }
+ | { status: 'needsConfirm' }
| { status: 'uncertain' }
interface Report {
@@ -123,6 +130,15 @@ function notifyAgentFollowUps(result: AgentPluginInstallResult, name: string, de
}
}
+/** The commit the dialog showed, which both halves are held to: a branch that moved, or a catalog entry
+ * re-pinned, since must not install a tree nobody reviewed. A catalog pick shows its reviewed pin
+ * (`request.sha`), unless the backend read the entry at that pin (`probe.catalogPin`: the browser-hosted
+ * app), whose commit a re-inspection re-reads. Electron's probe reads the branch tip, which a catalog
+ * install never checks out. */
+export function reviewedCommit({ probe, request }: Pick<InstallPlan, 'probe' | 'request'>): string | undefined {
+ return !request.catalogName || probe.catalogPin ? probe.sha : request.sha
+}
+
async function installAgentHalf(plan: InstallPlan, deps: InstallDeps, report: Report) {
const { request } = plan
@@ -132,9 +148,7 @@ async function installAgentHalf(plan: InstallPlan, deps: InstallDeps, report: Re
enable: plan.enable,
catalogName: request.catalogName,
ref: plan.ref,
- // The commit the dialog showed: a branch that moved since must not install a tree nobody reviewed.
- // A catalog pick installs at the catalog's own pin.
- inspectedSha: request.catalogName ? undefined : plan.probe.sha,
+ inspectedSha: plan.withoutReviewedCommit ? undefined : reviewedCommit(plan),
profile: plan.profile
})
@@ -155,7 +169,12 @@ async function installAgentHalf(plan: InstallPlan, deps: InstallDeps, report: Re
return result
}
-async function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, report: Report, deps: InstallDeps): Promise<void> {
+async function cloneDesktopHalf(
+ plan: InstallPlan,
+ copy: InstallModalCopy,
+ report: Report,
+ deps: InstallDeps
+): Promise<void> {
// Native Desktop clones it in Electron; a browser-hosted tab asks the host that serves it, and the
// plugin lands in the folder this Webapp already loads. A tab installing a package's agent half never
// clones the desktop half here: the host copies it out of that one checkout (`desktopHalfFromPackage`).
@@ -163,16 +182,16 @@ async function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, repor
const result: { error?: string; ok: boolean; pluginName?: string; sourceMoved?: boolean; unsupported?: boolean } =
installFn
- ? await installFn({ identifier: plan.request.repo, force: plan.force, sha: plan.ref ?? plan.probe.sha })
- : await installDesktopPluginHalf(deps.requestGateway, {
- identifier: plan.request.repo,
- catalogName: plan.request.catalogName,
- force: plan.force,
- profile: plan.profile,
- // The pin the user typed, else the commit the dialog showed: the host installs exactly that tree
- // or refuses.
- ref: plan.ref ?? plan.probe.sha
- })
+ ? await installFn({ identifier: plan.request.repo, force: plan.force, sha: plan.ref ?? reviewedCommit(plan) })
+ : await installDesktopPluginHalf(deps.requestGateway, {
+ identifier: plan.request.repo,
+ catalogName: plan.request.catalogName,
+ force: plan.force,
+ profile: plan.profile,
+ // The pin the user typed, else the commit the dialog showed: the host installs exactly that tree
+ // or refuses.
+ ref: plan.ref ?? reviewedCommit(plan)
+ })
if (!result.ok) {
// A backend older than this build has no place to put the half: say what this environment can do,
@@ -245,6 +264,42 @@ async function installDesktopHalf(
}
}
+/** An agent-half answer after which nothing else may install. A client timeout is `uncertain`: the backend
+ * may still be installing. A refusal because the source moved means nothing from that review installs, not
+ * the other half either. An older backend refusing the reviewed commit at admission installed nothing:
+ * the user decides. */
+function agentStopsInstall(
+ result: AgentPluginInstallResult,
+ plan: InstallPlan,
+ deps: InstallDeps,
+ report: Report
+): InstallOutcome | null {
+ if (result.timedOut) {
+ void loadAgentPlugins(deps.requestGateway, plan.profile)
+
+ return { status: 'uncertain' }
+ }
+
+ if (result.sourceMoved) {
+ return { status: 'stale', error: report.errors.join(' ') }
+ }
+
+ return result.inspectedShaUnsupported ? { status: 'needsConfirm' } : null
+}
+
+/** The outcome of an install that reported errors. The agent half in at the reviewed commit while the desktop
+ * half could not follow it is `partial`: a fresh review would lead the next Install to put the desktop half
+ * down at another commit beside it. */
+function failedOutcome(plan: InstallPlan, deps: InstallDeps, report: Report, agentInstalled: boolean): InstallOutcome {
+ if (agentInstalled && report.sourceMoved) {
+ const sha = plan.withoutReviewedCommit ? '' : (reviewedCommit(plan)?.slice(0, 12) ?? '')
+
+ return { status: 'partial', error: deps.copy.partialInstall(sha) }
+ }
+
+ return { status: report.sourceMoved ? 'stale' : 'failed', error: report.errors.join(' ') }
+}
+
/** Install every half `installComponents` picks, then refresh the inventory. A client timeout on the agent
* half is `uncertain`: the backend may still be installing, so nothing else starts. */
export async function runPluginInstall(plan: InstallPlan, deps: InstallDeps): Promise<InstallOutcome> {
@@ -256,16 +311,10 @@ export async function runPluginInstall(plan: InstallPlan, deps: InstallDeps): Pr
const report: Report = { errors: [], successes: [], sourceMoved: false }
const agentResult = components.agent ? await installAgentHalf(plan, deps, report) : undefined
+ const stopped = agentResult && agentStopsInstall(agentResult, plan, deps, report)
- if (agentResult?.timedOut) {
- void loadAgentPlugins(deps.requestGateway, plan.profile)
-
- return { status: 'uncertain' }
- }
-
- // Nothing from a review the source has moved past is installed: not the other half either.
- if (agentResult?.sourceMoved) {
- return { status: 'stale', error: report.errors.join(' ') }
+ if (stopped) {
+ return stopped
}
if (components.desktop) {
@@ -283,7 +332,7 @@ export async function runPluginInstall(plan: InstallPlan, deps: InstallDeps): Pr
}
if (report.errors.length > 0) {
- return { status: report.sourceMoved ? 'stale' : 'failed', error: report.errors.join(' ') }
+ return failedOutcome(plan, deps, report, Boolean(agentResult?.ok))
}
// Open chats of the profile already have the plugin's MCP tools and skills; say which servers did not connect.
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 183784e7736..76e2ffa92f9 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -658,6 +658,8 @@ declare global {
insecure?: boolean
/** The commit that was inspected; an install of this source is held to it. */
sha?: string
+ /** The backend read the catalog entry at its pin (`inspectAgentPlugin`); never set by Electron's probe. */
+ catalogPin?: boolean
/** Inspection itself is missing here (not a failed read): Retry cannot help. */
unavailable?: boolean
error?: string
@@ -776,8 +778,7 @@ export interface HermesPluginFolderGrant {
}
export type HermesPluginFilesResult<T extends object = Record<string, unknown>> =
- | ({ ok: true } & T)
- | { ok: false; error: string; message: string }
+ ({ ok: true } & T) | { ok: false; error: string; message: string }
export interface DesktopMarketplaceSearchItem {
extensionId: string
diff --git a/apps/desktop/src/i18n/ar_settings.ts b/apps/desktop/src/i18n/ar_settings.ts
index ce6a30fc072..425fc8ddc9a 100644
--- a/apps/desktop/src/i18n/ar_settings.ts
+++ b/apps/desktop/src/i18n/ar_settings.ts
@@ -229,6 +229,13 @@ export const arSettings = {
sha
? `تغيّر المستودع منذ مراجعتك له. راجع الإصدار الجديد (الإيداع ${sha}) قبل تثبيته.`
: 'تغيّر المستودع منذ مراجعتك له. جارٍ قراءة الإصدار الجديد…',
+ legacyBackendConfirm:
+ 'هذه الواجهة الخلفية أقدم من هذا التطبيق، لذا لا يمكنها ضمان أن يكون الإصدار الذي راجعته هو ما سيُثبَّت: إذا تغيّر المستودع منذ ذلك الحين، فسيُثبَّت الإصدار الأحدث بدلًا منه. حدّث الواجهة الخلفية للحصول على هذا الضمان.',
+ installAnyway: 'ثبّت على أي حال',
+ partialInstall: sha =>
+ sha
+ ? `لم يُثبَّت سوى جزء من هذه الإضافة: جزء الوكيل مثبَّت عند الإيداع ${sha}، لكن جزء سطح المكتب لم يتمكن من اللحاق به لأن المستودع تغيّر منذ مراجعتك له. فعّل فرض إعادة التثبيت ضمن «متقدم» لاستبدال الجزأين بالإصدار المعروض، أو ألغِ للإبقاء على جزء الوكيل وحده.`
+ : 'لم يُثبَّت سوى جزء من هذه الإضافة: جزء الوكيل مثبَّت، لكن جزء سطح المكتب لم يتمكن من اللحاق به لأن المستودع تغيّر منذ مراجعتك له. فعّل فرض إعادة التثبيت ضمن «متقدم» لاستبدال الجزأين بالإصدار المعروض، أو ألغِ للإبقاء على جزء الوكيل وحده.',
nothingToInstall: 'لا تحتوي هذه الحزمة على ما يُثبَّت هنا.'
}
},
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index 1b5f2040d8c..896e5d12a18 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -846,6 +846,13 @@ export const deOverrides = {
sha
? `Das Repository hat sich seit deiner Prüfung geändert. Prüfe die neue Version (Commit ${sha}), bevor du sie installierst.`
: 'Das Repository hat sich seit deiner Prüfung geändert. Die neue Version wird gelesen…',
+ legacyBackendConfirm:
+ 'Dieses Backend ist älter als diese App und kann nicht garantieren, dass genau die geprüfte Version installiert wird: Hat sich das Repository seitdem geändert, wird stattdessen die neuere Version installiert. Aktualisiere das Backend, um diese Garantie zu bekommen.',
+ installAnyway: 'Trotzdem installieren',
+ partialInstall: sha =>
+ sha
+ ? `Das Plugin ist nur teilweise installiert: Der Agent-Teil ist mit Commit ${sha} installiert, der Desktop-Teil konnte nicht folgen, weil sich das Repository seit deiner Prüfung geändert hat. Aktiviere unter „Erweitert“ die erzwungene Neuinstallation, um beide Teile durch die angezeigte Version zu ersetzen, oder brich ab, um nur den Agent-Teil zu behalten.`
+ : 'Das Plugin ist nur teilweise installiert: Der Agent-Teil ist installiert, der Desktop-Teil konnte nicht folgen, weil sich das Repository seit deiner Prüfung geändert hat. Aktiviere unter „Erweitert“ die erzwungene Neuinstallation, um beide Teile durch die angezeigte Version zu ersetzen, oder brich ab, um nur den Agent-Teil zu behalten.',
nothingToInstall: 'Dieses Paket hat hier nichts zu installieren.'
}
},
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 74609d87514..6aac52c6d4f 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -799,6 +799,13 @@ export const en: Translations = {
sha
? `The repository changed since you reviewed it. Review the new version (commit ${sha}) before installing it.`
: 'The repository changed since you reviewed it. Reading the new version…',
+ legacyBackendConfirm:
+ 'This backend is older than this app, so it cannot guarantee that the version you reviewed is the one that gets installed: if the repository changed since, the newer version installs instead. Update the backend to get that guarantee.',
+ installAnyway: 'Install anyway',
+ partialInstall: sha =>
+ sha
+ ? `Only part of this plugin is installed: the agent half is in at commit ${sha}, but the desktop half could not follow because the repository changed since you reviewed it. Turn on Force reinstall under Advanced to replace both halves with the version shown, or Cancel to keep only the agent half.`
+ : 'Only part of this plugin is installed: the agent half is in, but the desktop half could not follow because the repository changed since you reviewed it. Turn on Force reinstall under Advanced to replace both halves with the version shown, or Cancel to keep only the agent half.',
nothingToInstall: 'This package has nothing to install here.',
includesHeading: 'This package includes',
agentLabel: 'Agent plugin',
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index 4d644e853fd..3b5935378e0 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -849,6 +849,13 @@ export const esOverrides = {
sha
? `El repositorio cambió desde que lo revisaste. Revisa la nueva versión (commit ${sha}) antes de instalarla.`
: 'El repositorio cambió desde que lo revisaste. Leyendo la nueva versión…',
+ legacyBackendConfirm:
+ 'Este backend es más antiguo que esta aplicación y no puede garantizar que se instale la versión que revisaste: si el repositorio cambió desde entonces, se instala la versión más nueva. Actualiza el backend para tener esa garantía.',
+ installAnyway: 'Instalar de todos modos',
+ partialInstall: sha =>
+ sha
+ ? `El plugin solo se instaló en parte: la parte del agente está instalada en el commit ${sha}, pero la parte de escritorio no pudo seguirla porque el repositorio cambió desde que lo revisaste. Activa Forzar reinstalación en Avanzado para reemplazar ambas partes por la versión mostrada, o cancela para quedarte solo con la parte del agente.`
+ : 'El plugin solo se instaló en parte: la parte del agente está instalada, pero la parte de escritorio no pudo seguirla porque el repositorio cambió desde que lo revisaste. Activa Forzar reinstalación en Avanzado para reemplazar ambas partes por la versión mostrada, o cancela para quedarte solo con la parte del agente.',
nothingToInstall: 'Este paquete no tiene nada que instalar aquí.'
}
},
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index fefb9443006..84b90508fc4 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -848,6 +848,13 @@ export const frOverrides = {
sha
? `Le dépôt a changé depuis votre examen. Examinez la nouvelle version (commit ${sha}) avant de l'installer.`
: 'Le dépôt a changé depuis votre examen. Lecture de la nouvelle version…',
+ legacyBackendConfirm:
+ 'Ce backend est plus ancien que cette application : il ne peut pas garantir que la version examinée est celle qui sera installée. Si le dépôt a changé depuis, c\'est la version plus récente qui s\'installe. Mettez à jour le backend pour obtenir cette garantie.',
+ installAnyway: 'Installer quand même',
+ partialInstall: sha =>
+ sha
+ ? `Le plugin n'est installé qu'en partie : la partie agent est installée au commit ${sha}, mais la partie bureau n'a pas pu suivre car le dépôt a changé depuis votre examen. Activez Forcer la réinstallation dans Avancé pour remplacer les deux parties par la version affichée, ou annulez pour ne garder que la partie agent.`
+ : 'Le plugin n\'est installé qu\'en partie : la partie agent est installée, mais la partie bureau n\'a pas pu suivre car le dépôt a changé depuis votre examen. Activez Forcer la réinstallation dans Avancé pour remplacer les deux parties par la version affichée, ou annulez pour ne garder que la partie agent.',
nothingToInstall: 'Ce paquet n’a rien à installer ici.'
}
},
diff --git a/apps/desktop/src/i18n/ja_plugins.ts b/apps/desktop/src/i18n/ja_plugins.ts
index 79cb2890f7a..f8465af7e4e 100644
--- a/apps/desktop/src/i18n/ja_plugins.ts
+++ b/apps/desktop/src/i18n/ja_plugins.ts
@@ -41,6 +41,13 @@ export const jaPluginSettings = {
sha
? `レビュー後にリポジトリが変更されました。インストールする前に新しいバージョン(コミット ${sha})を確認してください。`
: 'レビュー後にリポジトリが変更されました。新しいバージョンを読み込んでいます…',
+ legacyBackendConfirm:
+ 'このバックエンドはこのアプリより古いため、レビューしたバージョンがそのままインストールされることを保証できません。その後リポジトリが変更されていれば、新しいバージョンがインストールされます。この保証を得るにはバックエンドを更新してください。',
+ installAnyway: 'このままインストール',
+ partialInstall: sha =>
+ sha
+ ? `プラグインは一部だけインストールされました。エージェント部分はコミット ${sha} でインストール済みですが、レビュー後にリポジトリが変更されたため、デスクトップ部分は続けてインストールできませんでした。「詳細」で強制再インストールをオンにすると両方を表示中のバージョンに置き換えます。キャンセルするとエージェント部分だけが残ります。`
+ : 'プラグインは一部だけインストールされました。エージェント部分はインストール済みですが、レビュー後にリポジトリが変更されたため、デスクトップ部分は続けてインストールできませんでした。「詳細」で強制再インストールをオンにすると両方を表示中のバージョンに置き換えます。キャンセルするとエージェント部分だけが残ります。',
nothingToInstall: 'このパッケージにはここでインストールするものがありません。'
}
}
diff --git a/apps/desktop/src/i18n/ru_plugins.ts b/apps/desktop/src/i18n/ru_plugins.ts
index afe5f0211d2..45f29df1e73 100644
--- a/apps/desktop/src/i18n/ru_plugins.ts
+++ b/apps/desktop/src/i18n/ru_plugins.ts
@@ -77,6 +77,13 @@ export const ruPluginSettings = {
sha
? `Репозиторий изменился после вашей проверки. Проверьте новую версию (коммит ${sha}) перед установкой.`
: 'Репозиторий изменился после вашей проверки. Читаем новую версию…',
+ legacyBackendConfirm:
+ 'Этот бэкенд старше приложения и не может гарантировать, что установится именно проверенная вами версия: если репозиторий с тех пор изменился, установится более новая. Обновите бэкенд, чтобы получить эту гарантию.',
+ installAnyway: 'Всё равно установить',
+ partialInstall: sha =>
+ sha
+ ? `Плагин установлен лишь частично: агентная часть установлена на коммите ${sha}, а настольная не смогла последовать за ней, потому что репозиторий изменился после вашей проверки. Включите принудительную переустановку в разделе «Дополнительно», чтобы заменить обе части показанной версией, или отмените, чтобы оставить только агентную часть.`
+ : 'Плагин установлен лишь частично: агентная часть установлена, а настольная не смогла последовать за ней, потому что репозиторий изменился после вашей проверки. Включите принудительную переустановку в разделе «Дополнительно», чтобы заменить обе части показанной версией, или отмените, чтобы оставить только агентную часть.',
nothingToInstall: 'В этом пакете нечего устанавливать здесь.'
}
}
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index f1917ccaab5..71ec717e7fb 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -653,6 +653,9 @@ catalog: CatalogTranslations
reviewedPin: (sha: string) => string
latestCommit: string
sourceMoved: (sha: string) => string
+ legacyBackendConfirm: string
+ installAnyway: string
+ partialInstall: (sha: string) => string
nothingToInstall: string
includesHeading: string
agentLabel: string
diff --git a/apps/desktop/src/i18n/zh-hant_settings.ts b/apps/desktop/src/i18n/zh-hant_settings.ts
index b49f7e67203..2d3b1ac7ce0 100644
--- a/apps/desktop/src/i18n/zh-hant_settings.ts
+++ b/apps/desktop/src/i18n/zh-hant_settings.ts
@@ -91,6 +91,13 @@ export const zhHantSettings = {
reviewedPin: sha => (sha ? `已審核的固定提交 ${sha}` : '已審核的固定提交'),
latestCommit: '最新提交',
sourceMoved: sha => (sha ? `自你審閱後儲存庫已變更。請先審閱新版本(提交 ${sha})再安裝。` : '自你審閱後儲存庫已變更。正在讀取新版本…'),
+ legacyBackendConfirm:
+ '此後端比本應用程式舊,無法保證安裝的就是你審閱過的版本:如果儲存庫之後有變更,安裝的會是較新的版本。更新後端即可獲得這項保證。',
+ installAnyway: '仍要安裝',
+ partialInstall: sha =>
+ sha
+ ? `外掛只安裝了一部分:代理部分已安裝在提交 ${sha},但由於儲存庫在你審閱後有變更,桌面部分未能隨之安裝。在「進階」中開啟強制重新安裝,可用顯示的版本取代兩部分;或取消,只保留代理部分。`
+ : '外掛只安裝了一部分:代理部分已安裝,但由於儲存庫在你審閱後有變更,桌面部分未能隨之安裝。在「進階」中開啟強制重新安裝,可用顯示的版本取代兩部分;或取消,只保留代理部分。',
nothingToInstall: '此套件在這裡沒有可安裝的內容。'
}
},
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 4989c6e8207..cdbfad0448d 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -676,6 +676,13 @@ export const zhOverrides = {
reviewedPin: sha => (sha ? `已审核的固定提交 ${sha}` : '已审核的固定提交'),
latestCommit: '最新提交',
sourceMoved: sha => (sha ? `自你审阅后仓库已变更。请先审阅新版本(提交 ${sha})再安装。` : '自你审阅后仓库已变更。正在读取新版本…'),
+ legacyBackendConfirm:
+ '此后端比本应用旧,无法保证安装的就是你审阅过的版本:如果仓库此后有变更,安装的会是更新的版本。更新后端即可获得这一保证。',
+ installAnyway: '仍然安装',
+ partialInstall: sha =>
+ sha
+ ? `插件只安装了一部分:代理部分已安装在提交 ${sha},但由于仓库在你审阅后有变更,桌面部分未能随之安装。在“高级”中打开强制重装,可用显示的版本替换两部分;或取消,仅保留代理部分。`
+ : '插件只安装了一部分:代理部分已安装,但由于仓库在你审阅后有变更,桌面部分未能随之安装。在“高级”中打开强制重装,可用显示的版本替换两部分;或取消,仅保留代理部分。',
nothingToInstall: '此包在这里没有可安装的内容。'
}
},
diff --git a/apps/desktop/src/store/agent-plugins.test.ts b/apps/desktop/src/store/agent-plugins.test.ts
index e710f21d563..f047524d4d5 100644
--- a/apps/desktop/src/store/agent-plugins.test.ts
+++ b/apps/desktop/src/store/agent-plugins.test.ts
@@ -64,8 +64,9 @@ describe('installAgentPlugin', () => {
const reviewed = 'e404b6816b20237a82f6fbe2749b5a576cf75dba'
- it('installs on a backend that predates inspected_sha by sending the install without it', async () => {
+ it('never resends without the inspected commit on its own when a backend predates inspected_sha', async () => {
// The admission refusal an origin/main backend gives the field (validate_params, handler never ran).
+ // Installing there without it takes whatever the branch holds now: only the user may choose that.
const request = vi.fn(async (_method: string, params: Record<string, unknown>) => {
if ('inspected_sha' in params) {
throw new JsonRpcGatewayError(
@@ -75,14 +76,23 @@ describe('installAgentPlugin', () => {
)
}
- return { ok: true, plugin_name: 'pkg', enabled: true }
+ return { ok: true, plugin_name: 'unreviewed-tip', enabled: true }
})
expect(
- await installAgentPlugin(request as never, { identifier: 'https://github.com/example/pkg', inspectedSha: reviewed })
- ).toMatchObject({ ok: true, pluginName: 'pkg' })
- expect(request).toHaveBeenCalledTimes(2)
- expect(request.mock.calls[1][1]).toMatchObject({ action: 'install', identifier: 'https://github.com/example/pkg' })
+ await installAgentPlugin(request as never, {
+ identifier: 'https://github.com/example/pkg',
+ inspectedSha: reviewed,
+ profile: 'research'
+ })
+ ).toMatchObject({ ok: false, inspectedShaUnsupported: true })
+ expect(request).toHaveBeenCalledTimes(1)
+
+ // The user's explicit "Install anyway" is an ordinary legacy install, still on the originating profile.
+ expect(
+ await installAgentPlugin(request as never, { identifier: 'https://github.com/example/pkg', profile: 'research' })
+ ).toMatchObject({ ok: true, pluginName: 'unreviewed-tip' })
+ expect(request.mock.calls[1][1]).toMatchObject({ action: 'install', profile: 'research' })
expect(request.mock.calls[1][1]).not.toHaveProperty('inspected_sha')
})
@@ -104,8 +114,11 @@ describe('installAgentPlugin', () => {
})
expect(
- await installAgentPlugin(request as never, { identifier: 'https://github.com/example/pkg', inspectedSha: reviewed })
- ).toMatchObject({ ok: false })
+ await installAgentPlugin(request as never, {
+ identifier: 'https://github.com/example/pkg',
+ inspectedSha: reviewed
+ })
+ ).toMatchObject({ ok: false, inspectedShaUnsupported: false })
expect(request).toHaveBeenCalledTimes(1)
}
})
@@ -132,10 +145,17 @@ describe('installAgentPlugin', () => {
})
expect(
- await installAgentPlugin(request as never, { identifier: 'https://github.com/example/pkg', inspectedSha: reviewed })
+ await installAgentPlugin(request as never, {
+ identifier: 'https://github.com/example/pkg',
+ inspectedSha: reviewed
+ })
).toMatchObject({ ok: false })
expect(request).toHaveBeenCalledTimes(1)
- expect(request.mock.calls[0]).toEqual(['plugins.manage', expect.objectContaining({ inspected_sha: reviewed }), 120_000])
+ expect(request.mock.calls[0]).toEqual([
+ 'plugins.manage',
+ expect.objectContaining({ inspected_sha: reviewed }),
+ 120_000
+ ])
})
})
@@ -147,11 +167,13 @@ describe('inspectAgentPlugin', () => {
const sha = 'ABCDEF0123456789abcdef0123456789abcdef01'
const request = answering(sha)
- expect(await inspectAgentPlugin(request as never, { identifier: 'owner/repo', profile: 'research' })).toMatchObject({
- ok: true,
- agentName: 'demo',
- sha: sha.toLowerCase()
- })
+ expect(await inspectAgentPlugin(request as never, { identifier: 'owner/repo', profile: 'research' })).toMatchObject(
+ {
+ ok: true,
+ agentName: 'demo',
+ sha: sha.toLowerCase()
+ }
+ )
expect(request).toHaveBeenCalledWith(
'plugins.manage',
{ action: 'inspect', identifier: 'owner/repo', profile: 'research' },
@@ -257,7 +279,12 @@ describe('saveAgentPluginSettings (#46600, #87934)', () => {
writeSecret: vi.fn(async () => ({ ok: true }))
})
- expect(request).toHaveBeenCalledWith('plugins.manage', { action: 'settings', key: 'demo', profile: 'workbot', values: {} })
+ expect(request).toHaveBeenCalledWith('plugins.manage', {
+ action: 'settings',
+ key: 'demo',
+ profile: 'workbot',
+ values: {}
+ })
expect(JSON.stringify(request.mock.calls)).not.toContain('sk-2')
})
diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.ts
index 6cdecbaf86e..3d4911fa260 100644
--- a/apps/desktop/src/store/agent-plugins.ts
+++ b/apps/desktop/src/store/agent-plugins.ts
@@ -254,6 +254,9 @@ export interface AgentPluginInstallResult {
timedOut?: boolean
/** Refused: the source moved off the reviewed commit (`isSourceMovedRefusal`). */
sourceMoved?: boolean
+ /** Refused at admission by a backend that predates `inspected_sha`: nothing was installed, and an install
+ * there cannot be held to the reviewed commit. Only the user may choose to install without it. */
+ inspectedShaUnsupported?: boolean
pluginName?: string
warnings?: string[]
missingEnv?: string[]
@@ -308,11 +311,11 @@ interface InstallReply {
const INSPECTED_SHA_ADMISSION_REFUSAL = 'invalid params for plugins.manage: inspected_sha: '
/** A backend predating `inspected_sha` (native Desktop on an older SSH/URL/Cloud runtime) refuses the
- * whole install at admission (code 4000, handler never ran), so resending without it installs the branch
- * tip exactly as those backends always did. Only that refusal qualifies: the code AND a message that
- * OPENS with the admission prefix. Any other error (a 5026 install failure echoing a git server's text
- * included) is never retried, or a hostile clone error could drop the reviewed commit. Delete once no
- * supported backend predates the field. */
+ * whole install at admission (code 4000, handler never ran). Installing there without the field takes
+ * whatever the source holds at that moment, so the dialog asks the user first; nothing resends on its
+ * own. Only that refusal qualifies: the code AND a message that OPENS with the admission prefix. Any
+ * other error (a 5026 install failure echoing a git server's text included) is an ordinary failure.
+ * Delete once no supported backend predates the field. */
function backendPredatesInspectedSha(params: Record<string, unknown>, error: unknown): boolean {
return (
'inspected_sha' in params &&
@@ -361,19 +364,8 @@ export async function installAgentPlugin(
opts.profile
)
- const send = (requestParams: Record<string, unknown>) =>
- request<InstallReply>('plugins.manage', requestParams, PLUGIN_INSTALL_REQUEST_TIMEOUT_MS)
-
try {
- const result = await send(params).catch((error: unknown) => {
- if (!backendPredatesInspectedSha(params, error)) {
- throw error
- }
-
- const { inspected_sha: _dropped, ...compatible } = params
-
- return send(compatible)
- })
+ const result = await request<InstallReply>('plugins.manage', params, PLUGIN_INSTALL_REQUEST_TIMEOUT_MS)
if (!result?.ok) {
return { ok: false, error: result?.error || 'Install failed', live: NO_LIVE, nextChat: false }
@@ -402,6 +394,7 @@ export async function installAgentPlugin(
ok: false,
timedOut: /^request timed out after \d+s: plugins\.manage$/.test(message),
sourceMoved: isSourceMovedRefusal(e),
+ inspectedShaUnsupported: backendPredatesInspectedSha(params, e),
error: message,
live: NO_LIVE,
nextChat: false
@@ -421,6 +414,8 @@ export interface AgentPluginInspection {
insecure?: boolean
/** The commit the backend read; absent when it reported none or not a full SHA. */
sha?: string
+ /** Read at the catalog entry's pin, as a catalog install checks it out: `sha` is what that install must be. */
+ catalogPin?: boolean
unavailable?: boolean
error?: string
}
@@ -473,7 +468,10 @@ export async function inspectAgentPlugin(
desktopName: result?.desktop_name ?? null,
warnings: result?.warnings ?? [],
insecure: Boolean(result?.insecure),
- ...(ok && typeof result.sha === 'string' && COMMIT_SHA_RE.test(result.sha) ? { sha: result.sha.toLowerCase() } : {}),
+ ...(ok && typeof result.sha === 'string' && COMMIT_SHA_RE.test(result.sha)
+ ? { sha: result.sha.toLowerCase() }
+ : {}),
+ ...(ok && opts.catalogName ? { catalogPin: true } : {}),
...(ok ? {} : { error: result?.error || 'Inspection failed' })
}
} catch (e) {
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index 24815ece3c5..3f3dfd649e1 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -307,10 +307,12 @@ def refuse_incompatible_catalog_entry(entry: PluginCatalogEntry) -> None:
def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Optional[str] = None,
allow_removed: bool = False, scan_decision_cb=None, python_deps: bool = True,
- assume_deps_consent: bool = False, before_swap=None) -> tuple:
+ assume_deps_consent: bool = False, before_swap=None,
+ inspected_sha: Optional[str] = None) -> tuple:
"""``_install_plugin_core`` at the catalog pin (an explicit *ref* wins) + provenance recorded on the
install-metadata record at the sha ACTUALLY checked out (a ``--ref`` install is not at the reviewed
- pin, so ``update_available`` must say so). Returns the core's ``(target, manifest, installed_name)``."""
+ pin, so ``update_available`` must say so). *inspected_sha*: the commit an install dialog showed; the
+ checkout must be that commit. Returns the core's ``(target, manifest, installed_name)``."""
from hermes_cli.plugins_cmd import _install_plugin_core
if not allow_removed:
raise_if_removed(entry.name, entry.repo)
@@ -319,7 +321,8 @@ def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Option
entry.install_identifier, force=force, ref=ref or entry.sha, scan_decision_cb=scan_decision_cb,
reviewed_pin=entry.sha, python_deps=python_deps, assume_deps_consent=assume_deps_consent,
allow_removed=allow_removed, before_swap=before_swap, app_title=entry.title or None,
- catalog={"name": entry.name, "repo": entry.repo, "tier": entry.tier, "pin": entry.sha})
+ catalog={"name": entry.name, "repo": entry.repo, "tier": entry.tier, "pin": entry.sha},
+ inspected_sha=inspected_sha)
return target, manifest, installed_name
diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.py
index 5d1ef6b5081..1ec9c0f203c 100644
--- a/hermes_cli/plugins_cmd_install.py
+++ b/hermes_cli/plugins_cmd_install.py
@@ -357,20 +357,25 @@ def scan_blocked_result(exc) -> dict[str, Any]:
def _clone_at_reviewed_commit(tmp_clone: Path, git_url: str, requested_revision: Optional[str],
- inspected_sha: Optional[str], subdir: Optional[str]) -> str:
+ inspected_sha: Optional[str], subdir: Optional[str], *, catalog_pin: bool = False) -> str:
"""Clone *git_url* and return the checked-out sha. *inspected_sha* is the commit the install dialog's
``inspect`` read and the user reviewed: a branch that moved since is refused, never installed. The
clone stays an ordinary checkout of the branch (a detached one at the old commit could not ``git
pull`` later), so the install stays unpinned and ``update`` still follows the branch. A retained pin
- that names another commit is refused too."""
+ that names another commit is refused too. A *catalog_pin* install clones the catalog's CURRENT pin
+ (possibly an annotated tag), which a re-pin since the dialog opened moves: the commit actually checked
+ out is what must equal the reviewed one."""
if not inspected_sha:
return _pc()._clone_plugin_repo(tmp_clone, git_url, requested_revision, subdir)
sha = _pc()._normalize_exact_revision(inspected_sha)
- if requested_revision is not None and requested_revision != sha:
+ if not catalog_pin and requested_revision is not None and requested_revision != sha:
raise _pc().PluginOperationError(
f"This plugin is pinned to commit {requested_revision[:12]}, not the commit {sha[:12]} you reviewed. "
"Reinstall it with that pin, or re-open the install dialog.", failure_class="already_installed")
head = _pc()._clone_plugin_repo(tmp_clone, git_url, requested_revision, subdir)
+ git_exe = _pc()._resolve_git_executable()
+ if git_exe:
+ sha = _pc()._git_resolve_commit(tmp_clone, git_exe, sha)
if head != sha:
raise _pc().PluginSourceMoved(
f"The source changed since you reviewed it: it is now at commit {head[:12]}, not {sha[:12]}. "
@@ -432,7 +437,8 @@ def _install_plugin_core(
with tempfile.TemporaryDirectory(prefix=".install-", dir=plugins_dir) as tmp:
tmp_clone = Path(tmp) / "plugin"
- installed_revision = _clone_at_reviewed_commit(tmp_clone, git_url, requested_revision, inspected_sha, subdir)
+ installed_revision = _clone_at_reviewed_commit(tmp_clone, git_url, requested_revision, inspected_sha, subdir,
+ catalog_pin=bool(catalog))
git_exe = _pc()._resolve_git_executable()
at_reviewed_pin = bool(reviewed_pin) and installed_revision == (
_pc()._git_resolve_commit(tmp_clone, git_exe, reviewed_pin) if git_exe and reviewed_pin else reviewed_pin)
@@ -791,18 +797,26 @@ def _select_memory_provider(name: str, console, *, select: bool) -> None:
f"Run `hermes memory setup {name}` to configure it; new sessions use it.")
-def _catalog_install_on_disk(catalog_name: str, ref: Optional[str]) -> Optional[tuple]:
+def _catalog_install_on_disk(catalog_name: str, ref: Optional[str],
+ inspected_sha: Optional[str] = None) -> Optional[tuple]:
"""``(target, manifest, installed_name)`` of the installed, not enabled tree whose install record
names catalog entry *catalog_name*, else None. A refused enable leaves the published clone in
place (there is no rollback), so the card's Try again, or the model asking again, stopped at
"already exists" on a second clone and the plugin could never be turned on from the card.
- Like ``hermes plugins enable``, the tree is used at the commit it has; an explicit *ref* only
- matches a tree checked out at that commit."""
+ Like ``hermes plugins enable``, the tree is used at the commit it has; an explicit *ref*, or the
+ commit an install dialog reviewed (*inspected_sha*), only matches a tree checked out at that commit.
+ Any other tree is not reused: the fresh install then answers "already exists" instead of enabling
+ code nobody reviewed."""
from hermes_cli.plugins_cmd_catalog import catalog_install_record
target = _pc()._catalog_installed_dir(catalog_name)
if target is None:
return None
- if ref and str(catalog_install_record(target)["sha"]).lower() != ref.lower():
+ record = catalog_install_record(target) or {}
+ installed_sha = str(record.get("sha") or "").lower()
+ if ref and installed_sha != ref.lower():
+ return None
+ # The dialog may name the commit or, from the catalog entry, the annotated tag the tree was installed at.
+ if inspected_sha and inspected_sha.lower() not in {installed_sha, str(record.get("pin") or "").lower()} - {""}:
return None
manifest = _pc()._read_manifest(target)
installed_name = manifest.get("name") or target.name
@@ -840,19 +854,21 @@ def _place_tree(entry, identifier: str, *, force: bool, ref: Optional[str], assu
"""``(target, manifest, installed_name)`` of the tree to enable, or the error result. A catalog
entry already on disk and not enabled (an earlier enable was refused) is used as it is, unless
an approved *ref* names another commit; a fresh install clones at *ref* when set, else the pin.
- A custom source with no *ref* is held to *inspected_sha* when given; a catalog entry keeps its pin."""
+ With no *ref*, either source is held to *inspected_sha* when given: a catalog entry re-pinned since
+ the dialog read it is refused like a moved branch, and only a tree on disk at that commit is reused."""
from hermes_cli import plugins_cmd_catalog as catalog
ref = (ref or "").strip() or None
- on_disk = _catalog_install_on_disk(entry.name, ref) if entry is not None and not force else None
+ inspected_sha = None if ref else inspected_sha
+ on_disk = _catalog_install_on_disk(entry.name, ref, inspected_sha) if entry is not None and not force else None
if on_disk is not None:
return on_disk
def _install() -> tuple:
if entry is not None:
return catalog.install_catalog_entry(entry, force=force, ref=ref, allow_removed=False,
- assume_deps_consent=assume_deps_consent)
+ assume_deps_consent=assume_deps_consent, inspected_sha=inspected_sha)
return _pc()._install_plugin_core(identifier, force=force, ref=ref, assume_deps_consent=assume_deps_consent,
- inspected_sha=None if ref else inspected_sha)
+ inspected_sha=inspected_sha)
step(InstallPhase.downloading)
try:
@@ -892,7 +908,8 @@ def dashboard_install_plugin(
the config already selects (``memory.provider``) would otherwise be refused every time, while
the same plugin unselected installs and enables. A forced replacement still needs explicit consent.
*on_step* hears each slow phase as it starts (the catalog card draws it under its bar). *inspected_sha*
- is the commit an install dialog reviewed: a custom source whose branch moved since is refused."""
+ is the commit an install dialog reviewed: a custom source whose branch moved since, or a catalog entry
+ re-pinned since, is refused."""
if assume_deps_consent is None:
assume_deps_consent = enable and not force
step = on_step or (lambda _phase: None)
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index ed1d2c069cb..a0000461279 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -4021,16 +4021,19 @@
"settings.plugins.installModal.includesHeading",
"settings.plugins.installModal.insecureWarning",
"settings.plugins.installModal.install",
+ "settings.plugins.installModal.installAnyway",
"settings.plugins.installModal.installFromGit",
"settings.plugins.installModal.installUncertain",
"settings.plugins.installModal.installing",
"settings.plugins.installModal.installsAndEnables",
"settings.plugins.installModal.installsOnly",
"settings.plugins.installModal.latestCommit",
+ "settings.plugins.installModal.legacyBackendConfirm",
"settings.plugins.installModal.missingEnv",
"settings.plugins.installModal.missingEnvAction",
"settings.plugins.installModal.nextChat",
"settings.plugins.installModal.nothingToInstall",
+ "settings.plugins.installModal.partialInstall",
"settings.plugins.installModal.pinToCommit",
"settings.plugins.installModal.pinToCommitHint",
"settings.plugins.installModal.pinToCommitInvalid",
diff --git a/tests/hermes_cli/test_plugin_install_inspected_sha_catalog.py b/tests/hermes_cli/test_plugin_install_inspected_sha_catalog.py
new file mode 100644
index 00000000000..4406c0aa8f6
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_install_inspected_sha_catalog.py
@@ -0,0 +1,148 @@
+"""A catalog install dialog's ``plugins.manage install`` is held to the commit its ``inspect`` read.
+
+The backend reloads the live catalog entry at Install, so a re-pin between the dialog's inspection and the
+click would otherwise install (and, through the one checkout, publish the desktop half of) a tree the
+dialog never showed. Reusing a disabled tree already on disk is held to the same commit. The catalog
+install itself stays what it always was: pinned to the catalog's sha, annotated-tag pins included.
+Real RPC dispatch, real clone of a local repo; only the https transport is redirected.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+import hermes_yaml as yaml
+from tests.hermes_cli.plugin_worker_support import (
+ isolated_python as isolated_python, # noqa: PLC0414 -- the self-alias is load-bearing: it suppresses F811 for the pytest fixture parameter shadowing this import
+ plugin_world as plugin_world, # noqa: PLC0414 -- the self-alias is load-bearing: it suppresses F811 for the pytest fixture parameter shadowing this import
+)
+from tui_gateway import server
+
+URL = "https://example.invalid/acme/demo.git"
+
+
[email protected](autouse=True)
+def _offline_pm(plugin_world):
+ (plugin_world.home / "config.yaml").unlink()
+
+
+def _git(repo: Path, *args: str) -> str:
+ return subprocess.run([
+ "git", "-c", "[email protected]", "-c", "user.name=t", *args,
+ ], cwd=repo, check=True, capture_output=True, text=True).stdout.strip()
+
+
+def _commit(repo: Path, marker: str) -> str:
+ (repo / "marker.txt").write_text(marker, encoding="utf-8")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-qm", marker)
+ return _git(repo, "rev-parse", "HEAD")
+
+
+def _rpc(action: str, **params):
+ return server.handle_request({"id": "1", "method": "plugins.manage",
+ "params": {"action": action, "identifier": URL, "catalog_name": "demo", **params}})
+
+
+def world(tmp_path, monkeypatch):
+ """``(home, repo, pin)``: a repo published through catalog entry ``demo``; ``pin(sha)`` re-pins it."""
+ from hermes_cli import plugins_cmd, plugins_cmd_catalog
+ from hermes_cli.plugin_catalog import PluginCatalogEntry
+ repo = tmp_path / "demo"
+ repo.mkdir()
+ _git(repo, "init", "-q", "-b", "main")
+ (repo / "plugin.yaml").write_text(yaml.safe_dump({"name": "demo", "version": "1.0.0"}), encoding="utf-8")
+ (repo / "__init__.py").write_text("def register(ctx):\n pass\n", encoding="utf-8")
+ real = plugins_cmd._clone_plugin_repo
+ monkeypatch.setattr(plugins_cmd, "_clone_plugin_repo",
+ lambda dest, _url, revision, subdir=None: real(dest, repo.as_uri(), revision, subdir))
+ current: dict[str, PluginCatalogEntry] = {}
+
+ def pin(sha: str) -> None:
+ current["demo"] = PluginCatalogEntry(name="demo", repo=URL, sha=sha, description="d", maintainer="m")
+ monkeypatch.setattr(plugins_cmd_catalog, "get_live_catalog_entry", lambda name: current.get(name))
+ from hermes_constants import get_hermes_home
+ return get_hermes_home(), repo, pin
+
+
+def _record(home: Path) -> dict:
+ return json.loads((home / "plugins" / ".install-metadata.json").read_text())["demo"]
+
+
+def test_a_catalog_entry_repinned_after_the_dialog_inspected_it_is_refused(world):
+ home, repo, pin = world
+ reviewed = _commit(repo, "reviewed")
+ pin(reviewed)
+ assert _rpc("inspect")["result"]["sha"] == reviewed
+ pin(_commit(repo, "moved")) # the catalog refreshes while the dialog is open
+
+ refused = _rpc("install", inspected_sha=reviewed, enable=False)["error"]
+
+ assert "source changed since you reviewed it" in refused["message"]
+ assert refused["data"] == {"reason": "source_moved"} # the dialog re-inspects and shows the new pin
+ assert not (home / "plugins" / "demo").exists()
+
+
+def test_a_disabled_tree_at_another_commit_is_not_enabled_for_the_reviewed_one(world):
+ home, repo, pin = world
+ old = _commit(repo, "old")
+ pin(old)
+ assert _rpc("install", enable=False)["result"]["ok"] is True # an earlier install left it disabled
+ reviewed = _commit(repo, "reviewed")
+ pin(reviewed)
+
+ result = _rpc("install", inspected_sha=reviewed, enable=True)
+
+ assert "already exists" in result["error"]["message"]
+ assert _record(home)["revision"] == old
+ from hermes_cli.plugins_cmd import _get_enabled_set
+ assert "demo" not in _get_enabled_set()
+
+
+def test_a_disabled_tree_at_the_reviewed_commit_is_still_reused(world):
+ home, repo, pin = world
+ reviewed = _commit(repo, "reviewed")
+ pin(reviewed)
+ assert _rpc("install", enable=False)["result"]["ok"] is True
+
+ result = _rpc("install", inspected_sha=reviewed, enable=False)["result"]
+
+ assert result["ok"] is True and _record(home)["revision"] == reviewed
+
+
+def test_an_annotated_tag_pin_installs_at_its_commit_and_stays_a_catalog_pin(world):
+ home, repo, pin = world
+ reviewed = _commit(repo, "reviewed")
+ _git(repo, "tag", "-a", "v1.0", reviewed, "-m", "v1.0")
+ _commit(repo, "later")
+ tag_object = _git(repo, "rev-parse", "v1.0")
+ assert tag_object != reviewed
+ pin(tag_object)
+ assert _rpc("inspect")["result"]["sha"] == reviewed # inspect reports the commit the tag peels to
+
+ result = _rpc("install", inspected_sha=reviewed, enable=False)["result"]
+
+ assert result["ok"] is True
+ record = _record(home)
+ assert (record["revision"], record["pinned"]) == (reviewed, True)
+ assert record["catalog"]["pin"] == tag_object # still at the catalog's pin: `update` follows re-pins
+ assert (home / "plugins" / "demo" / "marker.txt").read_text() == "reviewed"
+
+
+def test_a_disabled_tree_at_an_annotated_tag_pin_is_reused_for_that_pin(world):
+ """Native Desktop's dialog names the catalog's pin as published (the tag object), not the commit."""
+ home, repo, pin = world
+ reviewed = _commit(repo, "reviewed")
+ _git(repo, "tag", "-a", "v1.0", reviewed, "-m", "v1.0")
+ tag_object = _git(repo, "rev-parse", "v1.0")
+ pin(tag_object)
+ assert _rpc("install", enable=False)["result"]["ok"] is True
+
+ for shown in (tag_object, reviewed):
+ assert _rpc("install", inspected_sha=shown, enable=False)["result"]["ok"] is True
+ assert _record(home)["revision"] == reviewed
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 0828f6da9b5..f1ab2e4e50a 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -729,7 +729,12 @@ plugin is installed once, as an agent plugin on that host, and the host copies i
that checkout, as native Desktop does with a local backend. That install is held to the commit the
dialog showed too: if the branch moved after you reviewed it, nothing is installed and the dialog
reads the source again and shows the new commit for you to review before you click Install again
-(native Desktop works the same way). Because a browser tab asks for it, the
+(native Desktop works the same way). A catalog pick is held to the catalog pin the dialog showed: if the
+catalog re-pins the entry before you click Install, the dialog shows the new pin for review first. A
+backend older than the app cannot hold an install to the reviewed commit; the dialog says so and installs
+only if you choose **Install anyway**. If a package's agent half installs but its desktop half cannot
+follow because the source moved, the dialog says only the agent half is in, and installs again only with
+**Force reinstall**, which replaces both halves with the version shown. Because a browser tab asks for it, the
desktop-only clone takes `https://`
repositories only (no `http://`, `ssh`/`git@` or `file://` sources), refuses a plugin folder that
contains symbolic links or is larger than 64 MB, and never replaces an installed plugin unless