Skip to content

The agent that grows with you

fix(plugins): an install dialog installs only the commit it inspected

Teknium2c64c7fdb717
diff --git a/apps/desktop/electron/desktop-plugin-install.test.ts b/apps/desktop/electron/desktop-plugin-install.test.ts
index 9253d45a6b5..7eb66cf8ddd 100644
--- a/apps/desktop/electron/desktop-plugin-install.test.ts
+++ b/apps/desktop/electron/desktop-plugin-install.test.ts
@@ -246,6 +246,27 @@ describe('installDesktopPluginFromGit', () => {
return repo
}
+ it('installs the commit the dialog reviewed after the branch moved, and refuses one the source lacks', async () => {
+ const repo = pluginRepo(null, { 'panel.js': 'reviewed\n' })
+ const git = (...args: string[]) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' }).toString().trim()
+ const appRoot = mkdtemp('hermes-plugin-root-')
+ roots.push(appRoot)
+ const probe = await probePluginRepo('git', pathToFileURL(repo).href)
+ expect(probe.sha).toBe(git('rev-parse', 'HEAD'))
+ fs.writeFileSync(path.join(repo, 'desktop', 'panel.js'), 'moved\n')
+ git('-c', '[email protected]', '-c', 'user.name=Fixture', 'commit', '-qam', 'moved')
+
+ const result = await installDesktopPluginFromGit('git', pathToFileURL(repo).href, appRoot, false, probe.sha)
+
+ expect(result).toMatchObject({ ok: true })
+ 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.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')
+ })
+
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 40d2200bf30..15314271771 100644
--- a/apps/desktop/electron/desktop-plugin-install.ts
+++ b/apps/desktop/electron/desktop-plugin-install.ts
@@ -44,6 +44,8 @@ export interface PluginProbeResult {
desktopName?: string | null
warnings: string[]
insecure: boolean
+ /** The commit that was read; an install of this source is held to it. */
+ sha?: string
error?: string
}
@@ -371,6 +373,48 @@ 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'], {
+ cwd: cloneRoot,
+ env: noninteractiveGitEnv(),
+ timeoutMs: GIT_TIMEOUT_MS
+ })
+
+ if (code !== 0) {
+ throw new Error(`Git rev-parse failed:\n${stderr.trim()}`)
+ }
+
+ return stdout.trim().toLowerCase()
+}
+
+/** Detach the clone at `sha`, the commit the install dialog showed: a branch that moved after review must
+ * not put down a tree nobody inspected. A source that no longer has it is refused. */
+async function checkoutReviewedCommit(gitBin: string, cloneRoot: string, sha: string): Promise<void> {
+ const reviewed = sha.trim().toLowerCase()
+
+ if (!COMMIT_SHA.test(reviewed)) {
+ throw new Error('Installing a desktop plugin needs the full commit the install dialog reviewed.')
+ }
+
+ try {
+ if ((await headSha(gitBin, cloneRoot)) !== reviewed) {
+ await runGitOrThrow(gitBin, ['fetch', '--depth', '1', 'origin', reviewed], cloneRoot)
+ await runGitOrThrow(gitBin, ['checkout', '--detach', reviewed], cloneRoot)
+ }
+
+ if ((await headSha(gitBin, cloneRoot)) !== reviewed) {
+ throw new Error(`HEAD is not ${reviewed}.`)
+ }
+ } catch (err) {
+ throw new Error(
+ `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)}`
+ )
+ }
+}
+
async function resolvePluginRoot(cloneRoot: string, subdir: string | null): Promise<string> {
if (!subdir) {
return cloneRoot
@@ -425,7 +469,8 @@ export async function probePluginRepo(gitBin: string, identifier: string): Promi
agentName: detected.agentName ?? (detected.agent ? repoFallback : null),
desktopName: detected.desktop ? desktopPluginFolderName(gitUrl, subdir) : null,
warnings,
- insecure
+ insecure,
+ sha: await headSha(gitBin, cloneRoot)
}
} finally {
await fsp.rm(cloneRoot, { recursive: true, force: true }).catch(() => undefined)
@@ -446,13 +491,20 @@ export async function installDesktopPluginFromGit(
gitBin: string,
identifier: string,
desktopPluginsRoot: string,
- force = false
+ force = false,
+ /** The commit the install dialog reviewed (`probePluginRepo`'s `sha`): the half is installed from
+ * exactly that tree or refused. */
+ sha?: string
): Promise<DesktopPluginInstallResult> {
try {
const { gitUrl, subdir } = resolvePluginGitUrl(identifier)
const cloneRoot = await cloneToTemp(gitBin, gitUrl, subdir)
try {
+ if (sha !== undefined) {
+ await checkoutReviewedCommit(gitBin, cloneRoot, sha)
+ }
+
const pluginRoot = await resolvePluginRoot(cloneRoot, subdir)
const detected = await detectPluginComponents(pluginRoot)
diff --git a/apps/desktop/electron/fs-ipc.ts b/apps/desktop/electron/fs-ipc.ts
index a70a1cf8459..666a7801da9 100644
--- a/apps/desktop/electron/fs-ipc.ts
+++ b/apps/desktop/electron/fs-ipc.ts
@@ -191,7 +191,8 @@ export function registerFsIpc({
resolveGitBinary(),
identifier,
await desktopPluginsRoot(),
- Boolean(payload?.force)
+ Boolean(payload?.force),
+ typeof payload?.sha === 'string' ? payload.sha : undefined
)
})
diff --git a/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx b/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx
index 7bd333679b1..16b396dbc57 100644
--- a/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx
@@ -234,6 +234,24 @@ describe('Plugin install in the browser-hosted app with a backend that installs
await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())
})
+ it('holds the agent install to the commit the dialog inspected', async () => {
+ const reviewed = 'e404b6816b20237a82f6fbe2749b5a576cf75dba'
+
+ desktopBackend({ ok: true, agent: true, agent_name: 'pkg', desktop: false, sha: reviewed, warnings: [] }, {},
+ { ok: true, plugin_name: 'pkg', enabled: true })
+
+ renderModal()
+ act(() => openPluginInstallRequest({ repo: 'https://github.com/example/pkg' }))
+
+ await waitFor(() => expect(installButton()?.disabled).toBe(false))
+ fireEvent.click(installButton()!)
+
+ await waitFor(() => expect(callsFor('install')).toHaveLength(1))
+ expect(callsFor('install')[0][1]).toMatchObject({ action: 'install', inspected_sha: reviewed })
+ // Not a pin: the backend refuses a branch that moved, and updates still follow the branch.
+ expect(callsFor('install')[0][1]).not.toHaveProperty('ref')
+ })
+
it('installs a mixed package once and has the host copy its desktop half out of that checkout', async () => {
const reviewed = 'e404b6816b20237a82f6fbe2749b5a576cf75dba'
// The browser bridge's door to the host's desktop-plugins folder (browser-desktop-plugins.ts): the
diff --git a/apps/desktop/src/app/settings/plugin-install-modal.test.tsx b/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
index abd2bab095d..3e12c8034ec 100644
--- a/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
@@ -335,6 +335,26 @@ describe('Unified package desktop half on a local backend', () => {
expect(installDesktopPlugin).not.toHaveBeenCalled()
})
+ it('holds both halves to the commit Electron inspected', async () => {
+ const reviewed = '0123456789abcdef0123456789abcdef01234567'
+ $connection.set({ mode: 'remote' } as NonNullable<ReturnType<typeof $connection.get>>)
+ probePluginRepo.mockResolvedValue({ ok: true, agent: true, agentName: 'pkg', desktop: true, sha: reviewed, warnings: [] })
+ requestGateway.mockImplementation(async (method, params) =>
+ method === 'plugins.manage' && params?.action === 'install' ? { ok: true, plugin_name: 'pkg' } : { plugins: [] }
+ )
+ installDesktopPlugin.mockResolvedValue({ ok: true, pluginName: 'pkg' })
+ vi.stubGlobal('hermesDesktop', { installDesktopPlugin, probePluginRepo, reconcileDesktopPlugins })
+ renderFlow()
+ act(() => openPluginInstallRequest({ repo: 'https://github.com/example/pkg' }))
+ expect(await screen.findByText('This package includes')).toBeTruthy()
+ await waitFor(() => expect(installButton().disabled).toBe(false))
+ fireEvent.click(installButton())
+
+ await waitFor(() => expect(installDesktopPlugin).toHaveBeenCalled())
+ expect(installCalls()[0]?.[1]).toMatchObject({ action: 'install', inspected_sha: reviewed })
+ expect(installDesktopPlugin).toHaveBeenCalledWith({ identifier: 'https://github.com/example/pkg', force: false, sha: reviewed })
+ })
+
it('still clones the desktop half for a remote backend', async () => {
// A remote backend's plugins/ folder is unreadable from this machine, so
// the separate clone remains the only door for its desktop half.
diff --git a/apps/desktop/src/app/settings/plugin-install-run.ts b/apps/desktop/src/app/settings/plugin-install-run.ts
index e70fcceb58f..fb7ddec4cc3 100644
--- a/apps/desktop/src/app/settings/plugin-install-run.ts
+++ b/apps/desktop/src/app/settings/plugin-install-run.ts
@@ -124,6 +124,9 @@ 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,
profile: plan.profile
})
@@ -150,7 +153,7 @@ async function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, repor
const installFn = window.hermesDesktop?.installDesktopPlugin
const result: { error?: string; ok: boolean; pluginName?: string; unsupported?: boolean } = installFn
- ? await installFn({ identifier: plan.request.repo, force: plan.force })
+ ? 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,
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index bf713933189..9c67651654c 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -666,6 +666,8 @@ declare global {
identifier?: string
repo?: string
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 }>
/** Delete a STANDALONE desktop plugin folder (`<desktop-plugins root>/<name>`);
* Electron re-checks containment and refuses unified-package halves. */
diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.ts
index d5b15939200..f63d83f2cf4 100644
--- a/apps/desktop/src/store/agent-plugins.ts
+++ b/apps/desktop/src/store/agent-plugins.ts
@@ -297,6 +297,9 @@ export async function installAgentPlugin(
catalogName?: string
/** Pin a custom source to one full commit SHA (team-wide reproducible install). */
ref?: string
+ /** The commit the install dialog inspected: a custom source with no `ref` whose branch moved since is
+ * refused by the backend, never installed at the new tip. */
+ inspectedSha?: string
/** Target profile's HERMES_HOME (null/undefined = backend launch profile). */
profile?: string | null
}
@@ -325,7 +328,8 @@ export async function installAgentPlugin(
force: Boolean(opts.force),
enable: opts.enable ?? true,
...(opts.catalogName ? { catalog_name: opts.catalogName } : {}),
- ...(opts.ref ? { ref: opts.ref } : {})
+ ...(opts.ref ? { ref: opts.ref } : {}),
+ ...(!opts.ref && opts.inspectedSha ? { inspected_sha: opts.inspectedSha } : {})
},
opts.profile
),
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 652e7064d69..b4be1f6440e 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4388,7 +4388,7 @@ export interface PluginToolsetRow {
label: string
description: string
}
-/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``; ``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit ``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) — the desktop half onto the host that serves this client; ``remove_desktop``: ``name`` (+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose security scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only); ``presence``: ``names`` (catalog names, answered in that order). */
+/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``, ``inspected_sha`` = the commit ``inspect`` read: a custom source with no ``ref`` whose branch moved since is refused); ``inspect``: ``identifier``/``repo`` or ``catalog_name``; ``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit ``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) — the desktop half onto the host that serves this client; ``remove_desktop``: ``name`` (+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose security scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only); ``presence``: ``names`` (catalog names, answered in that order). */
export interface PluginsManageParams {
profile?: string | null
action?: PluginsAction
@@ -4400,6 +4400,7 @@ export interface PluginsManageParams {
catalog_name?: string | null
force?: boolean | null
ref?: string | null
+ inspected_sha?: string | null
accept_capabilities?: boolean | null
values?: Record<string, unknown> | null
names?: string[] | null
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 89a922b684b..3a8fa20fac6 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -27775,7 +27775,7 @@
},
"PluginsManageParams": {
"additionalProperties": false,
- "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``;\n``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit\n``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) \u2014 the desktop half onto\nthe host that serves this client; ``remove_desktop``: ``name``\n(+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose\nsecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);\n``presence``: ``names`` (catalog names, answered in that order).",
+ "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``, ``inspected_sha`` = the commit ``inspect`` read: a custom source with no\n``ref`` whose branch moved since is refused); ``inspect``: ``identifier``/``repo`` or ``catalog_name``;\n``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit\n``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) \u2014 the desktop half onto\nthe host that serves this client; ``remove_desktop``: ``name``\n(+ ``force`` for a package's own half); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose\nsecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);\n``presence``: ``names`` (catalog names, answered in that order).",
"properties": {
"profile": {
"anyOf": [
@@ -27889,6 +27889,18 @@
"default": null,
"title": "Ref"
},
+ "inspected_sha": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Inspected Sha"
+ },
"accept_capabilities": {
"anyOf": [
{
diff --git a/hermes_cli/plugins_cmd_inspect.py b/hermes_cli/plugins_cmd_inspect.py
index 7391e55b1a8..ed9ee2f0ca2 100644
--- a/hermes_cli/plugins_cmd_inspect.py
+++ b/hermes_cli/plugins_cmd_inspect.py
@@ -145,6 +145,17 @@ def _copy(result: dict[str, Any]) -> dict[str, Any]:
return {**result, "warnings": list(result["warnings"])}
+def forget_inspection(identifier: str, *, catalog_name: Optional[str] = None) -> None:
+ """Drop the kept answer for this source in the current profile home once an install consumed it: a
+ source that moved since must be read afresh when the dialog re-opens, not served for the rest of
+ :data:`_RESULT_TTL_SECONDS`. A read still running is left for the requests joined to it."""
+ from hermes_constants import get_hermes_home
+ key = (str(get_hermes_home()), catalog_name or "", identifier)
+ with _inspections_lock:
+ if _inspections.get(key, [None, None])[1] is not None:
+ del _inspections[key]
+
+
def _inspect(identifier: str, catalog_name: Optional[str]) -> dict[str, Any]:
pc = _pc()
revision = None
diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.py
index e0062e36a7c..ffb478651b7 100644
--- a/hermes_cli/plugins_cmd_install.py
+++ b/hermes_cli/plugins_cmd_install.py
@@ -356,6 +356,28 @@ 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:
+ """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."""
+ 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:
+ 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)
+ if head != sha:
+ raise _pc().PluginOperationError(
+ 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")
+ return head
+
+
def _install_plugin_core(
identifier: str,
*,
@@ -370,6 +392,7 @@ def _install_plugin_core(
allow_removed: bool = False,
before_swap=None,
app_title: Optional[str] = None,
+ inspected_sha: Optional[str] = None,
) -> tuple[Path, dict, str]:
"""Clone a Git plugin and atomically record its source and exact revision.
@@ -388,7 +411,8 @@ def _install_plugin_core(
included). It may return the relative paths it merged in, which a scan block then attributes,
and may raise :class:`PluginOperationError` to abort (re-pin consent). *accept_caution* decides a
caution scan verdict on its own when *force* only means "replace the existing tree" (an update's
- re-clone); None lets *force* decide both, as ``install --force`` does."""
+ re-clone); None lets *force* decide both, as ``install --force`` does. *inspected_sha*: see
+ :func:`_clone_at_reviewed_commit`."""
requested_revision = _pc()._normalize_exact_revision(ref) if ref is not None else None
try:
git_url, subdir = _pc()._resolve_git_url(identifier)
@@ -408,7 +432,7 @@ def _install_plugin_core(
with tempfile.TemporaryDirectory(prefix=".install-", dir=plugins_dir) as tmp:
tmp_clone = Path(tmp) / "plugin"
- installed_revision = _pc()._clone_plugin_repo(tmp_clone, git_url, requested_revision, subdir)
+ installed_revision = _clone_at_reviewed_commit(tmp_clone, git_url, requested_revision, inspected_sha, subdir)
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)
@@ -812,10 +836,11 @@ def _resolve_source(identifier: str, catalog_name: Optional[str]) -> tuple:
def _place_tree(entry, identifier: str, *, force: bool, ref: Optional[str], assume_deps_consent: bool,
- step: Callable[[InstallPhase], None]) -> tuple | dict:
+ step: Callable[[InstallPhase], None], inspected_sha: Optional[str] = None) -> tuple | dict:
"""``(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."""
+ 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."""
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
@@ -826,7 +851,8 @@ def _place_tree(entry, identifier: str, *, force: bool, ref: Optional[str], assu
if entry is not None:
return catalog.install_catalog_entry(entry, force=force, ref=ref, allow_removed=False,
assume_deps_consent=assume_deps_consent)
- return _pc()._install_plugin_core(identifier, force=force, ref=ref, assume_deps_consent=assume_deps_consent)
+ return _pc()._install_plugin_core(identifier, force=force, ref=ref, assume_deps_consent=assume_deps_consent,
+ inspected_sha=None if ref else inspected_sha)
step(InstallPhase.downloading)
try:
@@ -856,7 +882,7 @@ def _enable_placed(installed_name: str, deps, step: Callable[[InstallPhase], Non
def dashboard_install_plugin(
identifier: str, *, force: bool, enable: bool, catalog_name: Optional[str] = None,
ref: Optional[str] = None, assume_deps_consent: Optional[bool] = None,
- on_step: Optional[Callable[[InstallPhase], None]] = None,
+ on_step: Optional[Callable[[InstallPhase], None]] = None, inspected_sha: Optional[str] = None,
) -> dict[str, Any]:
"""Non-interactive install for the dashboard/TUI. *catalog_name* installs a curated entry at its
pinned SHA (identifier may be empty); *ref* pins either source to one full commit SHA (same
@@ -865,14 +891,20 @@ def dashboard_install_plugin(
None (a user's Install click) is the consent the fresh-install enable already acts on: a 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)."""
+ *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."""
if assume_deps_consent is None:
assume_deps_consent = enable and not force
step = on_step or (lambda _phase: None)
+ if inspected_sha:
+ # The dialog's inspection is spent either way; re-opening it must read the source again.
+ from hermes_cli.plugins_cmd_inspect import forget_inspection
+ forget_inspection(identifier, catalog_name=catalog_name)
entry, identifier, warnings, error = _resolve_source(identifier, catalog_name)
if error is not None:
return error
- placed = _place_tree(entry, identifier, force=force, ref=ref, assume_deps_consent=assume_deps_consent, step=step)
+ placed = _place_tree(entry, identifier, force=force, ref=ref, assume_deps_consent=assume_deps_consent, step=step,
+ inspected_sha=inspected_sha)
if isinstance(placed, dict):
return placed
target, installed_manifest, installed_name = placed
diff --git a/tests/hermes_cli/test_plugin_install_inspected_sha.py b/tests/hermes_cli/test_plugin_install_inspected_sha.py
new file mode 100644
index 00000000000..df984557859
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_install_inspected_sha.py
@@ -0,0 +1,98 @@
+"""An install dialog's ``plugins.manage install`` is held to the commit its ``inspect`` read.
+
+The dialog shows the user one commit; the branch may move before Install is clicked. The agent half (and
+the desktop half the host copies out of that checkout) must never be a tree nobody reviewed: a moved
+branch is refused. An install at the reviewed tip stays an unpinned checkout of the branch, so ``update``
+still follows it. Real RPC dispatch, real clone of a local repo.
+"""
+
+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
+
+
[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", *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, "-c", "[email protected]", "-c", "user.name=t", "commit", "-qm", marker)
+ return _git(repo, "rev-parse", "HEAD")
+
+
+def _install(**params):
+ return server.handle_request({"id": "1", "method": "plugins.manage",
+ "params": {"action": "install", "identifier": "https://example.invalid/acme/demo.git",
+ "enable": False, **params}})
+
+
+def moved_repo(tmp_path, monkeypatch):
+ """``(home, reviewed_sha, tip_sha, repo)``: a repo the dialog inspected at ``reviewed`` whose branch then moved."""
+ from hermes_cli import plugins_cmd
+ 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")
+ reviewed = _commit(repo, "reviewed")
+ tip = _commit(repo, "moved")
+ 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))
+ from hermes_constants import get_hermes_home
+ return get_hermes_home(), reviewed, tip, repo
+
+
+def test_install_refuses_a_branch_that_moved_since_the_dialog_inspected_it(moved_repo):
+ home, reviewed, tip, _repo = moved_repo
+
+ refused = _install(inspected_sha=reviewed)
+
+ message = refused["error"]["message"]
+ assert "source changed since you reviewed it" in message and tip[:12] in message
+ assert not (home / "plugins" / "demo").exists()
+
+
+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",
+ "params": {"action": "inspect", "identifier": "https://example.invalid/acme/demo.git"}}
+ _git(repo, "update-ref", "refs/heads/main", reviewed)
+ assert server.handle_request(inspect)["result"]["sha"] == reviewed
+ _git(repo, "update-ref", "refs/heads/main", tip) # the branch moves while the dialog is open
+ assert "source changed" in _install(inspected_sha=reviewed)["error"]["message"]
+
+ assert server.handle_request(inspect)["result"]["sha"] == tip
+
+
+def test_install_at_the_inspected_tip_stays_an_unpinned_branch_checkout(moved_repo):
+ home, _reviewed, tip, _repo = moved_repo
+
+ result = _install(inspected_sha=tip)["result"]
+
+ assert result["ok"] is True
+ target = home / "plugins" / "demo"
+ assert (target / "marker.txt").read_text() == "moved"
+ record = json.loads((home / "plugins" / ".install-metadata.json").read_text())["demo"]
+ assert (record["revision"], record["pinned"]) == (tip, False)
+ # On the branch, not detached at a sha: a later `update` can still pull it forward.
+ assert _git(target, "symbolic-ref", "--short", "HEAD") == "main"
diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.py
index 25f9e6cf692..fd6845989c3 100644
--- a/tui_gateway/contracts/tools_mcp_plugins.py
+++ b/tui_gateway/contracts/tools_mcp_plugins.py
@@ -628,7 +628,8 @@ class PluginsAction(WireEnum):
class PluginsManageParams(ProfileParams):
"""``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``
- (+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``;
+ (+ ``force``, ``enable``, ``ref``, ``inspected_sha`` = the commit ``inspect`` read: a custom source with no
+ ``ref`` whose branch moved since is refused); ``inspect``: ``identifier``/``repo`` or ``catalog_name``;
``install_desktop``: ``identifier``/``repo`` (https only) or ``catalog_name`` + ``ref`` (the commit
``inspect`` read and the dialog showed; another commit is refused) (+ ``force``) — the desktop half onto
the host that serves this client; ``remove_desktop``: ``name``
@@ -647,6 +648,7 @@ class PluginsManageParams(ProfileParams):
catalog_name: str | None = None
force: bool | None = None
ref: str | None = None
+ inspected_sha: str | None = None
accept_capabilities: bool | None = None
values: dict[str, JsonValue] | None = None
names: list[str] | None = None
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 1b379227d0a..109110fc54f 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -1764,7 +1764,8 @@ def _plugins_install(rid, params):
_ensure_plugin_activation_listener()
result = _tools_mod("hermes_cli.plugins_cmd").dashboard_install_plugin(
ident, force=bool(params.get("force")), enable=params.get("enable", True), catalog_name=catalog_name or None,
- ref=str(params.get("ref") or "").strip() or None)
+ 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 _ok(rid, _with_activation(result, str(result.get("plugin_name") or "")) if result.get("enabled") else result)
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 18d9a094218..3b16fac334c 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -726,7 +726,9 @@ first, then has the host that serves the tab clone a desktop-only repository int
the same folder name native Desktop uses. The host installs exactly the commit the dialog showed (or
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. Because a browser tab asks for it, the
+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
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