The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): one-click plugin install via hermes:// deeplinks
seref359e09fd65c8
diff --git a/apps/desktop/electron/desktop-plugin-install.test.ts b/apps/desktop/electron/desktop-plugin-install.test.tsnew file mode 100644index 00000000000..43b28867823--- /dev/null+++ b/apps/desktop/electron/desktop-plugin-install.test.ts@@ -0,0 +1,130 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++import { afterEach, describe, expect, it } from 'vitest'++import {+ desktopPluginFolderName,+ detectPluginComponents,+ findDesktopEntry,+ repoNameFromUrl,+ resolvePluginGitUrl,+ resolveSubdirWithin+} from './desktop-plugin-install'++const here = path.dirname(fileURLToPath(import.meta.url))++function mkdtemp(prefix: string) {+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix))+}++describe('resolvePluginGitUrl', () => {+ it('maps owner/repo shorthand to github git url', () => {+ expect(resolvePluginGitUrl('NousResearch/hermes-example-plugins')).toEqual({+ gitUrl: 'https://github.com/NousResearch/hermes-example-plugins.git',+ subdir: null+ })+ })++ it('supports monorepo subdir shorthand', () => {+ expect(resolvePluginGitUrl('owner/repo/plugins/foo')).toEqual({+ gitUrl: 'https://github.com/owner/repo.git',+ subdir: 'plugins/foo'+ })+ })++ it('supports hash subdir fragment', () => {+ expect(resolvePluginGitUrl('https://github.com/o/r.git#nested/plugin')).toEqual({+ gitUrl: 'https://github.com/o/r.git',+ subdir: 'nested/plugin'+ })+ })+})++describe('repoNameFromUrl', () => {+ it('strips .git suffix', () => {+ expect(repoNameFromUrl('https://github.com/o/my-plugin.git')).toBe('my-plugin')+ })+})++describe('desktopPluginFolderName', () => {+ it('uses the repo name for a root-level plugin, not the clone path', () => {+ expect(desktopPluginFolderName('https://github.com/o/my-plugin.git', null)).toBe('my-plugin')+ })++ it('uses the last meaningful subdir, not a generic desktop folder', () => {+ expect(desktopPluginFolderName('https://github.com/o/monorepo.git', 'plugins/alerts/desktop')).toBe(+ 'alerts'+ )+ })+})++describe('resolveSubdirWithin', () => {+ it('rejects path traversal', () => {+ const root = mkdtemp('hermes-plugin-root-')++ expect(() => resolveSubdirWithin(root, '../escape')).toThrow(/escapes/)+ })+})++describe('findDesktopEntry', () => {+ it('finds root plugin.js', () => {+ const root = mkdtemp('hermes-plugin-detect-')+ fs.mkdirSync(path.join(root, 'desktop'), { recursive: true })+ fs.writeFileSync(path.join(root, 'plugin.js'), 'export default {}')++ expect(findDesktopEntry(root)).toEqual({ entryFile: path.join(root, 'plugin.js'), sourceSubdir: '.' })+ })++ it('finds desktop/plugin.js', () => {+ const root = mkdtemp('hermes-plugin-detect-')+ fs.mkdirSync(path.join(root, 'desktop'), { recursive: true })+ fs.writeFileSync(path.join(root, 'desktop', 'plugin.js'), 'export default {}')++ expect(findDesktopEntry(root)).toEqual({+ entryFile: path.join(root, 'desktop', 'plugin.js'),+ sourceSubdir: 'desktop'+ })+ })+})++describe('detectPluginComponents', () => {+ const roots: string[] = []++ afterEach(() => {+ for (const root of roots.splice(0)) {+ fs.rmSync(root, { recursive: true, force: true })+ }+ })++ it('detects agent-only layout', async () => {+ const root = mkdtemp('hermes-plugin-agent-')+ roots.push(root)+ fs.writeFileSync(path.join(root, 'plugin.yaml'), 'name: hello-agent\n')+ fs.writeFileSync(path.join(root, '__init__.py'), 'def register(ctx): pass\n')++ await expect(detectPluginComponents(root)).resolves.toMatchObject({+ agent: true,+ desktop: false,+ agentName: 'hello-agent'+ })+ })++ it('detects dual layout', async () => {+ const root = mkdtemp('hermes-plugin-dual-')+ roots.push(root)+ fs.mkdirSync(path.join(root, 'desktop'), { recursive: true })+ fs.writeFileSync(path.join(root, 'plugin.yaml'), 'name: dual\n')+ fs.writeFileSync(path.join(root, '__init__.py'), 'def register(ctx): pass\n')+ fs.writeFileSync(path.join(root, 'desktop', 'plugin.js'), 'export default { id: "dual-ui" }')++ await expect(detectPluginComponents(root)).resolves.toMatchObject({+ agent: true,+ desktop: true,+ agentName: 'dual',+ desktopName: 'desktop'+ })+ })+})diff --git a/apps/desktop/electron/desktop-plugin-install.ts b/apps/desktop/electron/desktop-plugin-install.tsnew file mode 100644index 00000000000..8d9d2157487--- /dev/null+++ b/apps/desktop/electron/desktop-plugin-install.ts@@ -0,0 +1,452 @@+/**+ * Probe and install desktop runtime plugins from Git repositories.+ * Pure helpers are exported for unit tests; IPC handlers in main.ts call the+ * async entry points with a resolved git binary.+ */++import { execFile, spawn } from 'node:child_process'+import fs from 'node:fs'+import fsp from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++const GITHUB_BROWSER_SEGMENTS = new Set(['tree', 'blob', 'commit'])++export interface ResolvedGitUrl {+ gitUrl: string+ subdir: string | null+}++export interface PluginComponentDetection {+ agent: boolean+ desktop: boolean+ agentName: string | null+ desktopName: string | null+ desktopSourceSubdir: string | null+}++export interface PluginProbeResult {+ ok: boolean+ agent: boolean+ desktop: boolean+ agentName?: string | null+ desktopName?: string | null+ warnings: string[]+ insecure: boolean+ error?: string+}++export interface DesktopPluginInstallResult {+ ok: boolean+ pluginName?: string+ path?: string+ error?: string+}++export function resolvePluginGitUrl(identifier: string): ResolvedGitUrl {+ const trimmed = identifier.trim()++ if (!trimmed) {+ throw new Error('Plugin identifier is required.')+ }++ if (/^(https?:\/\/|git@|ssh:\/\/|file:\/\/)/.test(trimmed)) {+ if (trimmed.startsWith('https://github.com/')) {+ const rest = trimmed.slice('https://github.com/'.length).split(/[?#]/)[0].replace(/\/+$/, '')+ const parts = rest.split('/').filter(Boolean)++ if (parts.length >= 3 && parts[2] && GITHUB_BROWSER_SEGMENTS.has(parts[2])) {+ const repo = parts[1].replace(/\.git$/, '')+ let subdir: string | null = null++ if (parts[2] === 'tree' && parts.length >= 5) {+ subdir = parts.slice(4).join('/').replace(/\/+$/, '') || null+ }++ return { gitUrl: `https://github.com/${parts[0]}/${repo}.git`, subdir }+ }+ }++ if (trimmed.includes('#')) {+ const hashIdx = trimmed.indexOf('#')+ const gitUrl = trimmed.slice(0, hashIdx)+ const subdir = trimmed.slice(hashIdx + 1).replace(/^\/+|\/+$/g, '') || null++ return { gitUrl, subdir }+ }++ const marker = '.git/'++ if (trimmed.includes(marker)) {+ const idx = trimmed.indexOf(marker)+ const gitUrl = trimmed.slice(0, idx + marker.length - 1)+ const subdir = trimmed.slice(idx + marker.length).replace(/^\/+|\/+$/g, '') || null++ return { gitUrl, subdir }+ }++ return { gitUrl: trimmed, subdir: null }+ }++ const parts = trimmed.split('/').filter(Boolean)++ if (parts.length >= 2) {+ const [owner, repo, ...rest] = parts+ const gitUrl = `https://github.com/${owner}/${repo}.git`+ const subdir = rest.join('/').replace(/\/+$/, '') || null++ return { gitUrl, subdir }+ }++ throw new Error(+ "Invalid plugin identifier. Use a Git URL or 'owner/repo' (optionally with a subdirectory)."+ )+}++export function repoNameFromUrl(url: string): string {+ let name = url.replace(/\/+$/, '')++ if (name.endsWith('.git')) {+ name = name.slice(0, -4)+ }++ name = name.split('/').pop() || name++ if (name.includes(':')) {+ name = name.split(':').pop() || name+ name = name.split('/').pop() || name+ }++ return name+}++/** Stable on-disk folder for a desktop plugin. Never the clone temp dir or a generic `desktop/` folder. */+export function desktopPluginFolderName(gitUrl: string, subdir: string | null): string {+ if (subdir) {+ const last = subdir+ .split(/[/\\]/)+ .filter(part => part && part !== '.' && part !== 'desktop')+ .pop()++ if (last) {+ return last+ }+ }++ return repoNameFromUrl(gitUrl)+}++export function resolveSubdirWithin(cloneRoot: string, subdir: string): string {+ const root = path.resolve(cloneRoot)+ const candidate = path.resolve(root, subdir)++ if (candidate !== root && !candidate.startsWith(root + path.sep)) {+ throw new Error(`Plugin subdirectory '${subdir}' escapes the repository.`)+ }++ return candidate+}++function pathExistsSync(filePath: string): boolean {+ try {+ fs.accessSync(filePath)++ return true+ } catch {+ return false+ }+}++async function pathIsDirectory(filePath: string): Promise<boolean> {+ try {+ const stat = await fsp.stat(filePath)++ return stat.isDirectory()+ } catch {+ return false+ }+}++async function pathIsFile(filePath: string): Promise<boolean> {+ try {+ const stat = await fsp.stat(filePath)++ return stat.isFile()+ } catch {+ return false+ }+}++export function findDesktopEntry(pluginRoot: string): { entryFile: string; sourceSubdir: string } | null {+ const rootPlugin = path.join(pluginRoot, 'plugin.js')++ if (pathExistsSync(rootPlugin)) {+ return { entryFile: rootPlugin, sourceSubdir: '.' }+ }++ const nestedPlugin = path.join(pluginRoot, 'desktop', 'plugin.js')++ if (pathExistsSync(nestedPlugin)) {+ return { entryFile: nestedPlugin, sourceSubdir: 'desktop' }+ }++ return null+}++export async function detectPluginComponents(pluginRoot: string): Promise<PluginComponentDetection> {+ const hasYaml =+ pathExistsSync(path.join(pluginRoot, 'plugin.yaml')) ||+ pathExistsSync(path.join(pluginRoot, 'plugin.yml'))+ const hasInit = pathExistsSync(path.join(pluginRoot, '__init__.py'))+ const hasPortable = pathExistsSync(path.join(pluginRoot, 'plugin.json'))+ const agent = (hasYaml && hasInit) || hasPortable++ const desktopEntry = findDesktopEntry(pluginRoot)+ const desktop = desktopEntry !== null++ let agentName: string | null = null++ if (agent) {+ agentName = path.basename(pluginRoot)++ if (hasYaml) {+ try {+ const yamlPath = pathExistsSync(path.join(pluginRoot, 'plugin.yaml'))+ ? path.join(pluginRoot, 'plugin.yaml')+ : path.join(pluginRoot, 'plugin.yml')+ const text = await fsp.readFile(yamlPath, 'utf8')+ const match = text.match(/^name:\s*['"]?([^'"\n]+)['"]?\s*$/m)++ if (match?.[1]) {+ agentName = match[1].trim()+ }+ } catch {+ // Fall back to directory name.+ }+ } else if (hasPortable) {+ try {+ const raw = await fsp.readFile(path.join(pluginRoot, 'plugin.json'), 'utf8')+ const parsed = JSON.parse(raw) as { name?: string }++ if (parsed.name) {+ agentName = parsed.name+ }+ } catch {+ // Fall back to directory name.+ }+ }+ }++ const desktopName = desktop+ ? desktopEntry!.sourceSubdir === '.'+ ? path.basename(pluginRoot)+ : path.basename(path.dirname(desktopEntry!.entryFile))+ : null++ return {+ agent,+ desktop,+ agentName,+ desktopName,+ desktopSourceSubdir: desktopEntry?.sourceSubdir ?? null+ }+}++function noninteractiveGitEnv(): NodeJS.ProcessEnv {+ return {+ ...process.env,+ GIT_TERMINAL_PROMPT: '0',+ GIT_ASKPASS: 'echo',+ SSH_ASKPASS: 'echo'+ }+}++function runGit(gitBin: string, args: string[], cwd?: string): Promise<{ code: number; stderr: string }> {+ return new Promise((resolve, reject) => {+ const child = spawn(gitBin, args, {+ cwd,+ env: noninteractiveGitEnv(),+ stdio: ['ignore', 'ignore', 'pipe'],+ windowsHide: true+ })++ let stderr = ''+ const timer = setTimeout(() => {+ child.kill('SIGKILL')+ reject(new Error('Git clone timed out after 60 seconds.'))+ }, 60_000)++ child.stderr?.on('data', chunk => {+ stderr += String(chunk)+ })++ child.on('error', err => {+ clearTimeout(timer)+ reject(err)+ })++ child.on('close', code => {+ clearTimeout(timer)+ resolve({ code: code ?? 1, stderr })+ })+ })+}++async function cloneToTemp(gitBin: string, gitUrl: string): Promise<string> {+ const tmpRoot = await fsp.mkdtemp(path.join(os.tmpdir(), 'hermes-plugin-'))++ try {+ const { code, stderr } = await runGit(gitBin, ['clone', '--depth', '1', gitUrl, tmpRoot])++ if (code !== 0) {+ throw new Error(`Git clone failed:\n${stderr.trim()}`)+ }++ return tmpRoot+ } catch (err) {+ await fsp.rm(tmpRoot, { recursive: true, force: true }).catch(() => undefined)+ throw err+ }+}++async function resolvePluginRoot(cloneRoot: string, subdir: string | null): Promise<string> {+ if (!subdir) {+ return cloneRoot+ }++ const resolved = resolveSubdirWithin(cloneRoot, subdir)++ if (!(await pathIsDirectory(resolved))) {+ throw new Error(`Plugin subdirectory '${subdir}' does not exist in the repository.`)+ }++ return resolved+}++function insecureSchemeWarnings(gitUrl: string): { warnings: string[]; insecure: boolean } {+ if (gitUrl.startsWith('http://') || gitUrl.startsWith('file://')) {+ return {+ warnings: [+ 'This URL uses an insecure or local scheme. Prefer https:// or git@ for production installs.'+ ],+ insecure: true+ }+ }++ return { warnings: [], insecure: false }+}++export async function probePluginRepo(+ gitBin: string,+ identifier: string+): Promise<PluginProbeResult> {+ try {+ const { gitUrl, subdir } = resolvePluginGitUrl(identifier)+ const { warnings, insecure } = insecureSchemeWarnings(gitUrl)+ const cloneRoot = await cloneToTemp(gitBin, gitUrl)++ try {+ const pluginRoot = await resolvePluginRoot(cloneRoot, subdir)+ const detected = await detectPluginComponents(pluginRoot)+ const repoFallback = repoNameFromUrl(gitUrl)++ if (!detected.agent && !detected.desktop) {+ return {+ ok: false,+ agent: false,+ desktop: false,+ warnings,+ insecure,+ error: 'No agent or desktop plugin artifacts found in this repository.'+ }+ }++ return {+ ok: true,+ agent: detected.agent,+ desktop: detected.desktop,+ agentName: detected.agentName ?? (detected.agent ? repoFallback : null),+ desktopName: detected.desktop ? desktopPluginFolderName(gitUrl, subdir) : null,+ warnings,+ insecure+ }+ } finally {+ await fsp.rm(cloneRoot, { recursive: true, force: true }).catch(() => undefined)+ }+ } catch (err) {+ return {+ ok: false,+ agent: false,+ desktop: false,+ warnings: [],+ insecure: false,+ error: err instanceof Error ? err.message : String(err)+ }+ }+}++async function copyDesktopTree(sourceDir: string, targetDir: string): Promise<void> {+ await fsp.mkdir(path.dirname(targetDir), { recursive: true })+ await fsp.cp(sourceDir, targetDir, { recursive: true, force: true })+}++export async function installDesktopPluginFromGit(+ gitBin: string,+ identifier: string,+ desktopPluginsRoot: string,+ force = false+): Promise<DesktopPluginInstallResult> {+ try {+ const { gitUrl, subdir } = resolvePluginGitUrl(identifier)+ const cloneRoot = await cloneToTemp(gitBin, gitUrl)++ try {+ const pluginRoot = await resolvePluginRoot(cloneRoot, subdir)+ const detected = await detectPluginComponents(pluginRoot)++ if (!detected.desktop || !detected.desktopSourceSubdir) {+ return { ok: false, error: 'No desktop plugin.js found in this repository.' }+ }++ const sourceDir =+ detected.desktopSourceSubdir === '.'+ ? pluginRoot+ : path.join(pluginRoot, detected.desktopSourceSubdir)+ const pluginName = desktopPluginFolderName(gitUrl, subdir)+ 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.`+ }+ }++ await fsp.rm(targetDir, { recursive: true, force: true })+ }++ await copyDesktopTree(sourceDir, targetDir)++ if (!(await pathIsFile(targetPlugin))) {+ return { ok: false, error: `Install completed but ${targetPlugin} is missing.` }+ }++ return { ok: true, pluginName, path: targetDir }+ } finally {+ await fsp.rm(cloneRoot, { recursive: true, force: true }).catch(() => undefined)+ }+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) }+ }+}++/** Resolve git binary via execFile which path on unix; caller passes Windows-resolved path. */+export function runGitVersion(gitBin: string): Promise<boolean> {+ return new Promise(resolve => {+ execFile(gitBin, ['--version'], { windowsHide: true, timeout: 5_000 }, err => {+ resolve(!err)+ })+ })+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex cc6d656cdd4..b4877438788 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -117,6 +117,7 @@ import { describeCrashReason, installCrashForensics } from './crash-forensics'import { adoptServedDashboardToken } from './dashboard-token'import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'import { formatDesktopLogLine } from './desktop-log-line'+import { installDesktopPluginFromGit, probePluginRepo } from './desktop-plugin-install'import { resolveDesktopRemoteRoute } from './desktop-remote-route'import {buildPosixCleanupScript,@@ -14639,6 +14640,33 @@ ipcMain.handle('hermes:fs:desktopPluginsRoot', async () => localPluginsRoot('des// this root for it — one installable folder serving both SDKs.ipcMain.handle('hermes:fs:agentPluginsRoot', async () => localPluginsRoot('plugins'))+ipcMain.handle('hermes:plugin:probe', async (_event, payload) => {+ const identifier = String(payload?.identifier || payload?.repo || '').trim()++ if (!identifier) {+ return { ok: false, error: 'identifier is required', agent: false, desktop: false, warnings: [] }+ }++ return probePluginRepo(resolveGitBinary(), identifier)+})++ipcMain.handle('hermes:plugin:installDesktop', async (_event, payload) => {+ const identifier = String(payload?.identifier || payload?.repo || '').trim()++ if (!identifier) {+ return { ok: false, error: 'identifier is required' }+ }++ const desktopPluginsRoot = await localPluginsRoot('desktop-plugins')++ return installDesktopPluginFromGit(+ resolveGitBinary(),+ identifier,+ desktopPluginsRoot,+ Boolean(payload?.force)+ )+})+// Rename a file/folder in place. The renderer passes the existing path + a new// base name; the destination is resolved in the SAME parent dir so a rename can// never move the item elsewhere or traverse out. Rejects on a name collision.@@ -15224,15 +15252,20 @@ ipcMain.handle('hermes:vscode-theme:fetch', async (_event, id) => fetchMarketplaipcMain.handle('hermes:vscode-theme:search', async (_event, query) => searchMarketplaceThemes(String(query || ''), 20))// ----------------------------------------------------------------------------// hermes:// deep links (e.g. hermes://blueprint/morning-brief?time=08:00, or+// hermes:// deep links (e.g. hermes://blueprint/morning-brief?time=08:00,// hermes://mcp/install?name=NAME&config=B64 — the vendor "Add to Hermes"-// button). Parsing is generic ({kind, name, params}); the renderer routes per-// kind and anything install-shaped requires explicit user confirmation there.+// button, or hermes://plugin/install?repo=owner/repo). Dev+// (`HERMES_DESKTOP_DEV_SERVER`) registers hermes-dev:// instead — bare+// Electron or a stale OS handler often owns hermes:// on dev machines.+// Parsing is generic ({kind, name, params}); the renderer routes per kind+// and anything install-shaped requires explicit user confirmation there.// A docs/dashboard "Send to App" button opens this URL; we route it into the// running app. Three delivery paths: macOS 'open-url',// Win/Linux running-app 'second-instance' (argv), Win/Linux cold-start argv.// ----------------------------------------------------------------------------const HERMES_PROTOCOL = 'hermes'+const HERMES_PROTOCOL = DEV_SERVER ? 'hermes-dev' : 'hermes'+/** Schemes accepted when parsing inbound URLs (dev accepts both). */+const DEEPLINK_SCHEMES = DEV_SERVER ? ['hermes-dev', 'hermes'] : ['hermes']let _pendingDeepLink = nulllet _rendererReadyForDeepLink = false@@ -15241,7 +15274,11 @@ function _extractDeepLink(argv) {return null}- return argv.find(a => typeof a === 'string' && a.startsWith(`${HERMES_PROTOCOL}://`)) || null+ return (+ argv.find(+ a => typeof a === 'string' && DEEPLINK_SCHEMES.some(s => a.startsWith(`${s}://`))+ ) || null+ )}function handleDeepLink(url) {@@ -15259,6 +15296,14 @@ function handleDeepLink(url) {return}+ const scheme = parsed.protocol.replace(/:$/, '')++ if (!DEEPLINK_SCHEMES.includes(scheme)) {+ rememberLog(`[deeplink] ignoring scheme ${scheme} (expected ${DEEPLINK_SCHEMES.join(' or ')})`)++ return+ }+// hermes://blueprint/<key>?slot=val -> host="blueprint", path="/<key>"const kind = parsed.hostname || ''const name = decodeURIComponent((parsed.pathname || '').replace(/^\//, ''))@@ -15308,11 +15353,15 @@ function registerDeepLinkProtocol() {try {if (process.defaultApp && process.argv.length >= 2) {// Dev: register with the electron exec path + entry script so the OS can- // relaunch us with the URL.- app.setAsDefaultProtocolClient(HERMES_PROTOCOL, process.execPath, [path.resolve(process.argv[1])])+ // relaunch us with the URL. argv[1] is usually "." when launched via+ // `electron .` from apps/desktop — resolve against cwd.+ const entry = path.resolve(process.argv[1])+ app.setAsDefaultProtocolClient(HERMES_PROTOCOL, process.execPath, [entry])} else {app.setAsDefaultProtocolClient(HERMES_PROTOCOL)}++ rememberLog(`[deeplink] registered ${HERMES_PROTOCOL}:// handler`)} catch (err) {rememberLog(`[deeplink] protocol registration failed: ${err.message}`)}@@ -15394,6 +15443,7 @@ app.whenReady().then(() => {installEmbedReferer()installRemoteHeaderRules()registerDeepLinkProtocol()+ensureWslWindowsFonts()configureSpellChecker()registerPowerResumeListeners()diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex f18b831dd65..6b474b56d85 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -323,6 +323,8 @@ contextBridge.exposeInMainWorld('hermesDesktop', {return () => ipcRenderer.removeListener('hermes:deep-link', listener)},signalDeepLinkReady: () => ipcRenderer.invoke('hermes:deep-link-ready'),+ probePluginRepo: payload => ipcRenderer.invoke('hermes:plugin:probe', payload),+ installDesktopPlugin: payload => ipcRenderer.invoke('hermes:plugin:installDesktop', payload),onWindowStateChanged: callback => {const listener = (_event, payload) => callback(payload)ipcRenderer.on('hermes:window-state-changed', listener)diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.tsindex ea26871f027..f44e96017b1 100644--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts@@ -3,6 +3,7 @@ import { useEffect, useRef } from 'react'import { closeActiveTab } from '@/app/chat/close-tab'import { commandFocusedPreview } from '@/app/chat/right-rail/preview-nav'import { openSession } from '@/app/open-session'+import { resolveDeepLinkAction } from '@/lib/deeplink-routes'import { pathFromHermesDeepLink, resolveHermesOpenPath } from '@/lib/hermes-open-target'import { storedSessionIdForNotification } from '@/lib/session-ids'import { requestMcpInstallFromDeepLink } from '@/store/mcp-deeplink-install'@@ -13,6 +14,7 @@ import {invokePluginNotifyActivate,respondToApprovalAction} from '@/store/native-notifications'+import { openPluginInstallRequest } from '@/store/plugin-install-request'import { openFolderAsProject } from '@/store/projects'import {getRememberedRoute,@@ -234,9 +236,11 @@ export function useDesktopIntegrations({// hermes:// deep links:// - mcp/install?… → pending MCP install (explicit confirm, never auto-install)+ // - plugin/install?… (and legacy plugin-agent/plugin-desktop) → plugin install+ // modal awaiting explicit confirmation. Never auto-installs.+ // - blueprint/<name>?… → reviewable /blueprint command in the composer// - <plugin>/<path>?… → in-app navigate (e.g. index-network/intent/1)// - open/<path>?… → in-app navigate (generic)- // - blueprint/<name>?… → reviewable /blueprint command in the composeruseEffect(() => {const unsubscribe = window.hermesDesktop?.onDeepLink?.(payload => {if (!payload?.kind) {@@ -249,12 +253,10 @@ export function useDesktopIntegrations({return}- if (payload.kind === 'blueprint') {- if (!payload.name) {- return- }+ const action = resolveDeepLinkAction(payload)- const slots = Object.entries(payload.params || {})+ if (action.type === 'composer-blueprint') {+ const slots = Object.entries(action.params || {}).map(([k, v]) => {const sval = /\s/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v@@ -262,13 +264,27 @@ export function useDesktopIntegrations({}).join(' ')- const command = `/blueprint ${payload.name}${slots ? ' ' + slots : ''}`+ const command = `/blueprint ${action.name}${slots ? ' ' + slots : ''}`requestComposerInsert(command, { mode: 'block', target: 'main' })requestComposerFocus('main')return}+ if (action.type === 'plugin-install') {+ openPluginInstallRequest({+ repo: action.repo,+ enable: action.enable,+ force: action.force,+ legacyHint: action.legacyHint+ })++ return+ }++ // Not a core action — treat as a plugin-scoped or open/ navigation deep+ // link (hermes://index-network/intent/1, hermes://open/…). The resolver+ // rejects reserved kinds and unsafe paths.const path = pathFromHermesDeepLink(payload.kind, payload.name || '', payload.params || {})if (path) {diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 8688a5e30a6..bdea85b4217 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -113,6 +113,7 @@ import { useSessionActions } from '../session/hooks/use-session-actions'import { useSessionListActions } from '../session/hooks/use-session-list-actions'import { useSessionStateCache } from '../session/hooks/use-session-state-cache'import { startWorkspaceSession } from '../session/workspace-session-target'+import { PluginInstallModal } from '../settings/plugin-install-modal'import { useOverlayRouting } from '../shell/hooks/use-overlay-routing'import { useWindowControlsOverlayWidth } from '../shell/hooks/use-window-controls-overlay-width'import {@@ -1078,6 +1079,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {<GatewayConnectingOverlay /><BootFailureOverlay /><CommandPalette />+ <PluginInstallModal /><PetGenerateOverlay /><SessionSwitcher /><FileActionDialogs />diff --git a/apps/desktop/src/app/settings/plugin-install-modal.tsx b/apps/desktop/src/app/settings/plugin-install-modal.tsxnew file mode 100644index 00000000000..da7365de7a0--- /dev/null+++ b/apps/desktop/src/app/settings/plugin-install-modal.tsx@@ -0,0 +1,402 @@+import { useStore } from '@nanostores/react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useLocation, useNavigate } from 'react-router'++import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'+import { NEW_CHAT_ROUTE, SETTINGS_ROUTE } from '@/app/routes'+import { Button } from '@/components/ui/button'+import { Checkbox } from '@/components/ui/checkbox'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ preventCloseButtonAutoFocus+} from '@/components/ui/dialog'+import { Switch } from '@/components/ui/switch'+import { discoverRuntimePlugins } from '@/contrib/runtime-loader'+import { useI18n } from '@/i18n'+import { ExternalLink } from '@/lib/external-link'+import { AlertTriangle } from '@/lib/icons'+import { resolvePluginSourceLinks } from '@/lib/plugin-source-urls'+import { installAgentPlugin, loadAgentPlugins } from '@/store/agent-plugins'+import { notify } from '@/store/notifications'+import {+ $pluginInstallRequest,+ closePluginInstallRequest,+ type PluginInstallRequest+} from '@/store/plugin-install-request'+import { $activeGatewayProfile, $profileScope } from '@/store/profile'+import { $connection } from '@/store/session'++type ProbeResult = Awaited<+ ReturnType<NonNullable<NonNullable<Window['hermesDesktop']>['probePluginRepo']>>+>++type ProbePhase = 'idle' | 'probing' | 'ready' | 'error'++export function PluginInstallModal() {+ const request = useStore($pluginInstallRequest)+ const { t } = useI18n()+ const m = t.settings.plugins.installModal+ const { requestGateway } = useGatewayRequest()+ const navigate = useNavigate()+ const location = useLocation()+ const onSettings = location.pathname.startsWith(SETTINGS_ROUTE)+ const connection = useStore($connection)+ const activeProfile = useStore($activeGatewayProfile)+ const profileScope = useStore($profileScope)++ const [phase, setPhase] = useState<ProbePhase>('idle')+ const [probe, setProbe] = useState<ProbeResult | null>(null)+ const [installAgent, setInstallAgent] = useState(true)+ const [installDesktop, setInstallDesktop] = useState(true)+ const [enableAgent, setEnableAgent] = useState(true)+ const [forceReinstall, setForceReinstall] = useState(false)+ const [installing, setInstalling] = useState(false)+ const [installError, setInstallError] = useState<string | null>(null)+ const probeToken = useRef(0)++ const resetState = useCallback(() => {+ setPhase('idle')+ setProbe(null)+ setInstallAgent(true)+ setInstallDesktop(true)+ setEnableAgent(true)+ setForceReinstall(false)+ setInstalling(false)+ setInstallError(null)+ }, [])++ const applyLegacyHint = useCallback((payload: PluginInstallRequest, detected: ProbeResult) => {+ if (payload.legacyHint === 'agent') {+ setInstallAgent(Boolean(detected.agent))+ setInstallDesktop(false)+ } else if (payload.legacyHint === 'desktop') {+ setInstallAgent(false)+ setInstallDesktop(Boolean(detected.desktop))+ } else {+ setInstallAgent(Boolean(detected.agent))+ setInstallDesktop(Boolean(detected.desktop))+ }+ }, [])++ const runProbe = useCallback(+ async (payload: PluginInstallRequest) => {+ const token = ++probeToken.current+ setPhase('probing')+ setProbe(null)+ setInstallError(null)+ setEnableAgent(payload.enable ?? true)+ setForceReinstall(payload.force ?? false)++ const probeFn = window.hermesDesktop?.probePluginRepo++ if (!probeFn) {+ if (token !== probeToken.current) {+ return+ }++ setPhase('error')+ setProbe({+ ok: false,+ agent: false,+ desktop: false,+ warnings: [],+ error: m.probeUnavailable+ })++ return+ }++ const result = await probeFn({ identifier: payload.repo })++ if (token !== probeToken.current) {+ return+ }++ setProbe(result)++ if (!result.ok) {+ setPhase('error')++ return+ }++ applyLegacyHint(payload, result)+ setPhase('ready')+ },+ [applyLegacyHint, m.probeUnavailable]+ )++ useEffect(() => {+ if (request && onSettings) {+ navigate(NEW_CHAT_ROUTE)+ }+ }, [request, onSettings, navigate])++ useEffect(() => {+ if (!request) {+ resetState()++ return+ }++ void runProbe(request)+ }, [request, resetState, runProbe])++ const profileLabel = activeProfile || profileScope || 'default'+ const agentTargetHint =+ connection?.mode === 'remote' ? m.agentTargetRemote(profileLabel) : m.agentTargetLocal(profileLabel)+ const sourceLinks = useMemo(+ () => (request ? resolvePluginSourceLinks(request.repo) : null),+ [request]+ )++ const handleClose = () => {+ if (installing) {+ return+ }++ probeToken.current += 1+ closePluginInstallRequest()+ }++ const handleInstall = async () => {+ if (!request || !probe?.ok || installing) {+ return+ }++ if (!installAgent && !installDesktop) {+ setInstallError(m.selectComponent)++ return+ }++ setInstalling(true)+ setInstallError(null)++ const errors: string[] = []+ const successes: string[] = []++ try {+ if (installAgent && probe.agent) {+ const result = await installAgentPlugin(requestGateway, {+ identifier: request.repo,+ force: forceReinstall,+ enable: enableAgent+ })++ if (result.ok) {+ successes.push(m.agentSuccess(result.pluginName ?? request.repo))++ if (result.missingEnv?.length) {+ notify({+ kind: 'warning',+ message: m.missingEnv(result.missingEnv.join(', '))+ })+ }++ for (const warning of result.warnings ?? []) {+ notify({ kind: 'warning', message: warning })+ }+ } else {+ errors.push(result.error || m.agentFailed)+ }+ }++ if (installDesktop && probe.desktop) {+ const installFn = window.hermesDesktop?.installDesktopPlugin++ if (!installFn) {+ errors.push(m.desktopUnavailable)+ } else {+ const result = await installFn({ identifier: request.repo, force: forceReinstall })++ if (result.ok) {+ successes.push(m.desktopSuccess(result.pluginName ?? request.repo))+ await discoverRuntimePlugins()+ } else {+ errors.push(result.error || m.desktopFailed)+ }+ }+ }++ await loadAgentPlugins(requestGateway)++ if (errors.length === 0) {+ for (const message of successes) {+ notify({ kind: 'success', message })+ }++ closePluginInstallRequest()+ navigate('/settings?tab=plugins')++ return+ }++ if (successes.length > 0) {+ for (const message of successes) {+ notify({ kind: 'success', message })+ }+ }++ setInstallError(errors.join('\n'))+ } finally {+ setInstalling(false)+ }+ }++ const open = request !== null && !onSettings+ const busy = phase === 'probing' || installing++ return (+ <Dialog+ onOpenChange={next => {+ if (!next) {+ handleClose()+ }+ }}+ open={open}+ >+ <DialogContent className="max-w-lg" onOpenAutoFocus={preventCloseButtonAutoFocus}>+ <DialogHeader>+ <DialogTitle>{m.title}</DialogTitle>+ <DialogDescription>{m.description}</DialogDescription>+ </DialogHeader>++ {request && (+ <div className="space-y-4">+ <div>+ <div className="mb-1 text-[length:var(--conversation-caption-font-size)] font-medium text-foreground">+ {m.repoLabel}+ </div>+ <div className="rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) px-3 py-2 font-mono text-[length:var(--conversation-caption-font-size)] break-all text-foreground">+ {request.repo}+ </div>+ </div>++ <div className="space-y-3 rounded-lg border border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) px-3 py-2.5">+ <div className="space-y-2 text-[length:var(--conversation-caption-font-size)]">+ <div className="font-medium text-foreground">{m.securityHeading}</div>+ <p className="text-(--ui-text-secondary)">{m.securityIntro}</p>+ </div>++ {sourceLinks && (+ <div className="space-y-2 border-t border-(--ui-stroke-tertiary) pt-3">+ <div className="font-medium text-foreground">{m.sourceHeading}</div>+ {sourceLinks.browseUrl && (+ <ExternalLink+ className="text-[length:var(--conversation-caption-font-size)]"+ href={sourceLinks.browseUrl}+ showExternalIcon+ >+ {sourceLinks.subdir ? m.viewPluginFiles : m.viewRepository}+ </ExternalLink>+ )}+ <div>+ <div className="mb-1 text-(--ui-text-tertiary)">{m.gitCloneLabel}</div>+ <div className="rounded-md border border-(--ui-stroke-tertiary) bg-(--ui-bg-primary) px-2.5 py-1.5 font-mono break-all text-foreground">+ {sourceLinks.gitUrl}+ </div>+ </div>+ </div>+ )}+ </div>++ {phase === 'probing' && <p className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{m.probing}</p>}++ {phase === 'error' && probe?.error && (+ <p className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-[length:var(--conversation-caption-font-size)] text-destructive">+ {probe.error}+ </p>+ )}++ {phase === 'ready' && probe && (+ <div className="space-y-3">+ <div className="text-[length:var(--conversation-caption-font-size)] font-medium text-foreground">{m.includesHeading}</div>++ {probe.agent && (+ <label className="flex items-start gap-3 rounded-lg border border-(--ui-stroke-tertiary) px-3 py-2">+ <Checkbox+ checked={installAgent}+ disabled={busy}+ onCheckedChange={value => setInstallAgent(value === true)}+ />+ <span className="min-w-0">+ <span className="block font-medium text-foreground">{m.agentLabel}</span>+ <span className="block text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">+ {agentTargetHint}+ {probe.agentName ? ` · ${probe.agentName}` : ''}+ </span>+ </span>+ </label>+ )}++ {probe.desktop && (+ <label className="flex items-start gap-3 rounded-lg border border-(--ui-stroke-tertiary) px-3 py-2">+ <Checkbox+ checked={installDesktop}+ disabled={busy}+ onCheckedChange={value => setInstallDesktop(value === true)}+ />+ <span className="min-w-0">+ <span className="block font-medium text-foreground">{m.desktopLabel}</span>+ <span className="block text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">+ {m.desktopTarget}+ {probe.desktopName ? ` · ${probe.desktopName}` : ''}+ </span>+ </span>+ </label>+ )}++ {probe.desktop && !probe.agent && (+ <p className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{m.desktopOnlyNote}</p>+ )}++ {(probe.insecure || (probe.warnings?.length ?? 0) > 0) && (+ <div className="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[length:var(--conversation-caption-font-size)] text-foreground">+ <AlertTriangle aria-hidden className="mt-0.5 size-3.5 shrink-0 text-amber-600 dark:text-amber-400" />+ <span>{[...(probe.warnings ?? []), probe.insecure ? m.insecureWarning : ''].filter(Boolean).join(' ')}</span>+ </div>+ )}++ {probe.agent && (+ <label className="flex items-center justify-between gap-3">+ <span className="text-[length:var(--conversation-caption-font-size)] text-foreground">{m.enableAgent}</span>+ <Switch checked={enableAgent} disabled={busy || !installAgent} onCheckedChange={setEnableAgent} />+ </label>+ )}++ <label className="flex items-center justify-between gap-3">+ <span className="text-[length:var(--conversation-caption-font-size)] text-foreground">{m.forceReinstall}</span>+ <Switch checked={forceReinstall} disabled={busy} onCheckedChange={setForceReinstall} />+ </label>+ </div>+ )}++ {installError && (+ <p className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 whitespace-pre-wrap text-[length:var(--conversation-caption-font-size)] text-destructive">+ {installError}+ </p>+ )}+ </div>+ )}++ <DialogFooter>+ <Button disabled={busy} onClick={handleClose} variant="outline">+ {t.common.cancel}+ </Button>+ <Button+ disabled={busy || phase !== 'ready' || !probe?.ok}+ onClick={() => void handleInstall()}+ >+ {installing ? m.installing : m.install}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex e5f1e1de3be..72c6a4c6a30 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -359,6 +359,24 @@ declare global {callback: (payload: { kind: string; name: string; params: Record<string, string> }) => void) => () => voidsignalDeepLinkReady?: () => Promise<{ ok: boolean }>+ probePluginRepo?: (payload: {+ identifier?: string+ repo?: string+ }) => Promise<{+ ok: boolean+ agent: boolean+ desktop: boolean+ agentName?: string | null+ desktopName?: string | null+ warnings?: string[]+ insecure?: boolean+ error?: string+ }>+ installDesktopPlugin?: (payload: {+ identifier?: string+ repo?: string+ force?: boolean+ }) => Promise<{ ok: boolean; pluginName?: string; path?: string; error?: string }>onWindowStateChanged?: (callback: (payload: HermesWindowState) => void) => () => voidonFocusSession?: (callback: (sessionId: string) => void) => () => voidonNotificationAction?: (callback: (payload: { actionId: string; sessionId?: string }) => void) => () => voiddiff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 5b9c56a8c19..131006736fd 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -392,6 +392,40 @@ export const en: Translations = {toggleFailed: (name: string) => `Could not toggle ${name}`,updateBackendToManage: 'Update the Hermes backend to manage this plugin from Desktop.',sources: { bundled: 'bundled', user: 'user', git: 'git', project: 'project', entrypoint: 'pip' }+ },+ installModal: {+ title: 'Install plugin',+ description: 'Review what this repository contains before installing anything.',+ repoLabel: 'Repository',+ includesHeading: 'This package includes',+ agentLabel: 'Agent plugin',+ desktopLabel: 'Desktop UI',+ agentTargetLocal: profile => `Installs into the ${profile} backend (~/.hermes/plugins/)`,+ agentTargetRemote: profile => `Installs into the connected ${profile} backend`,+ desktopTarget: "Installs into this app's local desktop-plugins folder",+ desktopOnlyNote: 'Desktop-only packages do not install a backend agent plugin.',+ insecureWarning:+ 'This URL uses an insecure or local scheme. Prefer https:// or git@ for production installs.',+ securityHeading: 'Before you install',+ securityIntro:+ 'Install only from sources you trust — review the repository below if you want to see what will be added.',+ sourceHeading: 'Source code',+ viewRepository: 'View repository',+ viewPluginFiles: 'View plugin files',+ gitCloneLabel: 'Git clone URL',+ enableAgent: 'Enable agent plugin after install',+ forceReinstall: 'Force reinstall (replace if already installed)',+ install: 'Install',+ installing: 'Installing…',+ probing: 'Inspecting repository…',+ probeUnavailable: 'Plugin inspection is unavailable in this environment.',+ desktopUnavailable: 'Desktop plugin install is unavailable in this environment.',+ selectComponent: 'Select at least one component to install.',+ agentSuccess: name => `Agent plugin ${name} installed`,+ desktopSuccess: name => `Desktop plugin ${name} installed`,+ agentFailed: 'Agent plugin install failed',+ desktopFailed: 'Desktop plugin install failed',+ missingEnv: vars => `Missing env vars: ${vars}. Add them in Settings → Keys.`}},notifications: {diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 678e0f88e7c..67704864b4b 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -340,6 +340,38 @@ export interface Translations {updateBackendToManage: stringsources: Record<string, string>}+ installModal: {+ title: string+ description: string+ repoLabel: string+ includesHeading: string+ agentLabel: string+ desktopLabel: string+ agentTargetLocal: (profile: string) => string+ agentTargetRemote: (profile: string) => string+ desktopTarget: string+ desktopOnlyNote: string+ insecureWarning: string+ securityHeading: string+ securityIntro: string+ sourceHeading: string+ viewRepository: string+ viewPluginFiles: string+ gitCloneLabel: string+ enableAgent: string+ forceReinstall: string+ install: string+ installing: string+ probing: string+ probeUnavailable: string+ desktopUnavailable: string+ selectComponent: string+ agentSuccess: (name: string) => string+ desktopSuccess: (name: string) => string+ agentFailed: string+ desktopFailed: string+ missingEnv: (vars: string) => string+ }}notifications: {title: stringdiff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex dd3b63af90c..dc5e7907fc6 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -382,6 +382,38 @@ export const zh: Translations = {toggleFailed: (name: string) => `无法切换 ${name}`,updateBackendToManage: '请更新 Hermes 后端以便在桌面端管理此插件。',sources: { bundled: '内置', user: '用户', git: 'git', project: '项目', entrypoint: 'pip' }+ },+ installModal: {+ title: '安装插件',+ description: '在安装前查看此仓库包含哪些组件。',+ repoLabel: '仓库',+ includesHeading: '此包包含',+ agentLabel: '智能体插件',+ desktopLabel: '桌面 UI',+ agentTargetLocal: profile => `安装到 ${profile} 后端(~/.hermes/plugins/)`,+ agentTargetRemote: profile => `安装到已连接的 ${profile} 后端`,+ desktopTarget: '安装到此应用的本地 desktop-plugins 文件夹',+ desktopOnlyNote: '仅桌面包不会安装后端智能体插件。',+ insecureWarning: '此 URL 使用了不安全的本地 scheme。生产环境请优先使用 https:// 或 git@。',+ securityHeading: '安装前须知',+ securityIntro: '请仅安装你信任的来源 — 如需了解将添加的内容,可先查看下方仓库。',+ sourceHeading: '源代码',+ viewRepository: '查看仓库',+ viewPluginFiles: '查看插件文件',+ gitCloneLabel: 'Git 克隆地址',+ enableAgent: '安装后启用智能体插件',+ forceReinstall: '强制重装(替换已存在的安装)',+ install: '安装',+ installing: '正在安装…',+ probing: '正在检查仓库…',+ probeUnavailable: '当前环境无法检查插件仓库。',+ desktopUnavailable: '当前环境无法安装桌面插件。',+ selectComponent: '请至少选择一个要安装的组件。',+ agentSuccess: name => `智能体插件 ${name} 已安装`,+ desktopSuccess: name => `桌面插件 ${name} 已安装`,+ agentFailed: '智能体插件安装失败',+ desktopFailed: '桌面插件安装失败',+ missingEnv: vars => `缺少环境变量:${vars}。请在设置 → 密钥中添加。`}},notifications: {diff --git a/apps/desktop/src/lib/deeplink-routes.test.ts b/apps/desktop/src/lib/deeplink-routes.test.tsnew file mode 100644index 00000000000..76683577afc--- /dev/null+++ b/apps/desktop/src/lib/deeplink-routes.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'++import { resolveDeepLinkAction } from './deeplink-routes'++describe('resolveDeepLinkAction', () => {+ it('routes unified plugin install deeplinks', () => {+ expect(+ resolveDeepLinkAction({+ kind: 'plugin',+ name: 'install',+ params: { repo: 'owner/repo', enable: '0', force: '1' }+ })+ ).toEqual({+ type: 'plugin-install',+ repo: 'owner/repo',+ enable: false,+ force: true,+ legacyHint: null+ })+ })++ it('routes legacy plugin-agent alias', () => {+ expect(+ resolveDeepLinkAction({+ kind: 'plugin-agent',+ name: '',+ params: { repo: 'owner/repo' }+ })+ ).toMatchObject({ type: 'plugin-install', legacyHint: 'agent' })+ })++ it('routes blueprint composer inserts', () => {+ expect(+ resolveDeepLinkAction({+ kind: 'blueprint',+ name: 'morning-brief',+ params: { time: '08:00' }+ })+ ).toEqual({+ type: 'composer-blueprint',+ name: 'morning-brief',+ params: { time: '08:00' }+ })+ })+})diff --git a/apps/desktop/src/lib/deeplink-routes.ts b/apps/desktop/src/lib/deeplink-routes.tsnew file mode 100644index 00000000000..c943e234491--- /dev/null+++ b/apps/desktop/src/lib/deeplink-routes.ts@@ -0,0 +1,66 @@+import type { PluginInstallLegacyHint } from '@/store/plugin-install-request'++export interface DeepLinkPayload {+ kind: string+ name: string+ params: Record<string, string>+}++export type DeepLinkAction =+ | { type: 'plugin-install'; repo: string; enable: boolean; force: boolean; legacyHint: PluginInstallLegacyHint }+ | { type: 'composer-blueprint'; name: string; params: Record<string, string> }+ | { type: 'ignore' }++function truthyParam(value: string | undefined, defaultValue = false): boolean {+ if (value === undefined || value === '') {+ return defaultValue+ }++ const normalized = value.trim().toLowerCase()++ return normalized === '1' || normalized === 'true' || normalized === 'yes'+}++export function resolveDeepLinkAction(payload: DeepLinkPayload | null | undefined): DeepLinkAction {+ if (!payload?.kind) {+ return { type: 'ignore' }+ }++ if (payload.kind === 'blueprint' && payload.name) {+ return { type: 'composer-blueprint', name: payload.name, params: payload.params || {} }+ }++ const repo = (payload.params?.repo || payload.params?.identifier || payload.name || '').trim()++ if (payload.kind === 'plugin' && payload.name === 'install' && repo) {+ return {+ type: 'plugin-install',+ repo,+ enable: truthyParam(payload.params?.enable, true),+ force: truthyParam(payload.params?.force, false),+ legacyHint: null+ }+ }++ if (payload.kind === 'plugin-agent' && repo) {+ return {+ type: 'plugin-install',+ repo,+ enable: truthyParam(payload.params?.enable, true),+ force: truthyParam(payload.params?.force, false),+ legacyHint: 'agent'+ }+ }++ if (payload.kind === 'plugin-desktop' && repo) {+ return {+ type: 'plugin-install',+ repo,+ enable: truthyParam(payload.params?.enable, true),+ force: truthyParam(payload.params?.force, false),+ legacyHint: 'desktop'+ }+ }++ return { type: 'ignore' }+}diff --git a/apps/desktop/src/lib/plugin-source-urls.test.ts b/apps/desktop/src/lib/plugin-source-urls.test.tsnew file mode 100644index 00000000000..5a3d8986e6e--- /dev/null+++ b/apps/desktop/src/lib/plugin-source-urls.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest'++import { resolvePluginSourceLinks } from './plugin-source-urls'++describe('resolvePluginSourceLinks', () => {+ it('maps owner/repo to github browse and clone urls', () => {+ expect(resolvePluginSourceLinks('NousResearch/hermes-example-plugins')).toEqual({+ gitUrl: 'https://github.com/NousResearch/hermes-example-plugins.git',+ browseUrl: 'https://github.com/NousResearch/hermes-example-plugins',+ subdir: null+ })+ })++ it('includes monorepo subdir in browse url', () => {+ expect(resolvePluginSourceLinks('owner/repo/plugins/foo')).toEqual({+ gitUrl: 'https://github.com/owner/repo.git',+ browseUrl: 'https://github.com/owner/repo/tree/HEAD/plugins/foo',+ subdir: 'plugins/foo'+ })+ })++ it('supports git@ github urls', () => {+ expect(resolvePluginSourceLinks('[email protected]:owner/my-plugin.git')).toEqual({+ gitUrl: '[email protected]:owner/my-plugin.git',+ browseUrl: 'https://github.com/owner/my-plugin',+ subdir: null+ })+ })++ it('returns null for invalid identifiers', () => {+ expect(resolvePluginSourceLinks('not-a-repo')).toBeNull()+ })+})diff --git a/apps/desktop/src/lib/plugin-source-urls.ts b/apps/desktop/src/lib/plugin-source-urls.tsnew file mode 100644index 00000000000..606caae9024--- /dev/null+++ b/apps/desktop/src/lib/plugin-source-urls.ts@@ -0,0 +1,119 @@+const GITHUB_BROWSER_SEGMENTS = new Set(['tree', 'blob', 'commit'])++export interface PluginSourceLinks {+ gitUrl: string+ browseUrl: string | null+ subdir: string | null+}++function resolvePluginGitUrl(identifier: string): { gitUrl: string; subdir: string | null } {+ const trimmed = identifier.trim()++ if (!trimmed) {+ throw new Error('Plugin identifier is required.')+ }++ if (/^(https?:\/\/|git@|ssh:\/\/|file:\/\/)/.test(trimmed)) {+ if (trimmed.startsWith('https://github.com/')) {+ const rest = trimmed.slice('https://github.com/'.length).split(/[?#]/)[0].replace(/\/+$/, '')+ const parts = rest.split('/').filter(Boolean)++ if (parts.length >= 3 && parts[2] && GITHUB_BROWSER_SEGMENTS.has(parts[2])) {+ const repo = parts[1].replace(/\.git$/, '')+ let subdir: string | null = null++ if (parts[2] === 'tree' && parts.length >= 5) {+ subdir = parts.slice(4).join('/').replace(/\/+$/, '') || null+ }++ return { gitUrl: `https://github.com/${parts[0]}/${repo}.git`, subdir }+ }+ }++ if (trimmed.includes('#')) {+ const hashIdx = trimmed.indexOf('#')+ const gitUrl = trimmed.slice(0, hashIdx)+ const subdir = trimmed.slice(hashIdx + 1).replace(/^\/+|\/+$/g, '') || null++ return { gitUrl, subdir }+ }++ const marker = '.git/'++ if (trimmed.includes(marker)) {+ const idx = trimmed.indexOf(marker)+ const gitUrl = trimmed.slice(0, idx + marker.length - 1)+ const subdir = trimmed.slice(idx + marker.length).replace(/^\/+|\/+$/g, '') || null++ return { gitUrl, subdir }+ }++ return { gitUrl: trimmed, subdir: null }+ }++ const parts = trimmed.split('/').filter(Boolean)++ if (parts.length >= 2) {+ const [owner, repo, ...rest] = parts+ const gitUrl = `https://github.com/${owner}/${repo}.git`+ const subdir = rest.join('/').replace(/\/+$/, '') || null++ return { gitUrl, subdir }+ }++ throw new Error('Invalid plugin identifier.')+}++function githubBrowseBase(gitUrl: string): string | null {+ const sshMatch = gitUrl.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i)++ if (sshMatch) {+ return `https://github.com/${sshMatch[1]}/${sshMatch[2].replace(/\.git$/, '')}`+ }++ try {+ const url = new URL(gitUrl)++ if (url.hostname.toLowerCase() === 'github.com') {+ const parts = url.pathname.replace(/\/+$/, '').split('/').filter(Boolean)++ if (parts.length >= 2) {+ return `https://github.com/${parts[0]}/${parts[1].replace(/\.git$/, '')}`+ }+ }+ } catch {+ return null+ }++ return null+}++function browseUrlFromGitUrl(gitUrl: string, subdir: string | null): string | null {+ const githubBase = githubBrowseBase(gitUrl)++ if (githubBase) {+ return subdir ? `${githubBase}/tree/HEAD/${subdir}` : githubBase+ }++ if (/^https?:\/\//.test(gitUrl)) {+ const base = gitUrl.replace(/\.git$/, '')++ return subdir ? `${base}/tree/HEAD/${subdir}` : base+ }++ return null+}++export function resolvePluginSourceLinks(identifier: string): PluginSourceLinks | null {+ try {+ const { gitUrl, subdir } = resolvePluginGitUrl(identifier)++ return {+ gitUrl,+ browseUrl: browseUrlFromGitUrl(gitUrl, subdir),+ subdir+ }+ } catch {+ return null+ }+}diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.tsindex 9b08d9cdd52..96b00ee2b73 100644--- a/apps/desktop/src/store/agent-plugins.ts+++ b/apps/desktop/src/store/agent-plugins.ts@@ -168,3 +168,44 @@ export async function toggleAgentPlugin($agentPluginBusy.set(null)}}++export interface AgentPluginInstallResult {+ ok: boolean+ pluginName?: string+ warnings?: string[]+ missingEnv?: string[]+ error?: string+}++export async function installAgentPlugin(+ request: GatewayRequest,+ opts: { identifier: string; force?: boolean; enable?: boolean }+): Promise<AgentPluginInstallResult> {+ try {+ const result = await request<{+ ok?: boolean+ plugin_name?: string+ warnings?: string[]+ missing_env?: string[]+ error?: string+ }>('plugins.manage', {+ action: 'install',+ identifier: opts.identifier,+ force: Boolean(opts.force),+ enable: opts.enable ?? true+ })++ if (!result?.ok) {+ return { ok: false, error: result?.error || 'Install failed' }+ }++ return {+ ok: true,+ pluginName: result.plugin_name,+ warnings: result.warnings,+ missingEnv: result.missing_env+ }+ } catch (e) {+ return { ok: false, error: e instanceof Error ? e.message : String(e) }+ }+}diff --git a/apps/desktop/src/store/plugin-install-request.ts b/apps/desktop/src/store/plugin-install-request.tsnew file mode 100644index 00000000000..ff772b5b2b5--- /dev/null+++ b/apps/desktop/src/store/plugin-install-request.ts@@ -0,0 +1,22 @@+import { atom } from 'nanostores'++/** Which plugin component(s) a legacy deeplink pre-selects after probe. */+export type PluginInstallLegacyHint = 'agent' | 'desktop' | null++/** Future metrics (opt-in): install count + success/failure, per repo. */+export interface PluginInstallRequest {+ repo: string+ enable?: boolean+ force?: boolean+ legacyHint?: PluginInstallLegacyHint+}++export const $pluginInstallRequest = atom<PluginInstallRequest | null>(null)++export function openPluginInstallRequest(request: PluginInstallRequest): void {+ $pluginInstallRequest.set(request)+}++export function closePluginInstallRequest(): void {+ $pluginInstallRequest.set(null)+}diff --git a/tests/tui_gateway/test_plugins_manage_install.py b/tests/tui_gateway/test_plugins_manage_install.pynew file mode 100644index 00000000000..776dfef6c96--- /dev/null+++ b/tests/tui_gateway/test_plugins_manage_install.py@@ -0,0 +1,73 @@+"""Gateway plugins.manage install action."""++from unittest.mock import patch++from tui_gateway import server+++def test_plugins_manage_install_success():+ payload = {+ "ok": True,+ "plugin_name": "hello-world",+ "warnings": [],+ "missing_env": [],+ "after_install_path": None,+ "enabled": True,+ }+ with patch(+ "hermes_cli.plugins_cmd.dashboard_install_plugin",+ return_value=payload,+ ) as mock_install:+ resp = server.handle_request(+ {+ "id": "1",+ "method": "plugins.manage",+ "params": {+ "action": "install",+ "repo": "owner/hello-world",+ "force": True,+ "enable": False,+ },+ }+ )++ assert "result" in resp+ assert resp["result"]["plugin_name"] == "hello-world"+ mock_install.assert_called_once_with(+ "owner/hello-world",+ force=True,+ enable=False,+ )+++def test_plugins_manage_install_missing_identifier():+ resp = server.handle_request(+ {+ "id": "1",+ "method": "plugins.manage",+ "params": {"action": "install"},+ }+ )++ assert "error" in resp+ assert "identifier" in resp["error"]["message"]+++def test_plugins_manage_install_failure():+ with patch(+ "hermes_cli.plugins_cmd.dashboard_install_plugin",+ return_value={"ok": False, "error": "Git clone failed"},+ ):+ resp = server.handle_request(+ {+ "id": "1",+ "method": "plugins.manage",+ "params": {+ "action": "install",+ "identifier": "bad/repo",+ },+ }+ )++ assert "error" in resp+ assert "Git clone failed" in resp["error"]["message"]diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 7eff80ca10b..bf7d61e599a 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -2388,6 +2388,9 @@ def _(rid, params: dict) -> dict:status, portable}], "user_count": N, "bundled_count": M}- ``toggle`` → flip ``key`` (or ``name``) based on ``enable`` (bool).Returns the refreshed row plus {"ok", "unchanged"}.+ - ``install`` → git-clone into ``~/.hermes/plugins/`` (non-interactive).+ Params: ``identifier`` or ``repo``, optional ``force``,+ ``enable`` (default True). Returns dashboard install dict.Accepts an optional ``profile`` param (same contract as mcp.servers.*):plugins live under each profile's HERMES_HOME, so a client can list or@@ -2480,6 +2483,25 @@ def _(rid, params: dict) -> dict:},)+ if action == "install":+ from hermes_cli.plugins_cmd import dashboard_install_plugin++ ident = (+ params.get("identifier") or params.get("repo") or ""+ ).strip()+ if not ident:+ return _err(+ rid, 4019, "plugins.install requires 'identifier' or 'repo'"+ )+ result = dashboard_install_plugin(+ ident,+ force=bool(params.get("force")),+ enable=params.get("enable", True),+ )+ if not result.get("ok"):+ return _err(rid, 5026, result.get("error") or "install failed")+ return _ok(rid, result)+return _err(rid, 4017, f"unknown plugins action: {action}")except Exception as e:return _err(rid, 5026, str(e))