Skip to content

The agent that grows with you

fix(desktop): serialize writers of the desktop-plugins root

Tekniumf1b5275ca863
diff --git a/apps/desktop/electron/desktop-plugin-install.ts b/apps/desktop/electron/desktop-plugin-install.ts
index 528f7e096cf..f091547a376 100644
--- a/apps/desktop/electron/desktop-plugin-install.ts
+++ b/apps/desktop/electron/desktop-plugin-install.ts
@@ -10,7 +10,7 @@ import fsp from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
-import { publishDesktopTree, writeDesktopHalfMarker } from './desktop-plugins-root'
+import { publishDesktopTree, withDesktopPluginsRoot, writeDesktopHalfMarker } from './desktop-plugins-root'
import { execGit, hiddenGitSpawnSpec } from './no-console-git'
const GITHUB_BROWSER_SEGMENTS = new Set(['tree', 'blob', 'commit'])
@@ -440,47 +440,51 @@ export async function installDesktopPluginFromGit(
const targetDir = path.join(desktopPluginsRoot, pluginName)
const targetPlugin = path.join(targetDir, 'plugin.js')
- if ((await pathIsDirectory(targetDir)) || (await pathIsFile(targetPlugin))) {
- if (!force) {
- return {
- ok: false,
- error: `Desktop plugin '${pluginName}' already exists. Enable force reinstall to replace it.`
+ // Under the root's writer lock: the exists check and the publish must not
+ // interleave with a reconcile pass copying the same package folder.
+ return await withDesktopPluginsRoot<DesktopPluginInstallResult>(desktopPluginsRoot, async () => {
+ if ((await pathIsDirectory(targetDir)) || (await pathIsFile(targetPlugin))) {
+ if (!force) {
+ return {
+ ok: false,
+ error: `Desktop plugin '${pluginName}' already exists. Enable force reinstall to replace it.`
+ }
}
- }
-
- await fsp.rm(targetDir, { recursive: true, force: true })
- }
- // Staged copy + rename: a failed copy must not leave an empty `targetDir`
- // that turns every retry into "already exists. Enable force reinstall".
- // The half of a unified package is stamped with the package marker as
- // part of that publication — without it the Plugins page cannot tell this
- // copy belongs to the agent row (it sits on "copying…" forever) and the
- // half loads default-enabled instead of opt-in.
- await publishDesktopTree(sourceDir, targetDir, async staged => {
- if (!packageName) {
- return
+ await fsp.rm(targetDir, { recursive: true, force: true })
}
- await writeDesktopHalfMarker(staged, {
- package: packageName,
- repo: gitUrl,
- // The published folder, not the temp clone. The clone is deleted
- // below; a source that disappears is ghost-pruned on the next
- // reconcile when no local `plugins/<name>/desktop` exists to
- // re-copy from (remote backend, or Desktop UI only). A later pass
- // that does find the agent package still replaces this copy,
- // because this path is not that package's `desktop/` dir.
- source: targetDir,
- sourceMtimeMs: (await fsp.stat(path.join(staged, 'plugin.js'))).mtimeMs
+ // Staged copy + rename: a failed copy must not leave an empty `targetDir`
+ // that turns every retry into "already exists. Enable force reinstall".
+ // The half of a unified package is stamped with the package marker as
+ // part of that publication — without it the Plugins page cannot tell this
+ // copy belongs to the agent row (it sits on "copying…" forever) and the
+ // half loads default-enabled instead of opt-in.
+ await publishDesktopTree(sourceDir, targetDir, async staged => {
+ if (!packageName) {
+ return
+ }
+
+ await writeDesktopHalfMarker(staged, {
+ package: packageName,
+ repo: gitUrl,
+ // The published folder, not the temp clone. The clone is deleted
+ // below; a source that disappears is ghost-pruned on the next
+ // reconcile when no local `plugins/<name>/desktop` exists to
+ // re-copy from (remote backend, or Desktop UI only). A later pass
+ // that does find the agent package still replaces this copy,
+ // because this path is not that package's `desktop/` dir.
+ source: targetDir,
+ sourceMtimeMs: (await fsp.stat(path.join(staged, 'plugin.js'))).mtimeMs
+ })
})
- })
- if (!(await pathIsFile(targetPlugin))) {
- return { ok: false, error: `Install completed but ${targetPlugin} is missing.` }
- }
+ if (!(await pathIsFile(targetPlugin))) {
+ return { ok: false, error: `Install completed but ${targetPlugin} is missing.` }
+ }
- return { ok: true, pluginName, path: targetDir }
+ return { ok: true, pluginName, path: targetDir }
+ })
} finally {
await fsp.rm(cloneRoot, { recursive: true, force: true }).catch(() => undefined)
}
diff --git a/apps/desktop/electron/desktop-plugin-remove.ts b/apps/desktop/electron/desktop-plugin-remove.ts
index 3fd9370c092..a654a54c996 100644
--- a/apps/desktop/electron/desktop-plugin-remove.ts
+++ b/apps/desktop/electron/desktop-plugin-remove.ts
@@ -10,7 +10,7 @@
import fs from 'node:fs'
import path from 'node:path'
-import { PACKAGE_MARKER } from './desktop-plugins-root'
+import { PACKAGE_MARKER, withDesktopPluginsRoot } from './desktop-plugins-root'
export interface RemoveDesktopPluginResult {
ok: boolean
@@ -19,7 +19,13 @@ export interface RemoveDesktopPluginResult {
path?: string
}
-export async function removeDesktopPlugin(appRoot: string, rawName: unknown): Promise<RemoveDesktopPluginResult> {
+export function removeDesktopPlugin(appRoot: string, rawName: unknown): Promise<RemoveDesktopPluginResult> {
+ // Under the root's writer lock: a reconcile pass adopting this folder (it
+ // stamps the marker) must not land between the marker check and the delete.
+ return withDesktopPluginsRoot(appRoot, () => removeFolder(appRoot, rawName))
+}
+
+async function removeFolder(appRoot: string, rawName: unknown): Promise<RemoveDesktopPluginResult> {
const name = String(rawName ?? '').trim()
if (!name || name === '.' || name === '..' || /[\\/]/.test(name)) {
diff --git a/apps/desktop/electron/desktop-plugins-root.test.ts b/apps/desktop/electron/desktop-plugins-root.test.ts
index bc8596157dc..c6b360455e6 100644
--- a/apps/desktop/electron/desktop-plugins-root.test.ts
+++ b/apps/desktop/electron/desktop-plugins-root.test.ts
@@ -264,6 +264,27 @@ describe('reconcileUnifiedDesktopHalves', () => {
expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([])
})
+ it('overlapping passes publish a half once, from the first home that has it', async () => {
+ // Every window's disk poll and the Plugins page each run a pass through IPC,
+ // so passes overlap at boot. Unserialized, both copied, one rename hit the
+ // other's fresh folder (ENOTEMPTY) and that pass then took the profile's
+ // same-named package instead of the default home's.
+ const home = makeHome()
+ const appRoot = path.join(home, 'desktop-plugins')
+ write(path.join(home, 'plugins', 'media', 'desktop', 'plugin.js'), 'default home copy')
+ write(path.join(home, 'profiles', 'workbot', 'plugins', 'media', 'desktop', 'plugin.js'), 'profile copy')
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+
+ const passes = await Promise.all([1, 2, 3].map(() => reconcileUnifiedDesktopHalves(home, appRoot)))
+
+ warn.mockRestore()
+ expect(warn).not.toHaveBeenCalled()
+ expect(passes.flat()).toEqual([path.join(appRoot, 'media')])
+ expect(fs.readFileSync(path.join(appRoot, 'media', 'plugin.js'), 'utf8')).toBe('default home copy')
+ expect(fs.readdirSync(appRoot)).toEqual(['media'])
+ expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([])
+ })
+
it('cleans up failed staging copies without exposing a marker-less target', 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 e4dcc213bd0..3e655a4f946 100644
--- a/apps/desktop/electron/desktop-plugins-root.ts
+++ b/apps/desktop/electron/desktop-plugins-root.ts
@@ -71,6 +71,30 @@ async function packageOrigin(packageDir: string): Promise<Pick<DesktopHalfMarker
return {}
}
+const rootWriters = new Map<string, Promise<unknown>>()
+
+/** Run `task` once every earlier writer of the same app root has settled.
+ * Every writer of `<root>` (each window's 5 s disk poll and its Plugins page,
+ * the install/uninstall IPC) runs in this one main process, and each one
+ * decides "copy or keep" before it publishes with rm + rename. Two passes
+ * that overlap both copy, one `rename` lands on the other's fresh folder
+ * (ENOTEMPTY), and that pass then skips the package, so a same-named package
+ * in a later profile overwrote the default home's copy. */
+export function withDesktopPluginsRoot<T>(root: string, task: () => Promise<T>): Promise<T> {
+ const key = path.resolve(root)
+ const run = (rootWriters.get(key) ?? Promise.resolve()).then(task, task)
+ const settled = run.catch(() => undefined)
+
+ rootWriters.set(key, settled)
+ void settled.then(() => {
+ if (rootWriters.get(key) === settled) {
+ rootWriters.delete(key)
+ }
+ })
+
+ return run
+}
+
export async function ensureDir(dir: string): Promise<string> {
try {
await fs.promises.mkdir(dir, { recursive: true })
@@ -123,7 +147,11 @@ export async function localHomes(hermesHome: string): Promise<string[]> {
* id, so a duplicate is the same plugin installed twice); the profile copy is
* left in place for the user to delete rather than destroyed. Emptied profile
* roots are removed so the migration is a no-op on the next launch. */
-export async function migrateProfileScopedDesktopPlugins(hermesHome: string, appRoot: string): Promise<string[]> {
+export function migrateProfileScopedDesktopPlugins(hermesHome: string, appRoot: string): Promise<string[]> {
+ return withDesktopPluginsRoot(appRoot, () => migrateProfileScoped(hermesHome, appRoot))
+}
+
+async function migrateProfileScoped(hermesHome: string, appRoot: string): Promise<string[]> {
const moved: string[] = []
for (const profile of await listDirs(path.join(hermesHome, 'profiles'))) {
@@ -331,7 +359,11 @@ async function sourceGone(name: string, entry: string): Promise<boolean> {
* desktop half. First home wins for a name that appears in several profiles
* (the default home is first). Also drops root copies whose source package
* is gone — an uninstalled agent package must not leave a ghost pane. */
-export async function reconcileUnifiedDesktopHalves(hermesHome: string, appRoot: string): Promise<string[]> {
+export function reconcileUnifiedDesktopHalves(hermesHome: string, appRoot: string): Promise<string[]> {
+ return withDesktopPluginsRoot(appRoot, () => reconcilePass(hermesHome, appRoot))
+}
+
+async function reconcilePass(hermesHome: string, appRoot: string): Promise<string[]> {
const touched: string[] = []
const seen = new Set<string>()