Skip to content

The agent that grows with you

fix(plugins): retry only a real admission refusal; re-review a moved source

Tekniume4b0ab2365fc
diff --git a/apps/desktop/electron/desktop-plugin-install.test.ts b/apps/desktop/electron/desktop-plugin-install.test.ts
index 7eb66cf8ddd..f2dbfa304e5 100644
--- a/apps/desktop/electron/desktop-plugin-install.test.ts
+++ b/apps/desktop/electron/desktop-plugin-install.test.ts
@@ -262,7 +262,7 @@ describe('installDesktopPluginFromGit', () => {
expect(fs.readFileSync(path.join(appRoot, result.pluginName!, 'panel.js'), 'utf8')).toBe('reviewed\n')
const refused = await installDesktopPluginFromGit('git', pathToFileURL(repo).href, appRoot, true, 'f'.repeat(40))
- expect(refused.ok).toBe(false)
+ expect(refused).toMatchObject({ ok: false, sourceMoved: true })
expect(refused.error).toContain('the source may have changed since you reviewed it')
expect(fs.readFileSync(path.join(appRoot, result.pluginName!, 'panel.js'), 'utf8')).toBe('reviewed\n')
})
diff --git a/apps/desktop/electron/desktop-plugin-install.ts b/apps/desktop/electron/desktop-plugin-install.ts
index 15314271771..526436f0aed 100644
--- a/apps/desktop/electron/desktop-plugin-install.ts
+++ b/apps/desktop/electron/desktop-plugin-install.ts
@@ -54,8 +54,13 @@ export interface DesktopPluginInstallResult {
pluginName?: string
path?: string
error?: string
+ /** Refused: the reviewed commit is no longer in the source. The dialog reads the source again. */
+ sourceMoved?: boolean
}
+/** `checkoutReviewedCommit`'s refusal, told apart by class rather than by its message. */
+class ReviewedCommitUnavailable extends Error {}
+
export function resolvePluginGitUrl(identifier: string): ResolvedGitUrl {
const trimmed = identifier.trim()
@@ -408,7 +413,7 @@ async function checkoutReviewedCommit(gitBin: string, cloneRoot: string, sha: st
throw new Error(`HEAD is not ${reviewed}.`)
}
} catch (err) {
- throw new Error(
+ throw new ReviewedCommitUnavailable(
`The commit you reviewed (${reviewed.slice(0, 12)}) could not be checked out; the source may have changed ` +
`since you reviewed it. Re-open the install dialog to review it again. ${err instanceof Error ? err.message : String(err)}`
)
@@ -580,7 +585,11 @@ export async function installDesktopPluginFromGit(
await fsp.rm(cloneRoot, { recursive: true, force: true }).catch(() => undefined)
}
} catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) }
+ return {
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ ...(err instanceof ReviewedCommitUnavailable ? { sourceMoved: true } : {})
+ }
}
}
diff --git a/apps/desktop/src/app/settings/plugin-install-modal.tsx b/apps/desktop/src/app/settings/plugin-install-modal.tsx
index d996706458d..4b35c1ee3b0 100644
--- a/apps/desktop/src/app/settings/plugin-install-modal.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-modal.tsx
@@ -32,7 +32,13 @@ import { $activeGatewayProfile, $profiles, $profileScope, normalizeProfileKey, p
import { $connection } from '@/store/session'
import { PluginInstallDetails } from './plugin-install-details'
-import { installComponents, type InstallModalCopy, type ProbeResult, runPluginInstall } from './plugin-install-run'
+import {
+ installComponents,
+ type InstallModalCopy,
+ type InstallOutcome,
+ type ProbeResult,
+ runPluginInstall
+} from './plugin-install-run'
import { usePluginProbe } from './use-plugin-probe'
const CAPTION = 'text-[length:var(--conversation-caption-font-size)]'
@@ -297,6 +303,27 @@ function InstallFooter({ canInstall, failed, installing, onInstall, onRetry, ret
)
}
+interface SourceMovedNoticeProps {
+ copy: InstallModalCopy
+ /** A failure on screen replaces the notice. */
+ failure: null | string
+ probe: null | ProbeResult
+ 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) {
+ 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) ?? '') : '')}
+ </p>
+ )
+}
+
interface InstallViewProps {
request: PluginInstallRequest
installing: boolean
@@ -329,6 +356,8 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
const [pinRef, setPinRef] = useState('')
const [installError, setInstallError] = useState<null | string>(null)
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)
useEffect(() => {
start(request.repo)
@@ -354,6 +383,7 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
const install = async () => {
onInstallingChange(true)
setInstallError(null)
+ setSourceMoved(false)
try {
// A catalog pick may click Install while the inspection is still running: wait for it under the loader.
@@ -368,13 +398,19 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewPro
{ copy: m, navigate, requestGateway }
)
- if (outcome.status === 'done') {
- finishInstall(request, navigate)
- } else if (outcome.status === 'uncertain') {
- setInstallUncertain(true)
- } else {
- setInstallError(outcome.error)
+ const settle: Record<InstallOutcome['status'], () => void> = {
+ done: () => finishInstall(request, navigate),
+ uncertain: () => setInstallUncertain(true),
+ // Never resend the commit the source left: drop that inspection and read the source again, so
+ // Install waits on the new commit being on screen.
+ stale: () => {
+ setSourceMoved(true)
+ start(request.repo)
+ },
+ failed: () => setInstallError((outcome as Extract<InstallOutcome, { status: 'failed' }>).error)
}
+
+ settle[outcome.status]()
} finally {
onInstallingChange(false)
}
@@ -422,6 +458,7 @@ 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}
diff --git a/apps/desktop/src/app/settings/plugin-install-run.ts b/apps/desktop/src/app/settings/plugin-install-run.ts
index fb7ddec4cc3..aadb03898e4 100644
--- a/apps/desktop/src/app/settings/plugin-install-run.ts
+++ b/apps/desktop/src/app/settings/plugin-install-run.ts
@@ -77,11 +77,19 @@ export interface InstallDeps {
requestGateway: GatewayRequest
}
-export type InstallOutcome = { error: string; status: 'failed' } | { status: 'done' } | { status: 'uncertain' }
+/** `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. */
+export type InstallOutcome =
+ | { error: string; status: 'failed' }
+ | { error: string; status: 'stale' }
+ | { status: 'done' }
+ | { status: 'uncertain' }
interface Report {
errors: string[]
successes: string[]
+ /** A half was refused on the backend's or Electron's structured source-moved marker. */
+ sourceMoved: boolean
}
/** What an agent-plugin install made usable, as toast fragments ("12 tools connected", ...). */
@@ -132,6 +140,7 @@ async function installAgentHalf(plan: InstallPlan, deps: InstallDeps, report: Re
if (!result.ok) {
report.errors.push(result.error || deps.copy.agentFailed)
+ report.sourceMoved ||= Boolean(result.sourceMoved)
return result
}
@@ -152,7 +161,8 @@ async function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, repor
// clones the desktop half here: the host copies it out of that one checkout (`desktopHalfFromPackage`).
const installFn = window.hermesDesktop?.installDesktopPlugin
- const result: { error?: string; ok: boolean; pluginName?: string; unsupported?: boolean } = installFn
+ 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,
@@ -168,6 +178,8 @@ async function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, repor
// A backend older than this build has no place to put the half: say what this environment can do,
// which is what an install without Electron always said.
report.errors.push(result.unsupported ? copy.desktopUnavailable : result.error || copy.desktopFailed)
+ // A pin the user typed that the source lacks is their pin to fix; a fresh inspection cannot change it.
+ report.sourceMoved ||= !plan.ref && Boolean(result.sourceMoved)
return
}
@@ -242,7 +254,7 @@ export async function runPluginInstall(plan: InstallPlan, deps: InstallDeps): Pr
return { status: 'failed', error: deps.copy.nothingToInstall }
}
- const report: Report = { errors: [], successes: [] }
+ const report: Report = { errors: [], successes: [], sourceMoved: false }
const agentResult = components.agent ? await installAgentHalf(plan, deps, report) : undefined
if (agentResult?.timedOut) {
@@ -251,6 +263,11 @@ export async function runPluginInstall(plan: InstallPlan, deps: InstallDeps): Pr
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 (components.desktop) {
await installDesktopHalf(plan, components, deps, report, agentResult)
}
@@ -266,7 +283,7 @@ export async function runPluginInstall(plan: InstallPlan, deps: InstallDeps): Pr
}
if (report.errors.length > 0) {
- return { status: 'failed', error: report.errors.join(' ') }
+ return { status: report.sourceMoved ? 'stale' : 'failed', error: report.errors.join(' ') }
}
// 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/app/settings/plugin-install-source-moved.test.tsx b/apps/desktop/src/app/settings/plugin-install-source-moved.test.tsx
new file mode 100644
index 00000000000..23d03d060da
--- /dev/null
+++ b/apps/desktop/src/app/settings/plugin-install-source-moved.test.tsx
@@ -0,0 +1,160 @@
+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'
+
+// The source moves between the dialog's inspection and Install. The refusal says so with a structured
+// marker; the dialog must read the source again and show the new commit, never resend the old one.
+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 })
+}))
+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 MOVED = `The source changed since you reviewed it: it is now at commit ${V2.slice(0, 12)}, not ${V1.slice(0, 12)}.`
+
+const callsFor = (action: string) =>
+ requestGateway.mock.calls.filter(([method, params]) => method === 'plugins.manage' && params?.action === action)
+
+const installButton = () => screen.queryByRole('button', { name: /^Install/ }) 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('Install after the source moved past the reviewed commit', () => {
+ it('browser-hosted: re-inspects, shows the new commit, and installs that one instead of resending the old', async () => {
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ let tip = V1
+
+ 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: tip, warnings: [] }
+ }
+
+ if (params?.action === 'install') {
+ if (params.inspected_sha !== tip) {
+ throw new JsonRpcGatewayError(MOVED, { code: 5026, data: { reason: 'source_moved' } })
+ }
+
+ return { ok: true, plugin_name: 'pkg' }
+ }
+
+ return { plugins: [] }
+ })
+
+ renderModal()
+ act(() => openPluginInstallRequest({ repo: REPO }))
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ tip = V2 // the branch moves while the dialog is open
+ fireEvent.click(installButton()!)
+
+ // The dialog read the source again and names the new commit; Install, not Retry, is offered.
+ expect(await screen.findByText(new RegExp(`Review the new version \\(commit ${V2.slice(0, 12)}\\)`))).toBeTruthy()
+ expect(callsFor('inspect')).toHaveLength(2)
+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()
+ expect($pluginInstallRequest.get()).not.toBeNull()
+
+ 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])
+ })
+
+ it('an ordinary install failure still offers Retry and never re-inspects', async () => {
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ 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') {
+ // The same words with no marker: text from a git server is not the backend's verdict.
+ throw new JsonRpcGatewayError(MOVED, { code: 5026 })
+ }
+
+ return { plugins: [] }
+ })
+
+ renderModal()
+ act(() => openPluginInstallRequest({ repo: REPO }))
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+
+ expect(await screen.findByRole('button', { name: 'Retry' })).toBeTruthy()
+ expect(callsFor('inspect')).toHaveLength(1)
+ })
+
+ it('native Desktop: Electron refusing the reviewed commit re-inspects and installs the new commit', async () => {
+ const probePluginRepo = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: true, agent: false, desktop: true, desktopName: 'ui', sha: V1, warnings: [] })
+ .mockResolvedValueOnce({ ok: true, agent: false, desktop: true, desktopName: 'ui', sha: V2, warnings: [] })
+
+ const installDesktopPlugin = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: false, sourceMoved: true, error: 'The commit you reviewed could not be checked out.' })
+ .mockResolvedValueOnce({ ok: true, pluginName: 'ui' })
+
+ vi.stubGlobal('hermesDesktop', { installDesktopPlugin, probePluginRepo })
+
+ renderModal()
+ act(() => openPluginInstallRequest({ repo: REPO }))
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+
+ expect(await screen.findByText(new RegExp(`commit ${V2.slice(0, 12)}`))).toBeTruthy()
+ expect(probePluginRepo).toHaveBeenCalledTimes(2)
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+
+ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())
+ expect(installDesktopPlugin.mock.calls.map(([payload]) => payload.sha)).toEqual([V1, V2])
+ })
+})
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 9c67651654c..183784e7736 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -668,7 +668,14 @@ declare global {
force?: boolean
/** The commit the dialog reviewed; Electron installs exactly that tree or refuses. */
sha?: string
- }) => Promise<{ ok: boolean; pluginName?: string; path?: string; error?: string }>
+ }) => Promise<{
+ ok: boolean
+ pluginName?: string
+ path?: string
+ error?: string
+ /** The reviewed commit is gone from the source: the dialog reads it again. */
+ sourceMoved?: boolean
+ }>
/** Delete a STANDALONE desktop plugin folder (`<desktop-plugins root>/<name>`);
* Electron re-checks containment and refuses unified-package halves. */
removeDesktopPlugin?: (payload: { name: string }) => Promise<{ ok: boolean; path?: string; error?: string }>
diff --git a/apps/desktop/src/i18n/ar_settings.ts b/apps/desktop/src/i18n/ar_settings.ts
index 3980af999b6..ce6a30fc072 100644
--- a/apps/desktop/src/i18n/ar_settings.ts
+++ b/apps/desktop/src/i18n/ar_settings.ts
@@ -225,6 +225,10 @@ export const arSettings = {
versionLabel: 'الإصدار',
reviewedPin: sha => (sha ? `الإصدار المثبّت المراجَع ${sha}` : 'الإصدار المثبّت المراجَع'),
latestCommit: 'أحدث إيداع',
+ sourceMoved: sha =>
+ sha
+ ? `تغيّر المستودع منذ مراجعتك له. راجع الإصدار الجديد (الإيداع ${sha}) قبل تثبيته.`
+ : 'تغيّر المستودع منذ مراجعتك له. جارٍ قراءة الإصدار الجديد…',
nothingToInstall: 'لا تحتوي هذه الحزمة على ما يُثبَّت هنا.'
}
},
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index 0a20ed543a8..1b5f2040d8c 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -842,6 +842,10 @@ export const deOverrides = {
versionLabel: 'Version',
reviewedPin: sha => (sha ? `Geprüfter Pin ${sha}` : 'Geprüfter Pin'),
latestCommit: 'Neuester Commit',
+ sourceMoved: sha =>
+ 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…',
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 c0996da6895..74609d87514 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -795,6 +795,10 @@ export const en: Translations = {
versionLabel: 'Version',
reviewedPin: sha => (sha ? `Reviewed pin ${sha}` : 'Reviewed pin'),
latestCommit: 'Latest commit',
+ sourceMoved: sha =>
+ 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…',
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 fdb19c1d1c2..4d644e853fd 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -845,6 +845,10 @@ export const esOverrides = {
versionLabel: 'Versión',
reviewedPin: sha => (sha ? `Pin revisado ${sha}` : 'Pin revisado'),
latestCommit: 'Último commit',
+ sourceMoved: sha =>
+ 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…',
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 8fe6d100e06..fefb9443006 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -844,6 +844,10 @@ export const frOverrides = {
versionLabel: 'Version',
reviewedPin: sha => (sha ? `Pin examiné ${sha}` : 'Pin examiné'),
latestCommit: 'Dernier commit',
+ sourceMoved: sha =>
+ 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…',
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 0f58332b476..79cb2890f7a 100644
--- a/apps/desktop/src/i18n/ja_plugins.ts
+++ b/apps/desktop/src/i18n/ja_plugins.ts
@@ -37,6 +37,10 @@ export const jaPluginSettings = {
versionLabel: 'バージョン',
reviewedPin: sha => (sha ? `レビュー済みのピン ${sha}` : 'レビュー済みのピン'),
latestCommit: '最新のコミット',
+ sourceMoved: sha =>
+ sha
+ ? `レビュー後にリポジトリが変更されました。インストールする前に新しいバージョン(コミット ${sha})を確認してください。`
+ : 'レビュー後にリポジトリが変更されました。新しいバージョンを読み込んでいます…',
nothingToInstall: 'このパッケージにはここでインストールするものがありません。'
}
}
diff --git a/apps/desktop/src/i18n/ru_plugins.ts b/apps/desktop/src/i18n/ru_plugins.ts
index 85fc2289358..afe5f0211d2 100644
--- a/apps/desktop/src/i18n/ru_plugins.ts
+++ b/apps/desktop/src/i18n/ru_plugins.ts
@@ -73,6 +73,10 @@ export const ruPluginSettings = {
versionLabel: 'Версия',
reviewedPin: sha => (sha ? `Проверенный пин ${sha}` : 'Проверенный пин'),
latestCommit: 'Последний коммит',
+ sourceMoved: sha =>
+ sha
+ ? `Репозиторий изменился после вашей проверки. Проверьте новую версию (коммит ${sha}) перед установкой.`
+ : 'Репозиторий изменился после вашей проверки. Читаем новую версию…',
nothingToInstall: 'В этом пакете нечего устанавливать здесь.'
}
}
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 186168bd3b9..f1917ccaab5 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -652,6 +652,7 @@ catalog: CatalogTranslations
versionLabel: string
reviewedPin: (sha: string) => string
latestCommit: string
+ sourceMoved: (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 ed04807839a..b49f7e67203 100644
--- a/apps/desktop/src/i18n/zh-hant_settings.ts
+++ b/apps/desktop/src/i18n/zh-hant_settings.ts
@@ -90,6 +90,7 @@ export const zhHantSettings = {
versionLabel: '版本',
reviewedPin: sha => (sha ? `已審核的固定提交 ${sha}` : '已審核的固定提交'),
latestCommit: '最新提交',
+ sourceMoved: sha => (sha ? `自你審閱後儲存庫已變更。請先審閱新版本(提交 ${sha})再安裝。` : '自你審閱後儲存庫已變更。正在讀取新版本…'),
nothingToInstall: '此套件在這裡沒有可安裝的內容。'
}
},
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index fd685b0b6b3..4989c6e8207 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -675,6 +675,7 @@ export const zhOverrides = {
versionLabel: '版本',
reviewedPin: sha => (sha ? `已审核的固定提交 ${sha}` : '已审核的固定提交'),
latestCommit: '最新提交',
+ sourceMoved: 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 610f5fbf227..e710f21d563 100644
--- a/apps/desktop/src/store/agent-plugins.test.ts
+++ b/apps/desktop/src/store/agent-plugins.test.ts
@@ -86,6 +86,43 @@ describe('installAgentPlugin', () => {
expect(request.mock.calls[1][1]).not.toHaveProperty('inspected_sha')
})
+ it('never drops the inspected commit for an install failure that merely quotes the admission refusal', async () => {
+ // A git server controls its clone error's text; the backend forwards it as a 5026 install failure.
+ // Only a code-4000 refusal OPENING with the admission prefix means "this backend predates the field".
+ const quoted =
+ 'Git clone failed: remote: invalid params for plugins.manage: inspected_sha: Extra inputs are not permitted'
+
+ for (const error of [
+ new JsonRpcGatewayError('invalid params for plugins.manage: inspected_sha: Extra inputs are not permitted', {
+ code: 5026
+ }),
+ new JsonRpcGatewayError(quoted, { code: 4000 }),
+ new Error('invalid params for plugins.manage: inspected_sha: Extra inputs are not permitted')
+ ]) {
+ const request = vi.fn(async () => {
+ throw error
+ })
+
+ expect(
+ await installAgentPlugin(request as never, { identifier: 'https://github.com/example/pkg', inspectedSha: reviewed })
+ ).toMatchObject({ ok: false })
+ expect(request).toHaveBeenCalledTimes(1)
+ }
+ })
+
+ it('reports a refusal carrying the backend source-moved marker as sourceMoved, and only that one', async () => {
+ const refusing = (data?: unknown) =>
+ vi.fn(async () => {
+ throw new JsonRpcGatewayError('The source changed since you reviewed it.', { code: 5026, data })
+ })
+
+ const install = (request: ReturnType<typeof refusing>) =>
+ installAgentPlugin(request as never, { identifier: 'https://github.com/example/pkg', inspectedSha: reviewed })
+
+ expect(await install(refusing({ reason: 'source_moved' }))).toMatchObject({ ok: false, sourceMoved: true })
+ expect(await install(refusing())).toMatchObject({ ok: false, sourceMoved: false })
+ })
+
it('holds a current backend to the inspected commit and never resends a refusal of the moved branch', async () => {
const request = vi.fn(async () => {
throw new JsonRpcGatewayError(
diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.ts
index 855c0b2c0e7..6cdecbaf86e 100644
--- a/apps/desktop/src/store/agent-plugins.ts
+++ b/apps/desktop/src/store/agent-plugins.ts
@@ -252,6 +252,8 @@ export interface AgentPluginInstallResult {
ok: boolean
/** The client stopped waiting; the backend may still finish the install. */
timedOut?: boolean
+ /** Refused: the source moved off the reviewed commit (`isSourceMovedRefusal`). */
+ sourceMoved?: boolean
pluginName?: string
warnings?: string[]
missingEnv?: string[]
@@ -302,15 +304,30 @@ interface InstallReply {
error?: string
}
+/** The message `tui_gateway/contracts/registry.py::validate_params` opens its admission refusal with. */
+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 (`tui_gateway/contracts/registry.py::validate_params`, code 4000, handler
- * never ran), so resending without it installs the branch tip exactly as those backends always did.
- * Matched on the stable prefix, as `session-create-request.ts` does. Delete once no supported backend
- * predates the field. */
+ * 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. */
function backendPredatesInspectedSha(params: Record<string, unknown>, error: unknown): boolean {
- const message = error instanceof Error ? error.message : String(error)
+ return (
+ 'inspected_sha' in params &&
+ error instanceof JsonRpcGatewayError &&
+ error.code === 4000 &&
+ error.message.startsWith(INSPECTED_SHA_ADMISSION_REFUSAL)
+ )
+}
+
+/** The backend refused because the source is no longer at the commit the dialog reviewed
+ * (`tui_gateway/methods_tools.py::_source_moved_data`): read it again, never resend that commit. */
+export function isSourceMovedRefusal(error: unknown): boolean {
+ const data = error instanceof JsonRpcGatewayError ? (error.data as { reason?: unknown } | undefined) : undefined
- return 'inspected_sha' in params && message.includes('invalid params for plugins.manage: inspected_sha:')
+ return data?.reason === 'source_moved'
}
export async function installAgentPlugin(
@@ -384,6 +401,7 @@ export async function installAgentPlugin(
return {
ok: false,
timedOut: /^request timed out after \d+s: plugins\.manage$/.test(message),
+ sourceMoved: isSourceMovedRefusal(e),
error: message,
live: NO_LIVE,
nextChat: false
@@ -483,6 +501,8 @@ export async function installDesktopPluginHalf(
pluginName?: string
/** The backend predates the action: no retry changes that (a build older than this one). */
unsupported?: boolean
+ /** Refused: the source moved off the reviewed commit (`isSourceMovedRefusal`). */
+ sourceMoved?: boolean
warnings: string[]
error?: string
}> {
@@ -522,6 +542,7 @@ export async function installDesktopPluginHalf(
return {
ok: false,
unsupported: e instanceof JsonRpcGatewayError && INSTALL_DESKTOP_UNSUPPORTED_CODES.has(e.code ?? 0),
+ sourceMoved: isSourceMovedRefusal(e),
warnings: [],
error: e instanceof Error ? e.message : String(e)
}
diff --git a/hermes_cli/desktop_plugin_install.py b/hermes_cli/desktop_plugin_install.py
index 0a5b273b1cb..8f17e49dde5 100644
--- a/hermes_cli/desktop_plugin_install.py
+++ b/hermes_cli/desktop_plugin_install.py
@@ -112,7 +112,7 @@ def install_desktop_plugin(identifier: str, *, ref: Optional[str], catalog_name:
# annotated-tag pin names the tag object, and only its peeled commit is what the dialog read.
head = pc._clone_plugin_repo(clone, git_url, catalog_sha or sha, subdir)
if head != sha:
- raise pc.PluginOperationError(
+ raise pc.PluginSourceMoved(
"The catalog's reviewed commit changed since the dialog read it; inspect it again.")
# Nothing reads a plugin's Git metadata, and Git's read-only object files would make the
# published folder one that Windows cannot delete.
@@ -136,7 +136,7 @@ def install_desktop_plugin(identifier: str, *, ref: Optional[str], catalog_name:
return _failure(f"Desktop plugin '{folder}' already exists. Enable force reinstall to replace it.")
halves.publish_desktop_tree(source_dir, target, marker)
except pc.PluginOperationError as exc:
- return _failure(str(exc))
+ return {**_failure(str(exc)), **({"source_moved": True} if isinstance(exc, pc.PluginSourceMoved) else {})}
except OSError as exc:
return _failure(f"Could not install the desktop plugin: {exc}")
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 82055e85679..8bfd8af47c2 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -95,6 +95,13 @@ class PluginOperationError(Exception):
self.failure_class = failure_class
+class PluginSourceMoved(PluginOperationError):
+ """The source is no longer at the commit the install dialog reviewed. Clients answer it by reading
+ the source again (``plugins.manage`` error ``data.reason == "source_moved"``), never by resending."""
+
+ failure_class = "clone_failed"
+
+
class PluginScanBlocked(PluginOperationError):
"""Plugin failed the security scan and was not installed."""
diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.py
index ffb478651b7..5d1ef6b5081 100644
--- a/hermes_cli/plugins_cmd_install.py
+++ b/hermes_cli/plugins_cmd_install.py
@@ -372,9 +372,9 @@ def _clone_at_reviewed_commit(tmp_clone: Path, git_url: str, requested_revision:
"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)
if head != sha:
- raise _pc().PluginOperationError(
+ raise _pc().PluginSourceMoved(
f"The source changed since you reviewed it: it is now at commit {head[:12]}, not {sha[:12]}. "
- "Re-open the install dialog to review the new version.", failure_class="clone_failed")
+ "Re-open the install dialog to review the new version.")
return head
@@ -861,7 +861,7 @@ def _place_tree(entry, identifier: str, *, force: bool, ref: Optional[str], assu
except _pc().PluginScanBlocked as exc:
return scan_blocked_result(exc)
except _pc().PluginOperationError as exc:
- return {"ok": False, "error": str(exc)}
+ return {"ok": False, "error": str(exc), **({"source_moved": True} if isinstance(exc, _pc().PluginSourceMoved) else {})}
def _enable_placed(installed_name: str, deps, step: Callable[[InstallPhase], None]) -> Optional[dict]:
diff --git a/tests/hermes_cli/test_desktop_plugin_install.py b/tests/hermes_cli/test_desktop_plugin_install.py
index e8454be848a..6e5c21a279f 100644
--- a/tests/hermes_cli/test_desktop_plugin_install.py
+++ b/tests/hermes_cli/test_desktop_plugin_install.py
@@ -233,6 +233,7 @@ def test_a_catalog_pin_that_moved_since_the_review_is_refused(home, repo, monkey
result = install.install_desktop_plugin(URL, ref=reviewed, catalog_name="gizmo")
assert result["ok"] is False and "inspect it again" in result["error"], result
+ assert result.get("source_moved") is True # the client re-reads the source instead of resending
assert not (_root(home) / "gizmo").exists()
diff --git a/tests/hermes_cli/test_plugin_install_inspected_sha.py b/tests/hermes_cli/test_plugin_install_inspected_sha.py
index df984557859..6cfe8925280 100644
--- a/tests/hermes_cli/test_plugin_install_inspected_sha.py
+++ b/tests/hermes_cli/test_plugin_install_inspected_sha.py
@@ -69,9 +69,28 @@ def test_install_refuses_a_branch_that_moved_since_the_dialog_inspected_it(moved
message = refused["error"]["message"]
assert "source changed since you reviewed it" in message and tip[:12] in message
+ # The client re-inspects on this structured marker, never on the message text.
+ assert refused["error"]["data"] == {"reason": "source_moved"}
assert not (home / "plugins" / "demo").exists()
+def test_a_clone_failure_echoing_the_refusal_text_carries_no_marker(moved_repo, monkeypatch):
+ """A git server controls its clone error's text, so that text can say anything; only the backend's
+ own comparison of commits tags the refusal."""
+ from hermes_cli import plugins_cmd
+ _home, reviewed, _tip, _repo = moved_repo
+
+ def hostile(*_args, **_kwargs):
+ raise plugins_cmd.PluginOperationError(
+ "Git clone failed: remote: The source changed since you reviewed it: it is now at commit 0a415bc5c1d2. "
+ "invalid params for plugins.manage: inspected_sha: Extra inputs are not permitted")
+ monkeypatch.setattr(plugins_cmd, "_clone_plugin_repo", hostile)
+
+ refused = _install(inspected_sha=reviewed)["error"]
+
+ assert refused["code"] == 5026 and "data" not in refused
+
+
def test_reopening_the_dialog_after_a_refusal_reads_the_moved_source_again(moved_repo):
_home, reviewed, tip, repo = moved_repo
inspect = {"id": "1", "method": "plugins.manage",
diff --git a/tests/tui_gateway/test_plugins_manage_install_desktop.py b/tests/tui_gateway/test_plugins_manage_install_desktop.py
index cbc7b948c8b..61a4785f4b4 100644
--- a/tests/tui_gateway/test_plugins_manage_install_desktop.py
+++ b/tests/tui_gateway/test_plugins_manage_install_desktop.py
@@ -39,6 +39,7 @@ def test_install_desktop_round_trips_through_the_rpc(tmp_path, monkeypatch):
refused = _manage(action="install_desktop", **source)
assert refused["error"]["code"] == 5026 and "already exists" in refused["error"]["message"]
+ assert "data" not in refused["error"] # an ordinary refusal: the client offers Retry, not a re-review
assert _manage(action="remove_desktop", name="gizmo")["result"]["ok"] is True
assert not (home / "desktop-plugins" / "gizmo").exists()
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 109110fc54f..2bd46cb1db7 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -1754,6 +1754,12 @@ def _plugins_toggle(rid, params):
"name": key, "plugin": row}, key))
+def _source_moved_data(result: dict) -> dict | None:
+ """The structured marker of an install refused because the source left the reviewed commit: the
+ client re-inspects on ``reason``, never on the message, which echoes text a git server controls."""
+ return {"reason": "source_moved"} if result.get("source_moved") else None
+
+
def _plugins_install(rid, params):
# ``catalog_name`` alone installs a curated entry at its pinned SHA (resolved server-side, kill list
# enforced, no bypass) — same contract as the dashboard endpoint.
@@ -1767,7 +1773,7 @@ def _plugins_install(rid, params):
ref=str(params.get("ref") or "").strip() or None,
inspected_sha=str(params.get("inspected_sha") or "").strip() or None)
if not result.get("ok"):
- return _err(rid, 5026, result.get("error") or "install failed")
+ return _err(rid, 5026, result.get("error") or "install failed", data=_source_moved_data(result))
return _ok(rid, _with_activation(result, str(result.get("plugin_name") or "")) if result.get("enabled") else result)
@@ -1792,7 +1798,9 @@ def _plugins_install_desktop(rid, params):
return _err(rid, 4019, "plugins.manage install_desktop requires 'identifier', 'repo', or 'catalog_name'")
result = _tools_mod("hermes_cli.desktop_plugin_install").install_desktop_plugin(
ident, ref=params.get("ref"), catalog_name=catalog_name or None, force=bool(params.get("force")))
- return _ok(rid, result) if result.get("ok") else _err(rid, 5026, result.get("error") or "desktop install failed")
+ if not result.get("ok"):
+ return _err(rid, 5026, result.get("error") or "desktop install failed", data=_source_moved_data(result))
+ return _ok(rid, result)
def _plugins_remove_desktop(rid, params):
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 3b16fac334c..0828f6da9b5 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -727,8 +727,9 @@ the same folder name native Desktop uses. The host installs exactly the commit t
the one you pinned) and refuses if that commit cannot be fetched. A package that also ships an agent
plugin is installed once, as an agent plugin on that host, and the host copies its desktop half out of
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, the install is refused and re-opening
-the dialog reads the new version (native Desktop works the same way). Because a browser tab asks for it, 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
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