Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(plugins): 统一跨电脑插件与完整技能市场界面

nana06498690454c
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
index ba0aefe732..bbf6cc13b2 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
@@ -3,11 +3,18 @@ import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleAlert, LayoutGrid, MoonStar } from 'lucide-react';
import type { WebviewTag } from 'electron';
+import { AddRemoteProjectDialog } from '@/components/new-chat/AddRemoteProjectDialog';
+import type { RemotePluginSettingsDirectory } from '../../shared/remotePluginSettings';
import { useAuth } from '@/contexts/AuthContext';
import { cn } from '@/lib/utils';
import { GHOST_SCHEME, ghostInstallApprovalToken, type InstalledGhost } from '../../shared/ghost';
-import { installedGhostLogicalIdentity, installedGhostWebviewPartitionClaim, pluginStoragePart } from '../../shared/pluginIdentity';
+import {
+ installedGhostLogicalIdentity,
+ installedGhostStoragePart,
+ installedGhostWebviewPartitionClaim,
+ pluginStoragePart,
+} from '../../shared/pluginIdentity';
import {
buildGhostPluginSettingsThemeCss,
buildGhostSettingsThemeCss,
@@ -134,17 +141,26 @@ function SettingsWebviewBody({
appearance,
dataOwnerId,
hostAccount = false,
+ remoteDeviceId,
}: {
ghost: InstalledGhost;
appearance: 'settings' | 'plugin';
dataOwnerId: string | null;
hostAccount?: boolean;
+ remoteDeviceId?: string;
}): ReactNode {
const [crashed, setCrashed] = useState(false);
const [generation, setGeneration] = useState(0);
+ const [directory, setDirectory] = useState<RemotePluginSettingsDirectory | null>(null);
+ const remoteView = useRef<string | null>(null);
+ const answeredDirectory = useRef<string | null>(null);
+ const { t } = useTranslation();
const hostRef = useRef<HTMLDivElement | null>(null);
const { manifest } = ghost;
- const settingsHeightKey = pluginStoragePart(installedGhostLogicalIdentity(ghost));
+ const settingsHeightKey =
+ (remoteDeviceId ? remoteDeviceId + ':' : '') +
+ pluginStoragePart(installedGhostLogicalIdentity(ghost));
+ const instanceId = installedGhostStoragePart(ghost);
const partitionClaim = installedGhostWebviewPartitionClaim(ghost);
const approvalToken = ghostInstallApprovalToken(ghost.approval);
const settingsHtml = manifest.settingsHtml;
@@ -163,11 +179,12 @@ function SettingsWebviewBody({
const host = hostRef.current;
if (!host) return;
const webview = document.createElement('webview') as WebviewTag;
- webview.setAttribute('partition', partitionClaim);
+ if (!remoteDeviceId) webview.setAttribute('partition', partitionClaim);
webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${settingsHtml}`);
// 先透明留位,主题与布局注入完成后直接展示真实页面,不覆盖历史画面。
webview.setAttribute('style', 'display:flex;flex:1 1 auto;width:100%;height:100%;opacity:0;');
let disposed = false;
+ let remoteViewId: string | undefined;
let themeTimer: ReturnType<typeof setTimeout> | null = null;
const measureTimers: Array<ReturnType<typeof setTimeout>> = [];
// 状态机见 createGhostThemeInjector:换肤误触发去重、dom-ready 无条件重灌。
@@ -265,9 +282,45 @@ function SettingsWebviewBody({
webview.addEventListener('console-message', onConsoleMessage);
webview.addEventListener('render-process-gone', onGone);
const unobserveTheme = observeHostTheme(scheduleInjectTheme);
- host.appendChild(webview);
+ const unsubscribeDirectory = remoteDeviceId
+ ? window.electronAPI.ghosts.onRemoteSettingsDirectory((value) => {
+ if (
+ !disposed &&
+ value.viewId === remoteViewId &&
+ value.request.expiresAt > Date.now() &&
+ value.request.id !== answeredDirectory.current
+ )
+ setDirectory((previous) =>
+ previous?.request.id === value.request.id ? previous : value,
+ );
+ })
+ : undefined;
+ if (remoteDeviceId) {
+ void window.electronAPI.ghosts
+ .openRemoteSettings({
+ deviceId: remoteDeviceId,
+ instanceId,
+ expectedInstalledApproval: approvalToken,
+ })
+ .then((view) => {
+ if (disposed) {
+ void window.electronAPI.ghosts.closeRemoteSettings(view.id).catch(() => {});
+ return;
+ }
+ remoteViewId = view.id;
+ remoteView.current = view.id;
+ webview.setAttribute('partition', view.partition);
+ webview.setAttribute('src', view.src);
+ host.appendChild(webview);
+ })
+ .catch(() => {
+ if (!disposed) setCrashed(true);
+ });
+ } else host.appendChild(webview);
return () => {
disposed = true;
+ remoteView.current = null;
+ unsubscribeDirectory?.();
injector.dispose();
if (themeTimer !== null) clearTimeout(themeTimer);
for (const timer of measureTimers) clearTimeout(timer);
@@ -277,6 +330,8 @@ function SettingsWebviewBody({
webview.removeEventListener('console-message', onConsoleMessage);
webview.removeEventListener('render-process-gone', onGone);
webview.remove();
+ if (remoteViewId)
+ void window.electronAPI.ghosts.closeRemoteSettings(remoteViewId).catch(() => {});
};
// version 入依赖:原位更新换版后 webview 重挂载,设置区立刻跑新代码。
}, [
@@ -292,7 +347,17 @@ function SettingsWebviewBody({
settingsHeightKey,
approvalToken,
hostAccount,
+ remoteDeviceId,
+ instanceId,
]);
+ useEffect(() => {
+ if (!directory) return;
+ const timer = setTimeout(
+ () => setDirectory((previous) => (previous === directory ? null : previous)),
+ Math.max(0, directory.request.expiresAt - Date.now()),
+ );
+ return () => clearTimeout(timer);
+ }, [directory]);
if (crashed) {
return (
@@ -305,16 +370,53 @@ function SettingsWebviewBody({
/>
);
}
+ const answerDirectory = async (path: string | null) => {
+ if (directory?.request.id === answeredDirectory.current) return;
+ if (!directory || remoteView.current !== directory.viewId)
+ throw new Error('PLUGIN_PAGE_CLOSED');
+ answeredDirectory.current = directory.request.id;
+ try {
+ await window.electronAPI.ghosts.answerRemoteSettingsDirectory({
+ viewId: directory.viewId,
+ requestId: directory.request.id,
+ path,
+ });
+ setDirectory((previous) => (previous === directory ? null : previous));
+ } catch (error) {
+ answeredDirectory.current = null;
+ throw error;
+ }
+ };
return (
- <div
- ref={hostRef}
- data-ghost-webview
- className={cn(
- 'relative flex w-full min-w-0 max-w-full',
- fixedHeight === undefined && 'overflow-hidden',
+ <>
+ <div
+ ref={hostRef}
+ data-ghost-webview
+ className={cn(
+ 'relative flex w-full min-w-0 max-w-full',
+ fixedHeight === undefined && 'overflow-hidden',
+ )}
+ style={{ height: fixedHeight ?? autoHeight }}
+ />
+ {directory && directory.viewId === remoteView.current && remoteDeviceId && (
+ <AddRemoteProjectDialog
+ open
+ initialDeviceId={remoteDeviceId}
+ fixedDeviceId={remoteDeviceId}
+ title={t('settings.ghosts.pick.dialogMessage', { name: manifest.name })}
+ confirmText={t('settings.ghosts.pick.dialogTitle')}
+ errorText={t('settings.ghosts.errors.generic')}
+ onOpenChange={(open) => {
+ if (!open) void answerDirectory(null).catch(() => setDirectory(null));
+ }}
+ onProjectAdded={async (target) => {
+ if (target.kind !== 'device-link' || target.deviceId !== remoteDeviceId)
+ throw new Error('PLUGIN_PAGE_CLOSED');
+ await answerDirectory(target.path);
+ }}
+ />
)}
- style={{ height: fixedHeight ?? autoHeight }}
- />
+ </>
);
}
@@ -325,6 +427,7 @@ export function GhostSettingsWebview({
appearance = 'settings',
account,
reloadKey = 0,
+ remoteDeviceId,
}: {
ghost: InstalledGhost;
/** Product-facing section title; settings keeps the legacy fallback. */
@@ -333,12 +436,15 @@ export function GhostSettingsWebview({
appearance?: 'settings' | 'plugin';
account?: ReactNode;
reloadKey?: number;
+ remoteDeviceId?: string;
}): ReactNode {
const { t } = useTranslation();
const { mode, dataOwnerId } = useAuth();
const ownerKey = `${mode}:${dataOwnerId ?? ''}`;
const { manifest } = ghost;
- const settingsHeightKey = pluginStoragePart(installedGhostLogicalIdentity(ghost));
+ const settingsHeightKey =
+ (remoteDeviceId ? remoteDeviceId + ':' : '') +
+ pluginStoragePart(installedGhostLogicalIdentity(ghost));
if (!manifest.settingsHtml) return null;
return (
<div
@@ -374,6 +480,7 @@ export function GhostSettingsWebview({
appearance={appearance}
dataOwnerId={dataOwnerId}
hostAccount
+ remoteDeviceId={remoteDeviceId}
/>
</details>
) : ghost.enabled ? (
@@ -382,6 +489,7 @@ export function GhostSettingsWebview({
ghost={ghost}
appearance={appearance}
dataOwnerId={dataOwnerId}
+ remoteDeviceId={remoteDeviceId}
/>
) : (
<AsleepHint appearance={appearance} />
diff --git a/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx b/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
index b87163a7a7..f74b37e625 100644
--- a/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
@@ -5,10 +5,11 @@
* controls; persistence stays in ghost-errand-prefs.json via ghosts:errand-prefs.
*/
-import { useCallback, useState, type ReactNode } from 'react';
+import { useCallback, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Bot, FolderOpen, X } from 'lucide-react';
+import type { PluginTaskPreferences } from '@cindy/device-link';
import { Button } from '@/components/ui/button';
import { useModelPickerAgents } from '@/hooks/useAvailableAgents';
import { extractIpcError } from '@/utils/ipcError';
@@ -38,6 +39,8 @@ export function PluginTaskPrefs({
appearance = 'settings',
legacyDefault = false,
showTaskRows = true,
+ remote,
+ disabled = false,
}: {
ghostId: string;
/** Plugin detail aligns the card with the shared Plugin surface. */
@@ -46,48 +49,81 @@ export function PluginTaskPrefs({
legacyDefault?: boolean;
/** Plugins that cannot create tasks (quick answers only) show just the model row. */
showTaskRows?: boolean;
+ remote?: {
+ deviceId: string;
+ value: PluginTaskPreferences;
+ auxiliaryModelLabel: string | null;
+ onChange(config: TaskConfig): Promise<PluginTaskPreferences>;
+ };
+ disabled?: boolean;
}) {
const { t } = useTranslation();
- const [initial] = useState(() => window.electronAPI.ghosts.errandPrefsSync(ghostId));
- const [config, setConfig] = useState<TaskConfig>(() => (initial.config ?? {}) as TaskConfig);
- const auxiliaryModelLabel = initial.auxiliaryModelLabel ?? null;
+ const [initial] = useState(() =>
+ remote
+ ? { config: {}, auxiliaryModelLabel: null }
+ : window.electronAPI.ghosts.errandPrefsSync(ghostId),
+ );
+ const [localConfig, setConfig] = useState<TaskConfig>(() => (initial.config ?? {}) as TaskConfig);
+ const config = remote ? (remote.value.config as TaskConfig) : localConfig;
+ const auxiliaryModelLabel = remote
+ ? remote.auxiliaryModelLabel
+ : (initial.auxiliaryModelLabel ?? null);
+ const saveLock = useRef(false);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const save = useCallback(
async (next: TaskConfig) => {
+ if (disabled || saveLock.current) return false;
+ saveLock.current = true;
const prev = config;
setError(null);
setSaving(true);
setConfig(next);
try {
- const result = await window.electronAPI.ghosts.setErrandConfig(
- ghostId,
- next as Record<string, unknown>,
- );
+ const result = await (remote
+ ? remote.onChange(next)
+ : window.electronAPI.ghosts.setErrandConfig(ghostId, next as Record<string, unknown>));
setConfig((result.config ?? {}) as TaskConfig);
return true;
} catch (cause) {
setConfig(prev);
setError(extractIpcError(cause)?.message || t('settings.ghosts.errors.generic'));
return false;
- } finally { setSaving(false); }
+ } finally {
+ saveLock.current = false;
+ setSaving(false);
+ }
},
- [config, ghostId, t],
+ [config, ghostId, remote, disabled, t],
);
// Explicit model = the complete saved combination. Without one the plugin follows
// the system auxiliary model (quick answers) and the originating task (new tasks).
- const customized = [config.agentKind, config.model, config.providerId, config.effort, config.fastMode]
- .some(value => value !== undefined);
+ const customized = [
+ config.agentKind,
+ config.model,
+ config.providerId,
+ config.effort,
+ config.fastMode,
+ ].some((value) => value !== undefined);
const vendor = config.agentKind;
const pickerAgents = useModelPickerAgents(
vendor === 'cc' ? 'claude-code' : (vendor ?? 'codex'),
+ remote?.deviceId,
);
const shownModel = config.model ?? '';
- const shownEffort = (config.effort ?? getEffortForModel(shownModel) ?? 'high') as Effort;
- const shownFast = config.fastMode ?? getFastModeForModel(shownModel);
- const permissionMode = config.permissionMode ?? (legacyDefault ? 'plan' : 'ask');
+ const shownEffort = (config.effort ??
+ (remote ? '' : (getEffortForModel(shownModel) ?? 'high'))) as Effort;
+ const shownFast = config.fastMode ?? (remote ? false : getFastModeForModel(shownModel));
+ const permissionMode =
+ config.permissionMode ??
+ (remote
+ ? (remote.value.defaultPermissionMode as TaskConfig['permissionMode'])
+ : legacyDefault
+ ? 'plan'
+ : 'ask') ??
+ 'ask';
const restoreModel = (): Promise<boolean> =>
save({ permissionMode: config.permissionMode, workingDir: config.workingDir });
const followLabel = auxiliaryModelLabel
@@ -115,7 +151,8 @@ export function PluginTaskPrefs({
);
return (
- <fieldset disabled={saving}
+ <fieldset
+ disabled={saving || disabled}
className={cn(
'ghost-errand-prefs min-w-0 max-w-full flex flex-col gap-3 rounded-xl border px-5 py-4',
appearance === 'plugin'
@@ -145,16 +182,18 @@ export function PluginTaskPrefs({
<>
<div className="min-w-0 flex-1">
<ModelSelector
- disabled={saving}
+ disabled={saving || disabled}
unifiedAgents={pickerAgents}
- onUnifiedSelect={({ engine, providerId, modelId, effort, fast }) => save({
- ...config,
- agentKind: engine,
- providerId,
- model: modelId,
- effort: TASK_EFFORTS.has(effort ?? '') ? effort : undefined,
- fastMode: fast,
- })}
+ onUnifiedSelect={({ engine, providerId, modelId, effort, fast }) =>
+ save({
+ ...config,
+ agentKind: engine,
+ providerId,
+ model: modelId,
+ effort: TASK_EFFORTS.has(effort ?? '') ? effort : undefined,
+ fastMode: fast,
+ })
+ }
modelId={shownModel}
effort={shownEffort}
fastMode={shownFast}
@@ -172,7 +211,13 @@ export function PluginTaskPrefs({
onModelChange={(modelId) => {
// 选模型即整组钉住(agent 一起钉);未选过时没有可钉的 agent,交给统一面板。
if (!vendor) return false;
- return save({ ...config, agentKind: vendor, model: modelId, effort: undefined, fastMode: false });
+ return save({
+ ...config,
+ agentKind: vendor,
+ model: modelId,
+ effort: undefined,
+ fastMode: false,
+ });
}}
onEffortChange={(effort) => {
if (!customized || !TASK_EFFORTS.has(effort)) return;
@@ -196,80 +241,105 @@ export function PluginTaskPrefs({
/>
</div>
{customized ? (
- <Button type="button" variant="secondary" tone="quiet" size="sm" disabled={saving}
- className="shrink-0" onClick={() => void restoreModel()}>
+ <Button
+ type="button"
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ disabled={saving || disabled}
+ className="shrink-0"
+ onClick={() => void restoreModel()}
+ >
{t('settings.ghosts.detail.errandPrefs.restoreModel')}
</Button>
) : null}
</>,
)}
- {showTaskRows ? row(
- 'permission',
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <PermissionSelector
- disabled={saving}
- permissionMode={permissionMode}
- fallbackModeLabel={permissionMode === 'plan' ? t('settings.ghosts.detail.errandPrefs.legacyPermission') : undefined}
- vendorKey={vendor}
- triggerVariant="field"
- ariaContext={t('settings.ghosts.detail.errandPrefs.permission')}
- disabledModes={{
- default: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
- bypassPermissions: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
- }}
- onPermissionModeChange={(mode) => {
- // disabledModes 已灰置非法档;这里再执一道白名单(UI 不是安全边界,
- // 存储层与协议层各有一道,三道口径一致)。
- if (!PERMISSION_ALLOWED.has(mode)) return;
- save({
- ...config,
- permissionMode: mode as 'ask' | 'acceptEdits' | 'auto',
- });
- }}
- />
- {legacyDefault && config.permissionMode === undefined ? (
- <p className="text-12 leading-4 text-[var(--text-tertiary)]">
- {t('settings.ghosts.detail.errandPrefs.legacyPermissionHint')}
- </p>
- ) : null}
- </div>,
- ) : null}
+ {showTaskRows
+ ? row(
+ 'permission',
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <PermissionSelector
+ disabled={saving || disabled}
+ permissionMode={permissionMode}
+ fallbackModeLabel={
+ permissionMode === 'plan'
+ ? t('settings.ghosts.detail.errandPrefs.legacyPermission')
+ : undefined
+ }
+ vendorKey={vendor}
+ triggerVariant="field"
+ ariaContext={t('settings.ghosts.detail.errandPrefs.permission')}
+ disabledModes={{
+ default: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
+ bypassPermissions: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
+ }}
+ onPermissionModeChange={(mode) => {
+ // disabledModes 已灰置非法档;这里再执一道白名单(UI 不是安全边界,
+ // 存储层与协议层各有一道,三道口径一致)。
+ if (!PERMISSION_ALLOWED.has(mode)) return;
+ save({
+ ...config,
+ permissionMode: mode as 'ask' | 'acceptEdits' | 'auto',
+ });
+ }}
+ />
+ {legacyDefault && config.permissionMode === undefined ? (
+ <p className="text-12 leading-4 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.detail.errandPrefs.legacyPermissionHint')}
+ </p>
+ ) : null}
+ </div>,
+ )
+ : null}
- {showTaskRows ? row(
- 'workdir',
- <>
- <span
- className={cn('min-w-0 flex-1 truncate text-[var(--text-tertiary)]', textCls)}
- title={config.workingDir}
- >
- {config.workingDir ?? t('settings.ghosts.detail.errandPrefs.workdirDefault')}
- </span>
- {config.workingDir ? (
- <button
- type="button"
- onClick={() => save({ ...config, workingDir: undefined })}
- aria-label={t('settings.ghosts.detail.errandPrefs.workdirClear')}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)]"
- >
- <X size={13} />
- </button>
- ) : null}
- <Button
- variant="secondary"
- size="md"
- compact
- type="button"
- onClick={() => void pickWorkingDir()}
- className="shrink-0"
- >
- <FolderOpen size={13} />
- {t('settings.ghosts.detail.errandPrefs.workdirPick')}
- </Button>
- </>,
+ {showTaskRows ? (
+ remote ? (
+ <p className="text-12 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.taskWorkdirBoundary')}
+ </p>
+ ) : (
+ row(
+ 'workdir',
+ <>
+ <span
+ className={cn('min-w-0 flex-1 truncate text-[var(--text-tertiary)]', textCls)}
+ title={config.workingDir}
+ >
+ {config.workingDir ?? t('settings.ghosts.detail.errandPrefs.workdirDefault')}
+ </span>
+ {config.workingDir ? (
+ <button
+ type="button"
+ onClick={() => save({ ...config, workingDir: undefined })}
+ aria-label={t('settings.ghosts.detail.errandPrefs.workdirClear')}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)]"
+ >
+ <X size={13} />
+ </button>
+ ) : null}
+ <Button
+ variant="secondary"
+ size="md"
+ compact
+ type="button"
+ onClick={() => void pickWorkingDir()}
+ className="shrink-0"
+ >
+ <FolderOpen size={13} />
+ {t('settings.ghosts.detail.errandPrefs.workdirPick')}
+ </Button>
+ </>,
+ )
+ )
) : null}
- {error ? <p role="alert" className="text-12 leading-5 text-[var(--text-secondary)]">{error}</p> : null}
+ {error ? (
+ <p role="alert" className="text-12 leading-5 text-[var(--text-secondary)]">
+ {error}
+ </p>
+ ) : null}
</fieldset>
);
}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
index 80aabd362d..5228cbbd52 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
@@ -11,6 +11,12 @@ const authState = vi.hoisted(() => ({
mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
dataOwnerId: 'owner-a' as string | null,
}));
+const directoryPicker = vi.hoisted(() =>
+ vi.fn<(props: Record<string, unknown>) => null>(() => null),
+);
+vi.mock('@/components/new-chat/AddRemoteProjectDialog', () => ({
+ AddRemoteProjectDialog: directoryPicker,
+}));
import type { InstalledGhost } from '../../../shared/ghost';
import { GhostSettingsWebview } from '../GhostSettingsWebview';
@@ -39,6 +45,8 @@ afterEach(() => {
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ directoryPicker.mockClear();
});
function renderSettings(settingsHeight?: number, measuredHeight?: number) {
@@ -96,25 +104,107 @@ function renderSettings(settingsHeight?: number, measuredHeight?: number) {
}
describe('GhostSettingsWebview layout ownership', () => {
+ it('keeps the target page and directory picker bound to B, and closes the lease on unmount', async () => {
+ let receive!: (value: { viewId: string; request: { id: string; expiresAt: number } }) => void;
+ const unsubscribe = vi.fn(),
+ answer = vi.fn(async () => {}),
+ close = vi.fn(async () => {});
+ const open = vi.fn(async () => ({
+ id: 'view-b',
+ partition: 'remote-plugin-settings:view-b',
+ src: 'cindy-ghost://example-settings-layout/settings.html',
+ }));
+ vi.stubGlobal('electronAPI', {
+ ghosts: {
+ openRemoteSettings: open,
+ closeRemoteSettings: close,
+ answerRemoteSettingsDirectory: answer,
+ onRemoteSettingsDirectory: (listener: typeof receive) => {
+ receive = listener;
+ return unsubscribe;
+ },
+ },
+ });
+ const { ghost, view } = renderSettings();
+ view.rerender(<GhostSettingsWebview ghost={ghost} remoteDeviceId="B" />);
+ await waitFor(() =>
+ expect(view.container.querySelector('webview')?.getAttribute('partition')).toBe(
+ 'remote-plugin-settings:view-b',
+ ),
+ );
+ expect(open).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'B', instanceId: 'example-settings-layout' }),
+ );
+ act(() =>
+ receive({
+ viewId: 'foreign-view',
+ request: { id: 'foreign', expiresAt: Date.now() + 90_000 },
+ }),
+ );
+ expect(directoryPicker).not.toHaveBeenCalled();
+ act(() =>
+ receive({ viewId: 'view-b', request: { id: 'directory-b', expiresAt: Date.now() + 90_000 } }),
+ );
+ const props = directoryPicker.mock.calls.at(-1)?.[0] as unknown as {
+ fixedDeviceId: string;
+ onProjectAdded(target: unknown): Promise<void>;
+ onOpenChange(open: boolean): void;
+ };
+ expect(props.fixedDeviceId).toBe('B');
+ await expect(
+ props.onProjectAdded({ kind: 'device-link', deviceId: 'C', path: '/other' }),
+ ).rejects.toThrow();
+ expect(answer).not.toHaveBeenCalled();
+ await act(async () => {
+ await props.onProjectAdded({ kind: 'device-link', deviceId: 'B', path: '/target/folder' });
+ props.onOpenChange(false);
+ });
+ expect(answer).toHaveBeenCalledExactlyOnceWith({
+ viewId: 'view-b',
+ requestId: 'directory-b',
+ path: '/target/folder',
+ });
+ view.unmount();
+ expect(unsubscribe).toHaveBeenCalled();
+ expect(close).toHaveBeenCalledWith('view-b');
+ });
it('recreates the settings guest when a same-version source gets a new receipt', () => {
const { ghost, view } = renderSettings();
const approved = { ...ghost, approval: { state: 'approved' as const, revision: 'receipt-a' } };
view.rerender(<GhostSettingsWebview ghost={approved} />);
const original = view.container.querySelector('webview');
- view.rerender(<GhostSettingsWebview ghost={{ ...approved, approval: { state: 'approved', revision: 'receipt-b' } }} />);
+ view.rerender(
+ <GhostSettingsWebview
+ ghost={{ ...approved, approval: { state: 'approved', revision: 'receipt-b' } }}
+ />,
+ );
const replacement = view.container.querySelector('webview');
expect(replacement).not.toBe(original);
expect(original?.isConnected).toBe(false);
expect(replacement?.getAttribute('src')).toBe(original?.getAttribute('src'));
- view.rerender(<GhostSettingsWebview ghost={{ ...approved, approval: { state: 'approved', revision: 'receipt-b' } }} />);
+ view.rerender(
+ <GhostSettingsWebview
+ ghost={{ ...approved, approval: { state: 'approved', revision: 'receipt-b' } }}
+ />,
+ );
expect(view.container.querySelector('webview')).toBe(replacement);
});
it('keeps an in-place settings page on its physical WebView partition', () => {
const { ghost, view, webview } = renderSettings();
expect(webview.getAttribute('partition')).toBe('cindy-ghost-example-settings-layout');
- view.rerender(<GhostSettingsWebview ghost={{ ...ghost, dir: '/ghosts/example-settings-layout', instanceKey: 'example-settings-layout', namespace: 'acme' }} />);
- expect(view.container.querySelector('webview')?.getAttribute('partition'))
- .toBe('cindy-ghost-example-settings-layout');
+ view.rerender(
+ <GhostSettingsWebview
+ ghost={{
+ ...ghost,
+ dir: '/ghosts/example-settings-layout',
+ instanceKey: 'example-settings-layout',
+ namespace: 'acme',
+ }}
+ />,
+ );
+ expect(view.container.querySelector('webview')?.getAttribute('partition')).toBe(
+ 'cindy-ghost-example-settings-layout',
+ );
});
it('keeps account status visible and the plugin form collapsed without a duplicate title', () => {
const { ghost, view } = renderSettings();
diff --git a/apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx b/apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx
index 46f62873ec..2c81bba8a1 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx
@@ -2,7 +2,8 @@ import { useState } from 'react';
import { GhostPluginPage } from '@/features/plugin/GhostPluginPage';
import { SkillhubHomeView } from '@/features/skillhub/SkillhubHomeView';
-import { useSkillhubStoreSync } from '@/features/skillhub/SkillhubFeatureLayout';
+import { LocalSkillhubStoreSync } from '@/features/skillhub/SkillhubFeatureLayout';
+import { useCatalogDevice } from '@/features/plugin/useCatalogDevice';
/**
* Settings → Plugins embeds the same Plugin / Skill catalogs.
@@ -20,6 +21,7 @@ export function SettingsCatalogPanel() {
<div className={catalogTab === 'plugins' ? 'h-full min-h-0' : 'hidden'}>
<GhostPluginPage
embedded
+ active={catalogTab === 'plugins'}
onSelectCatalogTab={(tab) => {
if (tab === 'skills') setSkillsVisited(true);
setCatalogTab(tab);
@@ -40,10 +42,11 @@ function SettingsSkillsPane({
active: boolean;
onSelectTab: (tab: 'plugins' | 'skills') => void;
}) {
- useSkillhubStoreSync();
+ const { device } = useCatalogDevice();
return (
<div className={active ? 'h-full min-h-0' : 'hidden'}>
- <SkillhubHomeView embedded onSelectCatalogTab={onSelectTab} />
+ {!device ? <LocalSkillhubStoreSync /> : null}
+ <SkillhubHomeView embedded active={active} onSelectCatalogTab={onSelectTab} />
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx
new file mode 100644
index 0000000000..2833fac0b9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx
@@ -0,0 +1,102 @@
+import { useTranslation } from 'react-i18next';
+import { ChevronDown, Plus, Sparkles, Store, Upload } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+
+/** Add-plugin menu shared by local and remote catalogs. */
+export function GhostPluginActions({
+ onInstall,
+ onCreateWithCindy,
+ onAddMarketplace,
+ disabled = false,
+ installTarget,
+}: {
+ onInstall: () => void;
+ onCreateWithCindy?: () => void;
+ onAddMarketplace?: () => void;
+ disabled?: boolean;
+ installTarget?: string;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="primary"
+ size="lg"
+ type="button"
+ disabled={disabled}
+ aria-label={t('settings.ghosts.page.addPluginAria')}
+ className="plugin-management-action-trigger group shrink-0 shadow-[var(--plugin-card-shadow)] data-[state=open]:[--button-face-bg:var(--surface-chip)]"
+ >
+ <Plus size={14} strokeWidth={1.8} aria-hidden="true" />
+ <span className="plugin-management-action-label">
+ {t('settings.ghosts.page.addPlugin')}
+ </span>
+ <ChevronDown
+ size={13}
+ strokeWidth={1.75}
+ className="plugin-management-action-chevron transition-transform duration-150 group-data-[state=open]:rotate-180 motion-reduce:transition-none"
+ aria-hidden="true"
+ />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ sideOffset={8}
+ className="w-max min-w-52 max-w-[calc(100vw-2rem)] p-1.5"
+ >
+ {installTarget ? (
+ <DropdownMenuLabel>
+ {t('settings.ghosts.remote.installDestination', { device: installTarget })}
+ </DropdownMenuLabel>
+ ) : null}
+ {onCreateWithCindy ? (
+ <>
+ <DropdownMenuItem onSelect={onCreateWithCindy} className="gap-3 whitespace-nowrap">
+ <Sparkles
+ size={16}
+ strokeWidth={1.7}
+ className="text-[var(--text-secondary)]"
+ aria-hidden="true"
+ />
+ {t('settings.ghosts.page.createWithCindy')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ ) : null}
+ <DropdownMenuItem onSelect={onInstall} className="gap-3 whitespace-nowrap">
+ <Upload
+ size={16}
+ strokeWidth={1.7}
+ className="text-[var(--text-secondary)]"
+ aria-hidden="true"
+ />
+ {t('settings.ghosts.install')}
+ </DropdownMenuItem>
+ {onAddMarketplace ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={onAddMarketplace} className="gap-3 whitespace-nowrap">
+ <Store
+ size={16}
+ strokeWidth={1.7}
+ className="text-[var(--text-secondary)]"
+ aria-hidden="true"
+ />
+ {t('settings.ghosts.market.sources.addMarketplace')}
+ </DropdownMenuItem>
+ </>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 788ed75016..569e4d4b63 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -23,6 +23,8 @@ import {
FolderOpen,
LayoutTemplate,
MoreVertical,
+ Shield,
+ type LucideIcon,
Trash2,
X,
} from 'lucide-react';
@@ -64,6 +66,10 @@ import { PluginDetailTopBar, usePluginDetailScrolled } from './PluginDetailTopBa
import './plugin-motion.css';
interface GhostPluginDetailViewProps {
+ /** Remote configuration section, including its heading or disabled notice. */
+ remoteConfiguration?: ReactNode;
+ remote?: boolean;
+ remoteFileUpdate?: boolean;
ghost: InstalledGhost | null;
detail: GhostPluginDetail;
marketItem?: PluginMarketItem | null;
@@ -108,6 +114,9 @@ const DETAIL_SURFACE_INTERACTIVE_CLASS =
/** Installed Ghost detail surface, ordered around configuration and capability review. */
export function GhostPluginDetailView({
+ remote = false,
+ remoteFileUpdate = false,
+ remoteConfiguration,
ghost,
detail,
panelStatus,
@@ -133,13 +142,9 @@ export function GhostPluginDetailView({
const { t } = useTranslation();
const { scrolled, onScroll } = usePluginDetailScrolled();
const enableSwitchId = useId();
- const [descriptionExpanded, setDescriptionExpanded] = useState(false);
const [githubConnectionVersion, setGithubConnectionVersion] = useState(0);
const [taskApprovalPending, setTaskApprovalPending] = useState(false);
- const [descriptionOverflows, setDescriptionOverflows] = useState(false);
- const descriptionRef = useRef<HTMLParagraphElement>(null);
- // 安装记录不完整时不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它
- // 看起来只是"被关掉了"),再喂 main 改版的 primaryAction/primaryEnabled。
+ // 未批准的安装不可运行;恢复入口与普通停用区分。
const needsReapproval = detail.approvalState !== 'approved';
const enabled = (enabledOverride ?? detail.enabled) && !needsReapproval;
const primaryAction = ghostPrimaryAction(detail);
@@ -150,7 +155,7 @@ export function GhostPluginDetailView({
// Local imports with the same id cannot use the host gh credential. Match the
// official receipt before advertising that connection in this plugin's UI.
const hasGithubConnection =
- detail.ghostId === 'cindy-github' &&
+ !remote && detail.ghostId === 'cindy-github' &&
Boolean(ghost) &&
ghost?.trust?.level === 'cindy-official' &&
ghost.trust.publisherSigned &&
@@ -165,62 +170,12 @@ export function GhostPluginDetailView({
const summary = hasGithubConnection
? t('ccAgent.gitContext.pr.setup.account.summary')
: ghostPluginSummary(detail.description, detail.ghostId);
- /**
- * 「从 .cindy 文件更新」是否可用。官方保留前缀(cindy- / filo- / xd-)在**非 dev
- * 构建**上会被 Main 的用户装入通道以 GHOST_ID_RESERVED 直接拒绝(见
- * main/cindy-brain/index.ts 的 rejectReservedGhostId),把这个必失败的动作摆在
- * 菜单里只会让用户选文件、等一下、然后吃一个错误。
- *
- * 判据用 `import.meta.env.DEV` 而不是新开一条 IPC 去问 app.isPackaged:打包产物
- * 必然 DEV=false,覆盖 Main 拒绝的全部场景;唯一偏差是「本地 build 但未打包运行」
- * 会多隐藏一次入口——方向保守(少一个入口 vs 给用户一个必失败按钮),可接受。
- * 普通第三方插件不受影响。
- */
- const localUpdateAvailable = import.meta.env.DEV || !isUserInstallReservedGhostId(detail.ghostId);
+ // 远程文件更新按目标 Host 能力判断,不能使用控制端的 DEV 状态。
+ const localUpdateAvailable = remote
+ ? remoteFileUpdate && !isUserInstallReservedGhostId(detail.ghostId)
+ : import.meta.env.DEV || !isUserInstallReservedGhostId(detail.ghostId);
const hasAdditionalActions = localUpdateAvailable || onExport !== undefined;
- useLayoutEffect(() => {
- setDescriptionExpanded(false);
- const description = descriptionRef.current;
- if (!description) return;
- const measure = () => {
- const computedStyle = window.getComputedStyle(description);
- const lineHeight = Number.parseFloat(computedStyle.lineHeight);
- const width = description.getBoundingClientRect().width;
- if (!Number.isFinite(lineHeight) || width <= 0) {
- setDescriptionOverflows(false);
- return;
- }
-
- // Chromium reports the clamped element's scrollHeight as the visible height.
- // Measure an unclamped, off-screen clone so the affordance only appears when
- // the complete description genuinely exceeds three lines.
- const measurement = description.cloneNode(true) as HTMLParagraphElement;
- measurement.classList.remove('line-clamp-3');
- Object.assign(measurement.style, {
- position: 'fixed',
- left: '-10000px',
- top: '0',
- width: `${width}px`,
- height: 'auto',
- maxHeight: 'none',
- overflow: 'visible',
- visibility: 'hidden',
- pointerEvents: 'none',
- WebkitLineClamp: 'unset',
- WebkitBoxOrient: 'initial',
- });
- document.body.appendChild(measurement);
- const fullHeight = measurement.getBoundingClientRect().height;
- measurement.remove();
- setDescriptionOverflows(fullHeight > lineHeight * 3 + 1);
- };
- measure();
- const observer = new ResizeObserver(measure);
- observer.observe(description);
- return () => observer.disconnect();
- }, [detail.id, summary]);
-
return (
<main
className="app-wallpaper-surface plugin-motion-root h-full min-h-0 w-full overflow-y-auto bg-[var(--surface)] [scrollbar-gutter:stable_both-edges]"
@@ -232,22 +187,16 @@ export function GhostPluginDetailView({
scrolled={scrolled}
/>
<article className="plugin-detail-frame mx-auto w-full max-w-[824px] px-8 pb-16 pt-5 max-[760px]:px-6">
- <header>
- <div className="plugin-detail-hero grid grid-cols-[64px_minmax(0,1fr)_auto] items-center gap-3">
- <GhostPluginIcon
- iconDataUrl={detail.iconDataUrl}
- iconId={detail.id}
- iconName={detail.name}
- size="detail"
- onIconLoadError={onIconLoadError}
- />
- <div className="plugin-detail-heading min-w-0">
- <h1 className="truncate text-28 font-medium leading-[1.214] text-[var(--text-primary)]">
- {detail.name}
- </h1>
- <GhostPluginMetadata author={detail.author} version={detail.version} marketItem={marketItem} />
- </div>
-
+ <PluginDetailHeader
+ id={detail.id}
+ name={detail.name}
+ description={summary}
+ author={detail.author}
+ version={detail.version}
+ marketItem={marketItem}
+ iconDataUrl={detail.iconDataUrl}
+ onIconLoadError={onIconLoadError}
+ actions={
<div
className="plugin-detail-actions flex shrink-0 flex-nowrap items-center gap-1.5"
style={WINDOW_NO_DRAG_STYLE}
@@ -286,7 +235,7 @@ export function GhostPluginDetailView({
</>
</Button>
) : null}
- {primaryAction !== 'manage' ? (
+ {!remote && primaryAction !== 'manage' ? (
<Button
variant={updateVersion ? 'secondary' : 'cta'}
size="lg"
@@ -373,6 +322,7 @@ export function GhostPluginDetailView({
) : null}
<DropdownMenuItem
onSelect={onUninstall}
+ disabled={updateBusy}
variant="danger"
className="gap-2.5"
>
@@ -382,33 +332,8 @@ export function GhostPluginDetailView({
</DropdownMenuContent>
</DropdownMenu>
</div>
- </div>
-
- <div className="mt-5">
- <p
- ref={descriptionRef}
- className={cn(
- 'text-14 leading-[1.571] text-[var(--text-secondary)]',
- !descriptionExpanded && 'line-clamp-3',
- )}
- >
- {summary}
- </p>
- {descriptionOverflows ? (
- <button
- type="button"
- onClick={() => setDescriptionExpanded((expanded) => !expanded)}
- aria-expanded={descriptionExpanded}
- className="mt-1.5 rounded-full text-13 leading-5 text-[var(--text-secondary)] transition-colors duration-150 hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"
- >
- {t(
- descriptionExpanded
- ? 'settings.ghosts.detail.descriptionCollapse'
- : 'settings.ghosts.detail.descriptionExpand',
- )}
- </button>
- ) : null}
- </div>
+ }
+ >
{needsReapproval ? (
<div className={cn('mt-5 rounded-xl px-4 py-3.5', DETAIL_SURFACE_CLASS)} role="status">
@@ -426,9 +351,9 @@ export function GhostPluginDetailView({
</p>
</div>
) : null}
- </header>
+ </PluginDetailHeader>
- {ghost ? (
+ {ghost && !remote ? (
<PluginUsageCard
key={`${usageOwnerKey ?? 'local'}:${detail.id}`}
ghostId={detail.id}
@@ -436,7 +361,7 @@ export function GhostPluginDetailView({
/>
) : null}
- {hasConfiguration ? (
+ {remote ? remoteConfiguration : hasConfiguration ? (
<section
className={hasGithubConnection ? 'mt-6' : DETAIL_SECTION_CLASS}
aria-labelledby={hasGithubConnection ? undefined : 'ghost-configuration-title'}
@@ -546,7 +471,7 @@ export function GhostPluginDetailView({
{detail.tools.length > 0 ? <ToolsSection tools={detail.tools} /> : null}
{detail.permissions.length > 0 ? <PermissionSummary items={detail.permissions} /> : null}
- {enabled && ghost?.manifest.agent?.tasks === true && ghost.taskCapabilityApproved !== true ? (
+ {!remote && enabled && ghost?.manifest.agent?.tasks === true && ghost.taskCapabilityApproved !== true ? (
<Button variant="secondary" size="sm" className="mt-4" disabled={taskApprovalPending} onClick={async () => {
setTaskApprovalPending(true);
try {
@@ -561,9 +486,9 @@ export function GhostPluginDetailView({
</Button>
) : null}
- <GhostLibrarySection ghostId={detail.id} enabled={ghost?.manifest.library === true} />
+ {!remote ? <GhostLibrarySection ghostId={detail.id} enabled={ghost?.manifest.library === true} /> : null}
- <DetailsSection detail={detail} panelStatus={panelStatus} />
+ <DetailsSection detail={remote ? { ...detail, installDir: null } : detail} panelStatus={panelStatus} />
</article>
</main>
);
@@ -583,6 +508,123 @@ export function OauthScopeStaleBadge() {
);
}
+export function PluginDetailHeader({
+ id,
+ name,
+ description,
+ author,
+ version,
+ marketItem,
+ iconDataUrl,
+ actions,
+ children,
+ onIconLoadError,
+}: {
+ id: string;
+ name: string;
+ description: string;
+ author?: string | null;
+ version?: string;
+ marketItem?: PluginMarketItem | null;
+ iconDataUrl?: string;
+ actions?: ReactNode;
+ children?: ReactNode;
+ onIconLoadError?: () => void;
+}) {
+ const { t } = useTranslation();
+ const [descriptionExpanded, setDescriptionExpanded] = useState(false);
+ const [descriptionOverflows, setDescriptionOverflows] = useState(false);
+ const descriptionRef = useRef<HTMLParagraphElement>(null);
+ useLayoutEffect(() => {
+ setDescriptionExpanded(false);
+ const description = descriptionRef.current;
+ if (!description) return;
+ const measure = () => {
+ const computedStyle = window.getComputedStyle(description);
+ const lineHeight = Number.parseFloat(computedStyle.lineHeight);
+ const width = description.getBoundingClientRect().width;
+ if (!Number.isFinite(lineHeight) || width <= 0) {
+ setDescriptionOverflows(false);
+ return;
+ }
+
+ // Chromium reports the clamped element's scrollHeight as the visible height.
+ // Measure an unclamped, off-screen clone so the affordance only appears when
+ // the complete description genuinely exceeds three lines.
+ const measurement = description.cloneNode(true) as HTMLParagraphElement;
+ measurement.classList.remove('line-clamp-3');
+ Object.assign(measurement.style, {
+ position: 'fixed',
+ left: '-10000px',
+ top: '0',
+ width: `${width}px`,
+ height: 'auto',
+ maxHeight: 'none',
+ overflow: 'visible',
+ visibility: 'hidden',
+ pointerEvents: 'none',
+ WebkitLineClamp: 'unset',
+ WebkitBoxOrient: 'initial',
+ });
+ document.body.appendChild(measurement);
+ const fullHeight = measurement.getBoundingClientRect().height;
+ measurement.remove();
+ setDescriptionOverflows(fullHeight > lineHeight * 3 + 1);
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(description);
+ return () => observer.disconnect();
+ }, [id, description]);
+ return (
+ <header>
+ <div className="plugin-detail-hero grid grid-cols-[64px_minmax(0,1fr)_auto] items-center gap-3">
+ <GhostPluginIcon
+ iconDataUrl={iconDataUrl}
+ iconId={id}
+ iconName={name}
+ size="detail"
+ onIconLoadError={onIconLoadError}
+ />
+ <div className="min-w-0">
+ <h1 className="truncate text-28 font-medium leading-[1.214] text-[var(--text-primary)]">
+ {name}
+ </h1>
+ <GhostPluginMetadata author={author} version={version} marketItem={marketItem} />
+ </div>
+
+ {actions}
+ </div>
+ <div className="mt-5">
+ <p
+ ref={descriptionRef}
+ className={cn(
+ 'text-14 leading-[1.571] text-[var(--text-secondary)]',
+ !descriptionExpanded && 'line-clamp-3',
+ )}
+ >
+ {description}
+ </p>
+ {descriptionOverflows ? (
+ <button
+ type="button"
+ onClick={() => setDescriptionExpanded((expanded) => !expanded)}
+ aria-expanded={descriptionExpanded}
+ className="mt-1.5 rounded-full text-13 leading-5 text-[var(--text-secondary)] transition-colors duration-150 hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"
+ >
+ {t(
+ descriptionExpanded
+ ? 'settings.ghosts.detail.descriptionCollapse'
+ : 'settings.ghosts.detail.descriptionExpand',
+ )}
+ </button>
+ ) : null}
+ </div>
+ {children}
+ </header>
+ );
+}
+
/** Compact factual metadata with one shared color and stable product order. */
export function GhostPluginMetadata({
author,
@@ -590,10 +632,11 @@ export function GhostPluginMetadata({
marketItem,
}: {
author?: string | null;
- version: string;
+ version?: string;
marketItem?: PluginMarketItem | null;
}) {
const { t } = useTranslation();
+ if (!author && !version && !marketItem) return null;
return (
<div className="plugin-detail-metadata mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-13 leading-5 text-[var(--text-tertiary)]">
{author ? (
@@ -601,10 +644,10 @@ export function GhostPluginMetadata({
<span className="min-w-0 truncate">
{t('settings.ghosts.detail.byAuthor', { author })}
</span>
- <MetadataDivider />
+ {version ? <MetadataDivider /> : null}
</>
) : null}
- <span className="shrink-0">v{version}</span>
+ {version ? <span className="shrink-0">v{version}</span> : null}
{marketItem ? <PluginSharedUsage detail={marketItem} /> : null}
</div>
);
@@ -618,7 +661,7 @@ function MetadataDivider() {
);
}
-function DetailSectionHeader({
+export function DetailSectionHeader({
id,
title,
action,
@@ -658,7 +701,11 @@ function SectionTextAction({
);
}
-export function ToolsSection({ tools }: { tools: readonly GhostToolDecl[] }) {
+export function ToolsSection({
+ tools,
+}: {
+ tools: readonly (Pick<GhostToolDecl, 'name' | 'description'> & Partial<GhostToolDecl>)[];
+}) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const canExpand = tools.length > 6;
@@ -695,7 +742,7 @@ export function ToolsSection({ tools }: { tools: readonly GhostToolDecl[] }) {
}
/** A Tool exposes only its author-provided description after explicit activation. */
-export function ToolDescriptionChip({ tool }: { tool: GhostToolDecl }) {
+export function ToolDescriptionChip({ tool }: { tool: Pick<GhostToolDecl, 'name' | 'description'> & Partial<GhostToolDecl> }) {
const { t } = useTranslation();
return (
<Popover>
@@ -730,11 +777,40 @@ export function ToolDescriptionChip({ tool }: { tool: GhostToolDecl }) {
export function PermissionSummary({ items }: { items: readonly GhostPermissionItem[] }) {
const { t } = useTranslation();
- const permissionItems = items.filter((item) => item.kind !== 'tool');
+ return (
+ <PluginPermissionSummary
+ items={items
+ .filter((item) => item.kind !== 'tool')
+ .map((item) => ({
+ key: item.key,
+ title: t('settings.ghosts.perm.' + item.labelKey, item.labelArgs),
+ descriptions: [
+ item.detailKey ? t('settings.ghosts.perm.' + item.detailKey, item.detailArgs) : '',
+ item.detail ?? '',
+ ].filter(Boolean),
+ icon: permissionItemIcon(item),
+ }))}
+ />
+ );
+}
+
+interface PluginPermissionFact {
+ key: string;
+ title: string;
+ descriptions: readonly string[];
+ icon?: LucideIcon;
+}
+
+export function PluginPermissionSummary({
+ items: permissionItems,
+}: {
+ items: readonly PluginPermissionFact[];
+}) {
+ const { t } = useTranslation();
const [dialogOpen, setDialogOpen] = useState(false);
if (permissionItems.length === 0) return null;
const permissionCardLabel = `${t('settings.ghosts.detail.permissionsTitle')}: ${permissionItems
- .map((item) => t(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs))
+ .map((item) => item.title)
.join(', ')}`;
return (
<section className={DETAIL_SECTION_CLASS} aria-labelledby="ghost-permissions-title">
@@ -759,7 +835,7 @@ export function PermissionSummary({ items }: { items: readonly GhostPermissionIt
)}
>
{permissionItems.map((item) => {
- const Icon = permissionItemIcon(item);
+ const Icon = item.icon ?? Shield;
return (
<span
key={item.key}
@@ -772,7 +848,7 @@ export function PermissionSummary({ items }: { items: readonly GhostPermissionIt
aria-hidden="true"
/>
<span className="min-w-0 break-words text-13 font-normal leading-5">
- {t(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs)}
+ {item.title}
</span>
</span>
);
@@ -787,12 +863,8 @@ export function PermissionSummary({ items }: { items: readonly GhostPermissionIt
);
}
-function PermissionDetailRow({ item }: { item: GhostPermissionItem }) {
- const { t } = useTranslation();
- const Icon = permissionItemIcon(item);
- const hostDescription = item.detailKey
- ? t(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs)
- : null;
+function PermissionDetailRow({ item }: { item: PluginPermissionFact }) {
+ const Icon = item.icon ?? Shield;
return (
<div className="flex items-start gap-3 py-4 first:pt-0 last:pb-0">
<Icon
@@ -803,18 +875,16 @@ function PermissionDetailRow({ item }: { item: GhostPermissionItem }) {
/>
<div className="min-w-0 flex-1">
<p className="break-words text-14 font-medium leading-[1.571] text-[var(--text-primary)]">
- {t(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs)}
+ {item.title}
</p>
- {hostDescription ? (
- <p className="mt-1 whitespace-pre-line break-words text-13 leading-5 text-[var(--text-secondary)]">
- {hostDescription}
- </p>
- ) : null}
- {item.detail ? (
- <p className="mt-1 whitespace-pre-line break-words text-13 leading-5 text-[var(--text-secondary)]">
- {item.detail}
+ {item.descriptions.map((description, index) => (
+ <p
+ key={index}
+ className="mt-1 whitespace-pre-line break-words text-13 leading-5 text-[var(--text-secondary)]"
+ >
+ {description}
</p>
- ) : null}
+ ))}
</div>
</div>
);
@@ -931,6 +1001,22 @@ export function DetailsSection({
]
: []),
];
+ return <PluginDetailFactsSection facts={facts} />;
+}
+
+export function PluginDetailFactsSection({
+ facts,
+}: {
+ facts: readonly {
+ key: string;
+ label: string;
+ value: string;
+ monospace?: boolean;
+ action?: ReactNode;
+ fullWidth?: boolean;
+ }[];
+}) {
+ const { t } = useTranslation();
return (
<section className={DETAIL_SECTION_CLASS} aria-labelledby="ghost-details-title">
<DetailSectionHeader id="ghost-details-title" title={t('settings.ghosts.detail.infoTitle')} />
@@ -1065,7 +1151,7 @@ function PermissionDetailDialog({
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
- items: readonly GhostPermissionItem[];
+ items: readonly PluginPermissionFact[];
}) {
const { t } = useTranslation();
return (
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 3a86d4e7f9..67298a2ed1 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -1,3 +1,5 @@
+import { CatalogDeviceScope, type CatalogDeviceControl } from './useCatalogDevice';
+import { RemotePluginPage } from './RemotePluginPage';
import { featureRetirementById } from '../../../shared/featureRetirements';
import { RetiredFeatureDetail } from './RetiredFeatureDetail';
import { Button } from '@/components/ui/button';
@@ -29,24 +31,13 @@ import {
ChevronDown,
ChevronRight,
MessageCircle,
- Plus,
ShieldAlert,
SlidersHorizontal,
- Sparkles,
- Store,
- Upload,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from '@/components/ui/dropdown-menu';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
import { useAuth } from '@/contexts/AuthContext';
@@ -68,7 +59,7 @@ import { resetDraftWorkspaceTargets } from '@/state/newMakerDraft';
import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';
import { installGhostFromFile, pickAndUpdateGhost } from '@/cindy-brain/installFlow';
import { SegmentedControl } from '@/components/ui/segmented-control';
-import { cn } from '@/lib/utils';
+import { cn, basename } from '@/lib/utils';
import { AttentionDot } from '@/components/sidebar/AttentionDot';
import {
useGhostUnread,
@@ -124,10 +115,14 @@ import {
PLUGIN_MANAGEMENT_CARD_GRID_CLASS,
PLUGIN_INSTALLED_CARD_GRID_CLASS,
PluginManagementLayout,
+ InstalledCatalogHeader,
+ CatalogTargetControls,
+ CatalogManagementNotice,
PluginManagementPage,
} from './PluginManagementLayout';
import { usePluginListScrollRestoration } from './lib/usePluginListScrollRestoration';
import { GhostPagePanelHost } from './GhostPagePanelHost';
+import { GhostPluginActions } from './GhostPluginActions';
import { GhostPluginDetailView } from './GhostPluginDetailView';
import { PluginSharedUsage } from './PluginSharedUsage';
import {
@@ -139,7 +134,7 @@ import {
import { UpdateAllDialog } from './UpdateAllDialog';
import { GhostPluginIcon } from './GhostPluginIcon';
import { MarketPluginDetailView } from './MarketPluginDetailView';
-import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker';
+import { PluginProjectMenu, usePluginRecentWorkdirs } from './PluginScopePicker';
import {
canOfferMarketInstall,
ghostReapprovalRoute,
@@ -418,11 +413,19 @@ function readIgnoredRound(storageKey: string): string {
* real Ghost runtime. The page deliberately keeps the previous list/detail
* interaction shape, while every displayed field comes from InstalledGhost.
*/
-export function GhostPluginPage({
+export function GhostPluginPage(props: { embedded?: boolean; active?: boolean; onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void } = {}) {
+ return <CatalogDeviceScope>{(device, online, generation, deviceControl) => device
+ ? <RemotePluginPage key={`${generation}:${device.deviceId}`} device={device} online={online} deviceControl={deviceControl} {...props} />
+ : <LocalGhostPluginPage deviceControl={deviceControl} {...props} />}</CatalogDeviceScope>;
+}
+
+function LocalGhostPluginPage({
embedded = false,
+ deviceControl,
onSelectCatalogTab,
}: {
embedded?: boolean;
+ deviceControl?: CatalogDeviceControl;
onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void;
} = {}) {
const { i18n, t } = useTranslation();
@@ -995,7 +998,7 @@ export function GhostPluginPage({
const dir = scopeDirRef.current;
if (dir) {
const result = await window.electronAPI.ghosts.setWorkdirDisabled(dir, id, !enabled);
- setProjectDisabled(new Set(result.disabled));
+ if (scopeDirRef.current === dir) setProjectDisabled(new Set(result.disabled));
toast.success(
t(
enabled
@@ -1741,17 +1744,23 @@ export function GhostPluginPage({
>
<PluginManagementPage>
{recommendationNotice}
- <header className="plugin-motion-page-header pb-2">
+ <header className="plugin-motion-page-header pb-2" data-catalog-region="heading">
<div className="min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-28 font-medium leading-tight text-[var(--text-primary)]">
{t('settings.ghosts.title')}
</h1>
- <PluginScopePicker
- scopeDir={scopeDir}
- activeSessionWorkingDir={activeSessionWorkingDir ?? undefined}
- recentWorkdirs={recentWorkdirs}
- onPick={handlePickScope}
+ <CatalogTargetControls
+ computer={deviceControl}
+ project={
+ <PluginProjectMenu
+ scopeDir={scopeDir}
+ activeSessionWorkingDir={activeSessionWorkingDir ?? undefined}
+ recentWorkdirs={recentWorkdirs}
+ onPick={handlePickScope}
+ />
+ }
+ projectLabel={scopeDir ? basename(scopeDir) : undefined}
/>
</div>
<p className="mt-2 max-w-2xl text-14 leading-6 text-[var(--text-secondary)]">
@@ -1772,37 +1781,32 @@ export function GhostPluginPage({
/>
}
>
+ <section className="plugin-motion-page-section mt-6 min-w-0">
+ <InstalledCatalogHeader
+ title={t('settings.ghosts.page.installedSection')}
+ count={searchedInstalledItems.length}
+ />
{scopeDir ? (
- <div className="mt-5 flex items-center justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3">
- <div className="flex min-w-0 items-center gap-2.5">
- <span className="truncate text-13 font-medium text-[var(--text-primary)]">
- {scopeDir}
- </span>
- <span className="truncate text-12 text-[var(--text-tertiary)]">
- {t('settings.ghosts.projectBanner.desc')}
- </span>
- </div>
- <Button
- variant="secondary"
- size="sm"
- compact
- type="button"
- onClick={() => handlePickScope(null)}
- >
- {t('settings.ghosts.projectBanner.backToGlobal')}
- </Button>
- </div>
+ <CatalogManagementNotice
+ title={t('settings.ghosts.projectBanner.title', { name: basename(scopeDir) })}
+ action={
+ <Button
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ compact
+ onClick={() => handlePickScope(null)}
+ >
+ {t('settings.ghosts.projectBanner.backToGlobal')}
+ </Button>
+ }
+ >
+ {t('settings.ghosts.projectBanner.desc', {
+ device: t('settings.ghosts.remote.thisComputer'),
+ })}
+ </CatalogManagementNotice>
) : null}
- <section className="plugin-motion-page-section mt-6 min-w-0">
- <div className="mb-4 flex items-baseline gap-2">
- <h2 className="text-20 font-medium text-[var(--text-primary)]">
- {t('settings.ghosts.page.installedSection')}
- </h2>
- <span className="text-13 tabular-nums text-[var(--text-tertiary)]">
- {searchedInstalledItems.length}
- </span>
- </div>
{legacyRecoveryStatus ? (
<LegacyGhostRecoveryNotice
@@ -1985,6 +1989,9 @@ export function GhostPluginPage({
/>
</div>
+ <p className="mb-3 text-12 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.installDestination', { device: t('settings.ghosts.remote.thisComputer') })}
+ </p>
{marketSnapshot?.unavailableReason ? (
<p className="mb-4 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-12 text-[var(--text-secondary)]">
{t(
@@ -2276,88 +2283,6 @@ export function MarketPluginCard({
);
}
-/** Plugin-specific creation and import actions rendered after the shared search. */
-function GhostPluginActions({
- onInstall,
- onCreateWithCindy,
- onAddMarketplace,
-}: {
- onInstall: () => void;
- onCreateWithCindy: () => void;
- onAddMarketplace: () => void;
-}) {
- const { t } = useTranslation();
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="primary"
- size="lg"
- type="button"
- aria-label={t('settings.ghosts.page.addPluginAria')}
- className="plugin-management-action-trigger group shrink-0 shadow-[var(--plugin-card-shadow)] data-[state=open]:[--button-face-bg:var(--surface-chip)]"
- >
- <Plus size={14} strokeWidth={1.8} aria-hidden="true" />
- <span className="plugin-management-action-label">
- {t('settings.ghosts.page.addPlugin')}
- </span>
- <ChevronDown
- size={13}
- strokeWidth={1.75}
- className="plugin-management-action-chevron transition-transform duration-150 group-data-[state=open]:rotate-180 motion-reduce:transition-none"
- aria-hidden="true"
- />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- sideOffset={8}
- className="w-max min-w-52 max-w-[calc(100vw-2rem)] p-1.5"
- >
- <DropdownMenuItem
- onSelect={onCreateWithCindy}
- className="gap-3 whitespace-nowrap"
- >
- <Sparkles
- size={16}
- strokeWidth={1.7}
- className="text-[var(--text-secondary)]"
- aria-hidden="true"
- />
- {t('settings.ghosts.page.createWithCindy')}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={onInstall}
- className="gap-3 whitespace-nowrap"
- >
- <Upload
- size={16}
- strokeWidth={1.7}
- className="text-[var(--text-secondary)]"
- aria-hidden="true"
- />
- {t('settings.ghosts.install')}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={onAddMarketplace}
- className="gap-3 whitespace-nowrap"
- >
- <Store
- size={16}
- strokeWidth={1.7}
- className="text-[var(--text-secondary)]"
- aria-hidden="true"
- />
- {t('settings.ghosts.market.sources.addMarketplace')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
-
/**
* 已安装插件卡片(设计定稿):
* - 整卡可点 = 进详情(与滑杆管理入口同目标);
@@ -2367,7 +2292,9 @@ function GhostPluginActions({
*/
export function GhostPluginCard({
item,
+ readOnly = false,
sourceLabel,
+ showLocalUnread = true,
marketItem,
author,
updateVersion,
@@ -2380,8 +2307,10 @@ export function GhostPluginCard({
onManage,
onIconLoadError,
}: {
- item: GhostPluginListItem;
+ item: Pick<GhostPluginListItem, 'id' | 'name' | 'description'> & Partial<GhostPluginListItem>;
+ readOnly?: boolean;
sourceLabel?: string;
+ showLocalUnread?: boolean;
marketItem?: PluginMarketItem | null;
author?: string | null;
/** 市场存在新版本时的目标版本;与 onUpdate 同时提供。 */
@@ -2399,10 +2328,15 @@ export function GhostPluginCard({
const { t } = useTranslation();
const metadataId = useId();
const enabled = effectiveEnabled ?? item.enabled;
- // 单卡未读点使用呼吸动效,未读摘要替换静态描述。
- const unread = useGhostUnread(item.id);
- const unreadSummary = useGhostUnreadSummary(item.id);
- const primary = ghostPrimaryAction(item);
+ // 远程列表不投影本机同名插件的未读状态。
+ const localUnread = useGhostUnread(item.id);
+ const localUnreadSummary = useGhostUnreadSummary(item.id);
+ const unread = showLocalUnread && localUnread;
+ const unreadSummary = showLocalUnread ? localUnreadSummary : undefined;
+ const primary = ghostPrimaryAction({
+ canUse: item.canUse ?? false,
+ tabPanel: item.tabPanel ?? false,
+ });
const handleCardKeyDown = (event: KeyboardEvent<HTMLElement>) => {
if (event.target !== event.currentTarget) return;
if (event.key !== 'Enter' && event.key !== ' ') return;
@@ -2410,8 +2344,14 @@ export function GhostPluginCard({
onManage();
};
let primaryControl: ReactNode;
- if (item.retirement) {
- primaryControl = <CardPillButton onClick={onManage} label={t('settings.ghosts.retirement.view')} />;
+ if (readOnly) {
+ primaryControl = (
+ <CardPillButton onClick={onManage} label={t('settings.ghosts.market.details')} />
+ );
+ } else if (item.retirement) {
+ primaryControl = (
+ <CardPillButton onClick={onManage} label={t('settings.ghosts.retirement.view')} />
+ );
} else if (!enabled) {
primaryControl = (
<CardPillButton onClick={onManage} label={t('settings.ghosts.page.manageAction')} />
@@ -2456,7 +2396,7 @@ export function GhostPluginCard({
'active:translate-y-0 active:scale-[0.992]',
'motion-reduce:transform-none motion-reduce:transition-none',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- !enabled && !item.retirement && 'opacity-60',
+ enabled === false && !item.retirement && 'opacity-60',
)}
>
<GhostPluginIcon
@@ -2470,9 +2410,16 @@ export function GhostPluginCard({
<span className="truncate text-15 font-medium text-[var(--text-primary)]">
{item.name}
</span>
- {item.retirement?.unread ? <AttentionDot tone="awaiting" size={6} className="mt-px" /> : unread ? <AttentionDot breathing size={6} className="mt-px" /> : null}
+ {item.retirement?.unread ? (
+ <AttentionDot tone="awaiting" size={6} className="mt-px" />
+ ) : unread ? (
+ <AttentionDot breathing size={6} className="mt-px" />
+ ) : null}
</span>
- <span id={metadataId} className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-11 text-[var(--text-tertiary)]">
+ <span
+ id={metadataId}
+ className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-11 text-[var(--text-tertiary)]"
+ >
{sourceLabel ? <span className="shrink-0">{sourceLabel}</span> : null}
{author ? (
<>
@@ -2481,6 +2428,16 @@ export function GhostPluginCard({
</>
) : null}
{marketItem ? <PluginSharedUsage detail={marketItem} variant="list" /> : null}
+ {readOnly && item.version ? <span>v{item.version}</span> : null}
+ {readOnly && enabled !== undefined ? (
+ <span>
+ {t(
+ enabled
+ ? 'settings.ghosts.detail.enabledLabel'
+ : 'settings.ghosts.detail.disabledLabel',
+ )}
+ </span>
+ ) : null}
{item.retirement ? (
<span> · {t('settings.ghosts.retirement.status')}</span>
) : item.oauthAuthorizationExpired ? (
@@ -2496,7 +2453,9 @@ export function GhostPluginCard({
{t('settings.ghosts.installConsent.updateNeedsConsent')}
</span>
) : null}
- {!enabled && !item.retirement ? ` · ${t('settings.ghosts.disabledTag')}` : ''}
+ {!readOnly && enabled === false && !item.retirement
+ ? ` · ${t('settings.ghosts.disabledTag')}`
+ : ''}
</span>
<span
className={cn(
@@ -2504,7 +2463,9 @@ export function GhostPluginCard({
unreadSummary ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]',
)}
>
- {item.retirement ? t('settings.ghosts.retirement.cardNotice') : unreadSummary || item.description || item.id}
+ {item.retirement
+ ? t('settings.ghosts.retirement.cardNotice')
+ : unreadSummary || item.description || item.id}
</span>
</span>
{/* 仅真实控件拦截冒泡,右列空白仍可进入详情。 */}
@@ -2530,15 +2491,17 @@ export function GhostPluginCard({
{t('settings.ghosts.page.updateTo', { version: updateVersion })}
</Button>
) : null}
- <button
- type="button"
- onClick={stopAnd(onManage)}
- aria-label={t('settings.ghosts.page.manageAria', { name: item.name })}
- title={t('settings.ghosts.page.manageAction')}
- className="grid size-7 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- >
- <SlidersHorizontal size={14} aria-hidden="true" />
- </button>
+ {!readOnly ? (
+ <button
+ type="button"
+ onClick={stopAnd(onManage)}
+ aria-label={t('settings.ghosts.page.manageAria', { name: item.name })}
+ title={t('settings.ghosts.page.manageAction')}
+ className="grid size-7 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <SlidersHorizontal size={14} aria-hidden="true" />
+ </button>
+ ) : null}
</span>
{primaryControl}
</span>
diff --git a/apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx b/apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx
new file mode 100644
index 0000000000..276e448243
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx
@@ -0,0 +1,143 @@
+import { useEffect, useState, useSyncExternalStore, type ReactNode } from 'react';
+import { Check, ChevronDown, Monitor } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
+import { revokedDevicesStore } from '@/features/device-link/revokedDevicesStore';
+import type { DeviceLinkDeviceView } from '../../../shared/deviceLinkIpc';
+
+export function eligiblePluginDevices(
+ devices: readonly DeviceLinkDeviceView[],
+ revoked: ReadonlySet<string>,
+) {
+ return devices.filter(
+ (d) =>
+ !d.isSelf &&
+ d.controlEnabled &&
+ d.remoteControlEnabled &&
+ !revoked.has(d.deviceId) &&
+ d.platform !== 'ios' &&
+ d.platform !== 'android',
+ );
+}
+/** Presence is independent of where the page-heading picker is mounted. */
+export function usePluginDeviceDirectory(selected: { deviceId: string; name: string } | null) {
+ const devices = useDeviceLinkDeviceList();
+ const revoked = useSyncExternalStore(
+ revokedDevicesStore.subscribe,
+ revokedDevicesStore.getSnapshot,
+ );
+ const [relayOnline, setRelayOnline] = useState(false);
+ useEffect(() => {
+ let disposed = false,
+ revision = 0;
+ const off = window.electronAPI.deviceLink.onStatusChanged((state) => {
+ revision++;
+ setRelayOnline(state.status === 'online');
+ });
+ const start = revision;
+ void window.electronAPI.deviceLink
+ .getState()
+ .then((state) => {
+ if (!disposed && revision === start) setRelayOnline(state.linkStatus === 'online');
+ })
+ .catch(() => {});
+ return () => {
+ disposed = true;
+ off();
+ };
+ }, []);
+ const candidates = eligiblePluginDevices(devices ?? [], revoked);
+ const target = candidates.find((d) => d.deviceId === selected?.deviceId);
+ const online = !!target?.online && relayOnline;
+ return { candidates, target, online: !selected || online, relayOnline };
+}
+
+export type CatalogDeviceControl = {
+ selected: { deviceId: string; name: string } | null;
+ onSelect(device: { deviceId: string; name: string } | null): void;
+ directory: ReturnType<typeof usePluginDeviceDirectory>;
+};
+
+/** One host menu owns its optional project submenu. Presence never rewrites the selection. */
+export function PluginDevicePicker({
+ selected,
+ onSelect,
+ directory: { candidates, target, online, relayOnline },
+ projectMenu,
+ projectLabel,
+}: CatalogDeviceControl & { projectMenu?: ReactNode; projectLabel?: string }) {
+ const { t } = useTranslation();
+ const computerName = selected
+ ? (target?.name ?? selected.name)
+ : t('settings.ghosts.remote.thisComputer');
+ const label = projectMenu
+ ? `${computerName} / ${projectLabel ?? t('settings.ghosts.scopePicker.globalScope')}`
+ : computerName;
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ size="lg"
+ compact
+ pressFeedback={false}
+ className="min-w-[200px] max-w-[280px] justify-start [&>svg]:shrink-0"
+ aria-label={t('settings.ghosts.remote.device')}
+ title={label}
+ >
+ <Monitor size={14} aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-left">{label}</span>
+ {selected && !online ? (
+ <span className="text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.offline')}
+ </span>
+ ) : null}
+ <ChevronDown size={13} aria-hidden="true" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="w-[var(--radix-dropdown-menu-trigger-width)] max-w-[calc(100vw-32px)]"
+ >
+ <DropdownMenuLabel>{t('settings.ghosts.scopePicker.computers')}</DropdownMenuLabel>
+ <DropdownMenuItem className="gap-2" onSelect={() => onSelect(null)}>
+ <Monitor size={14} />
+ <span className="flex-1">{t('settings.ghosts.remote.thisComputer')}</span>
+ {!selected ? <Check size={14} /> : null}
+ </DropdownMenuItem>
+ {candidates.map((device) => (
+ <DropdownMenuItem
+ key={device.deviceId}
+ className="gap-2"
+ title={device.name}
+ onSelect={() => onSelect({ deviceId: device.deviceId, name: device.name })}
+ >
+ <Monitor size={14} />
+ <span className="min-w-0 flex-1 truncate">{device.name}</span>
+ {!device.online || !relayOnline ? (
+ <span className="text-12 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.offline')}
+ </span>
+ ) : null}
+ {selected?.deviceId === device.deviceId ? <Check size={14} /> : null}
+ </DropdownMenuItem>
+ ))}
+ {projectMenu ? (
+ <>
+ <DropdownMenuSeparator />
+ {projectMenu}
+ </>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx b/apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx
index 234bed9900..88a249cb0e 100644
--- a/apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx
+++ b/apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx
@@ -1,21 +1,17 @@
/**
- * Shared list-page shell for the Plugin and Skill product surfaces.
- *
- * Inputs: active tab, shared search state, optional labels with tab-derived defaults, and actions.
- * Outputs: one width, focus-order-aligned adaptive toolbar, scrolling frame, and transitions.
- * Settings embeds the same catalog and can intercept Plugins / Skills tab
- * clicks via `onSelectTab` so the switcher stays inside Settings.
- * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ * Shared Plugin / Skill catalog shell. Settings intercepts tab navigation via
+ * `onSelectTab` to keep the embedded catalog inside Settings.
*/
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import { Search, X } from 'lucide-react';
+import { Info, Search, TriangleAlert, X } from 'lucide-react';
import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { SegmentedControl } from '@/components/ui/segmented-control';
import { cn } from '@/lib/utils';
+import { PluginDevicePicker, type CatalogDeviceControl } from './PluginDevicePicker';
import './plugin-motion.css';
interface PluginManagementLayoutProps {
@@ -269,3 +265,111 @@ export function PluginManagementPage({ children, className }: PluginManagementPa
</div>
);
}
+
+export function CatalogTargetControls({
+ computer,
+ project,
+ projectLabel,
+}: {
+ computer?: CatalogDeviceControl;
+ project?: ReactNode;
+ projectLabel?: string;
+}) {
+ const { t } = useTranslation();
+ if (!computer && !project) return null;
+ return (
+ <div
+ role="group"
+ aria-label={t('settings.ghosts.scopePicker.management')}
+ data-catalog-region="target"
+ className="min-w-0 max-w-full"
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ <PluginDevicePicker
+ {...(computer ?? {
+ selected: null,
+ onSelect: () => {},
+ directory: { candidates: [], target: undefined, online: true, relayOnline: false },
+ })}
+ projectMenu={project}
+ projectLabel={projectLabel}
+ />
+ </div>
+ );
+}
+
+export function InstalledCatalogHeader({
+ title,
+ count,
+ controls,
+}: {
+ title: string;
+ count?: number;
+ controls?: ReactNode;
+}) {
+ return (
+ <header
+ className="mb-4 flex flex-wrap items-center justify-between gap-3"
+ data-catalog-region="installed"
+ >
+ <div className="flex items-baseline gap-2">
+ <h2 className="text-20 font-medium leading-6 text-[var(--text-primary)]">{title}</h2>
+ {count !== undefined ? (
+ <span className="text-13 tabular-nums text-[var(--text-tertiary)]">{count}</span>
+ ) : null}
+ </div>
+ {controls ? (
+ <div
+ className="flex min-w-0 max-w-full flex-wrap items-center gap-2"
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ {controls}
+ </div>
+ ) : null}
+ </header>
+ );
+}
+
+export function CatalogManagementNotice({
+ title,
+ children,
+ action,
+ warning = false,
+ className,
+}: {
+ title: string;
+ children: ReactNode;
+ action?: ReactNode;
+ warning?: boolean;
+ className?: string;
+}) {
+ const Icon = warning ? TriangleAlert : Info;
+ return (
+ <div
+ role="status"
+ data-catalog-region="notice"
+ className={cn(
+ 'mb-4 flex flex-wrap items-start justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3',
+ className,
+ )}
+ >
+ <div className="flex min-w-0 flex-1 basis-60 items-start gap-2.5">
+ <Icon
+ size={16}
+ aria-hidden="true"
+ className={cn(
+ 'mt-0.5 shrink-0',
+ warning ? 'text-[var(--warning-fg)]' : 'text-[var(--text-secondary)]',
+ )}
+ />
+ <div className="min-w-0 flex-1 [overflow-wrap:anywhere]">
+ <p className="text-13 font-medium leading-5 text-[var(--text-primary)]">{title}</p>
+ <div className="mt-0.5 text-13 leading-5 text-[var(--text-secondary)]">{children}</div>
+ </div>
+ </div>
+ {action ? (
+ <div className="ml-auto flex shrink-0 flex-wrap items-center gap-2">{action}</div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx b/apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx
index 79a8e9ca0d..9b85ca95c9 100644
--- a/apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx
+++ b/apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx
@@ -1,13 +1,14 @@
import { useEffect, useMemo, useSyncExternalStore } from 'react';
-import { Check, ChevronDown, Folder, FolderOpen, Globe } from 'lucide-react';
+import { Check, ChevronRight, FolderOpen, Globe } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuLabel,
DropdownMenuSeparator,
- DropdownMenuTrigger,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
} from '@/components/ui/dropdown-menu';
import { cn, basename } from '@/lib/utils';
import { recentWorkdirsStore, type RecentWorkdirEntry } from '@/lib/recentWorkdirsStore';
@@ -20,16 +21,27 @@ export function usePluginRecentWorkdirs(): RecentWorkdirEntry[] {
return snapshot ?? [];
}
-export function PluginScopePicker({
+export function PluginProjectMenu({
scopeDir,
activeSessionWorkingDir,
recentWorkdirs,
onPick,
+ projectOptions,
+ computerName,
+ disabled = false,
+ unavailable = false,
+ onBrowse,
}: {
scopeDir: string | null;
activeSessionWorkingDir: string | undefined;
recentWorkdirs: RecentWorkdirEntry[];
onPick: (dir: string | null) => void;
+ /** When supplied, identities and display paths belong to the selected Host. */
+ projectOptions?: Array<{ id: string; name: string; path?: string }>;
+ onBrowse?: () => void;
+ computerName?: string;
+ disabled?: boolean;
+ unavailable?: boolean;
}) {
const { t } = useTranslation();
const candidates = useMemo(() => {
@@ -45,91 +57,112 @@ export function PluginScopePicker({
for (const entry of recentWorkdirs) push(entry.path);
return out;
}, [activeSessionWorkingDir, recentWorkdirs, scopeDir]);
- const triggerLabel = scopeDir ? basename(scopeDir) : t('settings.ghosts.scopePicker.global');
+ const triggerLabel = scopeDir
+ ? (projectOptions?.find((project) => project.id === scopeDir)?.name ?? basename(scopeDir))
+ : t('settings.ghosts.scopePicker.globalScope');
+ const projectsLabel = t('settings.ghosts.scopePicker.projectsForComputer', {
+ device: computerName ?? t('settings.ghosts.remote.thisComputer'),
+ });
+ const projects = projectOptions
+ ? [...projectOptions.filter((project) => project.id === scopeDir),
+ ...projectOptions.filter((project) => project.id !== scopeDir)]
+ : candidates.map((dir) => ({ id: dir, name: basename(dir), path: dir }));
return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- aria-label={t('settings.ghosts.scopePicker.ariaLabel')}
- title={scopeDir ?? undefined}
- className={cn(
- 'flex h-9 max-w-[220px] shrink-0 items-center gap-1.5 rounded-full px-4',
- 'bg-[var(--surface-elevated-soft)] text-13 font-medium text-[var(--text-primary)]',
- 'hover:bg-[var(--surface-chip)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'transition-colors',
- )}
- >
- {scopeDir ? (
- <Folder size={14} className="shrink-0" />
- ) : (
- <Globe size={14} className="shrink-0" />
- )}
- <span className="truncate">{triggerLabel}</span>
- <ChevronDown size={13} className="shrink-0 opacity-60" />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-max min-w-0 max-w-[calc(100vw-32px)]">
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger
+ aria-label={t('settings.ghosts.scopePicker.ariaLabel')}
+ title={
+ unavailable
+ ? t('settings.ghosts.remote.projectsUnsupported')
+ : projectOptions
+ ? (projects.find((project) => project.id === scopeDir)?.path ?? triggerLabel)
+ : (scopeDir ?? undefined)
+ }
+ disabled={disabled}
+ className="gap-2"
+ >
+ <span className="shrink-0">{t('settings.ghosts.scopePicker.projectScope')}</span>
+ <span className="min-w-0 flex-1 truncate text-12 font-normal text-[var(--cmd-palette-item-meta)]">
+ {triggerLabel}
+ </span>
+ <ChevronRight size={14} className="shrink-0" aria-hidden="true" />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-80 min-w-0 max-w-[calc(100vw-32px)]">
+ <DropdownMenuLabel className="truncate" title={projectsLabel}>
+ {projectsLabel}
+ </DropdownMenuLabel>
<DropdownMenuItem
- onClick={() => onPick(null)}
- className="grid w-full cursor-pointer grid-cols-[14px_max-content] items-center gap-x-2.5 pr-4"
+ onSelect={() => onPick(null)}
+ className="grid w-full cursor-pointer grid-cols-[14px_minmax(0,1fr)] items-center gap-x-2.5"
>
<Check
size={14}
className={cn('shrink-0', scopeDir === null ? 'opacity-100' : 'opacity-0')}
/>
- <div className="flex items-center gap-1.5">
+ <div className="flex min-w-0 items-center gap-1.5">
<Globe size={13} className="shrink-0 text-[var(--text-secondary)]" />
- <span className="whitespace-nowrap">
- {t('settings.ghosts.scopePicker.global')}
- </span>
+ <span className="truncate">{t('settings.ghosts.scopePicker.global')}</span>
</div>
</DropdownMenuItem>
- <DropdownMenuSeparator />
- <div className="max-h-[min(320px,45vh)] overflow-y-auto">
- {candidates.map((dir) => {
- const isCurrent = dir === scopeDir;
- return (
- <DropdownMenuItem
- key={dir}
- onClick={() => onPick(dir)}
- // minmax(0,max-content):菜单仍按内容自适应宽,但路径超过菜单
- // max-w 上限时列可收缩、由 truncate 出省略号,不再水平溢出。
- className="grid w-full cursor-pointer grid-cols-[14px_minmax(0,max-content)] items-center gap-x-2.5 pr-4"
- >
- <Check
- size={14}
- className={cn('shrink-0', isCurrent ? 'opacity-100' : 'opacity-0')}
- />
- <div className="flex min-w-0 flex-col gap-0.5">
- <span className="truncate">{basename(dir)}</span>
- <span title={dir} className="truncate text-12 leading-[1.33] text-[var(--cmd-palette-item-meta)]">
- {dir}
- </span>
- </div>
- </DropdownMenuItem>
- );
- })}
- </div>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => {
- void window.electronAPI.showOpenDirectoryDialog().then((result) => {
- if (!result.canceled && result.path) onPick(result.path);
- });
- }}
- className="grid w-full cursor-pointer grid-cols-[14px_max-content] items-center gap-x-2.5 pr-4"
- >
- <span aria-hidden className="w-[14px]" />
- <div className="flex items-center gap-1.5">
- <FolderOpen size={13} className="shrink-0 text-[var(--text-secondary)]" />
- <span className="whitespace-nowrap">
- {t('settings.ghosts.scopePicker.browse')}
- </span>
+ {projects.length > 0 || projectOptions !== undefined ? <DropdownMenuSeparator /> : null}
+ {projects.length > 0 ? (
+ <div className="max-h-[min(320px,45vh)] overflow-y-auto">
+ {projects.map(({ id: dir, name, path }) => {
+ const isCurrent = dir === scopeDir;
+ return (
+ <DropdownMenuItem
+ key={dir}
+ onSelect={() => onPick(dir)}
+ title={path ?? name}
+ className="grid w-full cursor-pointer grid-cols-[14px_minmax(0,1fr)] items-center gap-x-2.5 pr-4"
+ >
+ <Check
+ size={14}
+ className={cn('shrink-0', isCurrent ? 'opacity-100' : 'opacity-0')}
+ />
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <span className="truncate">{name}</span>
+ {path ? (
+ <span
+ title={path}
+ className="truncate text-12 leading-[1.33] text-[var(--cmd-palette-item-meta)]"
+ >
+ {path}
+ </span>
+ ) : null}
+ </div>
+ </DropdownMenuItem>
+ );
+ })}
</div>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ ) : null}
+ {projectOptions?.length === 0 ? (
+ <p className="px-3 py-2 text-12 leading-4 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.noProjects')}
+ </p>
+ ) : null}
+ {!projectOptions || onBrowse ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ if (onBrowse) { onBrowse(); return; }
+ void window.electronAPI.showOpenDirectoryDialog().then((result) => {
+ if (!result.canceled && result.path) onPick(result.path);
+ });
+ }}
+ className="grid w-full cursor-pointer grid-cols-[14px_minmax(0,1fr)] items-center gap-x-2.5"
+ >
+ <span aria-hidden className="w-[14px]" />
+ <div className="flex min-w-0 items-center gap-1.5">
+ <FolderOpen size={13} className="shrink-0 text-[var(--text-secondary)]" />
+ <span className="truncate">{t('settings.ghosts.scopePicker.browse')}</span>
+ </div>
+ </DropdownMenuItem>
+ </>
+ ) : null}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
);
}
diff --git a/apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx b/apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx
new file mode 100644
index 0000000000..343b564396
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx
@@ -0,0 +1,251 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Switch } from '@/components/ui/switch';
+import { PluginTaskPrefs } from '@/cindy-brain/PluginTaskPrefs';
+import { GhostSettingsWebview } from '@/cindy-brain/GhostSettingsWebview';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
+import {
+ pluginHasModelPreferences,
+ type RemotePluginPreferenceSnapshot,
+} from '../../../shared/pluginPreferences';
+import { DetailSectionHeader } from './GhostPluginDetailView';
+import {
+ invokePluginManagement,
+ parseRemotePluginPreferences,
+} from './remotePluginManagementClient';
+
+export function RemotePluginConfiguration({
+ ghost,
+ device,
+ online,
+ active,
+ busy,
+ hostPreferences,
+ settingsPage,
+}: {
+ ghost: InstalledGhost;
+ device: { deviceId: string; name: string };
+ online: boolean;
+ active: boolean;
+ busy: boolean;
+ hostPreferences: boolean;
+ settingsPage: boolean;
+}) {
+ const { t } = useTranslation();
+ const [read, setRead] = useState<{
+ ghost: InstalledGhost;
+ preferences?: RemotePluginPreferenceSnapshot;
+ failed: boolean;
+ } | null>(null);
+ const [attempt, setAttempt] = useState(0),
+ [saving, setSaving] = useState(false);
+ const owner = useRef(getDataOwnerGeneration()).current;
+ const live = useRef(false),
+ epoch = useRef(0),
+ saveLock = useRef(false);
+ const scope = useRef({ ghost, online, active, deviceId: device.deviceId });
+ scope.current = { ghost, online, active, deviceId: device.deviceId };
+ const id = installedGhostStoragePart(ghost);
+ const current = useCallback(
+ (captured: InstalledGhost) =>
+ live.current &&
+ scope.current.deviceId === device.deviceId &&
+ scope.current.ghost === captured &&
+ scope.current.online &&
+ scope.current.active &&
+ isDataOwnerGenerationCurrent(owner),
+ [owner, device.deviceId],
+ );
+ const load = useCallback(async () => {
+ const revision = ++epoch.current;
+ if (!current(ghost) || !ghost.enabled) return;
+ try {
+ const preferences = hostPreferences
+ ? parseRemotePluginPreferences(
+ await invokePluginManagement(
+ device.deviceId,
+ 'preferences',
+ { expectedInstalledApproval: ghostInstallApprovalToken(ghost.approval) },
+ id,
+ ),
+ )
+ : undefined;
+ if (revision === epoch.current && current(ghost))
+ setRead({ ghost, preferences, failed: false });
+ } catch {
+ if (revision === epoch.current && current(ghost)) setRead({ ghost, failed: true });
+ }
+ }, [current, ghost, device.deviceId, id, hostPreferences]);
+ useEffect(() => {
+ live.current = true;
+ void load();
+ return () => {
+ live.current = false;
+ ++epoch.current;
+ };
+ }, [load, attempt, online, active]);
+ const data = read?.ghost === ghost ? read : null;
+ const preferences = data?.preferences;
+ const disabled = !online || !active || busy || saving || !data || data.failed;
+ const save = async (patch: Record<string, unknown>) => {
+ if (disabled || saveLock.current || !preferences || !current(ghost))
+ throw new Error('PLUGIN_SETTINGS_UNAVAILABLE');
+ saveLock.current = true;
+ setSaving(true);
+ try {
+ const value = parseRemotePluginPreferences(
+ await invokePluginManagement(
+ device.deviceId,
+ 'preferences-set',
+ {
+ ...patch,
+ expectedInstalledApproval: ghostInstallApprovalToken(ghost.approval),
+ expectedRevision: preferences.revision,
+ },
+ id,
+ ),
+ );
+ if (!current(ghost)) throw new Error('PLUGIN_SETTINGS_CLOSED');
+ ++epoch.current;
+ setRead({ ...data, ghost, preferences: value, failed: false });
+ return value;
+ } catch (error) {
+ if (current(ghost)) {
+ setRead((previous) =>
+ previous?.ghost === ghost ? { ...previous, failed: true } : previous,
+ );
+ // Only read the target after an uncertain write; never replay it.
+ await load();
+ }
+ throw error;
+ } finally {
+ saveLock.current = false;
+ if (live.current) setSaving(false);
+ }
+ };
+ const hasTasks = Boolean(
+ ghost.manifest.workspace || ghost.manifest.agent?.tasks || ghost.manifest.agent?.errand,
+ );
+ const hasNative = pluginHasModelPreferences(ghost.manifest) || ghost.manifest.mainView?.html;
+ if (!ghost.enabled)
+ return (
+ <p className="mt-10 text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.enableBeforeConfigure')}
+ </p>
+ );
+ if (!hasNative && !ghost.manifest.settingsHtml) return null;
+ return (
+ <section className="mt-10" aria-labelledby="ghost-configuration-title">
+ <DetailSectionHeader
+ id="ghost-configuration-title"
+ title={t('settings.ghosts.detail.configurationTitle')}
+ />
+ <div className="mt-5 max-w-[760px] space-y-3">
+ <p className="text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.targetOnly', { device: device.name })}
+ </p>
+ {!data && online && (
+ <p role="status" className="text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.configurationLoading')}
+ </p>
+ )}
+ {data?.failed && (
+ <div className="flex flex-wrap items-center gap-3">
+ <p role="status" className="text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.configurationReadFailed')}
+ </p>
+ <Button
+ size="sm"
+ variant="secondary"
+ disabled={!online || saving}
+ onClick={() => setAttempt((value) => value + 1)}
+ >
+ {t('settings.ghosts.remote.refreshConfiguration')}
+ </Button>
+ </div>
+ )}
+ {preferences?.sidebarVisible !== undefined && (
+ <div className="flex items-center justify-between gap-3 py-3">
+ <div className="min-w-0">
+ <p className="text-14 font-medium leading-[1.571] text-[var(--text-primary)]">
+ {t('settings.ghosts.detail.sidebarEntryTitle')}
+ </p>
+ <p className="text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.detail.sidebarEntryDescription', {
+ title: ghost.manifest.mainView?.title ?? ghost.manifest.name,
+ })}
+ </p>
+ </div>
+ <Switch
+ disabled={disabled}
+ checked={preferences.sidebarVisible}
+ aria-label={t('settings.ghosts.detail.showInSidebar')}
+ onCheckedChange={(visible) => {
+ void save({ kind: 'sidebar', visible }).catch(() => {});
+ }}
+ />
+ </div>
+ )}
+ {preferences?.tasks && (
+ <PluginTaskPrefs
+ ghostId={id}
+ appearance="plugin"
+ disabled={disabled}
+ showTaskRows={hasTasks}
+ legacyDefault={
+ ghost.manifest.agent?.errand === true &&
+ !ghost.manifest.agent?.tasks &&
+ !ghost.manifest.workspace
+ }
+ remote={{
+ auxiliaryModelLabel: preferences.auxiliaryModelLabel ?? null,
+ deviceId: device.deviceId,
+ value: preferences.tasks,
+ onChange: async (config) => {
+ const model =
+ config.agentKind && config.providerId && config.model
+ ? {
+ agentKind: config.agentKind,
+ providerId: config.providerId,
+ model: config.model,
+ ...(config.effort ? { effort: config.effort } : {}),
+ fastMode: config.fastMode ?? false,
+ }
+ : null;
+ const next = await save({
+ kind: 'tasks',
+ patch: { model, permissionMode: config.permissionMode ?? null },
+ });
+ return next.tasks!;
+ },
+ }}
+ />
+ )}
+ {hasNative && !hostPreferences && (
+ <p className="text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.hostPreferencesUnavailable', { device: device.name })}
+ </p>
+ )}
+ {ghost.manifest.settingsHtml && settingsPage && online && active && (
+ <GhostSettingsWebview
+ ghost={ghost}
+ title={t('settings.ghosts.detail.settingsTitle', { name: ghost.manifest.name })}
+ appearance="plugin"
+ remoteDeviceId={device.deviceId}
+ />
+ )}
+ {ghost.manifest.settingsHtml && !settingsPage && (
+ <p className="text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.settingsPageUnavailable', { device: device.name })}
+ </p>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx b/apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx
new file mode 100644
index 0000000000..0ad3e2387e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx
@@ -0,0 +1,906 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ REMOTE_RESOURCE_CHANGED_CHANNEL,
+ parseRemoteResourceChangedPayload,
+} from '@cindy/device-link';
+import { Button } from '@/components/ui/button';
+import { AddRemoteProjectDialog } from '@/components/new-chat/AddRemoteProjectDialog';
+import { SegmentedControl } from '@/components/ui/segmented-control';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
+import { extractIpcError } from '@/utils/ipcError';
+import { toast } from '@/lib/toast';
+import {
+ GhostInstallConsentContent,
+ ghostInstallConsentSourceLabel,
+} from '@/cindy-brain/GhostInstallConsentHost';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
+
+import type {
+ PluginManagementReceipt,
+ PluginManagementSnapshot,
+ PluginManagementProject,
+ PluginManagementProjectState,
+} from '../../../shared/pluginManagement';
+import type { PluginMarketDetail, PluginMarketItem } from '../../../shared/pluginMarket';
+import { GhostPluginCard, MarketPluginCard } from './GhostPluginPage';
+import { GhostPluginActions } from './GhostPluginActions';
+import type { CatalogDeviceControl } from './useCatalogDevice';
+import { GhostPluginDetailView } from './GhostPluginDetailView';
+import { RemotePluginConfiguration } from './RemotePluginConfiguration';
+import { RemotePluginReadOnlyDetail } from './RemotePluginReadOnlyDetail';
+import { MarketPluginDetailView } from './MarketPluginDetailView';
+import {
+ PluginManagementLayout,
+ InstalledCatalogHeader,
+ CatalogTargetControls,
+ CatalogManagementNotice,
+ PluginManagementPage,
+ PLUGIN_INSTALLED_CARD_GRID_CLASS,
+ PLUGIN_MANAGEMENT_CARD_GRID_CLASS,
+} from './PluginManagementLayout';
+import { PluginProjectMenu } from './PluginScopePicker';
+import { toGhostPluginDetail, toGhostPluginListItem } from './lib/ghostPluginViewModel';
+import {
+ marketItemMatchesInstalledGhost,
+ pluginPresentationOrigin,
+} from './lib/pluginMarketPresentation';
+import {
+ hasPluginManagement,
+ invokePluginManagement,
+ parsePluginManagementSnapshot,
+ parsePluginManagementProjectState,
+ parsePluginManagementProject,
+ parsePluginManagementDetail,
+ parsePluginManagementReceipt,
+ readLegacyManagedPlugins,
+ readLegacyManagedPlugin,
+ type LegacyManagedPlugin,
+ type LegacyManagedPluginDetail,
+} from './remotePluginManagementClient';
+
+/** Every async closure belongs to this mounted owner + selected computer. Never uses local Ghost IPC. */
+export function RemotePluginPage({
+ device,
+ online,
+ active = true,
+ embedded,
+ deviceControl,
+ onSelectCatalogTab,
+}: {
+ device: { deviceId: string; name: string };
+ online: boolean;
+ active?: boolean;
+ embedded?: boolean;
+ deviceControl?: CatalogDeviceControl;
+ onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void;
+}) {
+ const { t, i18n } = useTranslation();
+ const { confirm } = useConfirmDialog();
+ const [snapshot, setSnapshot] = useState<PluginManagementSnapshot | null>(null);
+ const [project, setProject] = useState<PluginManagementProject | null>(null);
+ const projectRef = useRef(project);
+ projectRef.current = project;
+ const [projectState, setProjectState] = useState<PluginManagementProjectState | null>(null);
+ const [projectReadStatus, setProjectReadStatus] = useState<'loading' | 'failed' | null>(null);
+ const projectReadRevision = useRef(0);
+ const [projectPickerOpen, setProjectPickerOpen] = useState(false);
+ const projectPickerRevision = useRef(0);
+ const projectPickerCurrent = useRef(false);
+ projectPickerCurrent.current = projectPickerOpen && active && online;
+ const [selected, setSelected] = useState<string | null>(null);
+ const ghost = snapshot?.ghosts.find((g) => installedGhostStoragePart(g) === selected);
+ const [marketDetail, setMarketDetail] = useState<PluginMarketDetail | null>(null);
+ const [query, setQuery] = useState('');
+ const [originFilter, setOriginFilter] = useState('all');
+ const [status, setStatus] = useState<
+ 'readFailed' | 'unknown' | 'changed' | 'actionFailed' | null
+ >(null);
+ const [unsupported, setUnsupported] = useState(false);
+ const [legacy, setLegacy] = useState<LegacyManagedPlugin[] | null>(null);
+ const [legacySelected, setLegacySelected] = useState<LegacyManagedPlugin | null>(null);
+ const [legacyDetail, setLegacyDetail] = useState<LegacyManagedPluginDetail | null>(null);
+ const [legacyDetailStatus, setLegacyDetailStatus] = useState<'loading' | 'failed' | null>(null);
+ const [receipt, setReceipt] = useState<PluginManagementReceipt | null>(null);
+ const scope = useRef({ owner: getDataOwnerGeneration(), alive: true, online });
+ scope.current.online = online;
+ const readRevision = useRef(0),
+ detailRevision = useRef(0);
+ const operation = useRef<string | null>(null),
+ preparing = useRef(false);
+ const [preparingUi, setPreparingUi] = useState(false);
+ const dialog = useRef<AbortController | null>(null);
+ const current = useCallback(
+ () => scope.current.alive && isDataOwnerGenerationCurrent(scope.current.owner),
+ [],
+ );
+ const writable = useCallback(() => current() && scope.current.online, [current]);
+ const invoke = useCallback(
+ (action: string, input?: Record<string, unknown>, instance?: string) =>
+ invokePluginManagement(device.deviceId, action, input, instance),
+ [device.deviceId],
+ );
+ const refresh = useCallback(async () => {
+ const revision = ++readRevision.current;
+ if (!writable()) return;
+ try {
+ const supported = await hasPluginManagement(device.deviceId);
+ if (!writable() || revision !== readRevision.current) return;
+ setUnsupported(!supported);
+ if (!supported) {
+ const items = await readLegacyManagedPlugins(device.deviceId, i18n.language);
+ if (writable() && revision === readRevision.current) {
+ setLegacy(items);
+ setLegacySelected((previous) =>
+ previous && items.some((item) => item.id === previous.id) ? previous : null,
+ );
+ setStatus(null);
+ }
+ return;
+ }
+ const next = parsePluginManagementSnapshot(await invoke('snapshot'));
+ if (writable() && revision === readRevision.current) {
+ setSnapshot(next);
+ setLegacySelected(null);
+ setLegacyDetail(null);
+ setStatus(null);
+ }
+ } catch {
+ if (writable() && revision === readRevision.current) setStatus('readFailed');
+ }
+ }, [device.deviceId, i18n.language, invoke, writable]);
+ const loadLegacyDetail = useCallback(
+ async (plugin: LegacyManagedPlugin) => {
+ const revision = ++detailRevision.current;
+ if (!writable()) return;
+ setLegacyDetailStatus('loading');
+ try {
+ const detail = await readLegacyManagedPlugin(device.deviceId, plugin.id, i18n.language);
+ if (writable() && revision === detailRevision.current) {
+ setLegacyDetail(detail);
+ setLegacyDetailStatus(null);
+ }
+ } catch {
+ if (writable() && revision === detailRevision.current) setLegacyDetailStatus('failed');
+ }
+ },
+ [device.deviceId, i18n.language, writable],
+ );
+ useEffect(() => {
+ if (legacySelected && online && active) void loadLegacyDetail(legacySelected);
+ return () => {
+ ++detailRevision.current;
+ };
+ }, [legacySelected, legacy, online, active, loadLegacyDetail]);
+ const refreshProject = useCallback(async () => {
+ const id = projectRef.current?.id;
+ const revision = ++projectReadRevision.current;
+ if (!id || !writable()) return;
+ setProjectReadStatus('loading');
+ try {
+ const next = parsePluginManagementProjectState(
+ await invoke('project-state', { projectId: id }),
+ id,
+ );
+ if (writable() && revision === projectReadRevision.current && projectRef.current?.id === id) {
+ setProjectState(next);
+ setProjectReadStatus(null);
+ }
+ } catch {
+ if (writable() && revision === projectReadRevision.current && projectRef.current?.id === id)
+ setProjectReadStatus('failed');
+ }
+ }, [invoke, writable]);
+ useEffect(() => {
+ if (online && active && project?.id) void refreshProject();
+ }, [online, active, project?.id, snapshot, refreshProject]);
+ useEffect(() => {
+ scope.current.alive = true;
+ return () => {
+ scope.current.alive = false;
+ ++projectPickerRevision.current;
+ dialog.current?.abort();
+ // Cancel only this page's pending request at the original Host, never another target.
+ if (operation.current && isDataOwnerGenerationCurrent(scope.current.owner))
+ void invoke('cancel', { operationId: operation.current }).catch(() => {});
+ };
+ }, [invoke]);
+ useEffect(() => {
+ if (!online || !active) {
+ ++projectPickerRevision.current;
+ setProjectPickerOpen(false);
+ }
+ }, [online, active]);
+ useEffect(() => {
+ if (!online) {
+ ++readRevision.current;
+ ++detailRevision.current;
+ ++projectReadRevision.current;
+ dialog.current?.abort();
+ } else if (active) void refresh();
+ }, [online, active, refresh]);
+ useEffect(
+ () =>
+ window.electronAPI.deviceLink.onRemotePush((push, stamp) => {
+ if (
+ active &&
+ push.deviceId === device.deviceId &&
+ push.channel === REMOTE_RESOURCE_CHANGED_CHANNEL &&
+ parseRemoteResourceChangedPayload(push.payload)?.collectionId === 'plugins' &&
+ isDeviceLinkRemotePushCurrent(push, stamp) &&
+ writable()
+ )
+ void refresh();
+ }),
+ [active, device.deviceId, refresh, writable],
+ );
+ const acceptReceipt = useCallback(
+ async (next: PluginManagementReceipt) => {
+ if (!writable() || next.operationId !== operation.current) return;
+ setReceipt(next);
+ if (['succeeded', 'cancelled', 'failed'].includes(next.phase)) {
+ operation.current = null;
+ setStatus(null);
+ const message = t('settings.ghosts.remote.' + (
+ next.phase === 'succeeded' ? 'success' : next.phase === 'cancelled' ? 'cancelled' :
+ next.errorCode === 'GHOST_ASLEEP' ? 'enableBeforeConfigure' : 'actionFailed'
+ ));
+ if (next.phase === 'succeeded') toast.success(message);
+ else if (next.phase === 'cancelled') toast.info(message);
+ else toast.error(message);
+ if (next.phase === 'succeeded' || next.errorCode === 'GHOST_ASLEEP') void refresh();
+ return;
+ }
+ if (next.phase === 'confirmation' && next.consent && !dialog.current) {
+ const abort = new AbortController();
+ dialog.current = abort;
+ try {
+ const consent = next.consent;
+ const confirmed = await confirm(
+ {
+ title: t('settings.ghosts.remote.confirmOn', {
+ device: device.name,
+ name: consent.facts.name,
+ }),
+ description: `${device.name} · ${consent.facts.kind === 'install' ? t('settings.ghosts.installConsent.installMeta', { version: consent.facts.version, source: ghostInstallConsentSourceLabel(t, consent) }) : t('settings.ghosts.installConsent.updateMeta', { from: consent.facts.previousVersion, to: consent.facts.version, source: ghostInstallConsentSourceLabel(t, consent) })}`,
+ content: <GhostInstallConsentContent facts={consent.facts} />,
+ confirmText: t(
+ consent.facts.kind === 'install'
+ ? 'settings.ghosts.installConsent.confirmInstall'
+ : 'settings.ghosts.installConsent.confirmUpdate',
+ ),
+ cancelText: t('settings.ghosts.installConsent.cancel'),
+ maxWidth: 460,
+ contentSelectable: true,
+ },
+ abort.signal,
+ );
+ if (writable() && !abort.signal.aborted && operation.current === next.operationId) {
+ await invoke('answer', {
+ operationId: next.operationId,
+ requestId: consent.requestId,
+ confirmed,
+ });
+ }
+ } catch {
+ if (writable()) setStatus('unknown');
+ } finally {
+ if (dialog.current === abort) dialog.current = null;
+ }
+ }
+ },
+ [confirm, device.name, invoke, refresh, t, writable],
+ );
+ const poll = useCallback(async () => {
+ const id = operation.current;
+ if (!id || !writable()) return;
+ try {
+ await acceptReceipt(
+ parsePluginManagementReceipt(await invoke('operation', { operationId: id }), id),
+ );
+ } catch {
+ if (writable() && id === operation.current) setStatus('unknown');
+ }
+ }, [acceptReceipt, invoke, writable]);
+ useEffect(() => {
+ if (!online || !receipt || !operation.current) return;
+ // A failure leaves the receipt id intact. Reconnect/retry only reads this id.
+ let alive = true,
+ timer: ReturnType<typeof setTimeout>;
+ const tick = async () => {
+ await poll();
+ if (alive && operation.current) timer = setTimeout(tick, 1200);
+ };
+ timer = setTimeout(tick, 600);
+ return () => {
+ alive = false;
+ clearTimeout(timer);
+ };
+ }, [online, poll, receipt?.operationId]);
+ useEffect(() => {
+ if (!status || !active || !current()) return;
+ const message = t('settings.ghosts.remote.' + status);
+ const options = { action: {
+ label: t('settings.ghosts.remote.refresh'),
+ onClick: () => { if (writable()) { if (operation.current) void poll(); else void refresh(); } },
+ } };
+ const id = status === 'unknown' ? toast.warning(message, options) : toast.error(message, options);
+ return () => toast.dismiss(id);
+ }, [status, active, current, writable, poll, refresh, t]);
+ const begin = useCallback(
+ async (
+ kind: string,
+ ghost?: InstalledGhost,
+ item?: PluginMarketDetail,
+ attachment?: string,
+ ) => {
+ if (!writable() || operation.current || unsupported) return;
+ const scopedToggle = !!project && ['enable', 'disable'].includes(kind);
+ if (
+ scopedToggle &&
+ (!projectState ||
+ projectState.projectId !== project.id ||
+ projectReadStatus ||
+ (kind === 'enable' && !ghost?.enabled))
+ )
+ return;
+ const id = crypto.randomUUID();
+ operation.current = id;
+ setReceipt({ operationId: id, phase: 'running' });
+ setStatus(null);
+ try {
+ const input = {
+ operationId: id,
+ kind,
+ ...(ghost
+ ? { expectedInstalledApproval: ghostInstallApprovalToken(ghost.approval) }
+ : {}),
+ ...(item
+ ? {
+ pluginId: item.pluginId,
+ expectedReleaseId: item.releaseId,
+ expectedManifest: item.manifest,
+ }
+ : {}),
+ ...(attachment ? { attachment } : {}),
+ ...(scopedToggle
+ ? { projectId: project.id, expectedProjectRevision: projectState!.revision }
+ : {}),
+ };
+ await acceptReceipt(
+ parsePluginManagementReceipt(
+ await invoke('begin', input, ghost ? installedGhostStoragePart(ghost) : undefined),
+ id,
+ ),
+ );
+ } catch (error) {
+ if (current() && id === operation.current) {
+ const code = extractIpcError(error)?.code;
+ if (
+ [
+ 'INVALID_PARAMS',
+ 'NOT_FOUND',
+ 'PRECONDITION_FAILED',
+ 'UNSUPPORTED_CAPABILITY',
+ 'PERMISSION_DENIED',
+ ].includes(code ?? '')
+ ) {
+ operation.current = null;
+ setReceipt({ operationId: id, phase: 'failed', errorCode: code });
+ setStatus('actionFailed');
+ } else setStatus('unknown');
+ }
+ }
+ },
+ [
+ acceptReceipt,
+ current,
+ invoke,
+ unsupported,
+ writable,
+ project,
+ projectState,
+ projectReadStatus,
+ ],
+ );
+ const selectMarket = async (item: PluginMarketItem) => {
+ const revision = ++detailRevision.current;
+ try {
+ const detail = parsePluginManagementDetail(
+ await invoke('market-detail', { pluginId: item.pluginId }),
+ );
+ if (writable() && revision === detailRevision.current) {
+ setSelected(null);
+ setMarketDetail(detail);
+ }
+ } catch {
+ if (writable() && revision === detailRevision.current) setStatus('readFailed');
+ }
+ };
+ const install = async (item: PluginMarketItem) => {
+ if (!writable() || operation.current || preparing.current) return;
+ preparing.current = true;
+ setPreparingUi(true);
+ try {
+ const detail = parsePluginManagementDetail(
+ await invoke('market-detail', { pluginId: item.pluginId }),
+ );
+ if (!writable() || detail.releaseId !== item.releaseId) {
+ if (current()) setStatus('changed');
+ return;
+ }
+ const ghost = snapshot?.ghosts.find((g) => marketItemMatchesInstalledGhost(detail, g));
+ await begin('install', ghost, detail);
+ } catch {
+ if (current()) setStatus('readFailed');
+ } finally {
+ preparing.current = false;
+ if (current()) setPreparingUi(false);
+ }
+ };
+ const installFile = async (target?: InstalledGhost) => {
+ if (!writable() || operation.current || preparing.current) return;
+ preparing.current = true;
+ setPreparingUi(true);
+ try {
+ const attachment = await window.electronAPI.deviceLink.pickPluginPackage(device.deviceId);
+ if (attachment && writable())
+ await begin('install-file', target, undefined, attachment.attachment);
+ } catch {
+ if (current()) setStatus('readFailed');
+ } finally {
+ preparing.current = false;
+ if (current()) setPreparingUi(false);
+ }
+ };
+ const uninstall = async (target: InstalledGhost) => {
+ if (!writable() || operation.current || preparing.current) return;
+ const abort = new AbortController();
+ dialog.current = abort;
+ preparing.current = true;
+ setPreparingUi(true);
+ try {
+ const accepted = await confirm(
+ {
+ title: t('settings.ghosts.remote.uninstallOn', {
+ name: target.manifest.name,
+ device: device.name,
+ }),
+ confirmText: t('settings.ghosts.remote.uninstall'),
+ confirmVariant: 'destructive',
+ },
+ abort.signal,
+ );
+ if (accepted && writable() && !abort.signal.aborted) await begin('uninstall', target);
+ } finally {
+ preparing.current = false;
+ if (dialog.current === abort) dialog.current = null;
+ if (current()) setPreparingUi(false);
+ }
+ };
+ const busy = !online || unsupported || preparingUi || !!operation.current;
+ const effectiveGhost = (item: InstalledGhost): InstalledGhost =>
+ project
+ ? {
+ ...item,
+ enabled:
+ item.enabled && !projectState?.disabled.includes(installedGhostStoragePart(item)),
+ }
+ : item;
+ const projectReady =
+ !project || (!!projectState && projectState.projectId === project.id && !projectReadStatus);
+ const applyProject = (next: PluginManagementProject | null) => {
+ ++projectReadRevision.current;
+ projectRef.current = next;
+ setProject(next);
+ setProjectState(null);
+ setProjectReadStatus(next ? 'loading' : null);
+ };
+ const pickProject = (id: string | null) => {
+ if (operation.current) return;
+ const next = snapshot?.projects?.find((item) => item.id === id) ?? null;
+ applyProject(next);
+ };
+ const update =
+ ghost &&
+ snapshot?.market.items.find(
+ (i) => marketItemMatchesInstalledGhost(i, ghost) && i.installState === 'update-available',
+ );
+ const configuration = ghost ? (
+ <RemotePluginConfiguration
+ key={`${device.deviceId}:${installedGhostStoragePart(ghost)}:${ghostInstallApprovalToken(ghost.approval)}`}
+ ghost={ghost}
+ device={device}
+ online={online}
+ active={active}
+ busy={busy}
+ hostPreferences={snapshot?.hostPreferences === true}
+ settingsPage={snapshot?.settingsPage === true}
+ />
+ ) : null;
+ const targetProblem = !online || unsupported || !snapshot;
+ const notice = (
+ <CatalogManagementNotice
+ title={
+ project
+ ? t('settings.ghosts.projectBanner.title', { name: project.name })
+ : t(
+ unsupported
+ ? 'settings.ghosts.remote.viewingTarget'
+ : 'settings.ghosts.remote.managingTarget',
+ { device: device.name },
+ )
+ }
+ warning={!online || projectReadStatus === 'failed'}
+ action={
+ project || (online && (unsupported || projectReadStatus === 'failed')) ? (
+ <>
+ {online && unsupported ? (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ if (operation.current) void poll();
+ else void refresh();
+ }}
+ >
+ {t('settings.ghosts.remote.refresh')}
+ </Button>
+ ) : online && projectReadStatus === 'failed' ? (
+ <Button size="sm" variant="secondary" onClick={() => void refreshProject()}>
+ {t('settings.ghosts.remote.retry')}
+ </Button>
+ ) : null}
+ {project ? (
+ <Button
+ size="sm"
+ variant="secondary"
+ tone="quiet"
+ compact
+ disabled={!!operation.current}
+ onClick={() => pickProject(null)}
+ >
+ {t('settings.ghosts.projectBanner.backToGlobal')}
+ </Button>
+ ) : null}
+ </>
+ ) : null
+ }
+ >
+ {!online
+ ? t('settings.ghosts.remote.offlineNotice', { device: device.name })
+ : unsupported
+ ? t(legacy ? 'settings.ghosts.remote.unsupported' : 'settings.ghosts.remote.loading', {
+ device: device.name,
+ })
+ : !snapshot
+ ? t('settings.ghosts.remote.loading')
+ : projectReadStatus === 'loading'
+ ? t('settings.ghosts.remote.projectLoading')
+ : projectReadStatus === 'failed'
+ ? t('settings.ghosts.remote.projectReadFailed')
+ : !snapshot.projects
+ ? t('settings.ghosts.remote.projectsUnsupported')
+ : project
+ ? t('settings.ghosts.projectBanner.desc', { device: device.name })
+ : t('settings.ghosts.remote.managingDescription')}
+ </CatalogManagementNotice>
+ );
+ const filteredLegacy = (legacy ?? []).filter((item) =>
+ [item.name, item.description, item.id]
+ .join(' ')
+ .toLocaleLowerCase()
+ .includes(query.trim().toLocaleLowerCase()),
+ );
+ const normalizedQuery = query.toLocaleLowerCase();
+ const filteredGhosts = snapshot?.ghosts.filter((item) =>
+ `${item.manifest.name} ${item.manifest.description ?? ''}`
+ .toLocaleLowerCase()
+ .includes(normalizedQuery),
+ );
+ const availableMarket =
+ snapshot?.market.items.filter(
+ (i) => !snapshot.ghosts.some((g) => marketItemMatchesInstalledGhost(i, g)),
+ ) ?? [];
+ const marketOrigins = ['all', ...new Set(availableMarket.map(pluginPresentationOrigin))];
+ const effectiveOriginFilter = marketOrigins.includes(originFilter) ? originFilter : 'all';
+ const pageHeading = (
+ <header className="mb-8" data-catalog-region="heading">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h1 className="text-28 font-medium leading-tight text-[var(--text-primary)]">
+ {t('settings.ghosts.title')}
+ </h1>
+ <CatalogTargetControls
+ computer={
+ deviceControl ?? {
+ selected: device,
+ onSelect: () => {},
+ directory: { candidates: [], target: undefined, online, relayOnline: online },
+ }
+ }
+ projectLabel={project?.name}
+ project={
+ <PluginProjectMenu
+ scopeDir={project?.id ?? null}
+ activeSessionWorkingDir={undefined}
+ recentWorkdirs={[]}
+ computerName={device.name}
+ projectOptions={snapshot?.projects ?? []}
+ onBrowse={snapshot?.projectBrowse ? () => setProjectPickerOpen(true) : undefined}
+ disabled={!online || !snapshot || !snapshot.projects || !!operation.current}
+ unavailable={unsupported || (!!snapshot && !snapshot.projects)}
+ onPick={pickProject}
+ />
+ }
+ />
+ </div>
+ <p className="mt-2 text-14 leading-6 text-[var(--text-secondary)]">
+ {t('settings.ghosts.description')}
+ </p>
+ </header>
+ );
+ return (
+ <div className="flex h-full min-h-0 flex-col bg-[var(--surface)]">
+ {projectPickerOpen ? (
+ <AddRemoteProjectDialog
+ open={projectPickerOpen}
+ onOpenChange={(open) => { ++projectPickerRevision.current; setProjectPickerOpen(open); }}
+ initialDeviceId={device.deviceId}
+ fixedDeviceId={device.deviceId}
+ title={t('settings.ghosts.scopePicker.projectsForComputer', { device: device.name })}
+ confirmText={t('newChat.folderPicker.selectFolder')}
+ errorText={t('settings.ghosts.remote.projectReadFailed')}
+ onProjectAdded={async (target) => {
+ if (target.kind !== 'device-link' || target.deviceId !== device.deviceId ||
+ !projectPickerCurrent.current || !writable() || operation.current) return;
+ const revision = ++projectPickerRevision.current;
+ const next = parsePluginManagementProject(await invoke('project-select', { path: target.path }));
+ if (!projectPickerCurrent.current || !writable() || revision !== projectPickerRevision.current) return;
+ // Re-read the Host catalogue so a previous transient browse does not remain selectable.
+ await refresh();
+ if (!projectPickerCurrent.current || !writable() || revision !== projectPickerRevision.current) return;
+ applyProject(next);
+ }}
+ />
+ ) : null}
+ {(ghost || marketDetail) && (targetProblem || projectReadStatus) ? notice : null}
+ <div className="min-h-0 flex-1">
+ {unsupported && legacySelected ? (
+ <RemotePluginReadOnlyDetail
+ detail={legacyDetail?.id === legacySelected.id ? legacyDetail : legacySelected}
+ notice={notice}
+ loading={online && legacyDetailStatus === 'loading'}
+ failed={legacyDetailStatus === 'failed'}
+ online={online}
+ onBack={() => {
+ ++detailRevision.current;
+ setLegacySelected(null);
+ setLegacyDetail(null);
+ setLegacyDetailStatus(null);
+ }}
+ onRetry={() => void loadLegacyDetail(legacySelected)}
+ />
+ ) : ghost ? (
+ <GhostPluginDetailView
+ remote
+ remoteConfiguration={configuration}
+ ghost={effectiveGhost(ghost)}
+ marketItem={snapshot?.market.items.find((item) =>
+ marketItemMatchesInstalledGhost(item, ghost),
+ )}
+ detail={toGhostPluginDetail(effectiveGhost(ghost))}
+ panelStatus={null}
+ onBack={() => setSelected(null)}
+ onToggle={(enabled) => {
+ void begin(enabled ? 'enable' : 'disable', ghost);
+ }}
+ toggleDisabled={busy || !projectReady || (!!project && !ghost.enabled)}
+ onUse={() => {}}
+ updateBusy={busy}
+ updateVersion={update?.version}
+ onUpdate={() => {
+ if (update) void install(update);
+ }}
+ onUpdateFromFile={() => {
+ void installFile(ghost);
+ }}
+ remoteFileUpdate={ghost.namespace === null && !ghost.builtin}
+ onUninstall={() => {
+ void uninstall(ghost);
+ }}
+ />
+ ) : marketDetail ? (
+ <MarketPluginDetailView
+ detail={marketDetail}
+ busy={busy}
+ onBack={() => setMarketDetail(null)}
+ onInstall={
+ marketDetail.installState === 'conflict'
+ ? undefined
+ : () => {
+ void install(marketDetail);
+ }
+ }
+ onIconLoadError={() => {}}
+ />
+ ) : (
+ <PluginManagementLayout
+ activeTab="plugins"
+ embedded={embedded}
+ onSelectTab={onSelectCatalogTab}
+ query={query}
+ onQueryChange={setQuery}
+ headerActions={
+ unsupported ? undefined : (
+ <GhostPluginActions
+ disabled={busy}
+ installTarget={device.name}
+ onInstall={() => void installFile()}
+ />
+ )
+ }
+ >
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <PluginManagementPage>
+ {pageHeading}
+ <section>
+ <InstalledCatalogHeader
+ title={t('settings.ghosts.page.installedSection')}
+ count={
+ unsupported
+ ? legacy
+ ? filteredLegacy.length
+ : undefined
+ : filteredGhosts?.length
+ }
+ />
+ {notice}
+ <div className={PLUGIN_INSTALLED_CARD_GRID_CLASS}>
+ {unsupported
+ ? filteredLegacy.map((item) => (
+ <GhostPluginCard
+ key={item.id}
+ readOnly
+ item={item}
+ showLocalUnread={false}
+ onManage={() => {
+ setLegacyDetail(null);
+ setLegacyDetailStatus('loading');
+ setLegacySelected(item);
+ }}
+ onPrimary={() => {
+ setLegacyDetail(null);
+ setLegacyDetailStatus('loading');
+ setLegacySelected(item);
+ }}
+ />
+ ))
+ : (!project || projectState?.projectId === project.id
+ ? (filteredGhosts ?? [])
+ : []
+ )
+ .map((g) => {
+ const item = {
+ ...toGhostPluginListItem(effectiveGhost(g)),
+ canUse: false,
+ tabPanel: false,
+ };
+ const market = snapshot?.market.items.find(
+ (i) =>
+ marketItemMatchesInstalledGhost(i, g) &&
+ i.installState === 'update-available',
+ );
+ return (
+ <GhostPluginCard
+ key={installedGhostStoragePart(g)}
+ item={item}
+ author={g.manifest.author}
+ marketItem={snapshot?.market.items.find((entry) =>
+ marketItemMatchesInstalledGhost(entry, g),
+ )}
+ showLocalUnread={false}
+ sourceLabel={
+ g.namespace ?? t('settings.ghosts.remote.personalInstall')
+ }
+ onManage={() => {
+ ++detailRevision.current;
+ setSelected(installedGhostStoragePart(g));
+ }}
+ onPrimary={() => setSelected(installedGhostStoragePart(g))}
+ updateBusy={busy}
+ updateVersion={market?.version}
+ onUpdate={
+ market
+ ? () => {
+ void install(market);
+ }
+ : undefined
+ }
+ />
+ );
+ })}
+ </div>
+ {(unsupported ? legacy?.length === 0 : snapshot && !snapshot.ghosts.length) ? (
+ <p className="text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.empty')}
+ </p>
+ ) : null}
+ </section>
+ {!unsupported ? (
+ <section className="mt-8">
+ <div className="mb-2 flex flex-wrap items-center justify-between gap-3">
+ <h2 className="text-20 font-medium leading-6 text-[var(--text-primary)]">
+ {t('settings.ghosts.page.recommendedSection')}
+ </h2>
+ <SegmentedControl
+ role="radiogroup"
+ aria-label={t('settings.ghosts.page.filtersAria')}
+ value={effectiveOriginFilter}
+ onValueChange={setOriginFilter}
+ height={32}
+ optionHeight={28}
+ optionClassName="px-3.5 text-12"
+ options={marketOrigins.map((filter) => ({
+ value: filter,
+ label:
+ filter === 'all'
+ ? t('settings.ghosts.page.filterAll')
+ : t('settings.ghosts.page.origin.' + filter),
+ }))}
+ />
+ </div>
+ <p className="mb-4 text-12 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.installDestination', { device: device.name })}
+ </p>
+ {snapshot?.market.unavailableReason ? (
+ <p className="mb-3 text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.marketUnavailable')}
+ </p>
+ ) : null}
+ <div className={PLUGIN_MANAGEMENT_CARD_GRID_CLASS}>
+ {availableMarket
+ .filter(
+ (i) =>
+ effectiveOriginFilter === 'all' ||
+ pluginPresentationOrigin(i) === effectiveOriginFilter,
+ )
+ .filter((i) =>
+ `${i.name} ${i.description ?? ''}`
+ .toLocaleLowerCase()
+ .includes(normalizedQuery),
+ )
+ .map((item) => (
+ <MarketPluginCard
+ key={item.pluginId}
+ item={item}
+ busy={busy}
+ onSelect={() => {
+ void selectMarket(item);
+ }}
+ onInstall={
+ item.installState === 'conflict'
+ ? undefined
+ : () => {
+ void install(item);
+ }
+ }
+ onIconLoadError={() => {}}
+ />
+ ))}
+ </div>
+ </section>
+ ) : null}
+ </PluginManagementPage>
+ </div>
+ </PluginManagementLayout>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx b/apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx
new file mode 100644
index 0000000000..eef748b141
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx
@@ -0,0 +1,124 @@
+import type { ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import {
+ PluginDetailHeader,
+ PluginDetailFactsSection,
+ PluginPermissionSummary,
+ ToolsSection,
+} from './GhostPluginDetailView';
+import { PluginDetailTopBar, usePluginDetailScrolled } from './PluginDetailTopBar';
+import type { LegacyManagedPluginDetail } from './remotePluginManagementClient';
+
+export function RemotePluginReadOnlyDetail({
+ detail,
+ notice,
+ loading,
+ failed,
+ online,
+ onBack,
+ onRetry,
+}: {
+ detail: LegacyManagedPluginDetail;
+ notice: ReactNode;
+ loading: boolean;
+ failed: boolean;
+ online: boolean;
+ onBack(): void;
+ onRetry(): void;
+}) {
+ const { t } = useTranslation();
+ const { scrolled, onScroll } = usePluginDetailScrolled();
+ const facts = detail.details?.length
+ ? detail.details.map((fact, index) => ({
+ key: `${index}:${fact.key}`,
+ label: fact.title,
+ value: fact.value,
+ monospace: fact.key === 'identifier',
+ fullWidth: fact.key === 'location',
+ }))
+ : [
+ ...(detail.version
+ ? [
+ {
+ key: 'version',
+ label: t('settings.ghosts.detail.infoVersion'),
+ value: `v${detail.version}`,
+ },
+ ]
+ : []),
+ {
+ key: 'instance',
+ label: t('settings.ghosts.remote.instanceId'),
+ value: detail.id,
+ monospace: true,
+ },
+ ];
+ return (
+ <main
+ className="app-wallpaper-surface plugin-motion-root h-full min-h-0 w-full overflow-y-auto bg-[var(--surface)] [scrollbar-gutter:stable_both-edges]"
+ onScroll={onScroll}
+ >
+ <PluginDetailTopBar
+ label={t('settings.ghosts.detail.backToList')}
+ onBack={onBack}
+ scrolled={scrolled}
+ />
+ <article className="plugin-detail-frame mx-auto w-full max-w-[824px] px-8 pb-16 pt-5 max-[760px]:px-6">
+ <PluginDetailHeader
+ {...detail}
+ author={detail.details?.find((fact) => fact.key === 'author')?.value}
+ actions={
+ detail.enabled !== undefined ? (
+ <span className="text-12 leading-5 text-[var(--text-secondary)]">
+ {t(
+ detail.enabled
+ ? 'settings.ghosts.detail.enabledLabel'
+ : 'settings.ghosts.detail.disabledLabel',
+ )}
+ </span>
+ ) : undefined
+ }
+ >
+ <div className="mt-5">{notice}</div>
+ </PluginDetailHeader>
+ {loading ? (
+ <p role="status" className="text-13 leading-5 text-[var(--text-secondary)]">
+ {t('settings.ghosts.remote.detailLoading')}
+ </p>
+ ) : null}
+ {failed ? (
+ <div
+ role="status"
+ className="flex flex-wrap items-center gap-3 text-13 leading-5 text-[var(--text-secondary)]"
+ >
+ <p>{t('settings.ghosts.remote.detailReadFailed')}</p>
+ <Button size="sm" variant="secondary" disabled={!online} onClick={onRetry}>
+ {t('settings.ghosts.remote.refreshDetail')}
+ </Button>
+ </div>
+ ) : null}
+ {detail.tools?.length ? <ToolsSection tools={detail.tools} /> : null}
+ {detail.permissions?.length ? (
+ <PluginPermissionSummary
+ items={detail.permissions.map((permission, index) => ({
+ key: String(index),
+ title: permission.title,
+ descriptions: [permission.description].filter(Boolean),
+ }))}
+ />
+ ) : null}
+ {!loading &&
+ !failed &&
+ (detail.tools === undefined ||
+ detail.permissions === undefined ||
+ !detail.details?.length) ? (
+ <p className="mt-8 text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.detailUnavailable')}
+ </p>
+ ) : null}
+ <PluginDetailFactsSection facts={facts} />
+ </article>
+ </main>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index 635c80ca55..ccfc2d8d42 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -178,6 +178,20 @@ const commandPlugin: GhostPluginListItem = {
oauthAuthorizationExpired: false,
};
+it('renders older Host facts in the standard card without invented version, updates or local actions', () => {
+ const manage = vi.fn();
+ const item = { id: 'remote-notes', name: 'Remote notes', description: 'Saved on the selected computer', enabled: false,
+ iconDataUrl: 'data:image/png;base64,aWNvbg==' };
+ const { container } = render(<GhostPluginCard item={item} readOnly showLocalUnread={false} onManage={manage} onPrimary={vi.fn()} />);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(item.iconDataUrl);
+ expect(screen.getByText('settings.ghosts.detail.disabledLabel')).toBeTruthy();
+ expect(screen.queryByText('settings.ghosts.page.upToDate')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.page.manageAction')).toBeNull();
+ expect(container.textContent).not.toContain('undefined');
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.market.details' }));
+ expect(manage).toHaveBeenCalledTimes(1);
+});
+
const panelPlugin: GhostPluginListItem = {
...commandPlugin,
id: 'signoff-board',
@@ -528,6 +542,16 @@ describe('GhostPluginCard', () => {
expect(screen.queryByText('Google services')).toBeNull();
});
+ it('keeps a remote card with the same id independent of local unread content', () => {
+ __ingestGhostBadgeForTest('filo-google', { unread: true, summary: 'local private summary', at: 1 });
+ const { container } = render(
+ <GhostPluginCard item={commandPlugin} showLocalUnread={false} onPrimary={vi.fn()} onManage={vi.fn()} />,
+ );
+ expect(container.querySelector('.session-card-dot')).toBeNull();
+ expect(screen.queryByText('local private summary')).toBeNull();
+ expect(screen.getByText('Google services')).toBeTruthy();
+ });
+
it('有未读但插件没给摘要:只点亮,静态描述保留(不留空白)', () => {
__ingestGhostBadgeForTest('filo-google', { unread: true, at: 1 });
const { container } = render(
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 341b233749..35c9d20f96 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -6,6 +6,7 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ReactNode } from 'react';
import path from 'node:path';
import type { InstalledGhost } from '../../../../shared/ghost';
@@ -32,7 +33,7 @@ vi.mock('@/hooks/useConnectedSource', () => ({
vi.mock('@/lib/toast', () => ({ toast: toastMocks }));
vi.mock('@/cindy-brain/GhostSettingsWebview', () => ({
- GhostSettingsWebview: ({ account, reloadKey }: any) => (
+ GhostSettingsWebview: ({ account, reloadKey }: { account?: ReactNode; reloadKey?: number }) => (
<>
{account}
<div key={reloadKey} data-testid="ghost-settings-webview" />
@@ -98,6 +99,7 @@ import {
ToolsSection,
} from '../GhostPluginDetailView';
import { toGhostPluginDetail, type GhostPluginDetail } from '../lib/ghostPluginViewModel';
+import { RemotePluginReadOnlyDetail } from '../RemotePluginReadOnlyDetail';
const permissions: GhostPermissionItem[] = [
{
@@ -183,6 +185,69 @@ afterEach(() => {
});
describe('Ghost plugin detail sections', () => {
+ it('shows target shared counts without reading local personal usage for a remote installation', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+ const usageSummary = vi.fn();
+ Object.assign(window.electronAPI, { ghosts: { usageSummary } });
+ render(
+ <GhostPluginDetailView
+ remote
+ ghost={{ manifest: { id: detail.ghostId }, enabled: true } as InstalledGhost}
+ detail={detail}
+ marketItem={
+ {
+ sourceType: 'server',
+ scope: 'organization',
+ downloadStatistics: { requestCount: '1284' },
+ } as import('../../../../shared/pluginMarket').PluginMarketItem
+ }
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+ expect(screen.getByText('1,284 settings.ghosts.usage.downloadsValue')).toBeTruthy();
+ expect(screen.queryByText('settings.ghosts.usage.title')).toBeNull();
+ expect(usageSummary).not.toHaveBeenCalled();
+ });
+
+ it('keeps unknown older-Host details honest and renders no local configuration or file actions', () => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ const { container } = render(<RemotePluginReadOnlyDetail
+ detail={{ id: '_ns__team__notes', name: 'Team notes', description: 'Installed on A' }}
+ notice={<p>Read only on A</p>} loading={false} failed={false} online
+ onBack={vi.fn()} onRetry={vi.fn()}
+ />);
+ expect(screen.getByRole('heading', { name: 'Team notes' })).toBeTruthy();
+ expect(screen.getByText('_ns__team__notes')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.remote.detailUnavailable')).toBeTruthy();
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.detail.configurationTitle')).toBeNull();
+ expect(screen.queryByLabelText('Open Install Location')).toBeNull();
+ expect(container.textContent).not.toMatch(/undefined|unverified|已停用|Disabled/);
+ });
+ it('renders Host permission descriptions through the existing permission dialog and disables retry offline', async () => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
+ render(<RemotePluginReadOnlyDetail
+ detail={{ id: 'notes', name: 'Notes', description: '', permissions: [{ title: 'Read service', description: 'Only the declared service' }] }}
+ notice={<p>Offline</p>} loading={false} failed online={false}
+ onBack={vi.fn()} onRetry={vi.fn()}
+ />);
+ expect((screen.getByRole('button', { name: 'settings.ghosts.remote.refreshDetail' }) as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Permissions: Read service' }));
+ expect(within(await screen.findByRole('dialog')).getByText('Only the declared service')).toBeTruthy();
+ });
it('does not advertise host login for a locally imported unverified GitHub plugin', () => {
vi.stubGlobal(
'ResizeObserver',
@@ -197,7 +262,7 @@ describe('Ghost plugin detail sections', () => {
render(
<GhostPluginDetailView
ghost={
- { manifest: { id: 'cindy-github' }, enabled: true, trust: { level: 'unverified' } } as any
+ { manifest: { id: 'cindy-github' }, enabled: true, trust: { level: 'unverified' } } as InstalledGhost
}
detail={{ ...detail, id: 'cindy-github', ghostId: 'cindy-github', hasSettingsUi: true }}
panelStatus={null}
@@ -346,6 +411,30 @@ describe('Ghost plugin detail sections', () => {
expect(onToggle).toHaveBeenCalledTimes(2);
});
+ it('renders a remote disabled notice without a configuration heading or local settings', () => {
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
+ render(
+ <GhostPluginDetailView
+ remote
+ remoteConfiguration={<p>Enable this plugin before configuring.</p>}
+ ghost={null}
+ detail={{ ...detail, enabled: false, hasSettingsUi: true }}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ expect(screen.getByText('Enable this plugin before configuring.')).toBeTruthy();
+ expect(screen.queryByRole('heading', { name: 'settings.ghosts.detail.configurationTitle' })).toBeNull();
+ expect(screen.queryByTestId('ghost-settings-webview')).toBeNull();
+ });
+
it('shows the main-view preference alongside the plugin settings UI', () => {
vi.stubGlobal(
'ResizeObserver',
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
index 1874b455d7..9a4372ad91 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
@@ -148,6 +148,25 @@ function page(entry: string, withRetirementNavigation = false) {
);
}
+it('keeps linked computer and project scope in the page heading without changing recommendation', async () => {
+ Object.assign(window.electronAPI, { showOpenDirectoryDialog: vi.fn(async () => ({ canceled: false, path: '/fixture/Cindy' })) });
+ Object.assign(window.electronAPI.ghosts, { workdirPrefsSync: vi.fn(() => ({ disabled: [] })) });
+ render(page('/plugins'));
+ const recommended = await screen.findByText(detail.name);
+ const scope = screen.getByRole('button', { name: 'settings.ghosts.remote.device' });
+ expect(scope.closest('[data-catalog-region="heading"]')).toBeTruthy();
+ expect(document.querySelector('[data-catalog-region="notice"]')).toBeNull();
+ fireEvent.keyDown(scope, { key: 'ArrowDown' });
+ fireEvent.keyDown(await screen.findByRole('menuitem', { name: 'settings.ghosts.scopePicker.ariaLabel' }), { key: 'ArrowRight' });
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'settings.ghosts.scopePicker.browse' }));
+ await screen.findByText('settings.ghosts.projectBanner.desc');
+ expect(screen.getByText(detail.name)).toBe(recommended);
+ expect(window.electronAPI.ghosts.workdirPrefsSync).toHaveBeenCalledWith('/fixture/Cindy');
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.projectBanner.backToGlobal' }));
+ expect(document.querySelector('[data-catalog-region="notice"]')).toBeNull();
+ expect(screen.getByText(detail.name)).toBe(recommended);
+});
+
async function openFromCatalog() {
const plugin = await screen.findByText(detail.name);
const catalog = screen.getByRole('main');
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginScopePicker.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginScopePicker.test.tsx
new file mode 100644
index 0000000000..bff8463bfd
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginScopePicker.test.tsx
@@ -0,0 +1,127 @@
+/** @vitest-environment jsdom */
+
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { PluginProjectMenu } from '../PluginScopePicker';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+async function openProjects(
+ projectOptions?: Array<{ id: string; name: string; path?: string }>,
+ recentPaths: string[] = [],
+ onBrowse?: () => void,
+) {
+ const onPick = vi.fn();
+ render(
+ <DropdownMenu defaultOpen>
+ <DropdownMenuTrigger>Computer</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <PluginProjectMenu
+ scopeDir={null}
+ activeSessionWorkingDir={undefined}
+ recentWorkdirs={recentPaths.map((path) => ({
+ path,
+ lastUsedAt: '2026-10-15T00:00:00.000Z',
+ exists: true,
+ }))}
+ onPick={onPick}
+ projectOptions={projectOptions}
+ onBrowse={onBrowse}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ );
+ fireEvent.keyDown(
+ await screen.findByRole('menuitem', {
+ name: 'settings.ghosts.scopePicker.ariaLabel',
+ }),
+ { key: 'ArrowRight' },
+ );
+ const global = await screen.findByRole('menuitem', {
+ name: 'settings.ghosts.scopePicker.global',
+ });
+ return { menu: within(global.closest('[role=menu]') as HTMLElement), onPick };
+}
+
+it('separates Global from folder browsing once when this computer has no projects', async () => {
+ const { menu } = await openProjects();
+ expect(menu.getAllByRole('menuitem')).toHaveLength(2);
+ expect(menu.getAllByRole('separator')).toHaveLength(1);
+});
+
+it('keeps recent projects between Global and folder browsing', async () => {
+ const { menu, onPick } = await openProjects(undefined, ['/fixture/Cindy']);
+ expect(menu.getAllByRole('separator')).toHaveLength(2);
+ fireEvent.click(menu.getByRole('menuitem', { name: /^Cindy/ }));
+ expect(onPick).toHaveBeenCalledWith('/fixture/Cindy');
+});
+
+it('shows the remote empty state without local folder browsing', async () => {
+ const { menu } = await openProjects([]);
+ expect(menu.getByText('settings.ghosts.remote.noProjects')).toBeTruthy();
+ expect(menu.getAllByRole('menuitem')).toHaveLength(1);
+ expect(menu.getAllByRole('separator')).toHaveLength(1);
+});
+
+it('selects a remote project by its Host id without showing local folders', async () => {
+ const { menu, onPick } = await openProjects(
+ [{ id: 'host-project', name: 'Remote Project' }],
+ ['/fixture/local'],
+ );
+ expect(menu.getAllByRole('menuitem')).toHaveLength(2);
+ expect(menu.getAllByRole('separator')).toHaveLength(1);
+ fireEvent.click(menu.getByRole('menuitem', { name: 'Remote Project' }));
+ expect(onPick).toHaveBeenCalledWith('host-project');
+});
+
+it('keeps target paths visible for same-name projects and browses the selected Host only', async () => {
+ const browse = vi.fn();
+ const localBrowse = vi.fn();
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { showOpenDirectoryDialog: localBrowse } });
+ const { menu, onPick } = await openProjects([
+ { id: 'target-a', name: 'Cindy', path: '/target/first/Cindy' },
+ { id: 'target-b', name: 'Cindy', path: 'D:\\Projects\\Cindy' },
+ ], ['/controller/local'], browse);
+ expect(menu.getByText('/target/first/Cindy')).toBeTruthy();
+ expect(menu.queryByText('/controller/local')).toBeNull();
+ fireEvent.click(menu.getByRole('menuitem', { name: /D:.*Projects/ }));
+ expect(onPick).toHaveBeenCalledWith('target-b');
+ cleanup();
+ const next = await openProjects([], [], browse);
+ fireEvent.click(next.menu.getByRole('menuitem', { name: 'settings.ghosts.scopePicker.browse' }));
+ expect(browse).toHaveBeenCalledOnce();
+ expect(localBrowse).not.toHaveBeenCalled();
+});
+
+it('retains the main local folder picker and cancellation behavior', async () => {
+ const localBrowse = vi.fn(async () => ({ canceled: true }));
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { showOpenDirectoryDialog: localBrowse } });
+ const { menu, onPick } = await openProjects();
+ fireEvent.click(menu.getByRole('menuitem', { name: 'settings.ghosts.scopePicker.browse' }));
+ await Promise.resolve();
+ expect(localBrowse).toHaveBeenCalledOnce();
+ expect(onPick).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/RemotePluginConfiguration.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/RemotePluginConfiguration.test.tsx
new file mode 100644
index 0000000000..21ead58701
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/RemotePluginConfiguration.test.tsx
@@ -0,0 +1,257 @@
+// @vitest-environment jsdom
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { RemotePluginConfiguration } from '../RemotePluginConfiguration';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../../shared/ghost';
+import type { RemotePluginPreferenceSnapshot } from '../../../../shared/pluginPreferences';
+const { invoke, local } = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ local: vi.fn(),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: { name?: string }) => (values?.name ? `${key}:${values.name}` : key),
+ i18n: { language: 'en' },
+ }),
+}));
+vi.mock('../remotePluginManagementClient', async (original) => ({
+ ...(await original<typeof import('../remotePluginManagementClient')>()),
+ invokePluginManagement: invoke,
+}));
+vi.mock('../GhostPluginDetailView', () => ({
+ DetailSectionHeader: ({ title }: { title: string }) => <h2>{title}</h2>,
+}));
+vi.mock('@/cindy-brain/PluginTaskPrefs', () => ({
+ PluginTaskPrefs: ({
+ remote,
+ disabled,
+ }: {
+ disabled: boolean;
+ remote: {
+ deviceId: string;
+ value: { config: Record<string, unknown> };
+ onChange(config: Record<string, unknown>): Promise<unknown>;
+ };
+ }) => (
+ <>
+ <output>{JSON.stringify(remote.value.config)}</output>
+ <button
+ disabled={disabled}
+ onClick={() => {
+ void remote
+ .onChange({
+ agentKind: 'codex',
+ providerId: 'target-provider',
+ model: 'only-on-target',
+ fastMode: false,
+ })
+ .catch(() => {});
+ }}
+ >
+ Target model
+ </button>
+ <button
+ disabled={disabled}
+ onClick={() => {
+ void remote.onChange({ ...remote.value.config, permissionMode: 'ask' }).catch(() => {});
+ }}
+ >
+ Task preferences {remote.deviceId}
+ </button>
+ </>
+ ),
+}));
+vi.mock('@/cindy-brain/GhostSettingsWebview', () => ({
+ GhostSettingsWebview: ({
+ ghost,
+ remoteDeviceId,
+ }: {
+ ghost: InstalledGhost;
+ remoteDeviceId: string;
+ }) => (
+ <div data-testid="original-settings">
+ {remoteDeviceId}:{ghost.manifest.settingsHtml}
+ </div>
+ ),
+}));
+const ghost = (cindy?: InstalledGhost['manifest']['cindy']): InstalledGhost => ({
+ manifest: {
+ schemaVersion: 3,
+ minCindyVersion: '0.1.61',
+ id: 'generic-plugin',
+ name: 'Generic plugin',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ cindy,
+ },
+ instanceKey: 'physical-plugin',
+ namespace: null,
+ dir: '/target/plugin',
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+});
+function preferences(): RemotePluginPreferenceSnapshot {
+ return {
+ revision: 'a'.repeat(64),
+ tasks: {
+ revision: 'tasks',
+ config: {},
+ permissionModes: ['ask'],
+ defaultPermissionMode: 'ask',
+ },
+ auxiliaryModelLabel: 'Target auxiliary model',
+ };
+}
+const props = {
+ device: { deviceId: 'target-b', name: 'B' },
+ online: true,
+ active: true,
+ busy: false,
+ hostPreferences: true,
+ settingsPage: true,
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ setDataOwnerGeneration('config-owner');
+ window.electronAPI = {
+ ghosts: {
+ errandPrefsSync: local,
+ setErrandConfig: local,
+ },
+ } as never;
+ invoke.mockResolvedValue({ revision: 'a'.repeat(64) });
+});
+describe('remote original settings and target Host controls', () => {
+ it('reuses the target single-model control and persists it without local preferences', async () => {
+ const installed = ghost({ image: ['generate'], text: ['oneshot'] });
+ let saved = preferences();
+ invoke.mockImplementation(async (_device, action, input) => {
+ if (action === 'preferences-set')
+ saved = {
+ ...saved,
+ revision: 'b'.repeat(64),
+ tasks: { ...saved.tasks!, config: input.patch.model },
+ };
+ return saved;
+ });
+ const ui = render(<RemotePluginConfiguration {...props} ghost={installed} />);
+ fireEvent.click(await screen.findByRole('button', { name: 'Target model' }));
+ await screen.findByText(/only-on-target/);
+ expect(invoke).toHaveBeenCalledWith(
+ 'target-b',
+ 'preferences-set',
+ expect.objectContaining({
+ expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
+ expectedRevision: 'a'.repeat(64),
+ kind: 'tasks',
+ patch: {
+ model: {
+ agentKind: 'codex',
+ providerId: 'target-provider',
+ model: 'only-on-target',
+ fastMode: false,
+ },
+ permissionMode: null,
+ },
+ }),
+ 'physical-plugin',
+ );
+ ui.unmount();
+ render(<RemotePluginConfiguration {...props} ghost={installed} />);
+ await screen.findByText(/only-on-target/);
+ expect(local).not.toHaveBeenCalled();
+ });
+ it('embeds the installed plugin settings page without reconstructing its fields', async () => {
+ const installed = ghost();
+ installed.manifest.settingsHtml = 'custom/settings.html';
+ render(<RemotePluginConfiguration {...props} ghost={installed} />);
+ expect(await screen.findByTestId('original-settings')).toHaveProperty(
+ 'textContent',
+ 'target-b:custom/settings.html',
+ );
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.remote.configure' })).toBeNull();
+ expect(local).not.toHaveBeenCalled();
+ });
+ it('removes the remote page when offline and opens the original again on reconnect', async () => {
+ const installed = ghost();
+ installed.manifest.settingsHtml = 'settings.html';
+ const ui = render(<RemotePluginConfiguration {...props} ghost={installed} />);
+ expect(await screen.findByTestId('original-settings')).toBeTruthy();
+ ui.rerender(<RemotePluginConfiguration {...props} ghost={installed} online={false} />);
+ expect(screen.queryByTestId('original-settings')).toBeNull();
+ ui.rerender(<RemotePluginConfiguration {...props} ghost={installed} />);
+ expect(await screen.findByTestId('original-settings')).toBeTruthy();
+ });
+ it('does not offer an empty Configure flow for plugins without configuration', async () => {
+ render(<RemotePluginConfiguration {...props} ghost={ghost()} />);
+ await waitFor(() =>
+ expect(screen.queryByText('settings.ghosts.remote.configurationLoading')).toBeNull(),
+ );
+ expect(screen.queryByText('settings.ghosts.detail.configurationTitle')).toBeNull();
+ });
+ it('uses target task preferences and patches them without a controller working directory', async () => {
+ const installed = ghost();
+ installed.manifest.agent = { tasks: true };
+ const value = {
+ revision: 'a'.repeat(64),
+ tasks: {
+ revision: 'tasks',
+ config: {},
+ permissionModes: ['ask'],
+ defaultPermissionMode: 'ask',
+ },
+ };
+ invoke.mockResolvedValue(value);
+ render(<RemotePluginConfiguration {...props} ghost={installed} />);
+ fireEvent.click(await screen.findByRole('button', { name: 'Task preferences target-b' }));
+ await waitFor(() =>
+ expect(invoke).toHaveBeenCalledWith(
+ 'target-b',
+ 'preferences-set',
+ expect.objectContaining({ kind: 'tasks', patch: { model: null, permissionMode: 'ask' } }),
+ 'physical-plugin',
+ ),
+ );
+ expect(JSON.stringify(invoke.mock.calls)).not.toContain('workingDir');
+ expect(local).not.toHaveBeenCalled();
+ });
+ it('discards old instance reads and disables writes offline', async () => {
+ let resolve!: (value: RemotePluginPreferenceSnapshot) => void;
+ invoke.mockReturnValueOnce(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const old = ghost({ text: ['oneshot'] });
+ const ui = render(<RemotePluginConfiguration {...props} ghost={old} />);
+ const next = ghost();
+ next.instanceKey = 'new-instance';
+ ui.rerender(<RemotePluginConfiguration {...props} ghost={next} />);
+ await act(async () => resolve(preferences()));
+ expect(screen.queryByRole('button', { name: 'Target model' })).toBeNull();
+ invoke.mockResolvedValue(preferences());
+ ui.rerender(<RemotePluginConfiguration {...props} ghost={old} />);
+ const change = await screen.findByRole('button', { name: 'Target model' });
+ ui.rerender(<RemotePluginConfiguration {...props} ghost={old} online={false} />);
+ fireEvent.click(change);
+ expect(invoke.mock.calls.some((call) => call[1] === 'preferences-set')).toBe(false);
+ });
+ it('shows the real old-Host capability limit instead of substituting a generic form', async () => {
+ const installed = ghost({ text: ['oneshot'] });
+ installed.manifest.settingsHtml = 'settings.html';
+ render(
+ <RemotePluginConfiguration
+ {...props}
+ hostPreferences={false}
+ settingsPage={false}
+ ghost={installed}
+ />,
+ );
+ expect(await screen.findByText('settings.ghosts.remote.settingsPageUnavailable')).toBeTruthy();
+ expect(screen.queryByTestId('original-settings')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.remote.configure' })).toBeNull();
+ expect(invoke).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/RemotePluginPage.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/RemotePluginPage.test.tsx
new file mode 100644
index 0000000000..56c16a1d2a
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/RemotePluginPage.test.tsx
@@ -0,0 +1,906 @@
+// @vitest-environment jsdom
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { RemotePluginPage } from '../RemotePluginPage';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { ghostInstallApprovalToken } from '../../../../shared/ghost';
+const { invoke, confirm, localGhosts, notices } = vi.hoisted(() => ({
+ notices: { success: vi.fn(), info: vi.fn(), error: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
+ invoke: vi.fn(),
+ confirm: vi.fn(async () => true),
+ localGhosts: vi.fn(),
+}));
+vi.mock('@/lib/toast', () => ({ toast: notices }));
+vi.mock('@/components/new-chat/AddRemoteProjectDialog', () => ({
+ AddRemoteProjectDialog: ({ fixedDeviceId, onProjectAdded, onOpenChange }: {
+ fixedDeviceId: string;
+ onProjectAdded(target: { kind: 'device-link'; deviceId: string; deviceName: string; path: string }): Promise<void>;
+ onOpenChange(open: boolean): void;
+ }) => <>
+ <output>Browse {fixedDeviceId}</output>
+ <button onClick={() => void onProjectAdded({ kind: 'device-link', deviceId: fixedDeviceId, deviceName: fixedDeviceId, path: '/target/browsed' }).then(() => onOpenChange(false))}>Select target folder</button>
+ <button onClick={() => onOpenChange(false)}>Cancel folder</button>
+ </>,
+}));
+vi.mock('@/cindy-brain/GhostSettingsWebview', () => ({
+ GhostSettingsWebview: ({
+ ghost,
+ remoteDeviceId,
+ }: {
+ ghost: { instanceKey: string };
+ remoteDeviceId: string;
+ }) => (
+ <output data-testid="original-settings">
+ {remoteDeviceId}/{ghost.instanceKey}
+ </output>
+ ),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+ initReactI18next: { type: '3rdParty', init: vi.fn() },
+ I18nextProvider: ({ children }: { children: React.ReactNode }) => children,
+}));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm }),
+}));
+vi.mock('../GhostPluginPage', () => ({
+ GhostPluginCard: ({ item, onManage }: { item: { name: string }; onManage(): void }) => (
+ <button onClick={onManage}>{item.name}</button>
+ ),
+ MarketPluginCard: () => null,
+}));
+vi.mock('../GhostPluginDetailView', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../GhostPluginDetailView')>()),
+ GhostPluginDetailView: (props: {
+ toggleDisabled: boolean;
+ onToggle(value: boolean): void;
+ remoteConfiguration: React.ReactNode;
+ onBack(): void;
+ detail: { enabled: boolean };
+ }) => (
+ <>
+ <output>{props.detail.enabled ? 'Scoped enabled' : 'Scoped disabled'}</output>
+ <button disabled={props.toggleDisabled} onClick={() => props.onToggle(false)}>
+ Disable
+ </button>
+ {props.remoteConfiguration}
+ <button onClick={props.onBack}>Back</button>
+ </>
+ ),
+}));
+vi.mock('../PluginManagementLayout', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../PluginManagementLayout')>()),
+ PLUGIN_INSTALLED_CARD_GRID_CLASS: '',
+ PLUGIN_MANAGEMENT_CARD_GRID_CLASS: '',
+ PluginManagementLayout: ({
+ children,
+ onSelectTab,
+ headerActions,
+ }: {
+ children: React.ReactNode;
+ onSelectTab?: (tab: 'plugins' | 'skills') => void;
+ headerActions?: React.ReactNode;
+ }) => (
+ <>
+ <button onClick={() => onSelectTab?.('skills')}>Skills</button>
+ {headerActions}
+ {children}
+ </>
+ ),
+ PluginManagementPage: ({ children }: { children: React.ReactNode }) => children,
+}));
+vi.mock('@/cindy-brain/useInstalledGhosts', () => ({ useInstalledGhosts: localGhosts }));
+const snapshot = (name: string) => ({
+ version: 1,
+ settingsPage: true,
+ ghosts: [
+ {
+ manifest: {
+ schemaVersion: 3,
+ minCindyVersion: '0.1.61',
+ id: 'weather',
+ name,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ settingsHtml: 'settings.html',
+ },
+ dir: '/fixture/weather',
+ instanceKey: 'weather',
+ namespace: null,
+ enabled: true,
+ approval: { state: 'approved' as const, revision: '00000000-0000-4000-8000-000000000001' },
+ },
+ ],
+ market: {
+ items: [],
+ unavailableReason: null,
+ customSourceNames: [],
+ unavailableCustomSourceNames: [],
+ },
+});
+const configurationResource = (state = 'configured', id = 'weather') => ({
+ ref: { collectionId: 'plugins', kind: 'plugin', id },
+ revision: 'r1',
+ blocks: [
+ {
+ id: 'capabilities',
+ primitive: 'plugin-capabilities',
+ fallbackMarkdown: '',
+ data: {
+ usage: {
+ taskUsable: true,
+ hasSettings: true,
+ approvalRequired: false,
+ builtin: false,
+ retired: false,
+ setup: { state: 'ready', missing: [], expired: [] },
+ configuration: {
+ items: [
+ {
+ id: 'oauth:account',
+ kind: 'oauth',
+ label: 'Example account',
+ state,
+ count: state === 'configured' ? 1 : 0,
+ },
+ ],
+ alternatives: [],
+ },
+ },
+ },
+ },
+ ],
+});
+beforeEach(() => {
+ vi.clearAllMocks();
+ setDataOwnerGeneration('test-owner');
+ window.electronAPI = {
+ deviceLink: {
+ invoke,
+ onRemotePush: () => () => {},
+ },
+ } as never;
+ invoke.mockImplementation(
+ async (
+ device: string,
+ channel: string,
+ args: Array<{ actionId?: string; input?: { operationId?: string } }>,
+ ) => {
+ if (channel.endsWith(':manifest'))
+ return { collections: [{ id: 'plugins', actions: [{ id: 'management:snapshot' }] }] };
+ if (channel === 'maker:remote-resources:get') return configurationResource();
+ if (args[0].actionId === 'management:snapshot')
+ return { effects: [], result: snapshot(device) };
+ if (args[0].actionId === 'management:begin')
+ return {
+ effects: [],
+ result: { operationId: args[0].input?.operationId, phase: 'succeeded' },
+ };
+ return { effects: [], result: { operationId: args[0].input?.operationId, phase: 'running' } };
+ },
+ );
+});
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+describe('selected plugin host', () => {
+ it('presents cancellation as a neutral overlay without inserting a banner', async () => {
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (device, channel, args) =>
+ args[0]?.actionId === 'management:begin'
+ ? { effects: [], result: { operationId: args[0].input.operationId, phase: 'cancelled' } }
+ : normal(device, channel, args),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ fireEvent.click(screen.getByText('Disable'));
+ await waitFor(() =>
+ expect(notices.info).toHaveBeenCalledWith('settings.ghosts.remote.cancelled'),
+ );
+ expect(screen.queryByText('settings.ghosts.remote.cancelled')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.remote.retry' })).toBeNull();
+ });
+ const projectRevision = 'a'.repeat(64);
+ function projects() {
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (device, channel, args) => {
+ if (args[0]?.actionId === 'management:snapshot')
+ return {
+ effects: [],
+ result: {
+ ...snapshot(device),
+ projectBrowse: true,
+ projects: [
+ { id: 'project-' + device, name: 'Project ' + device },
+ { id: 'other-' + device, name: 'Other project' },
+ ],
+ },
+ };
+ if (args[0]?.actionId === 'management:project-state')
+ return {
+ effects: [],
+ result: {
+ projectId: args[0].input.projectId,
+ revision: projectRevision,
+ disabled: args[0].input.projectId.startsWith('other-') ? ['weather'] : [],
+ },
+ };
+ return normal(device, channel, args);
+ });
+ }
+ async function selectProject(name: string) {
+ fireEvent.keyDown(screen.getByRole('button', { name: 'settings.ghosts.remote.device' }), {
+ key: 'ArrowDown',
+ });
+ fireEvent.keyDown(
+ await screen.findByRole('menuitem', { name: 'settings.ghosts.scopePicker.ariaLabel' }),
+ { key: 'ArrowRight' },
+ );
+ fireEvent.click(await screen.findByRole('menuitem', { name }));
+ }
+ it('uses the existing target folder picker and Host-issued identity without reading controller folders', async () => {
+ projects();
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (device, channel, args) =>
+ args[0]?.actionId === 'management:project-select'
+ ? { effects: [], result: { id: 'browsed', name: 'Browsed folder', path: '/target/browsed' } }
+ : normal(device, channel, args));
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ await screen.findByText('computer-a');
+ await selectProject('settings.ghosts.scopePicker.browse');
+ expect(screen.getByText('Browse computer-a')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Select target folder' }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('computer-a', expect.any(String), [expect.objectContaining({
+ actionId: 'management:project-state', input: { projectId: 'browsed' },
+ })]));
+ expect(invoke).toHaveBeenCalledWith('computer-a', expect.any(String), [expect.objectContaining({
+ actionId: 'management:project-select', input: { path: '/target/browsed' },
+ })]);
+ const actions = invoke.mock.calls.map(call => call[2][0].actionId);
+ expect(actions.slice(actions.indexOf('management:project-select') + 1)).toContain('management:snapshot');
+ expect(localGhosts).not.toHaveBeenCalled();
+ });
+ it('ignores a late folder selection after switching computers and cancels without changing scope', async () => {
+ projects();
+ const normal = invoke.getMockImplementation()!;
+ let resolve!: (value: unknown) => void;
+ invoke.mockImplementation((device, channel, args) => args[0]?.actionId === 'management:project-select'
+ ? new Promise(done => { resolve = done; }) : normal(device, channel, args));
+ const view = render(<RemotePluginPage key="a" device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ await screen.findByText('computer-a');
+ await selectProject('settings.ghosts.scopePicker.browse');
+ fireEvent.click(screen.getByRole('button', { name: 'Select target folder' }));
+ view.rerender(<RemotePluginPage key="b" device={{ deviceId: 'computer-b', name: 'B' }} online />);
+ await screen.findByText('computer-b');
+ await act(async () => { resolve({ effects: [], result: { id: 'late-a', name: 'Late A' } }); });
+ expect(invoke.mock.calls.some(call => call[2][0].actionId === 'management:project-state' && call[2][0].input.projectId === 'late-a')).toBe(false);
+ await selectProject('settings.ghosts.scopePicker.browse');
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel folder' }));
+ expect(screen.queryByText('Browse computer-b')).toBeNull();
+ expect(screen.getByRole('button', { name: 'settings.ghosts.remote.device' }).textContent).toContain('globalScope');
+ });
+ it('binds a project toggle to its Host, project revision and physical plugin while avoiding market reconciliation on scope change', async () => {
+ projects();
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ await screen.findByText('computer-a');
+ const snapshotsBefore = invoke.mock.calls.filter(
+ (call) => call[2][0].actionId === 'management:snapshot',
+ ).length;
+ expect(
+ screen
+ .getByRole('button', { name: 'settings.ghosts.remote.device' })
+ .closest('[data-catalog-region="heading"]'),
+ ).toBeTruthy();
+ expect(
+ screen
+ .getByRole('button', { name: 'settings.ghosts.remote.device' })
+ .closest('[data-catalog-region="target"]')
+ ?.querySelectorAll('button'),
+ ).toHaveLength(1);
+ await selectProject('Project computer-a');
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(screen.getByText('Scoped enabled')).toBeTruthy();
+ expect(
+ invoke.mock.calls.filter((call) => call[2][0].actionId === 'management:snapshot'),
+ ).toHaveLength(snapshotsBefore);
+ fireEvent.click(screen.getByText('Disable'));
+ await waitFor(() =>
+ expect(invoke.mock.calls.some((call) => call[2][0].actionId === 'management:begin')).toBe(
+ true,
+ ),
+ );
+ const call = invoke.mock.calls.find((call) => call[2][0].actionId === 'management:begin')!;
+ expect(call[0]).toBe('computer-a');
+ expect(call[2][0]).toMatchObject({
+ resourceRef: { id: 'weather' },
+ input: {
+ kind: 'disable',
+ projectId: 'project-computer-a',
+ expectedProjectRevision: projectRevision,
+ },
+ });
+ expect(localGhosts).not.toHaveBeenCalled();
+ });
+ it('ignores the previous project late response after switching projects', async () => {
+ projects();
+ const normal = invoke.getMockImplementation()!;
+ let resolve!: (value: unknown) => void;
+ invoke.mockImplementation((device, channel, args) =>
+ args[0]?.actionId === 'management:project-state' &&
+ args[0].input.projectId === 'project-computer-a'
+ ? new Promise((done) => {
+ resolve = done;
+ })
+ : normal(device, channel, args),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ await screen.findByText('computer-a');
+ await selectProject('Project computer-a');
+ await waitFor(() => expect(resolve).toBeTypeOf('function'));
+ expect(screen.queryByText('computer-a')).toBeNull();
+ await selectProject('Other project');
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(screen.getByText('Scoped disabled')).toBeTruthy();
+ await act(async () => {
+ resolve({
+ effects: [],
+ result: { projectId: 'project-computer-a', revision: projectRevision, disabled: [] },
+ });
+ });
+ expect(screen.getByText('Scoped disabled')).toBeTruthy();
+ });
+ it('loads the next computer own projects and resets its scope to global', async () => {
+ projects();
+ const ui = render(
+ <RemotePluginPage key="a" device={{ deviceId: 'computer-a', name: 'A' }} online />,
+ );
+ await screen.findByText('computer-a');
+ await selectProject('Other project');
+ await screen.findByText('computer-a');
+ ui.rerender(<RemotePluginPage key="b" device={{ deviceId: 'computer-b', name: 'B' }} online />);
+ await screen.findByText('computer-b');
+ expect(screen.getByRole('button', { name: 'settings.ghosts.remote.device' }).textContent).toBe(
+ 'B / settings.ghosts.scopePicker.globalScope',
+ );
+ fireEvent.keyDown(screen.getByRole('button', { name: 'settings.ghosts.remote.device' }), {
+ key: 'ArrowDown',
+ });
+ fireEvent.keyDown(
+ await screen.findByRole('menuitem', { name: 'settings.ghosts.scopePicker.ariaLabel' }),
+ { key: 'ArrowRight' },
+ );
+ await screen.findByRole('menuitem', { name: 'Project computer-b' });
+ expect(screen.queryByRole('menuitem', { name: 'Project computer-a' })).toBeNull();
+ });
+ it('keeps global management usable with old Host project capability absent', async () => {
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ await screen.findByText('computer-a');
+ expect(screen.getByText('settings.ghosts.remote.projectsUnsupported')).toBeTruthy();
+ fireEvent.keyDown(screen.getByRole('button', { name: 'settings.ghosts.remote.device' }), {
+ key: 'ArrowDown',
+ });
+ expect(
+ (
+ await screen.findByRole('menuitem', { name: 'settings.ghosts.scopePicker.ariaLabel' })
+ ).getAttribute('data-disabled'),
+ ).toBe('');
+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' });
+ fireEvent.click(screen.getByText('computer-a'));
+ await screen.findByTestId('original-settings');
+ expect((screen.getByText('Disable') as HTMLButtonElement).disabled).toBe(false);
+ });
+ it('project read failure retains the target with retry and blocks project actions', async () => {
+ projects();
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation((device, channel, args) =>
+ args[0]?.actionId === 'management:project-state'
+ ? Promise.reject(new Error('timeout'))
+ : normal(device, channel, args),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ await screen.findByText('computer-a');
+ await selectProject('Project computer-a');
+ await screen.findByText(/projectReadFailed/);
+ expect(screen.queryByText('computer-a')).toBeNull();
+ expect(invoke.mock.calls.some((call) => call[2][0].actionId === 'management:begin')).toBe(
+ false,
+ );
+ expect(screen.getByText('settings.ghosts.remote.retry')).toBeTruthy();
+ expect(screen.getAllByRole('status')).toHaveLength(1);
+ fireEvent.click(
+ screen.getByRole('button', { name: 'settings.ghosts.projectBanner.backToGlobal' }),
+ );
+ await screen.findByText('computer-a');
+ expect(screen.getByText('settings.ghosts.remote.managingDescription')).toBeTruthy();
+ expect(screen.queryByText(/projectReadFailed/)).toBeNull();
+ expect(screen.getAllByRole('status')).toHaveLength(1);
+ expect(invoke.mock.calls.some((call) => call[2][0].actionId === 'management:begin')).toBe(
+ false,
+ );
+ });
+ it('installs a file from the add-plugin menu onto the selected computer without a list-level import action', async () => {
+ const pick = vi.fn(async () => ({ attachment: 'sandbox-transferred-package' }));
+ Object.assign(window.electronAPI.deviceLink, { pickPluginPackage: pick });
+ render(<RemotePluginPage device={{ deviceId: 'computer-b', name: 'B' }} online />);
+ await screen.findByText('computer-b');
+ expect(screen.queryByText('settings.ghosts.remote.import')).toBeNull();
+ fireEvent.keyDown(screen.getByRole('button', { name: 'settings.ghosts.page.addPluginAria' }), {
+ key: 'ArrowDown',
+ });
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'settings.ghosts.install' }));
+ await waitFor(() => expect(pick).toHaveBeenCalledWith('computer-b'));
+ await waitFor(() =>
+ expect(invoke.mock.calls.some((call) => call[2][0].actionId === 'management:begin')).toBe(
+ true,
+ ),
+ );
+ const call = invoke.mock.calls.find((call) => call[2][0].actionId === 'management:begin')!;
+ expect(call[0]).toBe('computer-b');
+ expect(call[2][0].input).toMatchObject({
+ kind: 'install-file',
+ attachment: 'sandbox-transferred-package',
+ });
+ });
+ it('keeps add-plugin disabled while offline', async () => {
+ render(<RemotePluginPage device={{ deviceId: 'computer-b', name: 'B' }} online={false} />);
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'settings.ghosts.page.addPluginAria',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ expect(
+ (screen.getByRole('button', { name: 'settings.ghosts.remote.device' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(false);
+ expect(invoke).not.toHaveBeenCalled();
+ });
+ it('does not reconcile a hidden target market until the Plugins tab is shown', async () => {
+ const ui = render(
+ <RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online active={false} />,
+ );
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(invoke).not.toHaveBeenCalled();
+ ui.rerender(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online active />);
+ await screen.findByText('computer-a');
+ });
+ it('routes enable/disable with target physical instance and approval without reading the local store', async () => {
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ fireEvent.click(screen.getByText('Disable'));
+ await waitFor(() =>
+ expect(invoke.mock.calls.some((c) => c[2][0].actionId === 'management:begin')).toBe(true),
+ );
+ const call = invoke.mock.calls.find((c) => c[2][0].actionId === 'management:begin')!;
+ expect(call[0]).toBe('computer-a');
+ expect(call[2][0].resourceRef.id).toBe('weather');
+ expect(call[2][0].input).toMatchObject({
+ kind: 'disable',
+ expectedInstalledApproval: ghostInstallApprovalToken(snapshot('A').ghosts[0].approval),
+ });
+ expect(localGhosts).not.toHaveBeenCalled();
+ });
+ it('keeps offline target data, disables writes and never falls back to local APIs', async () => {
+ const ui = render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ ui.rerender(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online={false} />);
+ expect((screen.getByText('Disable') as HTMLButtonElement).disabled).toBe(true);
+ expect(localGhosts).not.toHaveBeenCalled();
+ });
+ it('shows only the disabled hint, then mounts the original settings when enabled', async () => {
+ let enabled = false;
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (device, channel, args) => {
+ if (args[0]?.actionId === 'management:snapshot') {
+ const data = snapshot(device);
+ data.ghosts[0].enabled = enabled;
+ return { effects: [], result: data };
+ }
+ return normal(device, channel, args);
+ });
+ const ui = render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(screen.queryByTestId('original-settings')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.detail.configurationTitle')).toBeNull();
+ expect(screen.getByText('settings.ghosts.remote.enableBeforeConfigure')).toBeTruthy();
+ enabled = true;
+ ui.rerender(
+ <RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online active={false} />,
+ );
+ ui.rerender(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online active />);
+ expect(await screen.findByTestId('original-settings')).toHaveProperty(
+ 'textContent',
+ 'computer-a/weather',
+ );
+ expect(screen.queryByText('settings.ghosts.remote.enableBeforeConfigure')).toBeNull();
+ expect(invoke.mock.calls.some((call) => call[2][0].actionId === 'management:begin')).toBe(
+ false,
+ );
+ expect(localGhosts).not.toHaveBeenCalled();
+ });
+ it('removes the original page when a Host operation returns its new disabled state', async () => {
+ let enabled = true;
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (device, channel, args) => {
+ if (args[0]?.actionId === 'management:snapshot') {
+ const data = snapshot(device);
+ data.ghosts[0].enabled = enabled;
+ return { effects: [], result: data };
+ }
+ if (args[0]?.actionId === 'management:begin') {
+ enabled = false;
+ return {
+ effects: [],
+ result: {
+ operationId: args[0].input.operationId,
+ phase: 'failed',
+ errorCode: 'GHOST_ASLEEP',
+ },
+ };
+ }
+ return normal(device, channel, args);
+ });
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(await screen.findByTestId('original-settings')).toBeTruthy();
+ fireEvent.click(screen.getByText('Disable'));
+ await screen.findByText('Scoped disabled');
+ expect(screen.queryByTestId('original-settings')).toBeNull();
+ expect(screen.getByText('settings.ghosts.remote.enableBeforeConfigure')).toBeTruthy();
+ });
+ it('reopens the original settings instead of rendering synthesized authorization metadata', async () => {
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(await screen.findByTestId('original-settings')).toHaveProperty(
+ 'textContent',
+ 'computer-a/weather',
+ );
+ expect(screen.queryByText('settings.ghosts.remote.authorizedAccounts')).toBeNull();
+ fireEvent.click(screen.getByText('Back'));
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(await screen.findByTestId('original-settings')).toBeTruthy();
+ expect(invoke.mock.calls.some((call) => call[1] === 'maker:remote-resources:get')).toBe(false);
+ });
+ it('does not open the setup coordinator or read a summary while displaying settings', async () => {
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ await screen.findByTestId('original-settings');
+ expect(invoke.mock.calls.some((call) => call[2][0].input?.kind === 'configure')).toBe(false);
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.remote.configure' })).toBeNull();
+ });
+ it('binds the original page to the selected computer when switching targets', async () => {
+ const ui = render(
+ <RemotePluginPage key="a" device={{ deviceId: 'computer-a', name: 'A' }} online />,
+ );
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(await screen.findByTestId('original-settings')).toHaveProperty(
+ 'textContent',
+ 'computer-a/weather',
+ );
+ ui.rerender(<RemotePluginPage key="b" device={{ deviceId: 'computer-b', name: 'B' }} online />);
+ expect(screen.queryByTestId('original-settings')).toBeNull();
+ fireEvent.click(await screen.findByText('computer-b'));
+ expect(await screen.findByTestId('original-settings')).toHaveProperty(
+ 'textContent',
+ 'computer-b/weather',
+ );
+ });
+ it('keeps settings bound to the physical instance when opening a namespaced copy', async () => {
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (device, channel, args) => {
+ if (args[0]?.actionId === 'management:snapshot') {
+ const state = snapshot(device);
+ return {
+ effects: [],
+ result: {
+ ...state,
+ ghosts: [
+ ...state.ghosts,
+ {
+ ...state.ghosts[0],
+ instanceKey: '_ns__xd__weather',
+ namespace: 'xd',
+ manifest: { ...state.ghosts[0].manifest, name: 'Organization weather' },
+ },
+ ],
+ },
+ };
+ }
+ return normal(device, channel, args);
+ });
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ expect(await screen.findByTestId('original-settings')).toHaveProperty(
+ 'textContent',
+ 'computer-a/weather',
+ );
+ fireEvent.click(screen.getByText('Back'));
+ fireEvent.click(await screen.findByText('Organization weather'));
+ expect(await screen.findByTestId('original-settings')).toHaveProperty(
+ 'textContent',
+ 'computer-a/_ns__xd__weather',
+ );
+ });
+ it('unmounts the original settings when its Host disconnects', async () => {
+ const ui = render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('computer-a'));
+ await screen.findByTestId('original-settings');
+ ui.rerender(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online={false} />);
+ expect(screen.queryByTestId('original-settings')).toBeNull();
+ expect(screen.getByText('settings.ghosts.remote.offlineNotice')).toBeTruthy();
+ expect(localGhosts).not.toHaveBeenCalled();
+ });
+ it('ignores a late response from a previous mounted device', async () => {
+ let reply!: (value: unknown) => void;
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation((device, channel, args) =>
+ device === 'computer-a' && args[0].actionId === 'management:snapshot'
+ ? new Promise((resolve) => {
+ reply = resolve;
+ })
+ : normal(device, channel, args),
+ );
+ const ui = render(
+ <RemotePluginPage key="a" device={{ deviceId: 'computer-a', name: 'A' }} online />,
+ );
+ await waitFor(() => expect(reply).toBeTypeOf('function'));
+ ui.rerender(<RemotePluginPage key="b" device={{ deviceId: 'computer-b', name: 'B' }} online />);
+ await screen.findByText('computer-b');
+ await act(async () => {
+ reply({ result: snapshot('stale-a') });
+ });
+ expect(screen.queryByText('stale-a')).toBeNull();
+ });
+ it('discards an owner’s late response after switching account', async () => {
+ let reply!: (value: unknown) => void;
+ invoke.mockImplementation(async (_device, channel) =>
+ channel.endsWith(':manifest')
+ ? { collections: [{ id: 'plugins', actions: [{ id: 'management:snapshot' }] }] }
+ : new Promise((resolve) => {
+ reply = resolve;
+ }),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'computer-a', name: 'A' }} online />);
+ await waitFor(() => expect(reply).toBeTypeOf('function'));
+ setDataOwnerGeneration('other-owner');
+ await act(async () => {
+ reply({ result: snapshot('old-account') });
+ });
+ expect(screen.queryByText('old-account')).toBeNull();
+ });
+ it('shows old Host plugins read-only when the capability is absent', async () => {
+ invoke.mockImplementation(async (_device, channel) =>
+ channel.endsWith(':manifest')
+ ? { collections: [{ id: 'plugins' }] }
+ : {
+ items: [
+ {
+ ref: { collectionId: 'plugins', kind: 'plugin', id: 'legacy' },
+ revision: 'r1',
+ display: { title: 'Legacy plugin', status: { label: 'enabled' } },
+ },
+ ],
+ },
+ );
+ const onSelectCatalogTab = vi.fn();
+ render(
+ <RemotePluginPage
+ device={{ deviceId: 'old', name: 'Old' }}
+ online
+ deviceControl={{
+ selected: { deviceId: 'old', name: 'Old' },
+ onSelect: vi.fn(),
+ directory: { candidates: [], target: undefined, online: true, relayOnline: true },
+ }}
+ onSelectCatalogTab={onSelectCatalogTab}
+ />,
+ );
+ await screen.findByText('Legacy plugin');
+ expect(
+ screen
+ .getByRole('button', { name: 'settings.ghosts.remote.device' })
+ .closest('[data-catalog-region="heading"]'),
+ ).toBeTruthy();
+ fireEvent.click(screen.getByText('Skills'));
+ expect(onSelectCatalogTab).toHaveBeenCalledWith('skills');
+ expect(screen.getByText('settings.ghosts.remote.unsupported')).toBeTruthy();
+ expect(invoke.mock.calls.some((c) => c[2][0].actionId === 'management:begin')).toBe(false);
+ });
+ const legacyItem = {
+ ref: { collectionId: 'plugins', kind: 'plugin', id: '_ns__team__notes' },
+ revision: 'r1',
+ display: { title: 'Team notes', subtitle: 'Organize notes', status: { label: 'enabled' } },
+ };
+ const legacyResource = {
+ ...legacyItem,
+ blocks: [
+ { id: 'about', primitive: 'markdown', fallbackMarkdown: 'Full description from A' },
+ { id: 'version', primitive: 'status', fallbackMarkdown: '1.2.3' },
+ {
+ id: 'capabilities',
+ primitive: 'plugin-capabilities',
+ fallbackMarkdown: '',
+ data: {
+ tools: [{ name: 'read_notes', description: 'Read saved notes' }],
+ permissions: [{ title: 'Access notes service', description: 'Only the declared host' }],
+ details: [{ key: 'author', title: 'Author', value: 'Example Team' }],
+ },
+ },
+ ],
+ };
+ function oldHost() {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+ invoke.mockImplementation(async (_device, channel) => {
+ if (channel.endsWith(':manifest')) return { collections: [{ id: 'plugins' }] };
+ if (channel.endsWith(':list')) return { items: [legacyItem] };
+ if (channel.endsWith(':get')) return legacyResource;
+ throw new Error('unexpected write');
+ });
+ }
+ it('opens a normal detail header and all provided facts for an older Host without using local actions', async () => {
+ oldHost();
+ render(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('Team notes'));
+ await screen.findByText('Full description from A');
+ expect(screen.getByRole('heading', { name: 'Team notes' })).toBeTruthy();
+ expect(screen.getByText('v1.2.3')).toBeTruthy();
+ expect(screen.getByText('Example Team')).toBeTruthy();
+ expect(screen.getByText('read_notes')).toBeTruthy();
+ expect(screen.getByText('Access notes service')).toBeTruthy();
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.remote.configure')).toBeNull();
+ expect(invoke.mock.calls.find((call) => call[1].endsWith(':get'))).toMatchObject([
+ 'old-a',
+ expect.any(String),
+ [{ ref: legacyItem.ref, client: { locale: 'en' } }],
+ ]);
+ expect(invoke.mock.calls.some((call) => call[1].endsWith(':invoke'))).toBe(false);
+ expect(localGhosts).not.toHaveBeenCalled();
+ });
+ it('keeps the readable header while loading, and Back prevents a late detail from reopening', async () => {
+ oldHost();
+ const normal = invoke.getMockImplementation()!;
+ let resolve!: (value: unknown) => void;
+ invoke.mockImplementation((device, channel, args) =>
+ channel.endsWith(':get')
+ ? new Promise((done) => {
+ resolve = done;
+ })
+ : normal(device, channel, args),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('Team notes'));
+ expect(screen.getByRole('heading', { name: 'Team notes' })).toBeTruthy();
+ await screen.findByText('settings.ghosts.remote.detailLoading');
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.detail.backToList' }));
+ await act(async () => resolve(legacyResource));
+ expect(screen.queryByText('Full description from A')).toBeNull();
+ expect(screen.queryByRole('heading', { name: 'Team notes' })).toBeNull();
+ });
+ it('does not let a late old-Host detail appear after selecting a different computer', async () => {
+ oldHost();
+ const normal = invoke.getMockImplementation()!;
+ let resolve!: (value: unknown) => void;
+ invoke.mockImplementation((device, channel, args) =>
+ channel.endsWith(':get')
+ ? new Promise((done) => {
+ resolve = done;
+ })
+ : normal(device, channel, args),
+ );
+ const ui = render(
+ <RemotePluginPage key="a" device={{ deviceId: 'old-a', name: 'A' }} online />,
+ );
+ fireEvent.click(await screen.findByText('Team notes'));
+ await waitFor(() => expect(resolve).toBeTypeOf('function'));
+ ui.rerender(<RemotePluginPage key="b" device={{ deviceId: 'old-b', name: 'B' }} online />);
+ await screen.findByText('Team notes');
+ await act(async () => resolve(legacyResource));
+ expect(screen.queryByText('Full description from A')).toBeNull();
+ expect(screen.queryByRole('heading', { name: 'Team notes' })).toBeNull();
+ });
+ it('shows a detail read failure and retries only that Host resource', async () => {
+ oldHost();
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation((device, channel, args) =>
+ channel.endsWith(':get')
+ ? Promise.reject(new Error('timeout'))
+ : normal(device, channel, args),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('Team notes'));
+ await screen.findByText('settings.ghosts.remote.detailReadFailed');
+ invoke.mockImplementation(normal);
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.remote.refreshDetail' }));
+ await screen.findByText('Full description from A');
+ expect(screen.queryByText('settings.ghosts.remote.detailReadFailed')).toBeNull();
+ expect(invoke.mock.calls.every((call) => call[0] === 'old-a')).toBe(true);
+ });
+ it('ignores a late detail after account ownership changes', async () => {
+ oldHost();
+ const normal = invoke.getMockImplementation()!;
+ let resolve!: (value: unknown) => void;
+ invoke.mockImplementation((device, channel, args) =>
+ channel.endsWith(':get')
+ ? new Promise((done) => {
+ resolve = done;
+ })
+ : normal(device, channel, args),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('Team notes'));
+ await waitFor(() => expect(resolve).toBeTypeOf('function'));
+ setDataOwnerGeneration('signed-out');
+ await act(async () => resolve(legacyResource));
+ expect(screen.queryByText('Full description from A')).toBeNull();
+ });
+ it('retains the detail offline and refreshes it on reconnect without invoking writes', async () => {
+ oldHost();
+ const ui = render(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('Team notes'));
+ await screen.findByText('Full description from A');
+ const previousReads = invoke.mock.calls.filter((call) => call[1].endsWith(':get')).length;
+ ui.rerender(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online={false} />);
+ expect(screen.getByRole('heading', { name: 'Team notes' })).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.remote.offlineNotice')).toBeTruthy();
+ ui.rerender(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ await waitFor(() =>
+ expect(invoke.mock.calls.filter((call) => call[1].endsWith(':get')).length).toBeGreaterThan(
+ previousReads,
+ ),
+ );
+ await waitFor(() =>
+ expect(screen.queryByText('settings.ghosts.remote.detailLoading')).toBeNull(),
+ );
+ expect(screen.getByText('Full description from A')).toBeTruthy();
+ expect(invoke.mock.calls.some((call) => call[1].endsWith(':invoke'))).toBe(false);
+ });
+ it('returns to the full management page when a refreshed Host gains the capability', async () => {
+ oldHost();
+ render(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ fireEvent.click(await screen.findByText('Team notes'));
+ await screen.findByText('Full description from A');
+ invoke.mockImplementation(async (_device, channel) =>
+ channel.endsWith(':manifest')
+ ? { collections: [{ id: 'plugins', actions: [{ id: 'management:snapshot' }] }] }
+ : { result: snapshot('Upgraded plugin') },
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.remote.refresh' }));
+ await screen.findByText('Upgraded plugin');
+ expect(screen.queryByText('Full description from A')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.remote.unsupported')).toBeNull();
+ });
+ it('shows list errors before upgrade advice and clears the error after refreshing', async () => {
+ oldHost();
+ const normal = invoke.getMockImplementation()!;
+ invoke.mockImplementation((device, channel, args) =>
+ channel.endsWith(':list')
+ ? Promise.reject(new Error('timeout'))
+ : normal(device, channel, args),
+ );
+ render(<RemotePluginPage device={{ deviceId: 'old-a', name: 'A' }} online />);
+ await waitFor(() =>
+ expect(notices.error).toHaveBeenCalledWith(
+ 'settings.ghosts.remote.readFailed',
+ expect.any(Object),
+ ),
+ );
+ expect(screen.queryByText('settings.ghosts.remote.unsupported')).toBeNull();
+ invoke.mockImplementation(normal);
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.remote.refresh' }));
+ await screen.findByText('Team notes');
+ expect(screen.queryByText('settings.ghosts.remote.readFailed')).toBeNull();
+ expect(screen.getByRole('button', { name: 'settings.ghosts.remote.refresh' })).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/remotePluginManagementClient.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/remotePluginManagementClient.test.ts
new file mode 100644
index 0000000000..323e1892ed
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/remotePluginManagementClient.test.ts
@@ -0,0 +1,168 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ parsePluginManagementProjectState,
+ parsePluginManagementProject,
+ parsePluginManagementSnapshot,
+ readLegacyManagedPlugin,
+ readLegacyManagedPlugins,
+} from '../remotePluginManagementClient';
+
+const snapshot = {
+ version: 1,
+ ghosts: [],
+ market: { items: [], customSourceNames: [], unavailableCustomSourceNames: [] },
+};
+describe('remote project response boundaries', () => {
+ it('distinguishes old Host capability absence from a supported empty project catalogue', () => {
+ expect(parsePluginManagementSnapshot(snapshot).projects).toBeUndefined();
+ expect(parsePluginManagementSnapshot({ ...snapshot, projects: [] }).projects).toEqual([]);
+ });
+ it('accepts optional target display paths and an explicit browser capability while rejecting malformed declarations', () => {
+ const project = { id: 'b', name: 'Cindy', path: 'D:\\Projects\\Cindy' };
+ expect(parsePluginManagementProject(project)).toEqual(project);
+ expect(parsePluginManagementSnapshot({ ...snapshot, projects: [project], projectBrowse: true }).projectBrowse).toBe(true);
+ for (const path of [42, '', 'bad\0path', 'x'.repeat(32769)]) {
+ expect(() => parsePluginManagementProject({ ...project, path })).toThrow('INVALID_RESPONSE');
+ expect(() => parsePluginManagementSnapshot({ ...snapshot, projects: [{ ...project, path }] })).toThrow('INVALID_RESPONSE');
+ }
+ expect(() => parsePluginManagementSnapshot({ ...snapshot, projectBrowse: 'yes' })).toThrow('INVALID_RESPONSE');
+ });
+ it.each<unknown[]>([
+ [
+ { id: 'a', name: 'Cindy' },
+ { id: 'a', name: 'Other' },
+ ],
+ [{ id: '', name: 'Cindy' }],
+ [{ id: 'a', name: null }],
+ ])('rejects ambiguous or malformed Host project declarations', (projects) => {
+ expect(() => parsePluginManagementSnapshot({ ...snapshot, projects })).toThrow(
+ 'INVALID_RESPONSE',
+ );
+ });
+ it('binds project state to the requested identity and a valid revision before enabling any writes', () => {
+ const state = { projectId: 'a', revision: 'a'.repeat(64), disabled: ['_ns__team__notes'] };
+ expect(parsePluginManagementProjectState(state, 'a')).toEqual(state);
+ expect(() => parsePluginManagementProjectState(state, 'b')).toThrow('INVALID_RESPONSE');
+ expect(() => parsePluginManagementProjectState({ ...state, revision: 'stale' }, 'a')).toThrow(
+ 'INVALID_RESPONSE',
+ );
+ expect(() => parsePluginManagementProjectState({ ...state, disabled: [true] }, 'a')).toThrow(
+ 'INVALID_RESPONSE',
+ );
+ });
+});
+
+describe('older Host plugin presentation', () => {
+ afterEach(() => vi.unstubAllGlobals());
+ const item = {
+ ref: { collectionId: 'plugins', kind: 'plugin', id: '_ns__team__notes' },
+ revision: 'r1',
+ display: {
+ title: { fallback: 'Notes', translations: { 'zh-CN': '笔记' } },
+ subtitle: 'Read and organize notes',
+ avatar: { kind: 'asset', value: 'data:image/png;base64,aWNvbg==', fallbackText: 'N' },
+ status: { label: 'disabled' },
+ },
+ actions: [{ id: 'enable', label: 'Enable' }],
+ };
+ function host(response: unknown) {
+ const invoke = vi.fn(async () => response);
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ return invoke;
+ }
+ it('keeps the selected Host instance, icon, localized name and actual enable state', async () => {
+ const invoke = host({ items: [item] });
+ const rows = await readLegacyManagedPlugins('old-host', 'zh-CN');
+ expect(rows).toEqual([
+ {
+ id: '_ns__team__notes',
+ name: '笔记',
+ description: 'Read and organize notes',
+ iconDataUrl: item.display.avatar.value,
+ enabled: false,
+ },
+ ]);
+ expect(invoke.mock.calls[0]).toMatchObject([
+ 'old-host',
+ expect.any(String),
+ [{ client: { locale: 'zh-CN' } }],
+ ]);
+ });
+ it('reads structured detail facts instead of discarding everything except fallback text', async () => {
+ const facts = {
+ tools: [{ name: 'read_notes', description: 'Read saved notes' }],
+ permissions: [{ title: 'Read notes', description: 'Only the declared notes service' }],
+ details: [{ key: 'author', title: 'Author', value: 'Example Team' }],
+ };
+ const invoke = host({
+ ...item,
+ blocks: [
+ { id: 'about', primitive: 'markdown', fallbackMarkdown: 'Full plugin description' },
+ { id: 'version', primitive: 'status', fallbackMarkdown: '1.2.3' },
+ { id: 'capabilities', primitive: 'plugin-capabilities', fallbackMarkdown: '', data: facts },
+ ],
+ });
+ expect(await readLegacyManagedPlugin('old-host', item.ref.id, 'zh-CN')).toEqual({
+ id: item.ref.id,
+ name: '笔记',
+ description: 'Full plugin description',
+ iconDataUrl: item.display.avatar.value,
+ enabled: false,
+ version: '1.2.3',
+ ...facts,
+ });
+ expect(invoke.mock.calls[0]).toMatchObject([
+ 'old-host',
+ expect.any(String),
+ [
+ {
+ client: { locale: 'zh-CN', primitives: expect.arrayContaining(['plugin-capabilities']) },
+ },
+ ],
+ ]);
+ });
+ it('leaves absent metadata and enable status unknown rather than fabricating facts', async () => {
+ host({ ...item, display: { title: 'Notes' }, actions: [], blocks: [] });
+ const detail = await readLegacyManagedPlugin('old-host', item.ref.id);
+ expect(detail).toMatchObject({ name: 'Notes', id: item.ref.id });
+ expect(detail.enabled).toBeUndefined();
+ expect(detail.version).toBeUndefined();
+ expect(detail.details).toBeUndefined();
+ expect(detail.permissions).toBeUndefined();
+ expect(detail.tools).toBeUndefined();
+ });
+ it('rejects another resource kind or collection with the same id', async () => {
+ host({ ...item, ref: { ...item.ref, collectionId: 'bots' }, blocks: [] });
+ await expect(readLegacyManagedPlugin('old-host', item.ref.id)).rejects.toThrow(
+ 'INVALID_RESPONSE',
+ );
+ });
+ it('ignores invalid optional detail groups without losing the readable plugin', async () => {
+ host({
+ ...item,
+ blocks: [
+ {
+ id: 'capabilities',
+ primitive: 'plugin-capabilities',
+ fallbackMarkdown: '',
+ data: {
+ tools: [{ name: 1 }],
+ permissions: [{ title: null }],
+ details: [{ key: 'author', value: [] }],
+ },
+ },
+ ],
+ });
+ const detail = await readLegacyManagedPlugin('old-host', item.ref.id);
+ expect(detail.name).toBe('Notes');
+ expect(detail.tools).toBeUndefined();
+ expect(detail.permissions).toBeUndefined();
+ expect(detail.details).toBeUndefined();
+ });
+ it('keeps readable fields when an optional action list has an invalid shape', async () => {
+ host({ items: [{ ...item, actions: {}, display: { title: 'Notes' } }] });
+ expect(await readLegacyManagedPlugins('old-host')).toEqual([
+ { id: item.ref.id, name: 'Notes', description: '' },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/useCatalogDevice.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/useCatalogDevice.test.tsx
new file mode 100644
index 0000000000..9d0173adcb
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/useCatalogDevice.test.tsx
@@ -0,0 +1,81 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { CatalogDeviceScope, useCatalogDevice } from '../useCatalogDevice';
+import { PluginDevicePicker } from '../PluginDevicePicker';
+
+const directory = vi.hoisted(() => ({ online: true }));
+vi.mock('../PluginDevicePicker', () => ({
+ usePluginDeviceDirectory: () => directory,
+ PluginDevicePicker: ({
+ onSelect,
+ }: {
+ onSelect(device: { deviceId: string; name: string }): void;
+ }) => (
+ <button onClick={() => onSelect({ deviceId: 'target', name: 'A' })}>Select computer</button>
+ ),
+}));
+afterEach(cleanup);
+
+let ownerId = 'owner';
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ dataOwnerId: ownerId, isAuthenticated: true }),
+}));
+function Page({ tab }: { tab: string }) {
+ const { device, selectDevice } = useCatalogDevice();
+ return (
+ <>
+ <output>
+ {tab}: {device?.name ?? 'local'}
+ </output>
+ <button onClick={() => selectDevice({ deviceId: 'target', name: 'A' })}>Select A</button>
+ </>
+ );
+}
+describe('shared Plugin and Skill host scope', () => {
+ it('keeps presence and the selected computer current while the installed picker is absent in detail', () => {
+ ownerId = 'owner';
+ setDataOwnerGeneration('owner');
+ directory.online = true;
+ const scoped = (detail = false) => (
+ <CatalogDeviceScope>
+ {(device, online, _generation, control) => (
+ <>
+ <output>
+ {device?.name ?? 'local'}: {online ? 'online' : 'offline'}
+ </output>
+ {!detail && control ? <PluginDevicePicker {...control} /> : null}
+ </>
+ )}
+ </CatalogDeviceScope>
+ );
+ const ui = render(scoped());
+ fireEvent.click(screen.getByText('Select computer'));
+ expect(screen.getByText('A: online')).toBeTruthy();
+ directory.online = false;
+ ui.rerender(scoped(true));
+ expect(screen.getByText('A: offline')).toBeTruthy();
+ expect(screen.queryByText('Select computer')).toBeNull();
+ ui.rerender(scoped());
+ expect(screen.getByText('A: offline')).toBeTruthy();
+ expect(screen.getByText('Select computer')).toBeTruthy();
+ });
+ it('retains the computer across separate page mounts and clears it across the account generation boundary', () => {
+ setDataOwnerGeneration('owner');
+ const first = render(<Page tab="Plugins" />);
+ fireEvent.click(screen.getByText('Select A'));
+ expect(screen.getByText('Plugins: A')).toBeTruthy();
+ first.unmount();
+ const skills = render(<Page tab="Skills" />);
+ expect(screen.getByText('Skills: A')).toBeTruthy();
+ setDataOwnerGeneration('owner');
+ skills.rerender(<Page tab="Skills" />);
+ expect(screen.getByText('Skills: local')).toBeTruthy();
+ fireEvent.click(screen.getByText('Select A'));
+ ownerId = 'other';
+ setDataOwnerGeneration('other');
+ skills.rerender(<Page tab="Skills" />);
+ expect(screen.getByText('Skills: local')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/remotePluginManagementClient.ts b/apps/desktop/src/renderer/features/plugin/remotePluginManagementClient.ts
new file mode 100644
index 0000000000..1720df65b7
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/remotePluginManagementClient.ts
@@ -0,0 +1,376 @@
+import {
+ REMOTE_RESOURCE_INVOKE_CHANNEL,
+ REMOTE_RESOURCE_MANIFEST_CHANNEL,
+ REMOTE_RESOURCE_LIST_CHANNEL,
+ REMOTE_RESOURCE_GET_CHANNEL,
+ REMOTE_RESOURCE_PROTOCOL_VERSION,
+ resolveRemoteText,
+ type RemoteCollectionItem,
+ type RemoteResource,
+ type RemoteText,
+ type RemoteActionInvokeResponse,
+} from '@cindy/device-link';
+import { validateNormalizedGhostManifest } from '../../../shared/ghost';
+import type {
+ PluginManagementReceipt,
+ PluginManagementSnapshot,
+ PluginManagementProjectState,
+ PluginManagementProject,
+} from '../../../shared/pluginManagement';
+import type { PluginMarketDetail } from '../../../shared/pluginMarket';
+import type { RemotePluginPreferenceSnapshot } from '../../../shared/pluginPreferences';
+
+const pluginManagementClient = {
+ protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,
+ primitives: ['status', 'markdown', 'action', 'form', 'list'],
+};
+/** Bound foreign Host declarations before any UI/manifest traversal. */
+export function boundedPluginResponse(
+ value: unknown,
+ depth = 0,
+ budget = { nodes: 50_000, chars: 8_000_000 },
+): boolean {
+ if (--budget.nodes < 0 || depth > 24) return false;
+ if (typeof value === 'string') return (budget.chars -= value.length) >= 0;
+ if (value === null || typeof value === 'boolean') return true;
+ if (typeof value === 'number') return Number.isFinite(value);
+ if (!value || typeof value !== 'object') return false;
+ return Object.entries(value).every(
+ ([key, child]) =>
+ !['__proto__', 'constructor', 'prototype'].includes(key) &&
+ boundedPluginResponse(child, depth + 1, budget),
+ );
+}
+export async function hasPluginManagement(deviceId: string): Promise<boolean> {
+ const manifest = await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ REMOTE_RESOURCE_MANIFEST_CHANNEL,
+ [{ client: pluginManagementClient }],
+ );
+ if (!boundedPluginResponse(manifest)) return false;
+ return !!(
+ manifest as { collections?: Array<{ id: string; actions?: Array<{ id: string }> }> }
+ ).collections?.some(
+ (c) => c.id === 'plugins' && c.actions?.some((a) => a.id === 'management:snapshot'),
+ );
+}
+export async function invokePluginManagement(
+ deviceId: string,
+ action: string,
+ input: Record<string, unknown> = {},
+ instance?: string,
+): Promise<unknown> {
+ const response = (await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ REMOTE_RESOURCE_INVOKE_CHANNEL,
+ [
+ {
+ client: pluginManagementClient,
+ collectionId: 'plugins',
+ actionId: `management:${action}`,
+ input,
+ ...(instance
+ ? { resourceRef: { collectionId: 'plugins', kind: 'plugin', id: instance } }
+ : {}),
+ },
+ ],
+ )) as RemoteActionInvokeResponse;
+ if (!boundedPluginResponse(response)) throw new Error('INVALID_RESPONSE');
+ return response.result;
+}
+export function parsePluginManagementSnapshot(value: unknown): PluginManagementSnapshot {
+ const data = value as PluginManagementSnapshot;
+ if (
+ !boundedPluginResponse(value) ||
+ data?.version !== 1 ||
+ !Array.isArray(data.ghosts) ||
+ !Array.isArray(data.market?.items) ||
+ !Array.isArray(data.market.customSourceNames) ||
+ !Array.isArray(data.market.unavailableCustomSourceNames) ||
+ (data.projects !== undefined &&
+ (!Array.isArray(data.projects) ||
+ !data.projects.every(
+ (project) =>
+ isPluginManagementProject(project),
+ ) ||
+ new Set(data.projects.map((project) => project.id)).size !== data.projects.length)) ||
+ (data.projectBrowse !== undefined && data.projectBrowse !== true) ||
+ !data.ghosts.every(
+ (g) =>
+ typeof g.instanceKey === 'string' &&
+ typeof g.enabled === 'boolean' &&
+ !!g.approval &&
+ validateNormalizedGhostManifest(g.manifest).ok,
+ ) ||
+ !data.market.items.every(
+ (i) =>
+ typeof i.pluginId === 'string' &&
+ typeof i.ghostId === 'string' &&
+ typeof i.releaseId === 'string' &&
+ typeof i.name === 'string',
+ )
+ )
+ throw new Error('INVALID_RESPONSE');
+ // Target-local icon keys cannot be resolved against this computer's market.
+ return {
+ ...data,
+ market: {
+ ...data.market,
+ items: data.market.items.map((item) => {
+ const safe = { ...item };
+ delete safe.customIconKey;
+ return safe;
+ }),
+ },
+ };
+}
+function isPluginManagementProject(project: PluginManagementProject): boolean {
+ return !!project && typeof project.id === 'string' && project.id.length > 0 &&
+ project.id.length <= 256 && typeof project.name === 'string' &&
+ (project.path === undefined || (typeof project.path === 'string' &&
+ project.path.length > 0 && project.path.length <= 32768 && !project.path.includes('\0')));
+}
+export function parsePluginManagementProject(value: unknown): PluginManagementProject {
+ if (!boundedPluginResponse(value) || !isPluginManagementProject(value as PluginManagementProject))
+ throw new Error('INVALID_RESPONSE');
+ return value as PluginManagementProject;
+}
+export function parsePluginManagementProjectState(
+ value: unknown,
+ projectId: string,
+): PluginManagementProjectState {
+ const state = value as PluginManagementProjectState;
+ if (
+ !boundedPluginResponse(value) ||
+ state?.projectId !== projectId ||
+ typeof state.revision !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(state.revision) ||
+ !Array.isArray(state.disabled) ||
+ !state.disabled.every((id) => typeof id === 'string' && id.length > 0 && id.length <= 256)
+ )
+ throw new Error('INVALID_RESPONSE');
+ return state;
+}
+
+export function parseRemotePluginPreferences(value: unknown): RemotePluginPreferenceSnapshot {
+ const data = value as RemotePluginPreferenceSnapshot;
+ if (
+ !boundedPluginResponse(value) ||
+ typeof data?.revision !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(data.revision) ||
+ (data.sidebarVisible !== undefined && typeof data.sidebarVisible !== 'boolean') ||
+ (data.auxiliaryModelLabel !== undefined &&
+ data.auxiliaryModelLabel !== null &&
+ typeof data.auxiliaryModelLabel !== 'string')
+ )
+ throw new Error('INVALID_RESPONSE');
+ if (
+ data.tasks &&
+ (typeof data.tasks.revision !== 'string' ||
+ !data.tasks.config ||
+ typeof data.tasks.config !== 'object' ||
+ Array.isArray(data.tasks.config) ||
+ !Array.isArray(data.tasks.permissionModes) ||
+ !data.tasks.permissionModes.every((mode) => typeof mode === 'string') ||
+ typeof data.tasks.defaultPermissionMode !== 'string')
+ )
+ throw new Error('INVALID_RESPONSE');
+ return data;
+}
+export function parsePluginManagementDetail(value: unknown): PluginMarketDetail {
+ const detail = value as PluginMarketDetail;
+ if (
+ !boundedPluginResponse(value) ||
+ typeof detail?.pluginId !== 'string' ||
+ !validateNormalizedGhostManifest(detail.manifest).ok
+ )
+ throw new Error('INVALID_RESPONSE');
+ const safe = { ...detail };
+ delete safe.customIconKey;
+ return safe;
+}
+export function parsePluginManagementReceipt(
+ value: unknown,
+ operationId: string,
+): PluginManagementReceipt {
+ if (!boundedPluginResponse(value)) throw new Error('INVALID_RESPONSE');
+ const receipt = value as PluginManagementReceipt;
+ const permissions = (items: unknown): boolean =>
+ Array.isArray(items) &&
+ items.every(
+ (item) => item && typeof item.key === 'string' && typeof item.labelKey === 'string',
+ );
+ const facts = receipt?.consent?.facts;
+ const validFacts =
+ !facts ||
+ (typeof facts.name === 'string' &&
+ typeof facts.version === 'string' &&
+ (facts.kind === 'install'
+ ? permissions(facts.permissions)
+ : facts.kind === 'update' &&
+ permissions(facts.added) &&
+ permissions(facts.removed) &&
+ Number.isSafeInteger(facts.unchangedCount)));
+ if (
+ !validFacts ||
+ receipt?.operationId !== operationId ||
+ !['running', 'confirmation', 'succeeded', 'cancelled', 'failed'].includes(receipt.phase) ||
+ (receipt.phase === 'confirmation' &&
+ (!receipt.consent?.requestId ||
+ !receipt.consent.facts ||
+ !['install', 'update'].includes(receipt.consent.facts.kind)))
+ )
+ throw new Error('INVALID_RESPONSE');
+ return receipt;
+}
+
+export interface LegacyManagedPlugin {
+ id: string;
+ name: string;
+ description: string;
+ iconDataUrl?: string;
+ enabled?: boolean;
+}
+export interface LegacyManagedPluginDetail extends LegacyManagedPlugin {
+ version?: string;
+ tools?: Array<{ name: string; description: string }>;
+ permissions?: Array<{ title: string; description: string }>;
+ details?: Array<{ key: string; title: string; value: string }>;
+}
+function remotePluginText(value: unknown, locale?: string): string | undefined {
+ if (typeof value === 'string') return value;
+ const text = value as Exclude<RemoteText, string> | undefined;
+ if (!text || typeof text.fallback !== 'string') return undefined;
+ return text.translations &&
+ Object.values(text.translations).every((entry) => typeof entry === 'string')
+ ? resolveRemoteText(text, locale)
+ : text.fallback;
+}
+function legacyPluginItem(item: RemoteCollectionItem, locale?: string): LegacyManagedPlugin | null {
+ const name = remotePluginText(item?.display?.title, locale);
+ if (
+ item?.ref?.collectionId !== 'plugins' ||
+ item.ref.kind !== 'plugin' ||
+ typeof item.ref.id !== 'string' ||
+ typeof item.revision !== 'string' ||
+ name === undefined
+ )
+ return null;
+ const status = remotePluginText(item.display.status?.label, locale);
+ const actions = Array.isArray(item.actions) ? item.actions : [];
+ const enabled = actions.some((action) => action?.id === 'disable')
+ ? true
+ : actions.some((action) => action?.id === 'enable')
+ ? false
+ : status === 'enabled'
+ ? true
+ : status === 'disabled'
+ ? false
+ : undefined;
+ const icon = item.display.avatar;
+ return {
+ id: item.ref.id,
+ name,
+ description: remotePluginText(item.display.subtitle, locale) ?? '',
+ ...(enabled !== undefined ? { enabled } : {}),
+ ...(icon?.kind === 'asset' &&
+ /^data:image\/(?:png|jpeg|webp|gif|svg\+xml)[;,]/i.test(icon.value)
+ ? { iconDataUrl: icon.value }
+ : {}),
+ };
+}
+export async function readLegacyManagedPlugins(
+ deviceId: string,
+ locale?: string,
+): Promise<LegacyManagedPlugin[]> {
+ const response = (await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ REMOTE_RESOURCE_LIST_CHANNEL,
+ [{ collectionId: 'plugins', client: { ...pluginManagementClient, locale } }],
+ )) as { items?: RemoteCollectionItem[] };
+ if (!boundedPluginResponse(response) || !Array.isArray(response?.items))
+ throw new Error('INVALID_RESPONSE');
+ return response.items.flatMap((item) => {
+ const plugin = legacyPluginItem(item, locale);
+ return plugin ? [plugin] : [];
+ });
+}
+async function readManagedPluginResource(
+ deviceId: string,
+ id: string,
+ locale?: string,
+): Promise<RemoteResource & { blocks: NonNullable<RemoteResource['blocks']> }> {
+ const response = (await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ REMOTE_RESOURCE_GET_CHANNEL,
+ [
+ {
+ ref: { collectionId: 'plugins', kind: 'plugin', id },
+ client: {
+ ...pluginManagementClient,
+ locale,
+ primitives: [...pluginManagementClient.primitives, 'plugin-capabilities'],
+ },
+ },
+ ],
+ )) as RemoteResource;
+ if (
+ !boundedPluginResponse(response) ||
+ response?.ref?.collectionId !== 'plugins' ||
+ response.ref.kind !== 'plugin' ||
+ response?.ref?.id !== id ||
+ !Array.isArray(response.blocks)
+ )
+ throw new Error('INVALID_RESPONSE');
+ return { ...response, blocks: response.blocks };
+}
+export async function readLegacyManagedPlugin(
+ deviceId: string,
+ id: string,
+ locale?: string,
+): Promise<LegacyManagedPluginDetail> {
+ const response = await readManagedPluginResource(deviceId, id, locale);
+ const plugin = legacyPluginItem(response, locale);
+ if (!plugin) throw new Error('INVALID_RESPONSE');
+ const capabilities = response.blocks.find(
+ (block) => block?.id === 'capabilities' && block.primitive === 'plugin-capabilities',
+ )?.data as Partial<LegacyManagedPluginDetail> | undefined;
+ const description = response.blocks.find((block) => block?.id === 'about')?.fallbackMarkdown;
+ const version = response.blocks.find((block) => block?.id === 'version')?.fallbackMarkdown;
+ const tools = capabilities?.tools;
+ const permissions = capabilities?.permissions;
+ const details = capabilities?.details;
+ return {
+ ...plugin,
+ description: typeof description === 'string' ? description : plugin.description,
+ ...(typeof version === 'string' && version ? { version } : {}),
+ ...(Array.isArray(tools) &&
+ tools.every(
+ (tool) =>
+ tool &&
+ typeof tool.name === 'string' &&
+ (tool.description === undefined || typeof tool.description === 'string'),
+ )
+ ? { tools: tools.map((tool) => ({ name: tool.name, description: tool.description ?? '' })) }
+ : {}),
+ ...(Array.isArray(permissions) &&
+ permissions.every(
+ (permission) =>
+ permission &&
+ typeof permission.title === 'string' &&
+ typeof permission.description === 'string',
+ )
+ ? { permissions: permissions.map(({ title, description }) => ({ title, description })) }
+ : {}),
+ ...(Array.isArray(details) &&
+ details.every(
+ (fact) =>
+ fact &&
+ typeof fact.key === 'string' &&
+ typeof fact.title === 'string' &&
+ typeof fact.value === 'string',
+ )
+ ? { details: details.map(({ key, title, value }) => ({ key, title, value })) }
+ : {}),
+ };
+}
diff --git a/apps/desktop/src/renderer/features/plugin/useCatalogDevice.tsx b/apps/desktop/src/renderer/features/plugin/useCatalogDevice.tsx
new file mode 100644
index 0000000000..57bc763ab2
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/useCatalogDevice.tsx
@@ -0,0 +1,65 @@
+import { useSyncExternalStore, type ReactNode } from 'react';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, type DataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { usePluginDeviceDirectory, type CatalogDeviceControl } from './PluginDevicePicker';
+export type { CatalogDeviceControl } from './PluginDevicePicker';
+
+export type CatalogDevice = { deviceId: string; name: string };
+let selection: { owner: DataOwnerGeneration; device: CatalogDevice | null } | null = null;
+const listeners = new Set<() => void>();
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+/** Plugins and Skills share only the selected host, never their local data stores. */
+export function useCatalogDevice() {
+ const { dataOwnerId, isAuthenticated } = useAuth();
+ const owner = getDataOwnerGeneration();
+ const snapshot = useSyncExternalStore(subscribe, () => selection);
+ const device =
+ isAuthenticated &&
+ snapshot?.owner.dataOwnerId === dataOwnerId &&
+ snapshot.owner.generation === owner.generation
+ ? snapshot.device
+ : null;
+ const selectDevice = (next: CatalogDevice | null) => {
+ selection = { owner: getDataOwnerGeneration(), device: next };
+ listeners.forEach((listener) => listener());
+ };
+ return { device, selectDevice, isAuthenticated, generation: owner.generation };
+}
+
+type CatalogContent = (
+ device: CatalogDevice | null,
+ online: boolean,
+ generation: number,
+ deviceControl?: CatalogDeviceControl,
+) => ReactNode;
+
+/** Share the host selection; each page places one menu in its page heading. */
+export function CatalogDeviceScope({ children }: { children: CatalogContent }) {
+ const scope = useCatalogDevice();
+ return scope.isAuthenticated ? (
+ <ConnectedCatalogScope scope={scope}>{children}</ConnectedCatalogScope>
+ ) : (
+ children(null, true, scope.generation)
+ );
+}
+
+function ConnectedCatalogScope({
+ scope,
+ children,
+}: {
+ scope: ReturnType<typeof useCatalogDevice>;
+ children: CatalogContent;
+}) {
+ const directory = usePluginDeviceDirectory(scope.device);
+ return children(scope.device, directory.online, scope.generation, {
+ selected: scope.device,
+ onSelect: scope.selectDevice,
+ directory,
+ });
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx b/apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx
new file mode 100644
index 0000000000..9c321b145b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx
@@ -0,0 +1,645 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ REMOTE_RESOURCE_CHANGED_CHANNEL,
+ parseRemoteResourceChangedPayload,
+} from '@cindy/device-link';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
+import { Button } from '@/components/ui/button';
+import { Select } from '@/components/ui/select';
+import { toast } from '@/lib/toast';
+import { CatalogManagementNotice } from '@/features/plugin/PluginManagementLayout';
+import type { CatalogDevice, CatalogDeviceControl } from '@/features/plugin/useCatalogDevice';
+import {
+ parseRemoteSkillReceipt,
+ type RemoteSkillItem,
+ type RemoteSkillMutation,
+ type RemoteSkillProject,
+ type RemoteSkillReceipt,
+ type RemoteSkillsSnapshot,
+} from '../../../shared/remoteSkills';
+import {
+ invokeRemoteSkills,
+ parseRemoteSkills,
+ remoteSkillsCapabilities,
+} from './remoteSkillsClient';
+import {
+ SkillhubTargetContext,
+ useSkillhubTarget,
+ type SkillhubTarget,
+ type SkillhubBrowseApi,
+} from './SkillhubTargetContext';
+import { SkillhubHomeContent } from './SkillhubHomeView';
+import { SkillhubMarketListView } from './SkillhubMarketListView';
+import { SkillhubDetailView } from './SkillhubDetailView';
+import { SkillhubMarketDetailView } from './SkillhubMarketDetailView';
+import { LocalSkillControls } from './components/LocalSkillControls';
+import { InstallTargetPicker } from './components/InstallTargetPicker';
+import { SkillDetailHeader, SkillDetailPage } from './components/SkillDetailLayout';
+import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
+import type { MarketSkill } from './hooks/useMarketList';
+import { marketInfoViewModel } from './lib/marketInfoViewModel';
+import { marketLocalCopies } from './lib/marketLocalCopies';
+
+type Detail = { localId?: string; market?: MarketSkill; showingMarket: boolean };
+
+/** The normal Skill pages, with a target-scoped store and fixed remote executors. */
+export function RemoteSkillsPage({
+ device,
+ online,
+ embedded,
+ active = true,
+ deviceControl,
+ onSelectCatalogTab,
+}: {
+ device: CatalogDevice;
+ online: boolean;
+ embedded?: boolean;
+ active?: boolean;
+ deviceControl?: CatalogDeviceControl;
+ onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void;
+}) {
+ const { t } = useTranslation();
+ const [snapshot, setSnapshot] = useState<RemoteSkillsSnapshot | null>(null);
+ const [capabilities, setCapabilities] = useState({ management: false, catalog: false });
+ const [status, setStatus] = useState<'readFailed' | 'unknown' | null>(null);
+ const [checked, setChecked] = useState(false);
+ const [page, setPage] = useState<'home' | 'market'>('home');
+ const [visitedMarket, setVisitedMarket] = useState(false);
+ const [detail, setDetail] = useState<Detail | null>(null);
+ const [receipt, setReceipt] = useState<RemoteSkillReceipt | null>(null);
+ const owner = useRef(getDataOwnerGeneration()).current;
+ const alive = useRef(true),
+ onlineRef = useRef(online),
+ revision = useRef(0);
+ onlineRef.current = online;
+ const operation = useRef<{ id: string; resolve(result: RemoteSkillReceipt): void } | null>(null);
+ const confirming = useRef(new Set<string>());
+ const snapshotRef = useRef(snapshot);
+ snapshotRef.current = snapshot;
+ const current = useCallback(() => alive.current && isDataOwnerGenerationCurrent(owner), [owner]);
+ const writable = useCallback(() => current() && onlineRef.current, [current]);
+ const invoke = useCallback(
+ (action: string, input?: Record<string, unknown>, item?: RemoteSkillItem) =>
+ invokeRemoteSkills(device.deviceId, action, input, item),
+ [device.deviceId],
+ );
+ const rootFor = useCallback(
+ (item: RemoteSkillItem) =>
+ `remote-skill/${encodeURIComponent(device.deviceId)}/${owner.generation}/${item.id}/${item.revision}`,
+ [device.deviceId, owner],
+ );
+ const toSkill = useCallback(
+ (item: RemoteSkillItem): SkillhubSkill => {
+ const root = rootFor(item);
+ const entryFile =
+ item.entryFile && !/[\\/]/.test(item.entryFile) && !['.', '..'].includes(item.entryFile)
+ ? item.entryFile
+ : item.kind === 'skill'
+ ? 'SKILL.md'
+ : `${item.name}.md`;
+ return {
+ id: item.id,
+ urlKey: item.id,
+ sourceKey: item.id,
+ engine: 'claude-code',
+ kind: item.kind,
+ scope: item.scope,
+ name: item.name,
+ description: item.description,
+ absolutePath: root,
+ discoveredPath: root,
+ mdPath: `${root}/${entryFile}`,
+ files: [],
+ projectRoot: item.projectId ? `remote-project/${item.projectId}` : item.project,
+ projectHash: item.projectId,
+ linkedEngines: item.engines.map((label) => ({ engine: 'claude-code' as const, label })),
+ cindyEnabled: item.enabled,
+ canUninstall: item.canUninstall,
+ managedByPlugin: item.managedByPlugin,
+ builtIn: item.builtIn,
+ registrySkillName: item.market?.name,
+ registryEntry: item.market
+ ? {
+ version: item.version ?? '',
+ catalogScope: item.market.catalogScope,
+ origin: item.market.origin ?? 'installed',
+ authorId: item.market.authorId ?? '',
+ folderHash: '',
+ installedAt: 0,
+ updatedAt: 0,
+ }
+ : null,
+ };
+ },
+ [rootFor],
+ );
+ const refresh = useCallback(async () => {
+ if (!writable()) return [];
+ const read = ++revision.current;
+ try {
+ const nextCapabilities = await remoteSkillsCapabilities(device.deviceId);
+ if (!writable() || read !== revision.current) return [];
+ setCapabilities(nextCapabilities);
+ setChecked(true);
+ if (!nextCapabilities.management) return [];
+ const next = parseRemoteSkills(await invoke('snapshot', { installedOnly: true }));
+ if (!writable() || read !== revision.current) return [];
+ setSnapshot(next);
+ snapshotRef.current = next;
+ setStatus((previous) => (previous === 'readFailed' ? null : previous));
+ return next.items.map(toSkill);
+ } catch {
+ if (writable() && read === revision.current) setStatus('readFailed');
+ return [];
+ }
+ }, [device.deviceId, invoke, toSkill, writable]);
+ const accept = useCallback(
+ (next: RemoteSkillReceipt) => {
+ if (!current() || next.operationId !== operation.current?.id) return;
+ setReceipt(next);
+ if (['succeeded', 'cancelled', 'failed'].includes(next.phase)) {
+ confirming.current.delete(next.operationId);
+ const pending = operation.current;
+ operation.current = null;
+ pending?.resolve(next);
+ setStatus(null);
+ if (next.phase === 'succeeded') void refresh();
+ }
+ },
+ [current, refresh],
+ );
+ const poll = useCallback(async () => {
+ const pending = operation.current;
+ if (!pending || !writable()) return;
+ try {
+ accept(
+ parseRemoteSkillReceipt(await invoke('operation', { operationId: pending.id }), pending.id),
+ );
+ } catch {
+ if (current() && operation.current === pending) setStatus('unknown');
+ }
+ }, [accept, current, invoke, writable]);
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ const pending = operation.current;
+ if (pending) {
+ pending.resolve({ operationId: pending.id, phase: 'cancelled' });
+ if (isDataOwnerGenerationCurrent(owner))
+ void invoke('cancel', { operationId: pending.id }).catch(() => {});
+ }
+ };
+ }, [invoke, owner]);
+ useEffect(() => {
+ if (!online) {
+ revision.current++;
+ return;
+ }
+ if (active) {
+ void refresh();
+ void poll();
+ }
+ }, [online, active, refresh, poll]);
+ useEffect(() => {
+ if (!online || !operation.current) return;
+ const timer = setInterval(() => {
+ void poll();
+ }, 1200);
+ return () => clearInterval(timer);
+ }, [online, receipt, poll]);
+ useEffect(() => {
+ if (!online || receipt?.phase !== 'confirmation' || confirming.current.has(receipt.operationId))
+ return;
+ const id = receipt.operationId;
+ confirming.current.add(id);
+ void window.electronAPI.deviceLink
+ .confirmSkillMutation(device.deviceId, id)
+ .then((result) => {
+ if (current()) accept(parseRemoteSkillReceipt(result, id));
+ })
+ .catch(() => {
+ confirming.current.delete(id);
+ if (current() && operation.current?.id === id) setStatus('unknown');
+ });
+ }, [online, receipt, device.deviceId, current, accept]);
+ useEffect(() => {
+ const focus = () => {
+ if (active) void refresh();
+ };
+ window.addEventListener('focus', focus);
+ const off = window.electronAPI.deviceLink.onRemotePush((push, stamp) => {
+ if (
+ active &&
+ push.deviceId === device.deviceId &&
+ push.channel === REMOTE_RESOURCE_CHANGED_CHANNEL &&
+ parseRemoteResourceChangedPayload(push.payload)?.collectionId === 'skills' &&
+ isDeviceLinkRemotePushCurrent(push, stamp)
+ )
+ void refresh();
+ });
+ return () => {
+ off();
+ window.removeEventListener('focus', focus);
+ };
+ }, [active, device.deviceId, refresh]);
+
+ const mutate = useCallback(
+ async (
+ kind: RemoteSkillMutation,
+ skill?: SkillhubSkill,
+ market?: { name: string; catalogScope?: 'market' | 'team'; latestVersion: string },
+ project?: RemoteSkillProject,
+ ) => {
+ if (!writable() || !capabilities.management || operation.current)
+ throw new Error('UNAVAILABLE');
+ const item = skill
+ ? snapshotRef.current?.items.find((entry) => entry.id === skill.id)
+ : undefined;
+ if (skill && !item) throw new Error('STALE_TARGET');
+ const id = crypto.randomUUID();
+ const completion = new Promise<RemoteSkillReceipt>((resolve) => {
+ operation.current = { id, resolve };
+ });
+ setReceipt({ operationId: id, phase: 'running' });
+ void (async () => {
+ try {
+ const next = parseRemoteSkillReceipt(
+ await invoke(
+ 'begin',
+ {
+ operationId: id,
+ kind,
+ ...(market
+ ? {
+ name: market.name,
+ catalogScope: market.catalogScope ?? 'market',
+ version: market.latestVersion,
+ }
+ : {}),
+ ...(project ? { projectId: project.id, projectRevision: project.revision } : {}),
+ },
+ item,
+ ),
+ id,
+ );
+ if (!current() || operation.current?.id !== id) return;
+ accept(next);
+ } catch {
+ if (current() && operation.current?.id === id) {
+ setReceipt({ operationId: id, phase: 'running' });
+ setStatus('unknown');
+ }
+ }
+ })();
+ return completion;
+ },
+ [accept, capabilities.management, current, device.deviceId, invoke, writable],
+ );
+ const api = useMemo<SkillhubBrowseApi>(() => {
+ const catalog = async <T,>(method: string, input: Record<string, unknown>): Promise<T> => {
+ if (!writable()) throw new Error('UNAVAILABLE');
+ const result = await invoke('catalog', { method, ...input });
+ if (!writable()) throw new Error('STALE_TARGET');
+ if (
+ !result ||
+ typeof result !== 'object' ||
+ typeof (result as { success?: unknown }).success !== 'boolean'
+ )
+ throw new Error('INVALID_RESPONSE');
+ return result as T;
+ };
+ const read = async <T,>(virtualPath: string, children: boolean): Promise<T> => {
+ if (!writable()) throw new Error('UNAVAILABLE');
+ const item = snapshotRef.current?.items.find(
+ (entry) => virtualPath === rootFor(entry) || virtualPath.startsWith(`${rootFor(entry)}/`),
+ );
+ if (!item) throw new Error('STALE_TARGET');
+ const relative = virtualPath.slice(rootFor(item).length).replace(/^\//, '');
+ if (!capabilities.catalog && !children && virtualPath === toSkill(item).mdPath) {
+ const result = (await invoke('detail', {}, item)) as { markdown?: unknown };
+ if (!writable() || typeof result?.markdown !== 'string')
+ throw new Error('INVALID_RESPONSE');
+ return { success: true, content: result.markdown } as T;
+ }
+ const result = await invoke(children ? 'children' : 'read-file', { path: relative }, item);
+ if (!writable()) throw new Error('STALE_TARGET');
+ return result as T;
+ };
+ return {
+ listMarket: (params) => catalog('list', { ...params, scope: params?.scope ?? 'market' }),
+ listCategories: (params) => catalog('categories', { scope: params?.scope ?? 'market' }),
+ info: (name, scope) => catalog('info', { name, scope: scope ?? 'market' }),
+ getPublishedFiles: ({ catalogScope, ...params }) =>
+ catalog('files', { ...params, scope: catalogScope ?? 'market' }),
+ readPublishedFile: ({ catalogScope, ...params }) =>
+ catalog('file', { ...params, scope: catalogScope ?? 'market' }),
+ getScanStatus: ({ slug, catalogScope, ...params }) =>
+ catalog('scan-status', { ...params, name: slug, scope: catalogScope ?? 'market' }),
+ listChildren: ({ dirPath }) => read(dirPath, true),
+ readSkill: ({ mdPath }) => read(mdPath, false),
+ readSiblingFile: ({ filePath }) => read(filePath, false),
+ };
+ }, [capabilities.catalog, invoke, rootFor, toSkill, writable]);
+ const skills = useMemo(() => (snapshot?.items ?? []).map(toSkill), [snapshot, toSkill]);
+ const projects = useMemo(
+ () =>
+ (snapshot?.projects ?? []).map((project) => ({
+ projectRoot: `remote-project/${project.id}`,
+ displayName: project.name,
+ hash: project.id,
+ target: project,
+ })),
+ [snapshot],
+ );
+ const state = useMemo<SkillhubTarget['state']>(
+ () => ({
+ skills,
+ projects,
+ sources: [],
+ loading: !snapshot,
+ error: status,
+ bootstrapped: !!snapshot,
+ learnSkillEnabled: false,
+ syncResults: new Map(),
+ syncError: null,
+ availableUninstalledCount: 0,
+ }),
+ [skills, projects, snapshot, status],
+ );
+ const target = useMemo<SkillhubTarget>(() => {
+ return {
+ name: device.name,
+ ready: online && capabilities.catalog,
+ writable: online && capabilities.management && !operation.current,
+ state,
+ projects,
+ api,
+ refresh,
+ current,
+ mutate,
+ openLocal: (skill) => setDetail({ localId: skill.id, showingMarket: false }),
+ openMarket: (market) => setDetail({ market, showingMarket: true }),
+ openMarketList: () => {
+ setVisitedMarket(true);
+ setPage('market');
+ },
+ back: () => {
+ if (detail) setDetail(null);
+ else setPage('home');
+ },
+ displayPath: (value) => {
+ const item = snapshot?.items.find(
+ (entry) => value === rootFor(entry) || value.startsWith(`${rootFor(entry)}/`),
+ );
+ const project = item?.project ? ` · ${item.project}` : '';
+ return item
+ ? `${device.name}${project} · ${item.name}${value.slice(rootFor(item).length)}`
+ : device.name;
+ },
+ };
+ }, [
+ snapshot,
+ state,
+ projects,
+ device.name,
+ online,
+ capabilities,
+ api,
+ refresh,
+ current,
+ mutate,
+ detail,
+ rootFor,
+ receipt,
+ ]);
+ const notice = (
+ <CatalogManagementNotice
+ className="mb-0"
+ title={t('settings.ghosts.remote.managingTarget', { device: device.name })}
+ warning={!online || !!status}
+ action={
+ online && (status || (checked && !capabilities.catalog)) ? (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ if (operation.current) void poll();
+ else void refresh();
+ }}
+ >
+ {t('settings.ghosts.remote.retry')}
+ </Button>
+ ) : null
+ }
+ >
+ {!online
+ ? t('settings.ghosts.remote.offlineNotice', { device: device.name })
+ : status
+ ? t(
+ status === 'readFailed'
+ ? 'skillhub.remote.readFailed'
+ : 'settings.ghosts.remote.unknown',
+ )
+ : checked && !capabilities.catalog
+ ? t('skillhub.remote.unsupported')
+ : !snapshot
+ ? t('skillhub.remote.loading')
+ : t('settings.ghosts.remote.managingDescription')}
+ </CatalogManagementNotice>
+ );
+ return (
+ <SkillhubTargetContext.Provider value={target}>
+ <div className="relative h-full min-h-0 w-full">
+ <div
+ className="absolute inset-0"
+ style={{ visibility: page === 'home' && !detail ? 'visible' : 'hidden' }}
+ aria-hidden={page !== 'home' || !!detail}
+ inert={page !== 'home' || !!detail}
+ >
+ <SkillhubHomeContent
+ deviceControl={deviceControl}
+ embedded={embedded}
+ active={active && page === 'home' && !detail}
+ onSelectCatalogTab={onSelectCatalogTab}
+ notice={notice}
+ />
+ </div>
+ {visitedMarket && (
+ <div
+ className="absolute inset-0"
+ style={{ visibility: page === 'market' && !detail ? 'visible' : 'hidden' }}
+ aria-hidden={page !== 'market' || !!detail}
+ inert={page !== 'market' || !!detail}
+ >
+ <SkillhubMarketListView active={active && page === 'market' && !detail} />
+ </div>
+ )}
+ {detail && (
+ <RemoteSkillDetail
+ key={detail.localId ?? `${detail.market?.catalogScope}:${detail.market?.name}`}
+ detail={detail}
+ onChange={setDetail}
+ />
+ )}
+ </div>
+ </SkillhubTargetContext.Provider>
+ );
+}
+
+/** Source switching and management use the same detail components as this computer. */
+function RemoteSkillDetail({
+ detail,
+ onChange,
+}: {
+ detail: Detail;
+ onChange(value: Detail): void;
+}) {
+ const target = useSkillhubTarget()!;
+ const { t } = useTranslation();
+ const explicit = target.state.skills.find((skill) => skill.id === detail.localId);
+ const [market, setMarket] = useState<MarketSkill | null>(detail.market ?? null);
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const update = useMarketSkillUpdate();
+ const reference = explicit?.registryEntry
+ ? {
+ name: explicit.registrySkillName ?? explicit.name,
+ catalogScope: explicit.registryEntry.catalogScope,
+ }
+ : detail.market;
+ useEffect(() => {
+ if (!reference || !target.ready) return;
+ let cancelled = false;
+ void target.api
+ .info(reference.name, reference.catalogScope)
+ .then((result) => {
+ if (!cancelled && result.success && result.info)
+ setMarket(marketInfoViewModel(result.info, explicit ?? null, reference.catalogScope));
+ })
+ .catch(() => {
+ if (!cancelled) toast.error(t('skillhub.unifiedDetail.marketUnavailable'));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ reference?.name,
+ reference?.catalogScope,
+ target.api,
+ target.ready,
+ explicit?.registryEntry?.version,
+ t,
+ ]);
+ const copies = market
+ ? marketLocalCopies(target.state.skills, market)
+ : explicit
+ ? [explicit]
+ : [];
+ const selected = explicit ?? copies[0];
+ const navigation = (
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-[var(--border-default)] px-4 py-2">
+ <div
+ className="flex items-center gap-1"
+ role="group"
+ aria-label={t('skillhub.unifiedDetail.contentSource')}
+ >
+ {selected && (
+ <Button
+ variant={detail.showingMarket ? 'secondary' : 'primary'}
+ aria-pressed={!detail.showingMarket}
+ onClick={() => onChange({ ...detail, localId: selected.id, showingMarket: false })}
+ >
+ {t('skillhub.unifiedDetail.local')}
+ </Button>
+ )}
+ {market && (
+ <Button
+ variant={detail.showingMarket ? 'primary' : 'secondary'}
+ aria-pressed={detail.showingMarket}
+ onClick={() => onChange({ ...detail, market, showingMarket: true })}
+ >
+ {t('skillhub.unifiedDetail.market')}
+ </Button>
+ )}
+ </div>
+ {copies.length > 1 && (
+ <Select
+ label={t('skillhub.sidebar.marketInstalledHeading')}
+ value={selected?.id ?? ''}
+ className="max-w-sm"
+ onValueChange={(id) => onChange({ ...detail, localId: id })}
+ options={copies.map((copy) => ({
+ value: copy.id,
+ label: `${
+ copy.scope === 'global'
+ ? t('skillhub.detail.scopeGlobal')
+ : (target.projects.find((project) => project.projectRoot === copy.projectRoot)
+ ?.displayName ?? '')
+ } · ${target.displayPath(copy.absolutePath)}`,
+ }))}
+ />
+ )}
+ {detail.showingMarket && selected && (
+ <span
+ className="min-w-0 truncate text-xs text-[var(--text-secondary)]"
+ title={target.displayPath(selected.absolutePath)}
+ >
+ {target.displayPath(selected.absolutePath)}
+ </span>
+ )}
+ </div>
+ );
+ if (!detail.showingMarket && selected)
+ return (
+ <SkillhubDetailView
+ entryOverride={selected}
+ renderNavigation={() => navigation}
+ onUninstalled={target.back}
+ />
+ );
+ if (!market)
+ return (
+ <SkillDetailPage>
+ <SkillDetailHeader
+ title={explicit?.name ?? detail.market?.name ?? ''}
+ backLabel={t('skillhub.detail.backToSkillhub')}
+ onBack={target.back}
+ />
+ {navigation}
+ </SkillDetailPage>
+ );
+ const currentMarket = marketInfoViewModel(market, selected ?? null, market.catalogScope);
+ return (
+ <>
+ <SkillhubMarketDetailView
+ skill={currentMarket}
+ onClose={target.back}
+ navigation={navigation}
+ primaryAction="clone"
+ onClone={() => setPickerOpen(true)}
+ learnSkillEnabled={false}
+ onUpdate={update.update}
+ updating={update.updatingNames.has(market.name)}
+ localActions={
+ selected ? (
+ <LocalSkillControls key={selected.id} skill={selected} disabled={!target.writable} />
+ ) : null
+ }
+ />
+ <InstallTargetPicker
+ open={pickerOpen}
+ skill={currentMarket}
+ onClose={() => setPickerOpen(false)}
+ onInstallComplete={() => {
+ setPickerOpen(false);
+ void target.refresh();
+ }}
+ />
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx
index 051b9b32ca..b29e8653a0 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx
@@ -13,26 +13,12 @@ import { InstallTargetPicker } from './components/InstallTargetPicker';
import { MarketManagementDialogs, useMarketManagement } from './hooks/useMarketManagement';
import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
-import { deriveLocalInstall, type MarketSkill } from './hooks/useMarketList';
+import { marketInfoViewModel } from './lib/marketInfoViewModel';
import { refresh, useSkillhub } from './hooks/useSkillhub';
import { buildLocalSkillRoute, findLocalSkillRouteEntry } from './lib/localRoutes';
import { buildMarketSkillRoute, skillDetailCatalog, skillDetailLocalParams, skillDetailReturnRoute, withSkillDetailReturn } from './lib/detailRoutes';
import { marketLocalCopies } from './lib/marketLocalCopies';
-function marketViewModel(info: SkillhubInfoResult, local: SkillhubSkill | null, catalogScope: MarketSkill['catalogScope']): MarketSkill {
- const primary = local ? {
- version: local.registryEntry?.version ?? null, absolutePath: local.absolutePath, hasRegistryEntry: !!local.registryEntry,
- } : undefined;
- const installed = deriveLocalInstall(info, primary ? { global: primary, projects: [] } : undefined);
- return {
- ...info, icon: info.icon ?? undefined, catalogScope, ...installed,
- authorAvatarUrl: null, avatarInitial: info.authorName.slice(0, 1),
- categories: info.categories ?? [], tags: info.tags ?? [], githubUrl: info.githubUrl ?? null,
- relativeTime: '', latestPublishedFromDeviceId: null,
- cardState: installed.updateAvailable ? 'installed-outdated' : installed.installedLocally ? 'installed-latest' : 'not-installed',
- };
-}
-
/** Both list entry points resolve identity here; content readers retain their own authority. */
export function SkillhubDetailRoute() {
const { t } = useTranslation();
@@ -78,7 +64,7 @@ export function SkillhubDetailRoute() {
? marketLocalCopies(skills, { ...info, isMine: info.isCreator === true, catalogScope })
: explicitLocal ? [explicitLocal] : [], [info, skills, explicitLocal, catalogScope]);
const selected = copies.find((copy) => copy.id === explicitLocal?.id) ?? copies[0] ?? null;
- const market = info ? marketViewModel(info, selected, catalogScope) : null;
+ const market = info ? marketInfoViewModel(info, selected, catalogScope) : null;
const selectSource = (view: 'local' | 'market', local: SkillhubSkill | null = selected, action?: 'publish') => {
if (!isDataOwnerGenerationCurrent(owner)) return;
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
index bfb0ff5a4e..7eef169433 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
@@ -85,6 +85,7 @@ import { type SkillUsageVersionComparison, selectSkillUsageVersionComparison } f
import { PublishDialog } from './PublishDialog';
import { ScanResultDialog } from './ScanResultDialog';
import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
+import { useSkillhubTarget, useSkillhubBrowseApi } from './SkillhubTargetContext';
import { usePublicationFeedback, useRejectionFeedback } from './hooks/useRejectionFeedback';
import { shouldHandlePublishProgressEvent } from './lib/publishProgressFilter';
import { SkillhubDiffPanel } from './SkillhubDiffPanel';
@@ -872,6 +873,7 @@ interface FileTreeRowProps {
}
function FileTreeRow({ entry, parentDir, depth, currentPath, onSelectFile }: FileTreeRowProps) {
const { t } = useTranslation();
+ const api = useSkillhubBrowseApi();
const fullPath = joinPath(parentDir, entry.name);
const [expanded, setExpanded] = useState(false);
const [children, setChildren] = useState<SkillhubFileEntry[] | null>(null);
@@ -883,7 +885,7 @@ function FileTreeRow({ entry, parentDir, depth, currentPath, onSelectFile }: Fil
setLoading(true);
setLoadError(null);
try {
- const res = await window.electronAPI.skillhub.listChildren({ dirPath: fullPath });
+ const res = await api.listChildren({ dirPath: fullPath });
if (res.success) setChildren(res.entries ?? []);
else setLoadError(res.error ?? t('skillhub.detail.fileTreeReadError'));
} catch (err) {
@@ -985,6 +987,8 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
onUninstalled?: () => void;
} = {}) {
const { t } = useTranslation();
+ const target = useSkillhubTarget();
+ const api = useSkillhubBrowseApi();
const { user } = useAuth();
const identityPolicy = useSkillhubIdentityPolicy(user);
const params = useParams();
@@ -995,8 +999,8 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
const commandPath = searchParams.get('path');
useEffect(() => {
// The palette can discover a newly added Skill before the SkillHub cache does.
- if (commandPath) void refreshSkillhub();
- }, [commandPath]);
+ if (commandPath && !target) void refreshSkillhub();
+ }, [commandPath, target === null]);
const { createSession } = useCCSessions();
// 入口来源:market 卡片会带 state.from。详情页返回不走浏览器式历史,
// 而是退出到 SkillHub 一级页:market 来源回 market,其它入口回 local 欢迎页。
@@ -1021,7 +1025,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// 记录最近访问项供下次打开 SkillHub 时恢复;返回按钮会清掉它,避免用户
// 主动退出详情页后又被 welcome 自动带回同一条记录。
useEffect(() => {
- if (!entry) return;
+ if (!entry || target) return;
if (shouldResetHistoryRef.current) clearHistory();
setLastEntryId(entry.id);
// shouldResetHistory 故意不进 deps —— 它是入口时刻的一次性信号,后续 entry
@@ -1048,6 +1052,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
setSaveError(null);
return;
}
+ if (target) return target.back();
clearLastEntryId();
clearHistory();
navigate(backTargetRoute, { state: { skillhubHome: navState?.skillhubHome } });
@@ -1071,15 +1076,15 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
? { ...entry, name: entryMarketName } : entry, [entry, entryMarketName]);
const entryCatalogScope = entry?.registryEntry?.catalogScope;
const [infoResult, setInfoResult] = useState<SkillhubInfoResult | null>(
- () => (entryMarketName ? getCachedInfo(entryMarketName, entryCatalogScope) : null),
+ () => (!target && entryMarketName ? getCachedInfo(entryMarketName, entryCatalogScope) : null),
);
const [infoLoading, setInfoLoading] = useState(false);
const [publishTargetInfo, setPublishTargetInfo] = useState<SkillhubInfoResult | null>(
- () => (entryMarketName && entryCatalogScope === 'team' ? getCachedInfo(entryMarketName) : null),
+ () => (!target && entryMarketName && entryCatalogScope === 'team' ? getCachedInfo(entryMarketName) : null),
);
const [publishTargetLoading, setPublishTargetLoading] = useState(false);
const [infoFetchTrigger, setInfoFetchTrigger] = useState(0);
- const { comparison: publishComparison, refresh: comparisonRefresh } = useSkillPublishComparison(infoResult?.isCreator === true ? entry : null);
+ const { comparison: publishComparison, refresh: comparisonRefresh } = useSkillPublishComparison(!target && infoResult?.isCreator === true ? entry : null);
// 同步重置:entry.name 变化时立刻把 infoResult 切到新 name 的缓存值。
// FadeSwitcher 按 feature 段(/skillhub)聚合 key,同 feature 内切 skill 不重挂,
@@ -1093,10 +1098,10 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
const [trackedEntryInfoKey, setTrackedEntryInfoKey] = useState<string | null>(entryInfoKey);
if (entryInfoKey !== trackedEntryInfoKey) {
setTrackedEntryInfoKey(entryInfoKey);
- const cached = entryMarketName ? getCachedInfo(entryMarketName, entryCatalogScope) : null;
+ const cached = !target && entryMarketName ? getCachedInfo(entryMarketName, entryCatalogScope) : null;
setInfoResult(cached);
setPublishTargetInfo(
- entryMarketName && entryCatalogScope === 'team' ? getCachedInfo(entryMarketName) : null,
+ !target && entryMarketName && entryCatalogScope === 'team' ? getCachedInfo(entryMarketName) : null,
);
setLiveScanStatus(null);
// 有缓存就不显示 loading(SWR 后台静默刷),没缓存才进 loading 态
@@ -1107,6 +1112,10 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
info: SkillhubInfoResult | null;
liveScanStatus: { status: string; version: string } | null;
}> => {
+ if (target) {
+ const result = await api.info(name, catalogScope);
+ return { info: result.success && result.info ? result.info : null, liveScanStatus: null };
+ }
const info = await refreshInfo(name, catalogScope);
if (!info) {
return { info: null, liveScanStatus: null };
@@ -1141,7 +1150,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
}
}
return { info, liveScanStatus: null };
- }, []);
+ }, [target === null, api]);
const remoteInfoName = isSkill ? (entryMarketName ?? null) : null;
const remoteInfoRequest = useMemo(() => {
@@ -1158,7 +1167,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
let cancelled = false;
// SWR:不再清空 infoResult。render 阶段已经 seed 过(缓存命中 → 旧值/缓存值;
// miss → null),这里只决定要不要显示 loading 态。后台 fetch 拿到新值再 setState。
- const cached = getCachedInfo(remoteInfoRequest.name, remoteInfoRequest.catalogScope);
+ const cached = target ? null : getCachedInfo(remoteInfoRequest.name, remoteInfoRequest.catalogScope);
if (cached === null) setInfoLoading(true);
refreshRemoteInfo(remoteInfoRequest.name, remoteInfoRequest.catalogScope)
.then((result) => {
@@ -1178,7 +1187,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// 组织目录条目可能来自只读代理,而发布始终写入原生 Hub。用无 scope
// 详情独立读取写入目标,避免拿组织目录的同名 Skill 判断首发/升级。
useEffect(() => {
- if (!remoteInfoRequest || remoteInfoRequest.catalogScope !== 'team') {
+ if (target || !remoteInfoRequest || remoteInfoRequest.catalogScope !== 'team') {
setPublishTargetLoading(false);
return;
}
@@ -1201,7 +1210,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// force=true:每次切换 entry 都强制重算,bypass 30s cache,
// 与下方 getInfo 一起组成"切换 entry 时的原子刷新"。
const { folderHash: localFolderHash, loading: hashLoading } = useSkillFolderHash(
- isSkill ? (entry?.absolutePath ?? null) : null,
+ !target && isSkill ? (entry?.absolutePath ?? null) : null,
{ force: true },
);
@@ -1214,7 +1223,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
const previousPublishOpenRef = useRef(publishOpen);
const deferredDoneRef = useRef(false);
publishOpenRef.current = publishOpen;
- const publishProgressName = isSkill ? (entryMarketName ?? null) : null;
+ const publishProgressName = !target && isSkill ? (entryMarketName ?? null) : null;
const publishProgressAbsolutePath = isSkill ? (entry?.absolutePath ?? null) : null;
const publishProgressTarget = useMemo(() => {
if (!publishProgressName || !publishProgressAbsolutePath) return null;
@@ -1299,18 +1308,18 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// 按钮区/banner 数据就绪:info 落定 + hash 算完即可,不再依赖批量 sync。
// 仅 isSkill 场景需要 hash;command/agent 直接视为 ready。
- const hashReady = !isSkill || (!hashLoading && localFolderHash !== null)
+ const hashReady = !!target || !isSkill || (!hashLoading && localFolderHash !== null)
|| publishComparison.status === 'same' || publishComparison.status === 'different'
|| publishComparison.status === 'unavailable';
const detailReady = !isSkill || (!infoLoading && !effectivePublishLoading && hashReady);
// 三维度 detail state
- const marketDeleted = !infoLoading && checkMarketDeleted(entryMarketName ?? '', entryCatalogScope);
+ const marketDeleted = !target && !infoLoading && checkMarketDeleted(entryMarketName ?? '', entryCatalogScope);
const detailState = useMemo<DetailState | null>(() => {
const state = deriveDetailState(isSkill ? entry : null, infoResult, marketDeleted);
return state;
}, [isSkill, entry, infoResult, marketDeleted]);
- const publishTargetDeleted = !effectivePublishLoading
+ const publishTargetDeleted = !target && !effectivePublishLoading
&& checkMarketDeleted(entryMarketName ?? '', entryCatalogScope === 'team' ? undefined : entryCatalogScope);
const publishDetailState = useMemo<DetailState | null>(() => (
deriveDetailState(isSkill ? entry : null, effectivePublishInfo, publishTargetDeleted)
@@ -1324,11 +1333,11 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
registryEntry,
localFolderHash,
publishedStatus,
- identityPolicy.canWrite && entry?.builtIn !== true,
+ !target && identityPolicy.canWrite && entry?.builtIn !== true,
publishDetailState,
publishComparison,
),
- [detailState, registryEntry, localFolderHash, publishedStatus, identityPolicy.canWrite, entry?.builtIn, publishDetailState, publishComparison],
+ [detailState, registryEntry, localFolderHash, publishedStatus, identityPolicy.canWrite, entry?.builtIn, publishDetailState, publishComparison, target === null],
);
const detailAction = detailActionState?.status ?? null;
const isOutdated = detailActionState?.isOutdated ?? false;
@@ -1339,7 +1348,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
entryKey: entryInfoKey,
name: entryMarketName ?? null,
version: publishedStatus === 'rejected' ? effectivePublishedStatusVersion(publishedStatusSource) : null,
- canManage: publishDetailState?.canManage === true,
+ canManage: !target && publishDetailState?.canManage === true,
});
// Diff panel state — 点 mine-dirty banner 时打开,看本地跟上次发布版的逐文件 diff
@@ -1371,7 +1380,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
const { confirm } = useConfirmDialog();
const openPublish = useCallback(async () => {
- if (entry?.kind !== 'skill' || entry.builtIn || !identityPolicy.canWrite) return;
+ if (target || entry?.kind !== 'skill' || entry.builtIn || !identityPolicy.canWrite) return;
if (isPublishedReviewing) {
const shouldProceed = await confirm({
@@ -1384,7 +1393,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
}
setPublishOpen(true);
- }, [entry, identityPolicy.canWrite, isPublishedReviewing, confirm, t]);
+ }, [entry, identityPolicy.canWrite, isPublishedReviewing, confirm, t, target === null]);
useEffect(() => {
if (searchParams.get('action') !== 'publish' || !detailReady
@@ -1414,6 +1423,16 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
}
setMarketActionRunning(true);
try {
+ if (target) {
+ const result = await target.mutate('update', entry, { name: entry.registrySkillName ?? entry.name,
+ catalogScope: entry.registryEntry?.catalogScope, latestVersion });
+ if (!target.current()) return;
+ if (result.phase === 'succeeded') {
+ toast.success(t('skillhub.detail.updatedToast', { name: entry.name, version: latestVersion }));
+ setInfoFetchTrigger((n) => n + 1);
+ } else if (result.phase !== 'cancelled') toast.error(t('skillhub.marketCard.updateFailed'));
+ return;
+ }
const res = await window.electronAPI.skillhub.install({
name: entry.registrySkillName ?? entry.name,
installPath: entry.absolutePath,
@@ -1439,7 +1458,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
} finally {
setMarketActionRunning(false);
}
- }, [entry, confirm, t]);
+ }, [entry, confirm, t, target]);
// viewingPath: which file's content is shown in the right pane.
// - default = entry.mdPath (the SKILL.md / command / agent file)
@@ -1467,12 +1486,12 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
}
let cancelled = false;
const dir = liveFilesRequest.dir;
- void window.electronAPI.skillhub.listChildren({ dirPath: dir }).then((res) => {
+ void api.listChildren({ dirPath: dir }).then((res) => {
if (cancelled) return;
if (res.success) setLiveFiles(res.entries ?? []);
- });
+ }).catch(() => { if (!cancelled) setLiveFiles([]); });
return () => { cancelled = true; };
- }, [liveFilesRequest]);
+ }, [liveFilesRequest, api]);
const [usageRefreshNonce, setUsageRefreshNonce] = useState(0);
const [diagnosisStarting, setDiagnosisStarting] = useState(false);
@@ -1483,7 +1502,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
error: null,
summary: null,
});
- const usageEntryId = entry?.kind === 'skill' ? entry.id : null;
+ const usageEntryId = !target && entry?.kind === 'skill' ? entry.id : null;
const usageSkillName = entry?.kind === 'skill' ? entry.name : null;
const usageSkillMdPath = entry?.kind === 'skill' ? entry.mdPath : null;
const usageTodayKey = useLocalTodayKey();
@@ -1535,12 +1554,12 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
}, [usageEntryId]);
const openDiagnosisAgentPicker = useCallback(() => {
- if (entry?.kind !== 'skill' || diagnosisStarting) return;
+ if (target || entry?.kind !== 'skill' || diagnosisStarting) return;
setDiagnosisAgentPickerOpen(true);
- }, [diagnosisStarting, entry?.kind]);
+ }, [diagnosisStarting, entry?.kind, target === null]);
const handleCreateDiagnosisSession = useCallback(async (agentKind: DiagnosisAgentKind) => {
- if (entry?.kind !== 'skill' || diagnosisStarting) return;
+ if (target || entry?.kind !== 'skill' || diagnosisStarting) return;
setDiagnosisStarting(true);
try {
const res = await window.electronAPI.skillhub.getUsageDiagnosisContext({
@@ -1579,7 +1598,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
} finally {
setDiagnosisStarting(false);
}
- }, [createSession, diagnosisStarting, entry, navigate, t]);
+ }, [createSession, diagnosisStarting, entry, navigate, t, target === null]);
// Leave-guard wrapper for switching the viewing file. Used by the FILES
// tree row clicks. If editing with unsaved changes, prompt; otherwise
@@ -1609,7 +1628,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// by `editButtonState` so the click handler can assume viewingPath is a
// valid .md.
const enterEditMode = useCallback(async () => {
- if (!viewingPath) return;
+ if (target || !viewingPath) return;
setSaveError(null);
try {
const res = await window.electronAPI.skillhub.readRaw({ filePath: viewingPath });
@@ -1623,7 +1642,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
- }, [viewingPath, t]);
+ }, [viewingPath, t, target === null]);
// Save the editor's current value back to disk. Re-validates frontmatter
// (warn-only — doesn't block save), invalidates folderHash to drive the
@@ -1633,7 +1652,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// isMd flag still gates frontmatter cache-strip + validation below
// (those rules are tied to the FILE TYPE, not the editor used).
const saveEdit = useCallback(async () => {
- if (!viewingPath || !entry || !plaintextEditorRef.current) return;
+ if (target || !viewingPath || !entry || !plaintextEditorRef.current) return;
const isMd = MD_EXTENSION_RE.test(viewingPath);
const next = plaintextEditorRef.current.getValue();
setSaving(true);
@@ -1706,7 +1725,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
} finally {
setSaving(false);
}
- }, [viewingPath, entry, t]);
+ }, [viewingPath, entry, t, target === null]);
// Cancel — leave guard prompts on dirty, then drops back to view mode.
const cancelEdit = useCallback(async () => {
@@ -1721,7 +1740,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// truth so the JSX below can read `state.disabled` / `state.tip` without
// re-doing the branching.
const editButtonState = useMemo(() => {
- if (!entry || !viewingPath) {
+ if (target || !entry || !viewingPath) {
return { hidden: true, disabled: true, tip: '' };
}
// v0.2.2 only ships skill + command edit. agent stays read-only — the
@@ -1750,7 +1769,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
disabled: false,
tip: isMd ? t('skillhub.detail.editTipMarkdown') : t('skillhub.detail.editTipPlaintext'),
};
- }, [entry, viewingPath, detailState, isOutdated, t]);
+ }, [entry, viewingPath, detailState, isOutdated, t, target === null]);
// Body content — fetched lazily per viewingPath. State initializes
// synchronously from contentCache so re-visiting a previously-loaded
@@ -1786,8 +1805,8 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
// a code fence below.
const isMarkdown = viewingPath.toLowerCase().endsWith('.md');
const promise = isMarkdown
- ? window.electronAPI.skillhub.readSkill({ mdPath: viewingPath })
- : window.electronAPI.skillhub.readSiblingFile({ filePath: viewingPath });
+ ? api.readSkill({ mdPath: viewingPath })
+ : api.readSiblingFile({ filePath: viewingPath });
void promise
.then((res) => {
@@ -1806,7 +1825,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
})
.catch((err) => {
if (cancelled) return;
- const msg = err instanceof Error ? err.message : String(err);
+ const msg = target ? t('skillhub.detail.readFailed') : err instanceof Error ? err.message : String(err);
setContentErrorCache(viewingPath, msg);
setContent('');
setContentError(msg);
@@ -1818,7 +1837,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
return () => {
cancelled = true;
};
- }, [viewingPath, t]);
+ }, [viewingPath, t, api, target === null]);
if (!entry) {
return (
@@ -1880,7 +1899,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
: null;
return (
<span
- key={le.engine}
+ key={`${le.engine}:${le.label}`}
className={cn(
'inline-flex h-5 shrink-0 items-center rounded-full px-2 whitespace-nowrap',
'bg-[var(--settings-btn-secondary-bg)] text-[var(--msg-assistant-text)]',
@@ -1910,6 +1929,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
subtitle={
<button
type="button"
+ disabled={!!target}
onClick={() => {
// Skill entries are folders → open the folder itself so the
// user lands inside it. Commands / agents are single .md files
@@ -1930,7 +1950,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
title=""
aria-label={entry.kind === 'skill' ? t('skillhub.detail.openDirAria') : t('skillhub.detail.showInFolderAria')}
>
- {entry.absolutePath}
+ {target?.displayPath(entry.absolutePath) ?? entry.absolutePath}
</button>
}
backLabel={backLabel}
@@ -1993,8 +2013,10 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
{entry && (
<LocalSkillControls skill={entry} disabled={marketActionRunning || editMode}
onUninstalled={() => {
- clearLastEntryId();
- clearHistory();
+ if (!target) {
+ clearLastEntryId();
+ clearHistory();
+ }
if (onUninstalled) onUninstalled();
else navigate(backTargetRoute, { state: { skillhubHome: navState?.skillhubHome } });
}} />
@@ -2306,7 +2328,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
);
})()}
</section>
- <SkillUsagePanel
+ {!target && <SkillUsagePanel
summary={usageState.entryId === entry.id ? usageState.summary : null}
loading={usageState.entryId === entry.id && usageState.loading}
error={usageState.entryId === entry.id ? usageState.error : null}
@@ -2314,7 +2336,7 @@ export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstal
diagnoseDisabled={usageState.entryId !== entry.id || usageState.loading}
todayKey={usageTodayKey}
onDiagnose={openDiagnosisAgentPicker}
- />
+ />}
{/* Resize handle — same pattern as the main sidebar: 4px transparent
hit area, 1px highlight line on hover, double-click to reset. */}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
index c2c600b08c..c956d605f3 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
@@ -18,7 +18,7 @@
*/
import { useEffect, useMemo, useRef } from 'react';
-import { Outlet } from 'react-router-dom';
+import { Outlet, useMatch } from 'react-router-dom';
import { skillhubCatalogKey } from '../../../shared/skillhubCatalog';
import { normalizeWorkingDirForStorage } from '../../../shared/workingDir';
@@ -39,6 +39,12 @@ import {
import { useSkillSync } from './hooks/useSkillSync';
import { projectHash } from './lib/projectHash';
import { useAuth } from '@/contexts/AuthContext';
+import { useCatalogDevice } from '@/features/plugin/useCatalogDevice';
+
+export function LocalSkillhubStoreSync() {
+ useSkillhubStoreSync();
+ return null;
+}
/** Shared SkillHub store sync. Settings embeds the home view without the route layout. */
export function useSkillhubStoreSync(): void {
@@ -167,10 +173,12 @@ export function SkillhubFeatureLayout() {
// 类型,只 reconcile、不 remount(实例状态保留);冷启动直接进 /skillhub 时则首次
// 播种,避免左栏空白(详见 useRegisterCCAgentSidebar)。
useRegisterCCAgentSidebar();
- useSkillhubStoreSync();
+ const { device } = useCatalogDevice();
+ const showingCatalog = useMatch({ path: '/skillhub/local', end: true }) !== null;
return (
<div className="flex h-full w-full flex-col">
+ {!device || !showingCatalog ? <LocalSkillhubStoreSync /> : null}
<Outlet />
</div>
);
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
index 2065b3aa6d..682d21f7ee 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
@@ -1,4 +1,6 @@
import { Button } from '@/components/ui/button';
+import { CatalogDeviceScope, type CatalogDeviceControl } from '@/features/plugin/useCatalogDevice';
+import { useSkillhubTarget } from './SkillhubTargetContext';
/**
* SkillhubHomeView — 技能(SkillHub)首页,/skillhub/local index。
*
@@ -9,7 +11,7 @@ import { Button } from '@/components/ui/button';
import { buildMarketSkillRoute, withSkillDetailReturn } from './lib/detailRoutes';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useNavigate, useSearchParams, type Location } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { skillhubCatalogKey } from '../../../shared/skillhubCatalog';
@@ -32,6 +34,7 @@ import {
PLUGIN_MANAGEMENT_CARD_GRID_CLASS,
PluginManagementLayout,
PluginManagementPage,
+ CatalogTargetControls,
} from '@/features/plugin/PluginManagementLayout';
import { buildLocalSkillRoute, findLocalSkillByPath } from './lib/localRoutes';
import {
@@ -64,6 +67,8 @@ import { OfficialSkillBadge } from './components/OfficialSkillBadge';
import { useSkillhubHomeNavigation } from './hooks/useSkillhubHomeNavigation';
import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
+import './skillhub-home.css';
+
const KIND_ICON: Record<string, LucideIcon> = {
skill: Package,
command: SquareTerminal,
@@ -75,18 +80,54 @@ function includesSkillQuery(values: ReadonlyArray<string | undefined>, query: st
return values.some((value) => value?.toLocaleLowerCase().includes(query));
}
-export function SkillhubHomeView({
+const RemoteSkillsPage = lazy(() => import('./RemoteSkillsPage').then((module) => ({ default: module.RemoteSkillsPage })));
+
+export function SkillhubHomeView(
+ props: {
+ embedded?: boolean;
+ active?: boolean;
+ navigationLocation?: Location;
+ onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void;
+ } = {},
+) {
+ return (
+ <CatalogDeviceScope>
+ {(device, online, generation, deviceControl) =>
+ device ? (
+ <Suspense fallback={null}><RemoteSkillsPage
+ key={`${generation}:${device.deviceId}`}
+ device={device}
+ online={online}
+ deviceControl={deviceControl}
+ embedded={props.embedded}
+ active={props.active}
+ onSelectCatalogTab={props.onSelectCatalogTab}
+ /></Suspense>
+ ) : (
+ <SkillhubHomeContent deviceControl={deviceControl} {...props} />
+ )
+ }
+ </CatalogDeviceScope>
+ );
+}
+
+export function SkillhubHomeContent({
+ deviceControl,
+ notice,
embedded = false,
active = true,
navigationLocation,
onSelectCatalogTab,
}: {
+ deviceControl?: CatalogDeviceControl;
+ notice?: ReactNode;
embedded?: boolean;
active?: boolean;
navigationLocation?: Location;
onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void;
} = {}) {
const { t } = useTranslation();
+ const target = useSkillhubTarget();
const navigate = useNavigate();
const [initialSearch] = useSearchParams();
const { skills, projects, bootstrapped, syncResults } = useSkillhub();
@@ -220,15 +261,16 @@ export function SkillhubHomeView({
const returnTo = `/skillhub/local?${new URLSearchParams({ tab: catalogTab, q: query, category: categoryFilter })}`;
const openLocal = (local: SkillhubSkill) => {
+ if (target) return target.openLocal(local);
const route = withSkillDetailReturn(buildLocalSkillRoute(local), returnTo);
navigate(route, { state: { from: '/skillhub/local', resetHistory: true, skillhubHome: { catalogTab, query } } });
};
- const openMarket = () => navigate('/skillhub/market');
- const openCatalogSkill = (skill: MarketSkill) => navigate(buildMarketSkillRoute(skill, returnTo));
+ const openMarket = () => target ? target.openMarketList() : navigate('/skillhub/market');
+ const openCatalogSkill = (skill: MarketSkill) => target ? target.openMarket(skill) : navigate(buildMarketSkillRoute(skill, returnTo));
const homeCatalogTabs = visibleHomeCatalogTabs(showOrganization);
const handleImportSkill = useCallback(async () => {
- if (importBusy) return;
+ if (target || importBusy) return;
setImportBusy(true);
try {
const picked = await window.electronAPI.skillhub.pickLocal();
@@ -250,13 +292,15 @@ export function SkillhubHomeView({
} finally {
setImportBusy(false);
}
- }, [importBusy, t]);
+ }, [importBusy, t, target]);
const closeImportPicker = useCallback(() => {
setImportPickerOpen(false);
setImportGrantToken(null);
setImportTarget(null);
}, []);
+ const showMarketCatalog = catalogTab !== 'local' &&
+ (!normalizedQuery || catalogItems.length > 0 || marketLoading || marketError);
return (
<PluginManagementLayout
@@ -274,7 +318,7 @@ export function SkillhubHomeView({
loading={importBusy}
type="button"
onClick={() => void handleImportSkill()}
- disabled={importBusy}
+ disabled={importBusy || !!target}
aria-label={t('skillhub.home.importAria')}
className="plugin-management-action-trigger shrink-0 shadow-[var(--plugin-card-shadow)]"
>
@@ -290,23 +334,31 @@ export function SkillhubHomeView({
)}
>
<main className="h-full overflow-x-hidden overflow-y-auto [scrollbar-gutter:stable_both-edges]">
- <PluginManagementPage className="gap-8">
- <header className="plugin-motion-page-header flex flex-wrap items-start justify-between gap-4">
- <div className="min-w-0 pt-1">
- <h1 className="text-28 font-medium leading-tight text-[var(--text-primary)]">
- {t('skillhub.home.title')}
- </h1>
- <p className="mt-2 max-w-2xl text-14 leading-6 text-[var(--text-secondary)]">
- {t('skillhub.home.description')}
- </p>
+ <PluginManagementPage className="gap-5">
+ <header className="plugin-motion-page-header flex flex-col gap-3" data-catalog-region="heading">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0 flex-1 basis-72 pt-1">
+ <h1 className="text-28 font-medium leading-tight text-[var(--text-primary)]">
+ {t('skillhub.home.title')}
+ </h1>
+ <p className="mt-2 max-w-2xl text-14 leading-6 text-[var(--text-secondary)]">
+ {t('skillhub.home.description')}
+ </p>
+ </div>
+ {deviceControl && <CatalogTargetControls computer={deviceControl} />}
</div>
- <div className="flex min-w-0 max-w-full flex-wrap items-center justify-end gap-1" style={WINDOW_NO_DRAG_STYLE}>
+ {notice}
+ </header>
+
+ <div className="flex min-w-0 flex-col gap-3" data-catalog-region="filters">
+ <div className="flex min-w-0 items-center justify-between gap-2 border-b border-[var(--border-default)]" style={WINDOW_NO_DRAG_STYLE}>
<SegmentedControl
+ className="skill-catalog-source-tabs min-w-0"
role="radiogroup"
aria-label={t('skillhub.home.catalogFiltersAria')}
- height={32}
- optionHeight={28}
- optionClassName="px-3.5 text-12"
+ height={40}
+ optionHeight={40}
+ optionClassName="px-1 text-13"
value={catalogTab}
onValueChange={(tab) => {
setCatalogTab(tab);
@@ -320,38 +372,32 @@ export function SkillhubHomeView({
}))}
/>
<button
- type="button"
- onClick={openMarket}
- className={cn(
- 'inline-flex shrink-0 items-center gap-1 rounded-full px-3.5 py-2 text-12 text-[var(--text-secondary)]',
- 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- )}
- >
- {t('skillhub.home.catalogMore')}
- <ChevronRight size={13} strokeWidth={1.8} aria-hidden="true" />
+ type="button"
+ onClick={openMarket}
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-1 rounded-full px-3.5 py-2 text-12 text-[var(--text-secondary)]',
+ 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ {t('skillhub.home.catalogMore')}
+ <ChevronRight size={13} strokeWidth={1.8} aria-hidden="true" />
</button>
</div>
- </header>
+ {showMarketCatalog && categories.length > 0 ? (
+ <SkillCategoryFilterBar
+ categories={categories}
+ selectedCategory={categoryFilter}
+ allLabel={t('skillhub.market.categoryAll')}
+ ariaLabel={t('skillhub.home.categoryFiltersAria')}
+ onSelectCategory={setCategoryFilter}
+ />
+ ) : null}
+ </div>
{/* ① 当前云端目录摘要 */}
- {catalogTab !== 'local' && (!normalizedQuery || catalogItems.length > 0 || marketLoading || marketError) ? (
+ {showMarketCatalog ? (
<section className="plugin-motion-page-section min-w-0">
- {categories.length > 0 ? (
- <SkillCategoryFilterBar
- categories={categories}
- selectedCategory={categoryFilter}
- allLabel={t('skillhub.market.categoryAll')}
- ariaLabel={t('skillhub.home.categoryFiltersAria')}
- scrollLeftLabel={t('skillhub.home.scrollCategoriesLeft')}
- scrollRightLabel={t('skillhub.home.scrollCategoriesRight')}
- scrollStartLabel={t('skillhub.home.categoryScrollAtStart')}
- scrollEndLabel={t('skillhub.home.categoryScrollAtEnd')}
- onSelectCategory={setCategoryFilter}
- className="mb-4"
- />
- ) : null}
-
<MarketListError error={marketError} loading={marketLoading} onRetry={reloadMarket} />
{(marketLoading || !marketResponseCurrent) && catalogItems.length === 0 ? (
// 占位骨架:与真实卡片同栅格、同行数、同高度,内容到位后原地替换不跳动。
@@ -418,7 +464,7 @@ export function SkillhubHomeView({
<LocalGroup
skills={globalSkills}
syncResults={syncResults}
- active={active}
+ active={active && !target}
onOpen={openLocal}
/>
)}
@@ -428,7 +474,7 @@ export function SkillhubHomeView({
label={g.label}
skills={g.skills}
syncResults={syncResults}
- active={active}
+ active={active && !target}
onOpen={openLocal}
/>
))}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx
index 306f5b1da6..364cd1d6e0 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx
@@ -38,6 +38,7 @@ import { MarketLocalSkills } from './components/MarketLocalSkills';
import { ManageMenu, type MarketCardManageAction } from './components/MarketCard';
import { ScanResultDialog } from './ScanResultDialog';
import type { ScanResultPayload } from './PublishDialog';
+import { useSkillhubBrowseApi } from './SkillhubTargetContext';
interface SkillhubMarketDetailViewProps {
skill: MarketSkill | null;
@@ -73,6 +74,7 @@ export function SkillhubMarketDetailView({
learnSkillEnabled = true,
}: SkillhubMarketDetailViewProps) {
const { t } = useTranslation();
+ const api = useSkillhubBrowseApi();
const navigate = useNavigate();
const metaResize = useMetaColumnResize();
const { dataOwnerId } = useAuth();
@@ -116,7 +118,7 @@ export function SkillhubMarketDetailView({
setFile(null);
setFilesError(null);
setSelectedPath(null);
- void window.electronAPI.skillhub
+ void api
.getPublishedFiles({ name: skillName, version: skillVersion, catalogScope: skill?.catalogScope })
.then((res) => {
if (cancelled) return;
@@ -137,7 +139,7 @@ export function SkillhubMarketDetailView({
return () => {
cancelled = true;
};
- }, [panelOpen, skill?.catalogScope, skillName, skillVersion, t]);
+ }, [panelOpen, skill?.catalogScope, skillName, skillVersion, t, api]);
useEffect(() => {
if (!panelOpen || !skillName || !selectedPath) {
@@ -148,7 +150,7 @@ export function SkillhubMarketDetailView({
let cancelled = false;
// 不预清空 file:切换文件时保留旧内容直到新内容到达,避免空白帧
setFileLoading(true);
- void window.electronAPI.skillhub
+ void api
.readPublishedFile({ name: skillName, path: selectedPath, version: skillVersion, catalogScope: skill?.catalogScope })
.then((res) => {
if (cancelled) return;
@@ -168,7 +170,7 @@ export function SkillhubMarketDetailView({
return () => {
cancelled = true;
};
- }, [panelOpen, selectedPath, skill?.catalogScope, skillName, skillVersion, t]);
+ }, [panelOpen, selectedPath, skill?.catalogScope, skillName, skillVersion, t, api]);
const tree = useMemo(() => buildPreviewTree(files), [files]);
const currentScanResult = scanResultOwner && isDataOwnerGenerationCurrent(scanResultOwner) ? scanResult : null;
@@ -199,7 +201,7 @@ export function SkillhubMarketDetailView({
if (!isDataOwnerGenerationCurrent(owner)) return;
const requestId = ++scanRequestId.current;
const isCurrentRequest = () => requestId === scanRequestId.current && isDataOwnerGenerationCurrent(owner);
- void window.electronAPI.skillhub
+ void api
.getScanStatus({
slug: skill.name,
version: reviewVersion,
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
index 823ebdd2f3..ae708bb6c0 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
@@ -31,6 +31,7 @@ import { useAuth } from '@/contexts/AuthContext';
import { CATEGORY_ALL } from '../../../shared/skillhubCategory';
import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
+import { useSkillhubTarget } from './SkillhubTargetContext';
// Must match the global native scrollbar width in styles/globals.css.
const MARKET_SCROLLBAR_GUTTER_PX = 12;
@@ -42,12 +43,13 @@ const SORT_OPTIONS: Array<{ value: SortBy; labelKey: string }> = [
{ value: 'created_at', labelKey: 'skillhub.market.sortCreated' },
];
-export function SkillhubMarketListView() {
- return <SkillhubMarketListViewInner />;
+export function SkillhubMarketListView({ active = true }: { active?: boolean } = {}) {
+ return <SkillhubMarketListViewInner active={active} />;
}
-function SkillhubMarketListViewInner() {
+function SkillhubMarketListViewInner({ active }: { active: boolean }) {
const { t } = useTranslation();
+ const target = useSkillhubTarget();
const { user, isInitializing } = useAuth();
const identityPolicy = useSkillhubIdentityPolicy(user);
const { update, updatingNames, isUpdating } = useMarketSkillUpdate();
@@ -76,6 +78,7 @@ function SkillhubMarketListViewInner() {
loadMore,
reload,
} = useMarketList(initialVisibility, {
+ enabled: active,
initialScope: 'market',
initialSort: SORT_OPTIONS.find((option) => option.value === initialSearch.get('sort'))?.value,
initialSearchQuery: initialSearch.get('q') ?? '',
@@ -145,6 +148,7 @@ function SkillhubMarketListViewInner() {
// 订阅 install progress 事件:done 时 refresh 本地 scan + toast
useEffect(() => {
+ if (target) return;
const unsubscribe = window.electronAPI.skillhub.onInstallProgress((event) => {
if (event.phase === 'done') {
void refreshSkillhub();
@@ -159,21 +163,21 @@ function SkillhubMarketListViewInner() {
}
});
return unsubscribe;
- }, [isUpdating, t]);
+ }, [isUpdating, t, target === null]);
const sortLabel = useMemo(() => {
return t(SORT_OPTIONS.find((option) => option.value === sortBy)?.labelKey ?? 'skillhub.market.sortLatest');
}, [sortBy, t]);
const returnTo = `/skillhub/market?${new URLSearchParams({ q: searchQuery, sort: sortBy, category: categoryFilter, visibility })}`;
- const handleCardClick = (skill: MarketSkill) => navigate(buildMarketSkillRoute(skill, returnTo));
+ const handleCardClick = (skill: MarketSkill) => target ? target.openMarket(skill) : navigate(buildMarketSkillRoute(skill, returnTo));
const handleClone = (skill: MarketSkill) => {
setPickerSkill(skill);
setPickerOpen(true);
};
const management = useMarketManagement({
- active: isMineView,
+ active: isMineView && !target,
reload,
onClone: handleClone,
});
@@ -189,7 +193,7 @@ function SkillhubMarketListViewInner() {
listVisibility: visibility,
cardState: skill.cardState,
});
- return action === 'manage' && !identityPolicy.canWrite ? 'clone' : action;
+ return action === 'manage' && (target || !identityPolicy.canWrite) ? 'clone' : action;
})()
: 'none'}
allowPrivateVisibilityLabel={visibility === 'mine'}
@@ -219,7 +223,7 @@ function SkillhubMarketListViewInner() {
这里在工具栏补一个返回入口。 */}
<button
type="button"
- onClick={() => navigate('/skillhub/local')}
+ onClick={() => target ? target.back() : navigate('/skillhub/local')}
aria-label={t('skillhub.sidebar.backToLocal')}
title={t('skillhub.sidebar.backToLocal')}
className="flex size-9 shrink-0 items-center justify-center rounded-full text-[var(--msg-assistant-text)] transition-colors hover:bg-sidebar-item-hover"
@@ -420,7 +424,7 @@ function SkillhubMarketListViewInner() {
skill={pickerSkill}
onClose={() => setPickerOpen(false)}
onInstallComplete={() => {
- void refreshSkillhub();
+ void (target?.refresh ?? refreshSkillhub)();
setPickerOpen(false);
}}
/>
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubTargetContext.ts b/apps/desktop/src/renderer/features/skillhub/SkillhubTargetContext.ts
new file mode 100644
index 0000000000..7cce8b88e2
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubTargetContext.ts
@@ -0,0 +1,50 @@
+import { createContext, useContext } from 'react';
+import type { SkillhubState, SkillhubProject } from './hooks/useSkillhub';
+import type { MarketSkill } from './hooks/useMarketList';
+import type {
+ RemoteSkillMutation,
+ RemoteSkillProject,
+ RemoteSkillReceipt,
+} from '../../../shared/remoteSkills';
+
+export type SkillhubBrowseApi = Pick<
+ Window['electronAPI']['skillhub'],
+ | 'listMarket'
+ | 'listCategories'
+ | 'info'
+ | 'getPublishedFiles'
+ | 'readPublishedFile'
+ | 'getScanStatus'
+ | 'listChildren'
+ | 'readSkill'
+ | 'readSiblingFile'
+>;
+
+/** A selected computer supplies data/executors to the existing Skill views. */
+export interface SkillhubTarget {
+ name: string;
+ ready: boolean;
+ writable: boolean;
+ state: SkillhubState;
+ api: SkillhubBrowseApi;
+ projects: Array<SkillhubProject & { target: RemoteSkillProject }>;
+ refresh(): Promise<SkillhubSkill[]>;
+ current(): boolean;
+ mutate(
+ kind: RemoteSkillMutation,
+ skill?: SkillhubSkill,
+ market?: { name: string; catalogScope?: 'market' | 'team'; latestVersion: string },
+ project?: RemoteSkillProject,
+ ): Promise<RemoteSkillReceipt>;
+ openLocal(skill: SkillhubSkill): void;
+ openMarket(skill: MarketSkill): void;
+ openMarketList(): void;
+ back(): void;
+ displayPath(path: string): string;
+}
+
+export const SkillhubTargetContext = createContext<SkillhubTarget | null>(null);
+export const useSkillhubTarget = () => useContext(SkillhubTargetContext);
+export function useSkillhubBrowseApi(): SkillhubBrowseApi {
+ return useSkillhubTarget()?.api ?? window.electronAPI.skillhub;
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/RemoteSkillsPage.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/RemoteSkillsPage.test.tsx
new file mode 100644
index 0000000000..869b3daacf
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/RemoteSkillsPage.test.tsx
@@ -0,0 +1,453 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router-dom';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ confirm: vi.fn(),
+ localScan: vi.fn(),
+ localInstall: vi.fn(),
+ localRead: vi.fn(),
+ t: (key: string) => key,
+ user: { id: 'owner', membershipKind: 'org' },
+}));
+vi.mock('react-i18next', async (original) => ({
+ ...(await original<typeof import('react-i18next')>()),
+ useTranslation: () => ({ t: mocks.t, i18n: { language: 'en' } }),
+}));
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ user: mocks.user, dataOwnerId: 'owner', mode: 'cloud' }),
+}));
+vi.mock('@/hooks/useCCSessions', () => ({
+ useCCSessions: () => ({ sessions: [], isLoading: false }),
+}));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn() }),
+}));
+vi.mock('@/components/chat/MarkdownRenderer', () => ({
+ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div>,
+}));
+vi.mock('@/features/cc-agent/NewMakerDraftRoute', () => ({ NEW_MAKER_DRAFT_KEY: 'draft' }));
+vi.mock('@/lib/composerDraftStore', () => ({ plainTextToTiptapDoc: vi.fn(), saveDraft: vi.fn() }));
+vi.mock('@/state/newMakerDraft', () => ({ resetDraftWorkspaceTargets: vi.fn() }));
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
+// Local detail rendering has separate coverage; keep its production controls/executor here.
+vi.mock('../SkillhubDetailView', async () => {
+ const { useEffect, useState } = await import('react');
+ const { useSkillhubTarget } = await import('../SkillhubTargetContext');
+ const { LocalSkillControls } = await import('../components/LocalSkillControls');
+ return {
+ SkillhubDetailView: ({
+ entryOverride: skill,
+ renderNavigation,
+ onUninstalled,
+ }: {
+ entryOverride: SkillhubSkill;
+ renderNavigation: () => React.ReactNode;
+ onUninstalled: () => void;
+ }) => {
+ const target = useSkillhubTarget()!;
+ const [text, setText] = useState('');
+ useEffect(() => {
+ void target.api
+ .readSkill({ mdPath: skill.mdPath })
+ .then((result) => setText(result.content ?? ''));
+ }, [target.api, skill.mdPath]);
+ return (
+ <div>
+ {renderNavigation()}
+ <p>{text}</p>
+ <LocalSkillControls skill={skill} onUninstalled={onUninstalled} />
+ </div>
+ );
+ },
+ };
+});
+import { RemoteSkillsPage } from '../RemoteSkillsPage';
+
+const market = (name = 'public-skill', scope = 'market') => ({
+ name,
+ displayName: name === 'public-skill' ? 'Public skill' : name,
+ description: name + ' description',
+ authorId: 'author',
+ authorName: 'Target author',
+ isMine: false,
+ canManage: false,
+ latestVersion: '1.0.0',
+ visibility: 'PUBLIC',
+ visibleDeptIds: [],
+ categories: ['knowledge'],
+ tags: [{ slug: 'research', name: 'Research' }],
+ githubUrl: null,
+ publishedAt: '2026-10-01T00:00:00Z',
+ downloads: 321,
+ catalogScope: scope,
+});
+const snapshot = (device: string) => ({
+ version: 1,
+ items: [
+ {
+ id: 'physical-instance',
+ revision: 'r1',
+ name: device + ' installed',
+ description: 'Target-only local skill',
+ kind: 'skill',
+ scope: 'global',
+ engines: ['Codex'],
+ enabled: true,
+ canUninstall: true,
+ managedByPlugin: false,
+ builtIn: false,
+ market: { name: 'public-skill', catalogScope: 'market' },
+ version: '1.0.0',
+ },
+ ],
+ market: [],
+ nextCursor: null,
+ marketUnavailable: false,
+ projects: [{ id: 'project-b', revision: 'p1', name: 'Target project' }],
+});
+const requests = (action: string) =>
+ mocks.invoke.mock.calls.filter((call) => call[2]?.[0]?.actionId === 'management:' + action);
+const page = (id = 'B', online = true, active = true) => (
+ <MemoryRouter initialEntries={['/skillhub/local']}>
+ <RemoteSkillsPage
+ key={id}
+ device={{ deviceId: id, name: 'Computer ' + id }}
+ online={online}
+ active={active}
+ />
+ </MemoryRouter>
+);
+beforeEach(() => {
+ vi.clearAllMocks();
+ setDataOwnerGeneration('owner');
+ window.matchMedia = vi
+ .fn()
+ .mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() });
+ mocks.confirm.mockImplementation(async (_device, operationId) => ({
+ operationId,
+ phase: 'succeeded',
+ }));
+ window.electronAPI = {
+ skillhub: { scan: mocks.localScan, install: mocks.localInstall, readSkill: mocks.localRead },
+ deviceLink: {
+ invoke: mocks.invoke,
+ confirmSkillMutation: mocks.confirm,
+ onRemotePush: () => () => {},
+ },
+ } as never;
+ mocks.invoke.mockImplementation(async (device, channel, [request]) => {
+ if (channel.endsWith(':manifest'))
+ return {
+ collections: [
+ { id: 'skills', actions: [{ id: 'management:snapshot' }, { id: 'management:catalog' }] },
+ ],
+ };
+ const input = request.input;
+ let result;
+ switch (request.actionId) {
+ case 'management:snapshot':
+ result = snapshot(device);
+ break;
+ case 'management:catalog': {
+ const scope = input.scope;
+ if (input.method === 'list')
+ result = {
+ success: true,
+ items: [
+ market(
+ input.cursor ? 'next-page' : scope === 'team' ? 'Team skill' : 'public-skill',
+ scope,
+ ),
+ ],
+ nextCursor: input.cursor ? null : '2',
+ };
+ if (input.method === 'categories')
+ result = {
+ success: true,
+ categories: [{ slug: 'knowledge', name: 'Knowledge', count: 40 }],
+ };
+ if (input.method === 'info') result = { success: true, info: market(input.name, scope) };
+ if (input.method === 'files')
+ result = {
+ success: true,
+ files: [{ path: 'SKILL.md', size: 18, language: 'markdown', truncated: false }],
+ };
+ if (input.method === 'file')
+ result = {
+ success: true,
+ file: { path: 'SKILL.md', content: '# Published target content', language: 'markdown' },
+ };
+ break;
+ }
+ case 'management:read-file':
+ case 'management:detail':
+ result = {
+ success: true,
+ content: '# Target local content',
+ markdown: '# Target local content',
+ };
+ break;
+ case 'management:children':
+ result = { success: true, entries: [] };
+ break;
+ case 'management:begin':
+ result = {
+ operationId: input.operationId,
+ phase: ['enable', 'disable'].includes(input.kind) ? 'succeeded' : 'confirmation',
+ ...(['enable', 'disable'].includes(input.kind)
+ ? {}
+ : {
+ confirmation: {
+ requestId: 'confirm',
+ kind: input.kind,
+ name: input.name ?? 'Target local',
+ },
+ }),
+ };
+ break;
+ default:
+ result = { operationId: input.operationId, phase: 'running' };
+ }
+ return { result, effects: [] };
+ });
+});
+afterEach(cleanup);
+
+describe('full Skill Hub bound to the selected computer', () => {
+ it('shows original market cards/categories and target installed state together', async () => {
+ render(page());
+ await screen.findByText('Public skill');
+ expect(screen.getByText('Target author')).toBeTruthy();
+ expect(screen.getByText('321')).toBeTruthy();
+ expect(await screen.findByRole('radio', { name: 'Knowledge' })).toBeTruthy();
+ expect(screen.getByText('skillhub.home.installed')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.remote.managingDescription')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.remote.retry' })).toBeNull();
+ expect(screen.queryByText('B installed')).toBeNull();
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(screen.queryByText('Public skill')).toBeNull();
+ expect(screen.getByText('settings.ghosts.remote.managingDescription')).toBeTruthy();
+ expect(requests('snapshot')[0][2][0].input).toEqual({ installedOnly: true });
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it('paginates and sends category/search/organization filters to the selected Host', async () => {
+ render(page());
+ await screen.findByText('Public skill');
+ fireEvent.click(screen.getByText('skillhub.home.loadMore'));
+ await screen.findByText('next-page');
+ expect(
+ requests('catalog').some((call) => call[0] === 'B' && call[2][0].input.cursor === '2'),
+ ).toBe(true);
+ fireEvent.click(screen.getByRole('radio', { name: 'Knowledge' }));
+ await waitFor(() =>
+ expect(requests('catalog').some((call) => call[2][0].input.category === 'knowledge')).toBe(
+ true,
+ ),
+ );
+ fireEvent.click(
+ screen.getByRole('radio', { name: 'skillhub.home.catalogFilter.organization' }),
+ );
+ await screen.findByText('Team skill');
+ expect(screen.queryByText('Public skill')).toBeNull();
+ expect(screen.queryByText('B installed')).toBeNull();
+ fireEvent.change(screen.getByRole('textbox', { name: 'skillhub.home.search' }), {
+ target: { value: 'Team' },
+ });
+ await waitFor(() =>
+ expect(
+ requests('catalog').some(
+ (call) => call[2][0].input.q === 'Team' && call[2][0].input.scope === 'team',
+ ),
+ ).toBe(true),
+ );
+ });
+ it('keeps the complete installed list when an older Host reports a built-in user scope', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ const response = await original(device, channel, args);
+ if (args[0].actionId === 'management:snapshot') {
+ response.result.items.push({
+ ...snapshot(device).items[0],
+ id: 'built-in',
+ name: 'Built-in user skill',
+ scope: 'user',
+ builtIn: true,
+ canUninstall: false,
+ });
+ }
+ return response;
+ });
+ render(page());
+ await screen.findByText('Public skill');
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(screen.getByText('Built-in user skill')).toBeTruthy();
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it('associates the target author’s published copy with its visible market record', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ const response = await original(device, channel, args);
+ if (args[0].actionId === 'management:snapshot') {
+ response.result.items[0].market = {
+ name: 'public-skill',
+ origin: 'published',
+ authorId: 'author',
+ };
+ }
+ if (args[0].actionId === 'management:catalog' && args[0].input.method === 'list') {
+ Object.assign(response.result.items[0], { isMine: true, isCreator: true, canManage: true });
+ }
+ return response;
+ });
+ render(page());
+ await screen.findByText('Public skill');
+ await screen.findByText('skillhub.home.installed');
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it.each(['learned', 'imported'])('keeps %s target copies readable', async (origin) => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ const response = await original(device, channel, args);
+ if (args[0].actionId === 'management:snapshot') {
+ response.result.items[0].market.origin = origin;
+ }
+ return response;
+ });
+ render(page());
+ await screen.findByText('Public skill');
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it('opens full market details and published content using the target Hub', async () => {
+ render(page());
+ fireEvent.click(await screen.findByText('Public skill'));
+ await screen.findByText('# Published target content');
+ expect(
+ requests('catalog')
+ .filter((call) => ['info', 'files', 'file'].includes(call[2][0].input.method))
+ .every((call) => call[0] === 'B'),
+ ).toBe(true);
+ expect(mocks.localRead).not.toHaveBeenCalled();
+ });
+ it('uses the original picker and installs to the target project with native confirmation', async () => {
+ render(page());
+ fireEvent.click(await screen.findByText('Public skill'));
+ await screen.findByText('# Published target content');
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.marketCard.clone' }));
+ fireEvent.click(
+ within(screen.getByRole('dialog')).getByRole('button', { name: /Target project/ }),
+ );
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(requests('begin')).toHaveLength(1);
+ expect(requests('begin')[0][0]).toBe('B');
+ expect(requests('begin')[0][2][0].input).toMatchObject({
+ kind: 'install',
+ name: 'public-skill',
+ catalogScope: 'market',
+ version: '1.0.0',
+ projectId: 'project-b',
+ projectRevision: 'p1',
+ });
+ expect(JSON.stringify(requests('begin')[0])).not.toContain('installPath');
+ expect(mocks.localInstall).not.toHaveBeenCalled();
+ });
+ it('can confirm the original operation after a lost native confirmation response and reconnect', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ if (args[0].actionId === 'management:operation')
+ return {
+ result: {
+ operationId: args[0].input.operationId,
+ phase: 'confirmation',
+ confirmation: { requestId: 'confirm', kind: 'install', name: 'Public skill' },
+ },
+ effects: [],
+ };
+ return original(device, channel, args);
+ });
+ mocks.confirm.mockRejectedValueOnce(new Error('CONNECTION_LOST'));
+ const ui = render(page());
+ fireEvent.click(await screen.findByText('Public skill'));
+ await screen.findByText('# Published target content');
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.marketCard.clone' }));
+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: /Target project/ }));
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());
+ ui.rerender(page('B', false));
+ ui.rerender(page());
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(2));
+ expect(requests('begin')).toHaveLength(1);
+ expect(mocks.confirm.mock.calls[1]).toEqual(mocks.confirm.mock.calls[0]);
+ expect(mocks.localInstall).not.toHaveBeenCalled();
+ });
+ it('toggles/uninstalls the displayed physical instance without local mutation IPC', async () => {
+ render(page());
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ fireEvent.click(await screen.findByText('B installed'));
+ await screen.findByText('# Target local content');
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(requests('begin')).toHaveLength(1));
+ expect(requests('begin')[0][2][0]).toMatchObject({
+ resourceRef: { id: 'physical-instance' },
+ input: { kind: 'disable', expectedRevision: 'r1' },
+ });
+ await userEvent.click(screen.getByRole('button', { name: 'skillhub.management.moreLabel' }));
+ await userEvent.click(screen.getByRole('menuitem', { name: 'skillhub.detail.uninstall' }));
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledWith('B', expect.any(String)));
+ expect(requests('begin')[1][2][0].input.kind).toBe('uninstall');
+ expect(requests('answer')).toHaveLength(0);
+ });
+ it('keeps offline content visible, disables writes and does not replay', async () => {
+ const ui = render(page());
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ fireEvent.click(await screen.findByText('B installed'));
+ await screen.findByText('# Target local content');
+ ui.rerender(page('B', false));
+ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.getByText('# Target local content')).toBeTruthy();
+ expect(requests('begin')).toHaveLength(0);
+ });
+ it('discards old computer responses and does not read hidden targets', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ let finish!: (value: unknown) => void;
+ mocks.invoke.mockImplementation((device, channel, args) =>
+ device === 'B' && args[0].actionId === 'management:snapshot'
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(device, channel, args),
+ );
+ const ui = render(page('B', true, false));
+ expect(mocks.invoke).not.toHaveBeenCalled();
+ ui.rerender(page());
+ await waitFor(() => expect(finish).toBeTypeOf('function'));
+ ui.rerender(page('C'));
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('C installed');
+ await act(async () => finish({ result: snapshot('Late B'), effects: [] }));
+ expect(screen.queryByText('Late B installed')).toBeNull();
+ });
+ it('keeps older Hosts readable without falling back to this computer', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation((device, channel, args) =>
+ channel.endsWith(':manifest')
+ ? { collections: [{ id: 'skills', actions: [{ id: 'management:snapshot' }] }] }
+ : original(device, channel, args),
+ );
+ render(page());
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(screen.getByText('skillhub.remote.unsupported')).toBeTruthy();
+ expect(requests('catalog')).toHaveLength(0);
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ expect(mocks.localInstall).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx b/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx
index 50e3da55f3..72e133f3f3 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx
@@ -29,6 +29,7 @@ import {
normalizeInstallPathKey,
} from '../lib/installTargetPaths';
import type { SkillhubCatalogScope } from '../../../../shared/skillhubCatalog';
+import { useSkillhubTarget } from '../SkillhubTargetContext';
/** Minimal skill identity for the picker (market Clone or local import). */
export interface InstallTargetSkill {
@@ -92,13 +93,14 @@ export function InstallTargetPicker({
skill,
onClose,
onInstallComplete,
- runAction = runMarketInstall,
+ runAction,
titleKey = 'skillhub.installPicker.title',
subtitleKey = 'skillhub.installPicker.subtitle',
successToastKey = 'skillhub.installPicker.installSuccess',
failedToastKey = 'skillhub.installPicker.installFailed',
}: InstallTargetPickerProps) {
const { t } = useTranslation();
+ const target = useSkillhubTarget();
const { projects, loading: projectsLoading } = useProjectsForPicker();
const { confirm } = useConfirmDialog();
const [installing, setInstalling] = useState(false);
@@ -108,8 +110,23 @@ export function InstallTargetPicker({
const [bannerError, setBannerError] = useState<string | null>(null);
const [installedPaths, setInstalledPaths] = useState<Map<string, string>>(new Map());
+ useEffect(() => {
+ if (open && target) void target.refresh();
+ }, [open, target?.refresh]);
+
useEffect(() => {
if (!open || !skill) return;
+ setInstalledPaths(new Map());
+ if (target) {
+ const paths = new Map<string, string>();
+ for (const local of target.state.skills) {
+ if (local.registrySkillName !== skill.name || !local.registryEntry
+ || (local.registryEntry.catalogScope ?? 'market') !== (skill.catalogScope ?? 'market')) continue;
+ paths.set(normalizeInstallPathKey(joinSkillInstallPath(local.projectRoot ?? 'remote-global', skill.name)), local.registryEntry.version);
+ }
+ setInstalledPaths(paths);
+ return;
+ }
let cancelled = false;
void window.electronAPI.skillhub.registry
.getByName({ name: skill.name })
@@ -125,7 +142,7 @@ export function InstallTargetPicker({
return () => {
cancelled = true;
};
- }, [open, skill?.name]);
+ }, [open, skill?.name, skill?.catalogScope, target?.state.skills]);
useEffect(() => {
if (!open) {
@@ -166,7 +183,15 @@ export function InstallTargetPicker({
const performInstall = async (installPath?: string) => {
setBannerError(null);
try {
- const res = await runAction({ name: skill.name, installPath, catalogScope: skill.catalogScope });
+ const execute = runAction ?? (target ? async (): Promise<InstallTargetActionResult> => {
+ const project = installPath ? target.projects.find((entry) => joinSkillInstallPath(entry.projectRoot, skill.name) === installPath)?.target : undefined;
+ if ((installPath && !project) || !target.writable) return { success: false, errorCode: 'UNAVAILABLE' };
+ const result = await target.mutate('install', undefined, { name: skill.name,
+ catalogScope: skill.catalogScope, latestVersion: String(skill.latestVersion ?? '') }, project);
+ if (!target.current()) return { success: false, errorCode: 'CANCELLED' };
+ return result.phase === 'succeeded' ? { success: true } : { success: false, errorCode: result.phase === 'cancelled' ? 'CANCELLED' : 'UNAVAILABLE' };
+ } : runMarketInstall);
+ const res = await execute({ name: skill.name, installPath, catalogScope: skill.catalogScope });
if (res.success) {
toast.success(
t(successToastKey, {
@@ -189,7 +214,7 @@ export function InstallTargetPicker({
cancelText: t('skillhub.installPicker.conflictDialog.cancel'),
});
if (!ok) return;
- const forced = await runAction({ name: skill.name, installPath, force: true, catalogScope: skill.catalogScope });
+ const forced = await execute({ name: skill.name, installPath, force: true, catalogScope: skill.catalogScope });
if (forced.success) {
toast.success(
t(successToastKey, {
@@ -221,7 +246,7 @@ export function InstallTargetPicker({
};
const handleOtherDirectory = async () => {
- if (!beginInstallBusy()) return;
+ if (target || !beginInstallBusy()) return;
try {
const r = await window.electronAPI.dialog.showOpenDirectory({});
if (!r.success || !r.path) return;
@@ -293,7 +318,7 @@ export function InstallTargetPicker({
onClick={() => {
void handleOtherDirectory();
}}
- disabled={installing}
+ disabled={installing || !!target}
>
<FolderOpen size={14} className="shrink-0 text-[var(--settings-section-desc)]" />
{t('skillhub.installPicker.otherDirectory')}
@@ -309,7 +334,7 @@ export function InstallTargetPicker({
<div className="flex flex-col" style={{ padding: '4px 12px 12px 12px' }}>
<button
type="button"
- disabled={installing || !!globalInstalledVersion}
+ disabled={installing || !!globalInstalledVersion || (!!target && !target.writable)}
onClick={() => {
void handleInstall(undefined);
}}
@@ -330,7 +355,7 @@ export function InstallTargetPicker({
</div>
<div className="flex min-w-0 flex-1 flex-col" style={{ gap: '2px' }}>
<span className="text-[var(--msg-assistant-text)]" style={{ fontSize: 'var(--text-13)', fontWeight: 500 }}>
- {t('skillhub.installPicker.global')}
+ {t('skillhub.installPicker.global')}{target ? ` · ${target.name}` : ''}
</span>
<span className="truncate text-[var(--cmd-palette-item-meta)]" style={{ fontSize: 'var(--text-11)' }}>
~/.agents/skills/{skill.name}
@@ -388,7 +413,7 @@ export function InstallTargetPicker({
<button
key={p.projectRoot}
type="button"
- disabled={installing || isRowInstalled}
+ disabled={installing || isRowInstalled || (!!target && !target.writable)}
onClick={() => {
void handleInstall(installPath);
}}
@@ -415,7 +440,7 @@ export function InstallTargetPicker({
{p.displayName}
</span>
<span className="truncate text-[var(--cmd-palette-item-meta)]" style={{ fontSize: 'var(--text-11)' }}>
- {installPath}
+ {target ? target.name : installPath}
</span>
</div>
{isRowInstalled ? (
diff --git a/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
index fef5dcecb8..bc9837335d 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx
@@ -9,6 +9,7 @@ import { extractIpcError } from '@/utils/ipcError';
import { toast } from '@/lib/toast';
import { refresh } from '../hooks/useSkillhub';
import { showUninstallCleanup } from '../lib/uninstallCleanupNotifications';
+import { useSkillhubTarget } from '../SkillhubTargetContext';
/** Local management for Skill details, independent of cloud ownership. */
export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
@@ -17,12 +18,15 @@ export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
onUninstalled?: () => void;
}) {
const { t } = useTranslation();
+ const target = useSkillhubTarget();
+ disabled = disabled || (!!target && !target.writable);
const busyRef = useRef(false);
const [busy, setBusy] = useState(false);
const [pendingEnabled, setPendingEnabled] = useState<boolean | null>(null);
if (skill.kind !== 'skill') return null;
const enabled = pendingEnabled ?? skill.cindyEnabled !== false;
const reportError = (error: unknown, operation: 'toggleFailed' | 'uninstallFailed') => {
+ if (target && !target.current()) return;
const code = extractIpcError(error)?.code;
toast.error(t(`skillhub.management.${code === 'PRECONDITION_FAILED' || code === 'PERMISSION_DENIED' ? 'refreshRequired' : operation}`));
};
@@ -32,8 +36,13 @@ export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
setBusy(true);
setPendingEnabled(value);
try {
- await window.electronAPI.skillhub.setEnabled({ absolutePath: skill.absolutePath, skillId: skill.id, enabled: value });
- await refresh();
+ if (target) {
+ const result = await target.mutate(value ? 'enable' : 'disable', skill);
+ if (!target.current()) return;
+ if (result.phase !== 'succeeded') throw new Error('UNAVAILABLE');
+ } else await window.electronAPI.skillhub.setEnabled({ absolutePath: skill.absolutePath, skillId: skill.id, enabled: value });
+ await (target?.refresh ?? refresh)();
+ if (target && !target.current()) return;
toast.success(t(value ? 'skillhub.management.enabledToast' : 'skillhub.management.disabledToast', { name: skill.name }));
} catch (error) { reportError(error, 'toggleFailed'); }
finally {
@@ -47,6 +56,15 @@ export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
busyRef.current = true;
setBusy(true);
try {
+ if (target) {
+ const result = await target.mutate('uninstall', skill);
+ if (!target.current() || result.phase === 'cancelled') return;
+ if (result.phase !== 'succeeded') throw new Error('UNAVAILABLE');
+ toast.success(t('skillhub.detail.uninstalledToast', { name: skill.name }));
+ await target.refresh();
+ if (target.current()) onUninstalled?.();
+ return;
+ }
const result = await window.electronAPI.skillhub.uninstall(skill.absolutePath, skill.id);
if (!result.success) {
if (result.errorCode === 'CANCELLED') return;
@@ -66,7 +84,7 @@ export function LocalSkillControls({ skill, disabled = false, onUninstalled }: {
return (
<div className="flex shrink-0 items-center gap-2" onClick={(event) => event.stopPropagation()}>
- <Tip text={`${skill.absolutePath}\n${t(skill.managedByPlugin ? 'skillhub.management.managedByPlugin' : 'skillhub.management.activationHint')}`}>
+ <Tip text={`${target?.displayPath(skill.absolutePath) ?? skill.absolutePath}\n${t(skill.managedByPlugin ? 'skillhub.management.managedByPlugin' : 'skillhub.management.activationHint')}`}>
{/* Keep Tooltip's open/closed data-state off the Switch's checked/unchecked root. */}
<span className="inline-flex">
<Switch checked={enabled} disabled={busy || disabled || skill.managedByPlugin}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx b/apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx
index 7f73ff4832..3c81806245 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx
@@ -1,9 +1,4 @@
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
-import { ChevronLeft, ChevronRight } from 'lucide-react';
-
-import { Tip } from '@/components/ui/tooltip';
import { SegmentedControl } from '@/components/ui/segmented-control';
-import { useReducedMotion } from '@/hooks/useReducedMotion';
import { cn } from '@/lib/utils';
import { CATEGORY_ALL, type MarketCategory } from '../../../../shared/skillhubCategory';
import type { CategoryFilter } from '../hooks/useMarketList';
@@ -13,166 +8,47 @@ interface SkillCategoryFilterBarProps {
selectedCategory: CategoryFilter;
allLabel: string;
ariaLabel: string;
- scrollLeftLabel: string;
- scrollRightLabel: string;
- scrollStartLabel: string;
- scrollEndLabel: string;
onSelectCategory: (category: CategoryFilter) => void;
className?: string;
}
-interface ScrollState {
- overflow: boolean;
- left: boolean;
- right: boolean;
-}
-
-const INITIAL_SCROLL_STATE: ScrollState = {
- overflow: false,
- left: false,
- right: false,
-};
-
-export function skillCategoryScrollStep(clientWidth: number): number {
- return Math.max(120, Math.floor(clientWidth * 0.7));
-}
-
-/**
- * Single-line category filters for the SkillHub catalog. Arrow controls stay
- * outside the scroll viewport so every category remains a full click target.
- */
export function SkillCategoryFilterBar({
categories,
selectedCategory,
allLabel,
ariaLabel,
- scrollLeftLabel,
- scrollRightLabel,
- scrollStartLabel,
- scrollEndLabel,
onSelectCategory,
className,
}: SkillCategoryFilterBarProps) {
- const reducedMotion = useReducedMotion();
- const scrollRef = useRef<HTMLDivElement | null>(null);
- const [scrollState, setScrollState] = useState<ScrollState>(INITIAL_SCROLL_STATE);
-
- const updateScrollState = useCallback(() => {
- const element = scrollRef.current;
- if (!element) return;
- const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
- const next: ScrollState = {
- overflow: maxScrollLeft > 1,
- left: element.scrollLeft > 1,
- right: element.scrollLeft < maxScrollLeft - 1,
- };
- setScrollState((previous) =>
- previous.overflow === next.overflow &&
- previous.left === next.left &&
- previous.right === next.right
- ? previous
- : next,
- );
- }, []);
-
- useLayoutEffect(() => {
- updateScrollState();
- const element = scrollRef.current;
- if (!element) return undefined;
- const resizeObserver =
- typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(updateScrollState);
- resizeObserver?.observe(element);
- window.addEventListener('resize', updateScrollState);
- return () => {
- resizeObserver?.disconnect();
- window.removeEventListener('resize', updateScrollState);
- };
- }, [updateScrollState]);
-
- useEffect(() => {
- updateScrollState();
- }, [categories, updateScrollState]);
-
- const scroll = (direction: -1 | 1) => {
- const element = scrollRef.current;
- if (!element) return;
- element.scrollBy({
- left: direction * skillCategoryScrollStep(element.clientWidth),
- behavior: reducedMotion ? 'auto' : 'smooth',
- });
- };
-
return (
- <div className={cn('flex min-w-0 items-center gap-1.5', className)}>
- {scrollState.overflow ? (
- <Tip text={scrollState.left ? scrollLeftLabel : scrollStartLabel} side="bottom">
- <span className="inline-flex shrink-0">
- <button
- type="button"
- aria-label={scrollState.left ? scrollLeftLabel : scrollStartLabel}
- disabled={!scrollState.left}
- onClick={() => scroll(-1)}
- className={cn(
- 'inline-flex size-7 shrink-0 items-center justify-center rounded-full border border-[var(--border-default)]',
- 'bg-[var(--surface-elevated)] text-[var(--text-secondary)] transition-colors duration-150',
- 'hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'disabled:cursor-default disabled:opacity-35',
- )}
- >
- <ChevronLeft size={14} strokeWidth={1.8} aria-hidden="true" />
- </button>
- </span>
- </Tip>
- ) : null}
-
- <div
- ref={scrollRef}
- data-testid="skill-category-filter-scroller"
- onScroll={updateScrollState}
- className="flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 overflow-x-auto overscroll-x-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
- >
- <SegmentedControl
- className="shrink-0 !max-w-none"
- role="radiogroup"
- aria-label={ariaLabel}
- height={32}
- optionHeight={28}
- optionClassName="max-w-40 px-3 text-12"
- value={selectedCategory}
- onValueChange={onSelectCategory}
- options={[
- { value: CATEGORY_ALL, label: <span className="truncate">{allLabel}</span>, title: allLabel },
- ...categories.map((category) => ({
- value: category.slug as CategoryFilter,
- label: <span className="truncate">{category.name}</span>,
- title: category.name,
- })),
- ]}
- />
- </div>
-
- {scrollState.overflow ? (
- <Tip text={scrollState.right ? scrollRightLabel : scrollEndLabel} side="bottom">
- <span className="inline-flex shrink-0">
- <button
- type="button"
- aria-label={scrollState.right ? scrollRightLabel : scrollEndLabel}
- disabled={!scrollState.right}
- onClick={() => scroll(1)}
- className={cn(
- 'inline-flex size-7 shrink-0 items-center justify-center rounded-full border border-[var(--border-default)]',
- 'bg-[var(--surface-elevated)] text-[var(--text-secondary)] transition-colors duration-150',
- 'hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'disabled:cursor-default disabled:opacity-35',
- )}
- >
- <ChevronRight size={14} strokeWidth={1.8} aria-hidden="true" />
- </button>
- </span>
- </Tip>
- ) : null}
+ <div
+ data-testid="skill-category-filter-scroller"
+ onFocusCapture={(event) => {
+ event.target.scrollIntoView({ block: 'nearest', inline: 'nearest' });
+ }}
+ className={cn(
+ 'flex min-w-0 items-center overflow-x-auto overscroll-x-contain [scroll-padding-inline:20%] [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden',
+ className,
+ )}
+ >
+ <SegmentedControl
+ className="skill-category-tags shrink-0 !max-w-none"
+ role="radiogroup"
+ aria-label={ariaLabel}
+ height={32}
+ optionHeight={32}
+ optionClassName="max-w-40 px-3 text-12"
+ value={selectedCategory}
+ onValueChange={onSelectCategory}
+ options={[
+ { value: CATEGORY_ALL, label: <span className="truncate">{allLabel}</span>, title: allLabel },
+ ...categories.map((category) => ({
+ value: category.slug as CategoryFilter,
+ label: <span className="truncate">{category.name}</span>,
+ title: category.name,
+ })),
+ ]}
+ />
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/__tests__/SkillCategoryFilterBar.test.tsx b/apps/desktop/src/renderer/features/skillhub/components/__tests__/SkillCategoryFilterBar.test.tsx
index 8388916611..930da59965 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/__tests__/SkillCategoryFilterBar.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/SkillCategoryFilterBar.test.tsx
@@ -3,7 +3,7 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import { SkillCategoryFilterBar, skillCategoryScrollStep } from '../SkillCategoryFilterBar';
+import { SkillCategoryFilterBar } from '../SkillCategoryFilterBar';
const categories = [
{ slug: 'automation', name: 'Automation', count: 10, myCount: 1 },
@@ -19,32 +19,12 @@ function renderBar(onSelectCategory = vi.fn()) {
selectedCategory="automation"
allLabel="All"
ariaLabel="Filter skills by category"
- scrollLeftLabel="Scroll categories left"
- scrollRightLabel="Scroll categories right"
- scrollStartLabel="Already at the first category"
- scrollEndLabel="Already at the last category"
onSelectCategory={onSelectCategory}
/>,
),
};
}
-function mockScroller(
- scroller: HTMLElement,
- values: { scrollLeft: number; clientWidth: number; scrollWidth: number },
-) {
- let scrollLeft = values.scrollLeft;
- Object.defineProperty(scroller, 'clientWidth', { configurable: true, value: values.clientWidth });
- Object.defineProperty(scroller, 'scrollWidth', { configurable: true, value: values.scrollWidth });
- Object.defineProperty(scroller, 'scrollLeft', {
- configurable: true,
- get: () => scrollLeft,
- set: (value: number) => {
- scrollLeft = value;
- },
- });
-}
-
describe('SkillCategoryFilterBar', () => {
it('renders a single-select category group', () => {
const { onSelectCategory } = renderBar();
@@ -59,36 +39,49 @@ describe('SkillCategoryFilterBar', () => {
expect(onSelectCategory).toHaveBeenCalledWith('productivity');
});
- it('shows edge controls only when the category row overflows', () => {
+ it('keeps the overflowing category row free of arrow controls', () => {
renderBar();
- expect(screen.queryByRole('button', { name: 'Scroll categories right' })).toBeNull();
-
const scroller = screen.getByTestId('skill-category-filter-scroller');
- mockScroller(scroller, { scrollLeft: 0, clientWidth: 200, scrollWidth: 600 });
+ Object.defineProperty(scroller, 'clientWidth', { configurable: true, value: 200 });
+ Object.defineProperty(scroller, 'scrollWidth', { configurable: true, value: 600 });
fireEvent.scroll(scroller);
- expect(
- screen
- .getByRole('button', { name: 'Already at the first category' })
- .hasAttribute('disabled'),
- ).toBe(true);
- expect(
- screen.getByRole('button', { name: 'Scroll categories right' }).hasAttribute('disabled'),
- ).toBe(false);
+ expect(screen.queryAllByRole('button')).toHaveLength(0);
+ expect(screen.getAllByRole('radio')).toHaveLength(3);
});
- it('scrolls by a bounded portion of the visible row', () => {
+ it('reveals the focused category without centering the page', () => {
renderBar();
- const scroller = screen.getByTestId('skill-category-filter-scroller');
- const scrollBy = vi.fn();
- mockScroller(scroller, { scrollLeft: 0, clientWidth: 200, scrollWidth: 600 });
- scroller.scrollBy = scrollBy;
- fireEvent.scroll(scroller);
+ const category = screen.getByRole('radio', { name: 'Productivity' });
+ category.scrollIntoView = vi.fn();
- fireEvent.click(screen.getByRole('button', { name: 'Scroll categories right' }));
- expect(scrollBy).toHaveBeenCalledWith({
- left: skillCategoryScrollStep(200),
- behavior: 'smooth',
+ fireEvent.focus(category);
+ expect(category.scrollIntoView).toHaveBeenCalledWith({
+ block: 'nearest',
+ inline: 'nearest',
});
});
+
+ it('preserves arrow-key selection and follows focus at both ends', () => {
+ const { onSelectCategory } = renderBar();
+ const all = screen.getByRole('radio', { name: 'All' });
+ const automation = screen.getByRole('radio', { name: 'Automation' });
+ const productivity = screen.getByRole('radio', { name: 'Productivity' });
+ for (const category of [all, automation, productivity]) {
+ category.scrollIntoView = vi.fn();
+ }
+
+ fireEvent.keyDown(automation, { key: 'ArrowRight' });
+ expect(document.activeElement).toBe(productivity);
+ expect(onSelectCategory).toHaveBeenLastCalledWith('productivity');
+ expect(productivity.scrollIntoView).toHaveBeenCalled();
+
+ fireEvent.keyDown(productivity, { key: 'Home' });
+ expect(document.activeElement).toBe(all);
+ expect(all.scrollIntoView).toHaveBeenCalled();
+
+ fireEvent.keyDown(all, { key: 'End' });
+ expect(document.activeElement).toBe(productivity);
+ expect(onSelectCategory).toHaveBeenLastCalledWith('productivity');
+ });
});
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
index 2e251abfe2..672d6322fd 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
@@ -35,6 +35,7 @@ import type { HubPublishedVisibility } from '../lib/marketVisibility';
import { filterAvailableMarketItems } from '../lib/marketDetailViewModel';
import { useSkillhub } from './useSkillhub';
+import { useSkillhubBrowseApi, useSkillhubTarget } from '../SkillhubTargetContext';
import { semverCompare } from '../versionUtils';
import { publishedLocalIdentity, publishedMarketIdentity, type MarketLocalIdentity } from '../lib/marketLocalCopies';
@@ -375,7 +376,9 @@ export function useMarketList(
initialCategoryFilter?: CategoryFilter;
},
) {
- const enabled = options?.enabled ?? true;
+ const target = useSkillhubTarget();
+ const api = useSkillhubBrowseApi();
+ const enabled = (options?.enabled ?? true) && (!target || target.ready);
const owner = getDataOwnerGeneration();
const { t, i18n: i18next } = useTranslation();
const [searchQuery, setSearchQueryState] = useState(options?.initialSearchQuery ?? '');
@@ -433,7 +436,7 @@ export function useMarketList(
const requestIdRef = useRef(0);
const requestMarketPage = useCallback(async (params: FetchMarketPageInput): Promise<MarketPageResult> => {
- const res = await window.electronAPI.skillhub.listMarket({
+ const res = await api.listMarket({
cursor: params.cursor,
limit: MARKET_PAGE_SIZE,
sort: params.sort,
@@ -452,7 +455,7 @@ export function useMarketList(
),
nextCursor: res.nextCursor ?? null,
};
- }, [owner]);
+ }, [owner, api]);
const collectVisiblePage = useCallback(async (
params: FetchMarketPageInput & { available: boolean },
@@ -702,6 +705,8 @@ const inflightCategories = new Map<
>();
export function useCategoryList(scope: SkillhubCatalogScope = 'market'): CategoryListState {
+ const target = useSkillhubTarget();
+ const api = useSkillhubBrowseApi();
const owner = getDataOwnerGeneration();
const [state, setState] = useState<ScopedCategoryListState>({
owner,
@@ -710,18 +715,19 @@ export function useCategoryList(scope: SkillhubCatalogScope = 'market'): Categor
});
useEffect(() => {
+ if (target && !target.ready) return;
let cancelled = false;
const ownerInflight =
inflightCategories.get(owner) ??
new Map<SkillhubCatalogScope, Promise<CategoryListState>>();
if (!inflightCategories.has(owner)) inflightCategories.set(owner, ownerInflight);
- const existing = ownerInflight.get(scope);
- const inflight = existing ?? window.electronAPI.skillhub.listCategories({ scope, includeEmpty: false })
+ const existing = target ? undefined : ownerInflight.get(scope);
+ const inflight = existing ?? api.listCategories({ scope, includeEmpty: false })
.then((res) => (res.success
? { categories: res.categories ?? [], totalCount: res.totalCount ?? 0, myTotalCount: res.myTotalCount ?? 0 }
: EMPTY_CATEGORY_STATE))
.catch(() => EMPTY_CATEGORY_STATE);
- if (!existing) ownerInflight.set(scope, inflight);
+ if (!existing && !target) ownerInflight.set(scope, inflight);
void inflight.then((next) => {
if (ownerInflight.get(scope) === inflight) ownerInflight.delete(scope);
if (ownerInflight.size === 0 && inflightCategories.get(owner) === ownerInflight) {
@@ -732,7 +738,7 @@ export function useCategoryList(scope: SkillhubCatalogScope = 'market'): Categor
}
});
return () => { cancelled = true; };
- }, [owner, scope]);
+ }, [owner, scope, api, target?.ready]);
return state.owner === owner && state.scope === scope ? state.value : EMPTY_CATEGORY_STATE;
}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketSkillUpdate.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketSkillUpdate.ts
index 34ff93e7a9..15a870d6a3 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketSkillUpdate.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketSkillUpdate.ts
@@ -8,10 +8,12 @@ import { semverCompare } from '../versionUtils';
import type { MarketSkill } from './useMarketList';
import { invalidateHash } from './useSkillFolderHash';
import { refresh } from './useSkillhub';
+import { useSkillhubTarget } from '../SkillhubTargetContext';
/** Update the copy represented by the card, without opening the install picker. */
export function useMarketSkillUpdate() {
const { t } = useTranslation();
+ const target = useSkillhubTarget();
const owner = getDataOwnerGeneration();
// The installer serializes by name, including same-name records in other catalogs.
const running = useRef(new Set<string>());
@@ -24,6 +26,16 @@ export function useMarketSkillUpdate() {
running.current.add(skill.name);
setUpdatingNames(new Set(running.current));
try {
+ if (target) {
+ const locals = await target.refresh();
+ if (!target.current()) return;
+ const local = marketLocalCopies(locals, skill).find((entry) => entry.id === target.state.skills.find((entry) => entry.absolutePath === skill.installedAbsolutePath)?.id);
+ if (!local) return;
+ const result = await target.mutate('update', local, skill);
+ if (target.current() && result.phase === 'failed') toast.error(t('skillhub.marketCard.updateFailed'));
+ else if (target.current() && result.phase === 'succeeded') toast.success(t('skillhub.detail.updatedToast', { name: skill.name, version: skill.latestVersion }));
+ return;
+ }
// Recheck the registry before authorizing replacement of an existing directory.
const locals = await refresh();
if (!isDataOwnerGenerationCurrent(owner)) return;
@@ -52,12 +64,12 @@ export function useMarketSkillUpdate() {
toast.error(t('skillhub.marketCard.updateFailed'));
}
} catch {
- if (isDataOwnerGenerationCurrent(owner)) toast.error(t('skillhub.marketCard.updateFailed'));
+ if (isDataOwnerGenerationCurrent(owner) && (!target || target.current())) toast.error(t('skillhub.marketCard.updateFailed'));
} finally {
running.current.delete(skill.name);
setUpdatingNames(new Set(running.current));
}
- }, [owner, t]);
+ }, [owner, t, target]);
return { update, updatingNames, isUpdating };
}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useProjectsForPicker.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useProjectsForPicker.ts
index 0d2c7ea873..91d67659bd 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useProjectsForPicker.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useProjectsForPicker.ts
@@ -12,6 +12,7 @@ import { useMemo } from 'react';
import { useCCSessions } from '@/hooks/useCCSessions';
import { groupSessions } from '@/features/cc-agent/lib/projectGrouping';
+import { useSkillhubTarget } from '../SkillhubTargetContext';
export interface PickerProject {
projectRoot: string;
@@ -19,6 +20,7 @@ export interface PickerProject {
}
export function useProjectsForPicker(): { projects: PickerProject[]; loading: boolean } {
+ const target = useSkillhubTarget();
const { sessions, isLoading } = useCCSessions();
const projects = useMemo<PickerProject[]>(() => {
@@ -30,5 +32,5 @@ export function useProjectsForPicker(): { projects: PickerProject[]; loading: bo
}));
}, [sessions, isLoading]);
- return { projects, loading: isLoading };
+ return target ? { projects: target.projects, loading: !target.state.bootstrapped } : { projects, loading: isLoading };
}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
index d72cde3c6e..e416a5222e 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
@@ -20,6 +20,7 @@ import { useEffect, useMemo, useState } from 'react';
import { skillhubCatalogKey } from '../../../../shared/skillhubCatalog';
import { syncUninstallCleanupNotices, resetUninstallCleanupNotices } from '../lib/uninstallCleanupNotifications';
import { invalidateSkillSyncRequests, registerSyncStoreSetters } from './useSkillSync';
+import { useSkillhubTarget } from '../SkillhubTargetContext';
interface SkillhubProject {
/** 项目资产归属根目录,来自会话分组后的 project root。 */
@@ -30,7 +31,7 @@ interface SkillhubProject {
displayName: string;
}
-interface SkillhubState {
+export interface SkillhubState {
skills: SkillhubSkill[];
sources: SkillhubSourceReport[];
loading: boolean;
@@ -270,9 +271,11 @@ interface UseSkillhubReturn extends SkillhubState {
}
export function useSkillhub(): UseSkillhubReturn {
+ const target = useSkillhubTarget();
const [snapshot, setSnapshot] = useState<SkillhubState>(state);
useEffect(() => {
+ if (target) return;
ensureAuthListener();
const sync = () => setSnapshot(state);
listeners.add(sync);
@@ -280,11 +283,11 @@ export function useSkillhub(): UseSkillhubReturn {
return () => {
listeners.delete(sync);
};
- }, []);
+ }, [target === null]);
return {
- ...snapshot,
- refresh,
+ ...(target?.state ?? snapshot),
+ refresh: target?.refresh ?? refresh,
};
}
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
index 10e9dddb13..918bc02427 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
@@ -90,6 +90,7 @@ describe('market route scope', () => {
expect(homeSource).not.toContain("title={t('skillhub.home.catalog')}");
expect(homeSource).toContain("t('skillhub.home.catalogMore')");
expect(homeSource).toContain('headerActions={(');
+ expect(homeSource).toContain('<CatalogTargetControls computer={deviceControl} />');
expect(homeSource).toContain('plugin-management-action-trigger');
expect(homeSource).toContain('<HomeMarketCard');
const homeCardSource = readFileSync(resolve(skillhubDir, 'components/HomeMarketCard.tsx'), 'utf8');
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/marketInfoViewModel.ts b/apps/desktop/src/renderer/features/skillhub/lib/marketInfoViewModel.ts
new file mode 100644
index 0000000000..bfb156aed8
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/marketInfoViewModel.ts
@@ -0,0 +1,43 @@
+import { deriveLocalInstall, type MarketSkill } from '../hooks/useMarketList';
+
+/** Share detail/install presentation across local and selected-computer routes. */
+export function marketInfoViewModel(
+ info: SkillhubInfoResult,
+ local: SkillhubSkill | null,
+ catalogScope: MarketSkill['catalogScope'],
+): MarketSkill {
+ const primary = local
+ ? {
+ version: local.registryEntry?.version ?? null,
+ absolutePath: local.absolutePath,
+ hasRegistryEntry: !!local.registryEntry,
+ }
+ : undefined;
+ const installed = deriveLocalInstall(
+ info,
+ primary
+ ? {
+ global: local?.scope === 'global' ? primary : undefined,
+ projects: local?.scope === 'project' ? [primary] : [],
+ }
+ : undefined,
+ );
+ return {
+ ...info,
+ icon: info.icon ?? undefined,
+ catalogScope,
+ ...installed,
+ authorAvatarUrl: null,
+ avatarInitial: info.authorName.slice(0, 1),
+ categories: info.categories ?? [],
+ tags: info.tags ?? [],
+ githubUrl: info.githubUrl ?? null,
+ relativeTime: '',
+ latestPublishedFromDeviceId: null,
+ cardState: installed.updateAvailable
+ ? 'installed-outdated'
+ : installed.installedLocally
+ ? 'installed-latest'
+ : 'not-installed',
+ };
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/remoteSkillsClient.ts b/apps/desktop/src/renderer/features/skillhub/remoteSkillsClient.ts
new file mode 100644
index 0000000000..c3662e521f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/remoteSkillsClient.ts
@@ -0,0 +1,102 @@
+import {
+ REMOTE_RESOURCE_INVOKE_CHANNEL,
+ REMOTE_RESOURCE_MANIFEST_CHANNEL,
+ REMOTE_RESOURCE_PROTOCOL_VERSION,
+} from '@cindy/device-link';
+import { boundedPluginResponse } from '@/features/plugin/remotePluginManagementClient';
+import type { RemoteSkillItem, RemoteSkillsSnapshot } from '../../../shared/remoteSkills';
+import { isRemoteSkillMarketItem } from '../../../shared/remoteSkills';
+
+const client = { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: [] };
+export async function remoteSkillsCapabilities(deviceId: string) {
+ const manifest = (await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ REMOTE_RESOURCE_MANIFEST_CHANNEL,
+ [{ client }],
+ )) as { collections?: Array<{ id: string; actions?: Array<{ id: string }> }> };
+ if (!boundedPluginResponse(manifest)) throw new Error('INVALID_RESPONSE');
+ const skills = manifest?.collections?.find((collection) => collection.id === 'skills');
+ return {
+ management: skills?.actions?.some((a) => a.id === 'management:snapshot') === true,
+ catalog: skills?.actions?.some((a) => a.id === 'management:catalog') === true,
+ };
+}
+export async function invokeRemoteSkills(
+ deviceId: string,
+ action: string,
+ input?: Record<string, unknown>,
+ item?: RemoteSkillItem,
+) {
+ const response = (await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ REMOTE_RESOURCE_INVOKE_CHANNEL,
+ [
+ {
+ client,
+ collectionId: 'skills',
+ actionId: `management:${action}`,
+ ...(item ? { resourceRef: { collectionId: 'skills', kind: 'skill', id: item.id } } : {}),
+ input: { ...input, ...(item ? { expectedRevision: item.revision } : {}) },
+ },
+ ],
+ )) as { result?: unknown };
+ if (!boundedPluginResponse(response)) throw new Error('INVALID_RESPONSE');
+ return response?.result;
+}
+export function parseRemoteSkills(value: unknown): RemoteSkillsSnapshot {
+ const snapshot = value as RemoteSkillsSnapshot | null;
+ if (
+ !boundedPluginResponse(value) ||
+ snapshot?.version !== 1 ||
+ !Array.isArray(snapshot.items) ||
+ !Array.isArray(snapshot.market) ||
+ typeof snapshot.marketUnavailable !== 'boolean' ||
+ (snapshot.nextCursor !== null && typeof snapshot.nextCursor !== 'string') ||
+ !snapshot.items.every(
+ (i) =>
+ typeof i.id === 'string' &&
+ typeof i.revision === 'string' &&
+ typeof i.name === 'string' &&
+ typeof i.description === 'string' &&
+ ['skill', 'command', 'agent'].includes(i.kind) &&
+ ['global', 'project', 'user'].includes(i.scope) &&
+ typeof i.enabled === 'boolean' &&
+ typeof i.canUninstall === 'boolean' &&
+ typeof i.managedByPlugin === 'boolean' &&
+ typeof i.builtIn === 'boolean' &&
+ (i.projectId === undefined || typeof i.projectId === 'string') &&
+ (i.entryFile === undefined ||
+ (typeof i.entryFile === 'string' &&
+ !/[\\/]/.test(i.entryFile) &&
+ !['.', '..'].includes(i.entryFile))) &&
+ Array.isArray(i.engines) &&
+ i.engines.every((e) => typeof e === 'string') &&
+ (i.market === undefined ||
+ (typeof i.market.name === 'string' &&
+ (i.market.origin === undefined ||
+ ['installed', 'published', 'learned', 'imported'].includes(i.market.origin)) &&
+ (i.market.authorId === undefined ||
+ (typeof i.market.authorId === 'string' && i.market.authorId.length <= 256)) &&
+ (i.market.catalogScope === undefined ||
+ ['market', 'team'].includes(i.market.catalogScope)))),
+ ) ||
+ !snapshot.market.every(isRemoteSkillMarketItem) ||
+ (snapshot.projects !== undefined &&
+ (!Array.isArray(snapshot.projects) ||
+ !snapshot.projects.every(
+ (project) =>
+ project &&
+ typeof project.id === 'string' &&
+ typeof project.revision === 'string' &&
+ typeof project.name === 'string',
+ )))
+ )
+ throw new Error('INVALID_RESPONSE');
+ // Older Hosts can report Claude's native `user` scope for a global Skill.
+ return {
+ ...snapshot,
+ items: snapshot.items.map((item) =>
+ (item as { scope: string }).scope === 'user' ? { ...item, scope: 'global' as const } : item,
+ ),
+ };
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/skillhub-home.css b/apps/desktop/src/renderer/features/skillhub/skillhub-home.css
new file mode 100644
index 0000000000..24b69610dd
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/skillhub-home.css
@@ -0,0 +1,58 @@
+.skill-catalog-source-tabs.cindy-segmented {
+ flex-shrink: 1;
+ gap: var(--space-6);
+ padding: 0;
+ border-radius: 0;
+ background: transparent;
+ scrollbar-width: none;
+}
+
+.skill-catalog-source-tabs::-webkit-scrollbar {
+ display: none;
+}
+
+.skill-catalog-source-tabs > .cindy-segmented-plate {
+ display: none;
+}
+
+.skill-catalog-source-tabs > .cindy-segmented-option {
+ font-weight: 400;
+}
+
+.skill-catalog-source-tabs > .cindy-segmented-option:enabled:hover {
+ background: transparent;
+}
+
+.skill-catalog-source-tabs > .cindy-segmented-option[data-selected='true'] {
+ font-weight: 500;
+}
+
+.skill-catalog-source-tabs > .cindy-segmented-option[data-selected='true']::before {
+ position: absolute;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ height: 2px;
+ background: var(--text-primary);
+ content: '';
+}
+
+.skill-category-tags.cindy-segmented {
+ gap: var(--space-2);
+ padding: 0;
+ background: transparent;
+}
+
+.skill-category-tags > .cindy-segmented-plate {
+ border-color: transparent;
+ box-shadow: none;
+}
+
+.skill-category-tags > .cindy-segmented-option {
+ font-weight: 400;
+}
+
+.skill-catalog-source-tabs > .cindy-segmented-option:focus-visible,
+.skill-category-tags > .cindy-segmented-option:focus-visible {
+ outline-offset: -2px;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4d9d2efc03..3cb838d4e4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6355,7 +6355,7 @@
"bodyInvalid": "This plugin's installation verification record is damaged, so the plugin is paused. Reinstall the marketplace release or select the matching .cindy package again.",
"bodyBuiltinRestart": "Something went wrong with this built-in plugin's installation verification record. Restart Cindy to recover automatically — no other action is needed."
},
- "install": "Install Plugin…",
+ "install": "Install from file…",
"empty": "No plugins installed yet",
"emptyHint": "Install from the market, or import a .cindy file from the menu above",
"legacyRecovery": {
@@ -6379,14 +6379,19 @@
"projectDisabledTag": "Off in this project",
"projectSwitchLockedTip": "This plugin is disabled globally; enable it in the Global view first",
"projectBanner": {
- "title": "Configuring project \"{{name}}\"",
- "desc": "Switches here only affect this project — turned-off plugins are unavailable in it",
+ "title": "Current Project: {{name}}",
+ "desc": "Switches affect only this project. Installation, updates, removal, and configuration apply to {{device}}.",
"backToGlobal": "Back to global"
},
"scopePicker": {
"global": "Global (default)",
"ariaLabel": "Choose where plugins take effect",
- "browse": "Choose another folder…"
+ "browse": "Choose another folder…",
+ "management": "Management scope",
+ "globalScope": "Global",
+ "computers": "Computers",
+ "projectScope": "Project Scope",
+ "projectsForComputer": "Projects on {{device}}"
},
"enableAria": "Enable {{name}}",
"uninstall": "Uninstall",
@@ -6885,6 +6890,49 @@
"dataNotice": "Your original simulator devices and app data will not be deleted. Installing Baguette does not automatically migrate devices, apps, or sign-ins."
}
},
+ "remote": {
+ "device": "Manage computer",
+ "thisComputer": "This computer",
+ "offline": "Offline",
+ "confirmOn": "{{name}} on {{device}}",
+ "targetOnly": "Configuration is saved on {{device}}.",
+ "hostPreferencesUnavailable": "This computer does not support remote editing of model, task or sidebar preferences. Configure them on {{device}}.",
+ "taskWorkdirBoundary": "The working directory stays on the target computer. Change it there.",
+ "configurationLoading": "Loading settings…",
+ "configurationReadFailed": "Could not load settings.",
+ "refreshConfiguration": "Refresh Settings",
+ "enableBeforeConfigure": "This plugin is disabled. Enable it with the switch above before configuring.",
+ "settingsPageUnavailable": "Open Cindy on {{device}} to use this plugin’s settings page. This version of the target computer cannot display it remotely.",
+ "offlineNotice": "{{device}} is offline. Management is unavailable until the connection is restored.",
+ "managingTarget": "Managing {{device}}",
+ "managingDescription": "Changes are saved on this computer.",
+ "viewingTarget": "Installed on {{device}}",
+ "unsupported": "The Cindy version on {{device}} does not support remote management yet. You can view its installed plugins here. To install, update, uninstall, enable, disable or configure plugins and manage project settings, update Cindy on that computer.",
+ "refresh": "Refresh Plugins",
+ "instanceId": "Plugin Instance",
+ "detailLoading": "Reading plugin details…",
+ "detailReadFailed": "Could not read plugin details.",
+ "refreshDetail": "Refresh Details",
+ "detailUnavailable": "This computer has not provided all plugin details. Only the information it returned is shown.",
+ "retry": "Retry",
+ "readFailed": "Could not read plugins.",
+ "unknown": "The result is not confirmed. Query the original operation to check it.",
+ "success": "Completed on the target computer.",
+ "cancelled": "Cancelled.",
+ "actionFailed": "The operation failed. Refresh the list before trying again.",
+ "changed": "The plugin changed. Refresh before trying again.",
+ "uninstallOn": "Uninstall {{name}} from {{device}}?",
+ "uninstall": "Uninstall",
+ "empty": "No plugins installed on this computer.",
+ "marketUnavailable": "The target computer’s plugin market is unavailable.",
+ "personalInstall": "Personal installation",
+ "loading": "Reading plugins…",
+ "installDestination": "Install to: {{device}}",
+ "projectsUnsupported": "Update Cindy on this computer to manage project settings.",
+ "noProjects": "No projects are available on this computer yet.",
+ "projectLoading": "Reading project settings…",
+ "projectReadFailed": "Could not read project settings. Try again."
+ },
"usage": {
"title": "Your calls",
"explanationLabel": "How usage is counted",
@@ -13697,6 +13745,17 @@
"projectSkillNotLoaded": "This Pi task hasn't loaded this project Skill. New tasks will automatically try to load it."
},
"skillhub": {
+ "remote": {
+ "loading": "Loading skills…",
+ "readFailed": "Could not load skills. Try again.",
+ "unsupported": "Update Cindy on the target computer to manage skills remotely.",
+ "confirm": {
+ "install": "Install {{name}} on {{device}}?",
+ "update": "Update {{name}} on {{device}} to v{{version}}?",
+ "uninstall": "Uninstall {{name}} from {{device}}?",
+ "installDescription": "The skill will be saved on the selected computer. Updates keep a backup of the existing files."
+ }
+ },
"unifiedDetail": {
"contentSource": "Content source",
"local": "Local",
@@ -13714,17 +13773,13 @@
},
"home": {
"title": "Skills",
- "description": "Manage local skills, or discover and install more from Skill Hub.",
+ "description": "Manage installed skills or discover more in SkillHub.",
"descriptionLocalOnly": "Manage the local skills installed on this device.",
"search": "Search skills",
"clearSearch": "Clear skill search",
"noSearchResults": "No matching skills found",
"catalogFiltersAria": "SkillHub categories",
"categoryFiltersAria": "Filter skills by category",
- "scrollCategoriesLeft": "View more categories to the left",
- "scrollCategoriesRight": "View more categories to the right",
- "categoryScrollAtStart": "Already at the first category",
- "categoryScrollAtEnd": "Already at the last category",
"catalogFilter": {
"public": "Public",
"organization": "Organization",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 06e87995fc..e177c8d9bc 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6326,7 +6326,7 @@
"bodyInvalid": "このプラグインのインストール検証記録が破損しているため、実行を停止しています。元のマーケット版を再インストールするか、対応する .cindy パッケージをもう一度選択してください。",
"bodyBuiltinRestart": "この内蔵プラグインのインストール検証記録に問題が発生しました。Cindy を再起動すると自動的に復旧します。他の操作は不要です。"
},
- "install": "プラグインをインストール…",
+ "install": "ファイルからインストール…",
"empty": "まだプラグインがインストールされていません",
"emptyHint": "マーケットからインストールするか、上のメニューから .cindy ファイルを読み込めます",
"legacyRecovery": {
@@ -6350,14 +6350,19 @@
"projectDisabledTag": "このプロジェクトでは無効",
"projectSwitchLockedTip": "このプラグインはグローバルで無効です。先に「グローバル」ビューで有効にしてください",
"projectBanner": {
- "title": "プロジェクト「{{name}}」を設定中",
- "desc": "ここのスイッチはこのプロジェクトのみに適用されます。オフにしたプラグインはこのプロジェクトでは使用できません",
+ "title": "現在のプロジェクト:{{name}}",
+ "desc": "スイッチの変更はこのプロジェクトにのみ適用されます。インストール・更新・アンインストール・設定は{{device}}全体に適用されます。",
"backToGlobal": "グローバルに戻る"
},
"scopePicker": {
"global": "グローバル(デフォルト)",
"ariaLabel": "プラグインの適用範囲を選択",
- "browse": "別のフォルダを選択…"
+ "browse": "別のフォルダを選択…",
+ "management": "管理範囲",
+ "globalScope": "グローバル",
+ "computers": "コンピューター",
+ "projectScope": "プロジェクト範囲",
+ "projectsForComputer": "{{device}}のプロジェクト"
},
"enableAria": "{{name}} を有効化",
"uninstall": "アンインストール",
@@ -6856,6 +6861,49 @@
"dataNotice": "元のシミュレーターのデバイスや App データは削除されません。Baguette をインストールしても、デバイス、App、ログイン状態は自動移行されません。"
}
},
+ "remote": {
+ "device": "管理するコンピューター",
+ "thisComputer": "このコンピューター",
+ "offline": "オフライン",
+ "confirmOn": "{{device}} 上の {{name}}",
+ "targetOnly": "設定は {{device}} に保存されます。",
+ "hostPreferencesUnavailable": "このコンピューターはモデル・タスク・サイドバーの設定のリモート編集に対応していません。{{device}}で設定してください。",
+ "taskWorkdirBoundary": "作業ディレクトリは対象コンピューターの設定を維持します。変更は対象コンピューターで行ってください。",
+ "configurationLoading": "設定を読み込み中…",
+ "configurationReadFailed": "設定を読み込めませんでした。",
+ "refreshConfiguration": "設定を更新",
+ "enableBeforeConfigure": "このプラグインは無効です。設定するには、上のスイッチをオンにしてください。",
+ "settingsPageUnavailable": "{{device}} の Cindy でこのプラグインの設定ページを開いてください。接続先の現在のバージョンではリモート表示に対応していません。",
+ "offlineNotice": "{{device}}はオフラインです。接続が復旧すると管理を再開できます。",
+ "managingTarget": "管理対象:{{device}}",
+ "managingDescription": "変更はこのコンピューターに保存されます。",
+ "viewingTarget": "{{device}} にインストール済み",
+ "unsupported": "{{device}} の Cindy は、まだリモート管理に対応していません。インストール済みプラグインはここで確認できます。インストール、更新、アンインストール、有効・無効の切り替え、設定、プロジェクト管理を行うには、そのコンピューターの Cindy を更新してください。",
+ "refresh": "プラグインを再読み込み",
+ "instanceId": "プラグインインスタンス",
+ "detailLoading": "プラグインの詳細を読み込み中…",
+ "detailReadFailed": "プラグインの詳細を読み込めませんでした。",
+ "refreshDetail": "詳細を再読み込み",
+ "detailUnavailable": "このコンピューターからプラグインの詳細がすべて提供されていないため、取得できた情報のみ表示しています。",
+ "retry": "再試行",
+ "readFailed": "プラグインを読み込めませんでした。",
+ "unknown": "操作結果は未確認です。元の操作結果を確認してください。",
+ "success": "対象コンピューターで完了しました。",
+ "cancelled": "キャンセルしました。",
+ "actionFailed": "操作に失敗しました。一覧を更新して再試行してください。",
+ "changed": "プラグインが変更されました。更新して再試行してください。",
+ "uninstallOn": "{{device}} から {{name}} をアンインストールしますか?",
+ "uninstall": "アンインストール",
+ "empty": "このコンピューターにはプラグインがありません。",
+ "marketUnavailable": "対象コンピューターのマーケットを利用できません。",
+ "personalInstall": "個人のインストール",
+ "loading": "プラグインを読み込み中…",
+ "installDestination": "インストール先:{{device}}",
+ "projectsUnsupported": "プロジェクト設定を管理するには、対象コンピューターの Cindy を更新してください。",
+ "noProjects": "このコンピューターには選択できるプロジェクトがまだありません。",
+ "projectLoading": "プロジェクト設定を読み込み中…",
+ "projectReadFailed": "プロジェクト設定を読み込めませんでした。再試行してください。"
+ },
"usage": {
"title": "自分の呼び出し",
"explanationLabel": "集計方法",
@@ -13639,6 +13687,17 @@
"projectSkillNotLoaded": "現在の Pi タスクでは、このプロジェクト Skill はまだ読み込まれていません。新しいタスクでは自動的に読み込みを試みます。"
},
"skillhub": {
+ "remote": {
+ "loading": "スキルを読み込み中…",
+ "readFailed": "スキルを読み込めませんでした。再試行してください。",
+ "unsupported": "リモートでスキルを管理するには、対象のコンピューターの Cindy を更新してください。",
+ "confirm": {
+ "install": "{{device}} に {{name}} をインストールしますか?",
+ "update": "{{device}} の {{name}} を v{{version}} に更新しますか?",
+ "uninstall": "{{device}} から {{name}} をアンインストールしますか?",
+ "installDescription": "スキルは選択したコンピューターに保存されます。更新時は元のファイルのバックアップを保持します。"
+ }
+ },
"unifiedDetail": {
"contentSource": "表示する内容",
"local": "ローカル",
@@ -13656,17 +13715,13 @@
},
"home": {
"title": "スキル",
- "description": "ローカルスキルを管理し、Skill Hub から新しいスキルを見つけてインストールできます。",
+ "description": "インストール済みのスキルを管理し、SkillHub で新しいスキルを探します。",
"descriptionLocalOnly": "このデバイスにインストールされたローカルスキルを管理します。",
"search": "スキルを検索",
"clearSearch": "スキル検索をクリア",
"noSearchResults": "一致するスキルが見つかりません",
"catalogFiltersAria": "SkillHub カテゴリ",
"categoryFiltersAria": "カテゴリでスキルを絞り込む",
- "scrollCategoriesLeft": "左のカテゴリをさらに表示",
- "scrollCategoriesRight": "右のカテゴリをさらに表示",
- "categoryScrollAtStart": "最初のカテゴリです",
- "categoryScrollAtEnd": "最後のカテゴリです",
"catalogFilter": {
"public": "公開",
"organization": "組織",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index cf7ce97f33..a6b63924bb 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6326,7 +6326,7 @@
"bodyInvalid": "이 플러그인의 설치 확인 기록이 손상되어 실행을 중지했습니다. 원래 마켓 버전을 다시 설치하거나 해당 .cindy 패키지를 다시 선택해 주세요.",
"bodyBuiltinRestart": "이 내장 플러그인의 설치 확인 기록에 문제가 발생했습니다. Cindy를 다시 시작하면 자동으로 복구되며 다른 조치는 필요하지 않습니다."
},
- "install": "플러그인 설치…",
+ "install": "파일에서 설치…",
"empty": "아직 설치된 플러그인이 없습니다",
"emptyHint": "마켓에서 설치하거나 위 메뉴에서 .cindy 파일을 가져올 수 있습니다",
"legacyRecovery": {
@@ -6350,14 +6350,19 @@
"projectDisabledTag": "이 프로젝트에서 꺼짐",
"projectSwitchLockedTip": "이 플러그인은 전역에서 비활성 상태입니다. 먼저 '전역' 보기에서 활성화해 주세요",
"projectBanner": {
- "title": "프로젝트 \"{{name}}\" 설정 중",
- "desc": "여기 스위치는 이 프로젝트에만 적용됩니다. 끈 플러그인은 이 프로젝트에서 사용할 수 없습니다",
+ "title": "현재 프로젝트: {{name}}",
+ "desc": "스위치 변경은 이 프로젝트에만 적용됩니다. 설치, 업데이트, 제거 및 설정은 {{device}} 전체에 적용됩니다.",
"backToGlobal": "전역으로 돌아가기"
},
"scopePicker": {
"global": "전역(기본값)",
"ariaLabel": "플러그인 적용 범위 선택",
- "browse": "다른 폴더 선택…"
+ "browse": "다른 폴더 선택…",
+ "management": "관리 범위",
+ "globalScope": "전역",
+ "computers": "컴퓨터",
+ "projectScope": "프로젝트 범위",
+ "projectsForComputer": "{{device}}의 프로젝트"
},
"enableAria": "{{name}} 활성화",
"uninstall": "제거",
@@ -6856,6 +6861,49 @@
"dataNotice": "기존 시뮬레이터 기기와 App 데이터는 삭제되지 않습니다. Baguette를 설치해도 기기, App, 로그인 상태는 자동으로 이전되지 않습니다."
}
},
+ "remote": {
+ "device": "관리할 컴퓨터",
+ "thisComputer": "현재 컴퓨터",
+ "offline": "오프라인",
+ "confirmOn": "{{device}}의 {{name}}",
+ "targetOnly": "설정은 {{device}}에 저장됩니다.",
+ "hostPreferencesUnavailable": "이 컴퓨터는 모델, 작업 및 사이드바 환경설정의 원격 편집을 지원하지 않습니다. {{device}}에서 설정하세요.",
+ "taskWorkdirBoundary": "작업 디렉터리는 대상 컴퓨터의 설정을 유지합니다. 대상 컴퓨터에서 변경하세요.",
+ "configurationLoading": "설정을 불러오는 중…",
+ "configurationReadFailed": "설정을 불러오지 못했습니다.",
+ "refreshConfiguration": "설정 새로고침",
+ "enableBeforeConfigure": "이 플러그인은 비활성화되어 있습니다. 설정하려면 위의 스위치를 켜세요.",
+ "settingsPageUnavailable": "{{device}}의 Cindy에서 이 플러그인의 설정 페이지를 열어 주세요. 대상 컴퓨터의 현재 버전은 원격 표시를 지원하지 않습니다。",
+ "offlineNotice": "{{device}}이(가) 오프라인입니다. 연결이 복구되면 관리를 계속할 수 있습니다.",
+ "managingTarget": "관리 대상: {{device}}",
+ "managingDescription": "변경 사항은 이 컴퓨터에 저장됩니다.",
+ "viewingTarget": "{{device}}에 설치된 플러그인",
+ "unsupported": "{{device}}의 Cindy 버전은 아직 원격 관리를 지원하지 않습니다. 설치된 플러그인은 여기서 확인할 수 있습니다. 설치, 업데이트, 제거, 활성화·비활성화, 설정 및 프로젝트 관리를 하려면 해당 컴퓨터에서 Cindy를 업데이트하세요.",
+ "refresh": "플러그인 새로 고침",
+ "instanceId": "플러그인 인스턴스",
+ "detailLoading": "플러그인 세부 정보를 불러오는 중…",
+ "detailReadFailed": "플러그인 세부 정보를 불러오지 못했습니다.",
+ "refreshDetail": "세부 정보 새로 고침",
+ "detailUnavailable": "이 컴퓨터에서 플러그인의 전체 세부 정보를 제공하지 않아 반환된 정보만 표시합니다.",
+ "retry": "다시 시도",
+ "readFailed": "플러그인을 읽을 수 없습니다.",
+ "unknown": "작업 결과가 확인되지 않았습니다. 원래 작업 결과를 조회하세요.",
+ "success": "대상 컴퓨터에서 완료했습니다.",
+ "cancelled": "취소했습니다.",
+ "actionFailed": "작업에 실패했습니다. 목록을 새로 고친 후 다시 시도하세요.",
+ "changed": "플러그인이 변경되었습니다. 새로 고친 후 다시 시도하세요.",
+ "uninstallOn": "{{device}}에서 {{name}}을(를) 제거할까요?",
+ "uninstall": "제거",
+ "empty": "이 컴퓨터에 설치된 플러그인이 없습니다.",
+ "marketUnavailable": "대상 컴퓨터의 마켓을 사용할 수 없습니다.",
+ "personalInstall": "개인 설치",
+ "loading": "플러그인 읽는 중…",
+ "installDestination": "설치 대상: {{device}}",
+ "projectsUnsupported": "프로젝트 설정을 관리하려면 대상 컴퓨터의 Cindy를 업데이트하세요.",
+ "noProjects": "이 컴퓨터에는 아직 선택할 프로젝트가 없습니다.",
+ "projectLoading": "프로젝트 설정을 읽는 중…",
+ "projectReadFailed": "프로젝트 설정을 읽지 못했습니다. 다시 시도하세요."
+ },
"usage": {
"title": "내 호출",
"explanationLabel": "집계 방식",
@@ -13639,6 +13687,17 @@
"projectSkillNotLoaded": "현재 Pi 작업에는 이 프로젝트 Skill이 아직 로드되지 않았습니다. 새 작업에서는 자동으로 로드를 시도합니다."
},
"skillhub": {
+ "remote": {
+ "loading": "스킬을 불러오는 중…",
+ "readFailed": "스킬을 불러오지 못했습니다. 다시 시도해 주세요.",
+ "unsupported": "원격으로 스킬을 관리하려면 대상 컴퓨터의 Cindy를 업데이트하세요.",
+ "confirm": {
+ "install": "{{device}}에 {{name}}을 설치할까요?",
+ "update": "{{device}}의 {{name}}을 v{{version}}으로 업데이트할까요?",
+ "uninstall": "{{device}}에서 {{name}}을 제거할까요?",
+ "installDescription": "스킬은 선택한 컴퓨터에 저장됩니다. 업데이트 전에 기존 파일의 백업을 보관합니다."
+ }
+ },
"unifiedDetail": {
"contentSource": "콘텐츠 출처",
"local": "로컬",
@@ -13656,17 +13715,13 @@
},
"home": {
"title": "스킬",
- "description": "로컬 스킬을 관리하거나 Skill Hub에서 새로운 스킬을 찾아 설치하세요.",
+ "description": "설치된 스킬을 관리하거나 SkillHub에서 더 많은 스킬을 찾아보세요.",
"descriptionLocalOnly": "이 기기에 설치된 로컬 스킬을 관리하세요.",
"search": "스킬 검색",
"clearSearch": "스킬 검색 지우기",
"noSearchResults": "일치하는 스킬을 찾을 수 없습니다",
"catalogFiltersAria": "SkillHub 카테고리",
"categoryFiltersAria": "카테고리로 스킬 필터링",
- "scrollCategoriesLeft": "왼쪽 카테고리 더 보기",
- "scrollCategoriesRight": "오른쪽 카테고리 더 보기",
- "categoryScrollAtStart": "첫 번째 카테고리입니다",
- "categoryScrollAtEnd": "마지막 카테고리입니다",
"catalogFilter": {
"public": "공개",
"organization": "조직",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 72cff2848c..31713f2726 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6326,7 +6326,7 @@
"bodyInvalid": "这个插件的安装验证记录已损坏,因此已暂停运行。请重新安装原市场版本,或重新选择对应的 .cindy 包。",
"bodyBuiltinRestart": "这个内置插件的安装验证记录出了问题。重启 Cindy 即可自动恢复,无需其他操作。"
},
- "install": "安装插件…",
+ "install": "从文件安装…",
"empty": "还没有安装任何插件",
"emptyHint": "可从插件市场安装,或点击右上角导入 .cindy 文件",
"legacyRecovery": {
@@ -6350,14 +6350,19 @@
"projectDisabledTag": "本项目已停用",
"projectSwitchLockedTip": "该插件已在全局停用;请先切回「全局」视图启用",
"projectBanner": {
- "title": "正在配置项目「{{name}}」",
- "desc": "开关只影响此项目:关闭的插件在该项目中不可用",
+ "title": "当前项目:{{name}}",
+ "desc": "开关仅影响此项目;安装、更新、卸载和配置作用于{{device}}。",
"backToGlobal": "返回全局"
},
"scopePicker": {
"global": "全局(默认)",
"ariaLabel": "选择插件启用范围",
- "browse": "选择其它目录…"
+ "browse": "选择其它目录…",
+ "management": "管理范围",
+ "globalScope": "全局",
+ "computers": "电脑",
+ "projectScope": "项目范围",
+ "projectsForComputer": "{{device}}上的项目"
},
"enableAria": "启用 {{name}}",
"uninstall": "卸载",
@@ -6856,6 +6861,49 @@
"dataNotice": "原模拟器的设备和应用数据不会被删除。安装 Baguette 不会自动迁移设备、App 或登录状态。"
}
},
+ "remote": {
+ "device": "管理电脑",
+ "thisComputer": "当前电脑",
+ "offline": "离线",
+ "confirmOn": "在 {{device}} 上操作 {{name}}",
+ "targetOnly": "配置保存在 {{device}}。",
+ "hostPreferencesUnavailable": "这台电脑暂不支持远程编辑模型、任务和侧栏偏好,请在{{device}}上配置。",
+ "taskWorkdirBoundary": "工作目录沿用目标电脑的设置,请在目标电脑修改。",
+ "configurationLoading": "正在读取设置…",
+ "configurationReadFailed": "未能读取设置。",
+ "refreshConfiguration": "刷新设置",
+ "enableBeforeConfigure": "插件已停用,请先打开上方开关,再进行配置。",
+ "settingsPageUnavailable": "请在 {{device}} 的 Cindy 中打开此插件的设置页,目标电脑当前版本暂不支持远程显示。",
+ "offlineNotice": "「{{device}}」已离线,暂时无法管理。连接恢复后可继续。",
+ "managingTarget": "正在管理「{{device}}」",
+ "managingDescription": "更改将保存在这台电脑上。",
+ "viewingTarget": "「{{device}}」的已装插件",
+ "unsupported": "「{{device}}」的 Cindy 版本尚不支持远程管理。当前可查看它的已装插件;如需安装、升级、卸载、启停、配置或项目管理,请先在该电脑更新 Cindy。",
+ "refresh": "刷新插件",
+ "instanceId": "插件实例",
+ "detailLoading": "正在读取插件详情…",
+ "detailReadFailed": "未能读取插件详情",
+ "refreshDetail": "刷新详情",
+ "detailUnavailable": "该电脑未提供完整的插件详情,此处仅展示已返回的信息。",
+ "retry": "重试",
+ "readFailed": "无法读取插件,请重试。",
+ "unknown": "操作结果尚未确认,可查询原操作结果。",
+ "success": "目标电脑已完成操作。",
+ "cancelled": "已取消。",
+ "actionFailed": "操作失败,请刷新列表后重试。",
+ "changed": "插件已发生变化,请刷新后重试。",
+ "uninstallOn": "从 {{device}} 卸载 {{name}}?",
+ "uninstall": "卸载",
+ "empty": "这台电脑尚未安装插件。",
+ "marketUnavailable": "目标电脑的插件市场暂时不可用。",
+ "personalInstall": "个人安装",
+ "loading": "正在读取插件…",
+ "installDestination": "安装到:{{device}}",
+ "projectsUnsupported": "目标电脑暂不支持项目管理,请更新该电脑上的 Cindy。",
+ "noProjects": "这台电脑还没有可选项目。",
+ "projectLoading": "正在读取项目开关…",
+ "projectReadFailed": "项目开关读取失败,请重试。"
+ },
"usage": {
"title": "个人调用",
"explanationLabel": "统计口径",
@@ -13639,6 +13687,17 @@
"projectSkillNotLoaded": "当前 Pi 任务尚未加载此项目 Skill,新任务会自动尝试加载"
},
"skillhub": {
+ "remote": {
+ "loading": "正在读取技能…",
+ "readFailed": "无法读取技能,请重试。",
+ "unsupported": "目标电脑暂不支持远程技能管理,请更新其 Cindy。",
+ "confirm": {
+ "install": "在“{{device}}”安装“{{name}}”?",
+ "update": "将“{{device}}”的“{{name}}”更新至 v{{version}}?",
+ "uninstall": "从“{{device}}”卸载“{{name}}”?",
+ "installDescription": "技能将写入所选电脑,更新前保留原文件备份。"
+ }
+ },
"unifiedDetail": {
"contentSource": "内容来源",
"local": "本地",
@@ -13656,17 +13715,13 @@
},
"home": {
"title": "技能",
- "description": "管理本地技能,或从 Skill Hub 发现并安装更多技能。",
+ "description": "管理已安装的技能,或从 SkillHub 发现更多技能。",
"descriptionLocalOnly": "管理本机安装的本地技能。",
"search": "搜索技能",
"clearSearch": "清除技能搜索",
"noSearchResults": "没有找到匹配的技能",
"catalogFiltersAria": "SkillHub 分类",
"categoryFiltersAria": "按分类筛选技能",
- "scrollCategoriesLeft": "向左查看更多分类",
- "scrollCategoriesRight": "向右查看更多分类",
- "categoryScrollAtStart": "已经是第一个分类",
- "categoryScrollAtEnd": "已经是最后一个分类",
"catalogFilter": {
"public": "公开",
"organization": "组织",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c15274944c..6bb3247b89 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6317,7 +6317,7 @@
"replaceAria": "以此市場版本取代 {{name}}",
"replaceDescription": "已安裝相同 ID 的插件;繼續安裝會切換來源。原來源的資料將隔離保留,新來源不會繼承原帳號和金鑰,需要重新連接。"
},
- "install": "安裝插件…",
+ "install": "從檔案安裝…",
"empty": "還沒有安裝任何插件",
"emptyHint": "可從插件市場安裝,或點選右上角匯入 .cindy 檔案",
"reapproval": {
@@ -6350,14 +6350,19 @@
"projectDisabledTag": "本專案未生效",
"projectSwitchLockedTip": "該插件已在全域性停用;請先切回「全域性」檢視開啟",
"projectBanner": {
- "title": "正在配置專案「{{name}}」",
- "desc": "開關只影響此專案:關閉的插件在該專案中不可用",
+ "title": "目前專案:{{name}}",
+ "desc": "開關僅影響此專案;安裝、更新、解除安裝與設定會套用至{{device}}。",
"backToGlobal": "返回全域性"
},
"scopePicker": {
"global": "全域性(預設)",
"ariaLabel": "選擇插件生效範圍",
- "browse": "選擇其它目錄…"
+ "browse": "選擇其它目錄…",
+ "management": "管理範圍",
+ "globalScope": "全域",
+ "computers": "電腦",
+ "projectScope": "專案範圍",
+ "projectsForComputer": "{{device}}上的專案"
},
"enableAria": "使 {{name}} 生效",
"uninstall": "解除安裝",
@@ -6856,6 +6861,49 @@
"dataNotice": "原模擬器的裝置和應用程式資料不會被刪除。安裝 Baguette 不會自動遷移裝置、App 或登入狀態。"
}
},
+ "remote": {
+ "device": "管理電腦",
+ "thisComputer": "目前電腦",
+ "offline": "離線",
+ "confirmOn": "在 {{device}} 上操作 {{name}}",
+ "targetOnly": "設定儲存在 {{device}}。",
+ "hostPreferencesUnavailable": "這台電腦暫不支援遠端編輯模型、任務與側欄偏好,請在{{device}}上配置。",
+ "taskWorkdirBoundary": "工作目錄沿用目標電腦的設定,請在目標電腦修改。",
+ "configurationLoading": "正在讀取設定…",
+ "configurationReadFailed": "未能讀取設定。",
+ "refreshConfiguration": "重新整理設定",
+ "enableBeforeConfigure": "插件已停用,請先開啟上方開關,再進行設定。",
+ "settingsPageUnavailable": "請在 {{device}} 的 Cindy 中開啟此插件的設定頁,目標電腦目前版本暫不支援遠端顯示。",
+ "offlineNotice": "「{{device}}」已離線,暫時無法管理。連線恢復後即可繼續。",
+ "managingTarget": "正在管理「{{device}}」",
+ "managingDescription": "變更將儲存在這台電腦上。",
+ "viewingTarget": "「{{device}}」的已安裝插件",
+ "unsupported": "「{{device}}」的 Cindy 版本尚不支援遠端管理。目前可檢視它的已安裝插件;如需安裝、升級、解除安裝、啟用、停用、設定或專案管理,請先在該電腦更新 Cindy。",
+ "refresh": "重新整理插件",
+ "instanceId": "插件執行個體",
+ "detailLoading": "正在讀取插件詳情…",
+ "detailReadFailed": "未能讀取插件詳情",
+ "refreshDetail": "重新整理詳情",
+ "detailUnavailable": "該電腦未提供完整的插件詳情,此處僅顯示已傳回的資訊。",
+ "retry": "重試",
+ "readFailed": "無法讀取插件,請重試。",
+ "unknown": "操作結果尚未確認,可查詢原操作結果。",
+ "success": "目標電腦已完成操作。",
+ "cancelled": "已取消。",
+ "actionFailed": "操作失敗,請重新整理列表後重試。",
+ "changed": "插件已變更,請重新整理後重試。",
+ "uninstallOn": "從 {{device}} 卸載 {{name}}?",
+ "uninstall": "卸載",
+ "empty": "這台電腦尚未安裝插件。",
+ "marketUnavailable": "目標電腦的插件市場暫時無法使用。",
+ "personalInstall": "個人安裝",
+ "loading": "正在讀取插件…",
+ "installDestination": "安裝到:{{device}}",
+ "projectsUnsupported": "目標電腦尚不支援專案管理,請更新該電腦上的 Cindy。",
+ "noProjects": "這台電腦還沒有可選專案。",
+ "projectLoading": "正在讀取專案開關…",
+ "projectReadFailed": "專案開關讀取失敗,請重試。"
+ },
"usage": {
"title": "個人呼叫",
"explanationLabel": "統計口徑",
@@ -13639,6 +13687,17 @@
"projectSkillNotLoaded": "目前的 Pi 任務尚未載入此專案 Skill,新任務會自動嘗試載入"
},
"skillhub": {
+ "remote": {
+ "loading": "正在讀取技能…",
+ "readFailed": "無法讀取技能,請重試。",
+ "unsupported": "目標電腦暫不支援遠端技能管理,請更新其 Cindy。",
+ "confirm": {
+ "install": "在「{{device}}」安裝「{{name}}」?",
+ "update": "將「{{device}}」的「{{name}}」更新至 v{{version}}?",
+ "uninstall": "從「{{device}}」解除安裝「{{name}}」?",
+ "installDescription": "技能將寫入所選電腦,更新前保留原檔案備份。"
+ }
+ },
"unifiedDetail": {
"contentSource": "內容來源",
"local": "本機",
@@ -13656,17 +13715,13 @@
},
"home": {
"title": "技能",
- "description": "管理本地技能,或從 Skill Hub 發現並安裝更多技能。",
+ "description": "管理已安裝的技能,或從 SkillHub 探索更多技能。",
"descriptionLocalOnly": "管理本機安裝的本地技能。",
"search": "搜尋技能",
"clearSearch": "清除技能搜尋",
"noSearchResults": "沒有找到匹配的技能",
"catalogFiltersAria": "SkillHub 分類",
"categoryFiltersAria": "按分類篩選技能",
- "scrollCategoriesLeft": "向左查看更多分類",
- "scrollCategoriesRight": "向右查看更多分類",
- "categoryScrollAtStart": "已經是第一個分類",
- "categoryScrollAtEnd": "已經是最後一個分類",
"catalogFilter": {
"public": "公開",
"organization": "組織",