Skip to content

The agent that grows with you

fix(desktop-plugins): real copies of linked root checkouts; desktop success from disk; layout moves need no consent

Tekniumccba14cb75e2
diff --git a/apps/desktop/electron/desktop-plugins-root.test.ts b/apps/desktop/electron/desktop-plugins-root.test.ts
index 92032a087d6..426f4611766 100644
--- a/apps/desktop/electron/desktop-plugins-root.test.ts
+++ b/apps/desktop/electron/desktop-plugins-root.test.ts
@@ -259,6 +259,82 @@ describe('reconcileUnifiedDesktopHalves', () => {
expect(fs.existsSync(path.join(appRoot, 'radar'))).toBe(false)
})
+ it.skipIf(process.platform === 'win32')(
+ 'publishes a real copy of a LINKED root-layout checkout, keeps its marker out of the checkout, and prunes it with the link',
+ async () => {
+ const home = makeHome()
+ const appRoot = path.join(home, 'desktop-plugins')
+ const checkout = path.join(home, 'src', 'radar')
+ write(path.join(checkout, 'plugin.yaml'), 'name: radar')
+ write(path.join(checkout, 'plugin.js'), 'root entry')
+ fs.mkdirSync(path.join(home, 'plugins'), { recursive: true })
+ const link = path.join(home, 'plugins', 'radar')
+ fs.symlinkSync(checkout, link)
+ const target = path.join(appRoot, 'radar')
+
+ expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([target])
+ expect(fs.lstatSync(target).isSymbolicLink()).toBe(false)
+ expect(fs.readFileSync(path.join(target, 'plugin.js'), 'utf8')).toBe('root entry')
+ expect(JSON.parse(fs.readFileSync(path.join(target, PACKAGE_MARKER), 'utf8'))).toMatchObject({
+ linked: true,
+ package: 'radar',
+ source: link
+ })
+ expect(fs.existsSync(path.join(checkout, PACKAGE_MARKER))).toBe(false)
+ expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([])
+
+ fs.unlinkSync(link)
+ expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([target])
+ expect(fs.existsSync(target)).toBe(false)
+ expect(fs.readdirSync(checkout).sort()).toEqual(['plugin.js', 'plugin.yaml'])
+ }
+ )
+
+ it.skipIf(process.platform === 'win32')(
+ 'replaces an earlier copy that kept the checkout link, and drops it once the package link is gone',
+ async () => {
+ // What a pass that copied the link itself left: <appRoot>/radar -> the checkout, marker inside it.
+ const home = makeHome()
+ const appRoot = path.join(home, 'desktop-plugins')
+ const checkout = path.join(home, 'src', 'radar')
+ const link = path.join(home, 'plugins', 'radar')
+ const target = path.join(appRoot, 'radar')
+ write(path.join(checkout, 'plugin.js'), 'root entry')
+ const ghost = { linked: true, package: 'radar', source: link, sourceMtimeMs: Date.now() + 60_000 }
+ write(path.join(checkout, PACKAGE_MARKER), JSON.stringify(ghost))
+ fs.mkdirSync(path.join(home, 'plugins'), { recursive: true })
+ fs.mkdirSync(appRoot, { recursive: true })
+ fs.symlinkSync(checkout, link)
+ fs.symlinkSync(checkout, target)
+
+ expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([target])
+ expect(fs.lstatSync(target).isSymbolicLink()).toBe(false)
+ expect(fs.readFileSync(path.join(target, 'plugin.js'), 'utf8')).toBe('root entry')
+
+ // The same leftover once the package link is gone: the link in the app root goes, the checkout stays.
+ fs.rmSync(target, { force: true, recursive: true })
+ fs.symlinkSync(checkout, target)
+ fs.unlinkSync(link)
+ expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([target])
+ expect(fs.existsSync(target)).toBe(false)
+ expect(fs.readFileSync(path.join(checkout, 'plugin.js'), 'utf8')).toBe('root entry')
+ }
+ )
+
+ it.skipIf(process.platform === 'win32')('never stamps a marker into a plugin the user linked into the app root', async () => {
+ const home = makeHome()
+ const appRoot = path.join(home, 'desktop-plugins')
+ const own = path.join(home, 'src', 'pkg')
+ write(path.join(own, 'plugin.js'), 'same')
+ write(path.join(home, 'plugins', 'pkg', 'desktop', 'plugin.js'), 'same')
+ fs.mkdirSync(appRoot, { recursive: true })
+ fs.symlinkSync(own, path.join(appRoot, 'pkg'))
+
+ expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([])
+ expect(fs.existsSync(path.join(own, PACKAGE_MARKER))).toBe(false)
+ expect(fs.lstatSync(path.join(appRoot, 'pkg')).isSymbolicLink()).toBe(true)
+ })
+
it('never overwrites a standalone plugin the user installed under the same name', async () => {
const home = makeHome()
const appRoot = path.join(home, 'desktop-plugins')
diff --git a/apps/desktop/electron/desktop-plugins-root.ts b/apps/desktop/electron/desktop-plugins-root.ts
index f2e69426202..48b9060febc 100644
--- a/apps/desktop/electron/desktop-plugins-root.ts
+++ b/apps/desktop/electron/desktop-plugins-root.ts
@@ -333,6 +333,14 @@ export async function materializeDesktopHalf(
const target = path.join(appRoot, packageName)
const existing = await readMarker(target)
const linked = (await fs.promises.lstat(packageDir)).isSymbolicLink()
+ // A link at `<appRoot>/<name>` is never a copy this pass may keep or stamp: a marker-less one is
+ // the user's own linked plugin, and one carrying a marker is an earlier copy of a linked checkout
+ // that kept the link instead of the files, whose marker sits inside that checkout.
+ const targetIsLink = await isLink(target)
+
+ if (targetIsLink && !existing) {
+ return null
+ }
const marker: DesktopHalfMarker = {
package: packageName,
@@ -374,6 +382,7 @@ export async function materializeDesktopHalf(
// that lands an older timestamp, and the copy would stay stale silently.
if (
existing &&
+ !targetIsLink &&
existing.source === sourceDir &&
Boolean(existing.linked) === linked &&
(linked ? await sameFile(path.join(target, 'plugin.js'), entry) : existing.sourceMtimeMs >= stat.mtimeMs)
@@ -425,7 +434,9 @@ export async function publishDesktopTree(
const staged = path.join(stagingRoot, name)
try {
- await fs.promises.cp(sourceDir, staged, { filter, force: true, recursive: true })
+ // From the resolved folder: `cp` keeps a source that is itself a link (a dev checkout linked into
+ // `plugins/`) as a link, so the published "copy" was the checkout and the marker landed in it.
+ await fs.promises.cp(await fs.promises.realpath(sourceDir), staged, { filter, force: true, recursive: true })
await finalize?.(staged)
// rename() refuses to replace a non-empty directory, so the old copy goes first.
await fs.promises.rm(target, { force: true, recursive: true })
@@ -435,6 +446,14 @@ export async function publishDesktopTree(
}
}
+async function isLink(target: string): Promise<boolean> {
+ try {
+ return (await fs.promises.lstat(target)).isSymbolicLink()
+ } catch {
+ return false
+ }
+}
+
function isMissing(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | null)?.code
@@ -503,7 +522,9 @@ async function reconcilePass(hermesHome: string, appRoot: string): Promise<strin
}
}
- for (const name of await listDirs(appRoot)) {
+ // Links count too: a marker read through one is an earlier copy of a linked checkout that kept the
+ // link, and `rm` drops only the link, never the folder it points at.
+ for (const name of await listDirs(appRoot, true)) {
const dir = path.join(appRoot, name)
const marker = await readMarker(dir)
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 927029c0c8a..7bd333679b1 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
@@ -301,6 +301,39 @@ describe('Plugin install in the browser-hosted app with a backend that installs
}
})
+ it('never reports a desktop half installed when the host pass only pruned the old copy', async () => {
+ // A force reinstall whose new tree dropped its desktop entry: the host's pass deletes
+ // desktop-plugins/pkg and names it among the folders it touched. Nothing is on disk to load.
+ const reconcileDesktopPlugins = vi.fn(async () => ['/srv/hermes/desktop-plugins/pkg'])
+ const desktopPluginsRoot = vi.fn(async () => '/srv/hermes/desktop-plugins')
+
+ const readDir = vi.fn(async (path: string) => ({
+ entries: path === '/srv/hermes/desktop-plugins' ? [{ name: 'other', path: `${path}/other`, isDirectory: true }] : []
+ }))
+
+ window.hermesDesktop = { desktopPluginsRoot, readDir, reconcileDesktopPlugins } as unknown as Window['hermesDesktop']
+
+ try {
+ desktopBackend(
+ { ok: true, agent: true, agent_name: 'pkg', desktop: true, desktop_name: 'pkg', sha: 'e404b6816b20237a82f6fbe2749b5a576cf75dba', warnings: [] },
+ { ok: true, plugin_name: 'pkg', paired_with_agent: true },
+ { 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()!)
+
+ expect(await screen.findByText('Desktop plugin install failed')).toBeTruthy()
+ expect(readDir).toHaveBeenCalledWith('/srv/hermes/desktop-plugins')
+ expect($notifications.get().some(n => n.message === 'Desktop plugin pkg installed')).toBe(false)
+ } finally {
+ delete (window as { hermesDesktop?: unknown }).hermesDesktop
+ }
+ })
+
it('says the install is unavailable when the backend predates the action', async () => {
requestGateway.mockImplementation(async (method, params) => {
if (method !== 'plugins.manage') {
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 44721568e7d..abd2bab095d 100644
--- a/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
@@ -373,6 +373,30 @@ describe('Unified package desktop half on a local backend', () => {
$pluginDecisions.set({})
})
+ it('never reports a desktop half installed when the reconcile only pruned the old copy', async () => {
+ // A force reinstall whose new tree dropped its desktop entry: Electron's pass deletes
+ // desktop-plugins/pkg and names it among the folders it touched.
+ probePluginRepo.mockResolvedValue({ ok: true, agent: true, agentName: 'pkg', desktop: true, warnings: [] })
+ requestGateway.mockImplementation(async (method, params) =>
+ method === 'plugins.manage' && params?.action === 'install'
+ ? { ok: true, plugin_name: 'pkg', enabled: false }
+ : { plugins: [] }
+ )
+ reconcileDesktopPlugins.mockImplementation(async () => ['/app/desktop-plugins/pkg'])
+ const desktopPluginsRoot = vi.fn(async () => '/app/desktop-plugins')
+ const readDir = vi.fn(async () => ({ entries: [] }))
+ vi.stubGlobal('hermesDesktop', { desktopPluginsRoot, installDesktopPlugin, probePluginRepo, readDir, 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())
+
+ expect(await screen.findByText('Desktop plugin install failed')).toBeTruthy()
+ expect(readDir).toHaveBeenCalledWith('/app/desktop-plugins')
+ expect(installDesktopPlugin).not.toHaveBeenCalled()
+ })
+
it('does not start the desktop half or offer a retry when the agent install outcome is unknown', async () => {
$connection.set({ mode: 'remote' } as NonNullable<ReturnType<typeof $connection.get>>)
probePluginRepo.mockResolvedValue({ ok: true, agent: true, agentName: 'pkg', desktop: true, warnings: [] })
diff --git a/apps/desktop/src/app/settings/plugin-install-run.ts b/apps/desktop/src/app/settings/plugin-install-run.ts
index 297d9d4a8d1..e70fcceb58f 100644
--- a/apps/desktop/src/app/settings/plugin-install-run.ts
+++ b/apps/desktop/src/app/settings/plugin-install-run.ts
@@ -173,19 +173,16 @@ async function cloneDesktopHalf(plan: InstallPlan, copy: InstallModalCopy, repor
await discoverRuntimePlugins()
}
-/** Whether the app's desktop-plugins root holds `<name>/plugin.js` after a reconcile: a pass that copied
- * it names the folder; one that found it already current touches nothing, so the folder is read. A
- * reconcile that put nothing down (no entry the host recognises, a refused tree) must not read as
- * installed. */
+/** Whether the app's desktop-plugins root holds `<name>/plugin.js` after a reconcile, read from the folder
+ * itself (Electron's fs bridge, or the host's /api/desktop-plugins on a browser tab). `touched` names
+ * folders the pass DELETED as well as copied (a force reinstall whose new tree dropped its desktop entry
+ * prunes the old copy), and one that found the copy current touches nothing. Only a bridge with no
+ * folder reader falls back to the pass's own list. */
async function desktopHalfLanded(name: string, touched: readonly string[]): Promise<boolean> {
- if (touched.some(folder => folder.split(/[\\/]/).pop() === name)) {
- return true
- }
-
const desktop = window.hermesDesktop
if (!desktop?.desktopPluginsRoot || !desktop.readDir) {
- return false
+ return touched.some(folder => folder.split(/[\\/]/).pop() === name)
}
try {
diff --git a/hermes_cli/desktop_plugin_halves.py b/hermes_cli/desktop_plugin_halves.py
index 28bec598436..92ef5cb7edd 100644
--- a/hermes_cli/desktop_plugin_halves.py
+++ b/hermes_cli/desktop_plugin_halves.py
@@ -206,6 +206,12 @@ def materialize_desktop_half(package_dir: Path, app_root: Path, name: str) -> Pa
target = app_root / name
existing = read_package_marker(target)
linked = package_dir.is_symlink()
+ # A link at ``<app_root>/<name>`` is never a copy this pass may keep or stamp: a marker-less one is
+ # the user's own linked plugin, and one carrying a marker is an earlier copy of a linked checkout
+ # that kept the link instead of the files (Electron's ``cp`` did), its marker inside the checkout.
+ target_is_link = target.is_symlink()
+ if target_is_link and existing is None:
+ return None
marker = {
"package": name,
"source": str(source_dir),
@@ -224,6 +230,7 @@ def materialize_desktop_half(package_dir: Path, app_root: Path, name: str) -> Pa
return None
if (
existing is not None
+ and not target_is_link
and existing["source"] == str(source_dir)
and bool(existing.get("linked")) == linked
and (
@@ -282,10 +289,15 @@ def reconcile_desktop_halves(hermes_root: Path, app_root: Path) -> list[str]:
if result is not None:
touched.append(str(result))
- for name in _list_dirs(app_root):
+ # Links count too: a marker read through one is an earlier copy of a linked checkout that kept
+ # the link. Only the link goes, never the folder it points at.
+ for name in _list_dirs(app_root, follow_links=True):
folder = app_root / name
marker = read_package_marker(folder)
if marker and _source_gone(name, Path(marker["source"]) / "plugin.js"):
- shutil.rmtree(folder, ignore_errors=True)
+ if folder.is_symlink():
+ folder.unlink(missing_ok=True)
+ else:
+ shutil.rmtree(folder, ignore_errors=True)
touched.append(str(folder))
return touched
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index cd01edfb499..24815ece3c5 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -584,10 +584,21 @@ def _desktop_surface(tree: Path) -> set:
return {(source / "plugin.js").relative_to(tree).as_posix()} if source else set()
+# Surfaces that are one thing however they are spelled: the Desktop half is present or not, and moving
+# it between ``plugin.js`` and ``desktop/plugin.js`` grants nothing new.
+_PRESENCE_SURFACES = frozenset({"desktop"})
+
+
+def _added(surface: str, old: set, new: set) -> set:
+ if surface in _PRESENCE_SURFACES:
+ return set() if old else new
+ return new - old
+
+
def surface_delta(old: dict[str, set], new: dict[str, set]) -> dict[str, list[str]]:
"""``{surface: [added...]}`` for every surface the new tree widens; empty when nothing widened."""
- return {k: sorted(new.get(k, set()) - old.get(k, set())) for k in _SURFACE_LABELS
- if new.get(k, set()) - old.get(k, set())}
+ delta = {k: sorted(_added(k, old.get(k, set()), new.get(k, set()))) for k in _SURFACE_LABELS}
+ return {k: v for k, v in delta.items() if v}
def surface_delta_lines(delta: dict[str, list[str]]) -> list[str]:
diff --git a/tests/hermes_cli/test_desktop_plugin_halves_linked.py b/tests/hermes_cli/test_desktop_plugin_halves_linked.py
new file mode 100644
index 00000000000..06ce8cb2800
--- /dev/null
+++ b/tests/hermes_cli/test_desktop_plugin_halves_linked.py
@@ -0,0 +1,83 @@
+"""A dev checkout linked into ``plugins/`` with its ``plugin.js`` at the root publishes a real copy.
+
+The host pass shares ``<root>/desktop-plugins`` with native Desktop, whose earlier copy of such a
+checkout kept the link itself (marker written into the checkout). Neither writer may stamp a folder
+reached through a link, and the prune drops that leftover link once the package link is gone.
+"""
+
+import json
+import shutil
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.desktop_plugin_halves import PACKAGE_MARKER, reconcile_desktop_halves
+
+pytestmark = pytest.mark.platforms("posix")
+
+
+def _checkout(tmp_path: Path) -> tuple[Path, Path, Path, Path]:
+ root = tmp_path / "hermes"
+ checkout = tmp_path / "src" / "radar"
+ checkout.mkdir(parents=True)
+ (checkout / "plugin.yaml").write_text("name: radar\n", encoding="utf-8")
+ (checkout / "plugin.js").write_text("root entry", encoding="utf-8")
+ (root / "plugins").mkdir(parents=True)
+ link = root / "plugins" / "radar"
+ link.symlink_to(checkout, target_is_directory=True)
+ return root, root / "desktop-plugins", checkout, link
+
+
+def test_a_linked_root_layout_checkout_publishes_a_copy_and_leaves_with_its_link(tmp_path):
+ root, app_root, checkout, link = _checkout(tmp_path)
+ target = app_root / "radar"
+
+ assert reconcile_desktop_halves(root, app_root) == [str(target)]
+ assert not target.is_symlink()
+ assert (target / "plugin.js").read_text(encoding="utf-8") == "root entry"
+ marker = json.loads((target / PACKAGE_MARKER).read_text(encoding="utf-8"))
+ assert (marker["package"], marker["source"], marker["linked"]) == ("radar", str(link), True)
+ assert not (checkout / PACKAGE_MARKER).exists()
+ assert reconcile_desktop_halves(root, app_root) == []
+
+ link.unlink()
+ assert reconcile_desktop_halves(root, app_root) == [str(target)]
+ assert not target.exists()
+ assert sorted(p.name for p in checkout.iterdir()) == ["plugin.js", "plugin.yaml"]
+
+
+def test_a_copy_that_kept_the_checkout_link_is_replaced_then_pruned_without_touching_the_checkout(tmp_path):
+ root, app_root, checkout, link = _checkout(tmp_path)
+ target = app_root / "radar"
+ ghost = {"linked": True, "package": "radar", "source": str(link), "sourceMtimeMs": 9e15}
+ (checkout / PACKAGE_MARKER).write_text(json.dumps(ghost), encoding="utf-8")
+ app_root.mkdir()
+ target.symlink_to(checkout, target_is_directory=True)
+
+ assert reconcile_desktop_halves(root, app_root) == [str(target)]
+ assert not target.is_symlink()
+ assert (target / "plugin.js").read_text(encoding="utf-8") == "root entry"
+
+ shutil.rmtree(target)
+ target.symlink_to(checkout, target_is_directory=True)
+ link.unlink()
+ assert reconcile_desktop_halves(root, app_root) == [str(target)]
+ assert not target.is_symlink() and not target.exists()
+ assert (checkout / "plugin.js").read_text(encoding="utf-8") == "root entry"
+
+
+def test_a_plugin_the_user_linked_into_the_app_root_is_never_stamped(tmp_path):
+ root = tmp_path / "hermes"
+ own = tmp_path / "src" / "pkg"
+ own.mkdir(parents=True)
+ (own / "plugin.js").write_text("same", encoding="utf-8")
+ half = root / "plugins" / "pkg" / "desktop"
+ half.mkdir(parents=True)
+ (half / "plugin.js").write_text("same", encoding="utf-8")
+ app_root = root / "desktop-plugins"
+ app_root.mkdir()
+ (app_root / "pkg").symlink_to(own, target_is_directory=True)
+
+ assert reconcile_desktop_halves(root, app_root) == []
+ assert not (own / PACKAGE_MARKER).exists()
+ assert (app_root / "pkg").is_symlink()
diff --git a/tests/hermes_cli/test_plugin_surface_desktop.py b/tests/hermes_cli/test_plugin_surface_desktop.py
index eb860608661..a2995f632d5 100644
--- a/tests/hermes_cli/test_plugin_surface_desktop.py
+++ b/tests/hermes_cli/test_plugin_surface_desktop.py
@@ -23,3 +23,14 @@ def test_new_desktop_half_widens_the_surface_in_either_layout(tmp_path: Path, en
delta = surface_delta(plugin_surface({"name": "demo"}, old), plugin_surface({"name": "demo"}, new))
assert delta.get("desktop") == [entry]
+
+
[email protected](("before", "after"), [("plugin.js", "desktop/plugin.js"), ("desktop/plugin.js", "plugin.js")])
+def test_moving_an_existing_desktop_half_between_layouts_widens_nothing(tmp_path: Path, before: str, after: str):
+ old, new = tmp_path / "old", tmp_path / "new"
+ for tree, entry in ((old, before), (new, after)):
+ (tree / entry).parent.mkdir(parents=True, exist_ok=True)
+ (tree / "plugin.yaml").write_text("name: demo\n")
+ (tree / entry).write_text("export default {}\n")
+
+ assert surface_delta(plugin_surface({"name": "demo"}, old), plugin_surface({"name": "demo"}, new)) == {}