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(desktop): refresh installed plugin display metadata (#671)

xxxccd550bc14b000
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index a674c5f4f5..3f0c5256ed 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -158,6 +158,50 @@ function harness(items: VisiblePluginSummary[]) {
}
describe('PluginMarketService migration and defaultInstall', () => {
+ it('projects same-release display metadata without reinstalling the package', async () => {
+ runtime.ghosts = [
+ {
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: false,
+ },
+ ];
+ const item = summary({
+ name: 'Renamed Plugin',
+ description: 'Updated market description',
+ author: 'Updated Publisher',
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-07-27T00:00:00.000Z',
+ });
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [
+ {
+ name: 'Renamed Plugin',
+ description: 'Updated market description',
+ author: 'Updated Publisher',
+ releaseId: 'release-1',
+ version: '1.0.0',
+ installState: 'installed',
+ enabled: false,
+ },
+ ],
+ unavailableReason: null,
+ });
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
it('passes the optional release icon metadata to renderer-safe market items', async () => {
const icon = {
mimeType: 'image/png',
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
index 91b8350baf..76570075a6 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
@@ -6,9 +6,11 @@
import { describe, expect, it } from 'vitest';
import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';
+import type { PluginMarketItem } from '../../../shared/pluginMarket';
import {
filterGhostPluginItems,
ghostFallbackIconKind,
+ marketPresentationForInstalledGhost,
sortGhostPluginItemsByRecentUse,
toGhostPluginDetail,
toGhostPluginListItem,
@@ -56,6 +58,32 @@ function installed(overrides: Partial<InstalledGhost> = {}): InstalledGhost {
};
}
+function marketItem(overrides: Partial<PluginMarketItem> = {}): PluginMarketItem {
+ return {
+ pluginId: `c${'a'.repeat(24)}`,
+ ghostId: 'xd-mivo',
+ name: 'Mivo Studio',
+ description: 'Latest market description.',
+ author: 'Xindong Design',
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: false,
+ releaseId: 'release-1',
+ version: '1.5.10',
+ publishedAt: '2026-07-27T00:00:00.000Z',
+ icon: {
+ mimeType: 'image/png',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 128,
+ url: 'https://plugin.example.invalid/mivo.png?signature=new',
+ expiresAt: '2026-07-27T01:00:00.000Z',
+ },
+ installState: 'installed',
+ enabled: true,
+ ...overrides,
+ };
+}
+
describe('ghostPluginViewModel', () => {
it('maps iconless Plugins to restrained functional fallback symbols', () => {
expect(ghostFallbackIconKind('Lizi Mivo', 'lizi-mivo')).toBe('media');
@@ -117,6 +145,63 @@ describe('ghostPluginViewModel', () => {
});
});
+ it('overlays exact installed market presentation without changing runtime facts', () => {
+ const ghost = installed({
+ iconDataUrl: 'data:image/png;base64,OLD',
+ enabled: false,
+ });
+ const presentation = marketPresentationForInstalledGhost(ghost, marketItem());
+
+ expect(toGhostPluginListItem(ghost, presentation)).toMatchObject({
+ id: 'xd-mivo',
+ name: 'Mivo Studio',
+ description: 'Latest market description.',
+ iconDataUrl: 'https://plugin.example.invalid/mivo.png?signature=new',
+ version: '1.5.10',
+ enabled: false,
+ canUse: true,
+ });
+ const detail = toGhostPluginDetail(ghost, presentation);
+ expect(detail.author).toBe('Xindong Design');
+ expect(detail.permissions.map((item) => item.kind)).toEqual([
+ 'network',
+ 'network',
+ 'tool',
+ 'tool',
+ 'command',
+ 'card',
+ 'code',
+ ]);
+ });
+
+ it('treats a market null icon as an explicit presentation override', () => {
+ const ghost = installed({ iconDataUrl: 'data:image/png;base64,OLD' });
+ const presentation = marketPresentationForInstalledGhost(ghost, marketItem({ icon: null }));
+
+ expect(presentation).not.toBeNull();
+ expect(toGhostPluginListItem(ghost, presentation)).not.toHaveProperty('iconDataUrl');
+ });
+
+ it.each([
+ ['local market miss', null],
+ ['not installed', marketItem({ installState: 'not-installed' })],
+ ['source conflict', marketItem({ installState: 'conflict' })],
+ ['pending update', marketItem({ installState: 'update-available', version: '1.6.0' })],
+ ['unresolved same-version provenance', marketItem({ installState: 'update-available' })],
+ ['version mismatch', marketItem({ version: '1.6.0' })],
+ ['ghost ID mismatch', marketItem({ ghostId: 'another-plugin' })],
+ ] as const)('keeps local presentation for %s', (_label, item) => {
+ const ghost = installed({ iconDataUrl: 'data:image/png;base64,LOCAL' });
+ const presentation = marketPresentationForInstalledGhost(ghost, item);
+
+ expect(presentation).toBeNull();
+ expect(toGhostPluginListItem(ghost, presentation)).toMatchObject({
+ name: 'XD Mivo',
+ description: 'Generate media assets.',
+ iconDataUrl: 'data:image/png;base64,LOCAL',
+ });
+ });
+
it('keeps disabled state and does not invent marketplace fields', () => {
const item = toGhostPluginListItem(installed({ enabled: false }));
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index e3bf022c27..1e41072555 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -73,6 +73,7 @@ interface GhostPluginDetailViewProps {
updateBusy?: boolean;
onUninstall: () => void;
toggleDisabled: boolean;
+ onIconLoadError?: () => void;
}
const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {
@@ -132,6 +133,7 @@ export function GhostPluginDetailView({
updateBusy = false,
onUninstall,
toggleDisabled,
+ onIconLoadError,
}: GhostPluginDetailViewProps) {
const { t } = useTranslation();
const [descriptionExpanded, setDescriptionExpanded] = useState(false);
@@ -205,6 +207,7 @@ export function GhostPluginDetailView({
iconId={detail.id}
iconName={detail.name}
size="detail"
+ onIconLoadError={onIconLoadError}
/>
<div className="min-w-0">
<h1 className="truncate text-28 font-medium leading-[34px] text-[var(--text-primary)]">
@@ -229,7 +232,9 @@ export function GhostPluginDetailView({
'disabled:cursor-wait disabled:opacity-40 disabled:active:scale-100',
)}
>
- {t('settings.ghosts.market.updateTo', { version: updateVersion })}
+ {updateVersion === detail.version
+ ? t('settings.ghosts.market.update')
+ : t('settings.ghosts.market.updateTo', { version: updateVersion })}
</button>
) : null}
<button
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index c692a2a60a..6db962585c 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -55,6 +55,7 @@ import {
toGhostPluginDetail,
toGhostPluginListItem,
filterGhostPluginItems,
+ marketPresentationForInstalledGhost,
sortGhostPluginItemsByRecentUse,
type GhostPluginListItem,
} from './lib/ghostPluginViewModel';
@@ -71,10 +72,12 @@ import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker'
import {
orderPluginCatalogItems,
pluginPresentationOrigin,
+ pluginUpdateForInstalledVersion,
type PluginPresentationOrigin,
} from './lib/pluginMarketPresentation';
import { pluginMarketErrorKey } from './lib/pluginMarketErrorKey';
import { usePluginIconRefresh } from './lib/usePluginIconRefresh';
+import { usePluginMarketForegroundRefresh } from './lib/usePluginMarketForegroundRefresh';
import './plugin-motion.css';
const MAX_VISIBLE_INSTALLED_GHOSTS = 5;
@@ -145,6 +148,7 @@ export function GhostPluginPage() {
[],
);
const marketRefreshRequestRef = useRef(0);
+ const lastMarketRefreshAtRef = useRef(0);
const marketDetailRequestRef = useRef(0);
const installedGhostIdsKeyRef = useRef(installedGhostIdsKey);
const legacyRecoveryStatusRequestRef = useRef(0);
@@ -164,6 +168,7 @@ export function GhostPluginPage() {
throw new Error(snapshot.unavailableReason);
}
setMarketSnapshot(snapshot);
+ lastMarketRefreshAtRef.current = Date.now();
} catch (error) {
if (requestId !== marketRefreshRequestRef.current) return;
setMarketSnapshot((current) =>
@@ -187,6 +192,8 @@ export function GhostPluginPage() {
marketDetailRequestRef.current += 1;
void refreshMarket();
}, [refreshMarket, mode, dataOwnerId]);
+ const refreshMarketOnForeground = useCallback(() => refreshMarket(true), [refreshMarket]);
+ usePluginMarketForegroundRefresh(refreshMarketOnForeground, lastMarketRefreshAtRef);
useEffect(() => {
if (installedGhostIdsKeyRef.current === installedGhostIdsKey) return;
installedGhostIdsKeyRef.current = installedGhostIdsKey;
@@ -298,16 +305,13 @@ export function GhostPluginPage() {
)
.map((ghost) => {
const marketItem = marketByGhostId.get(ghost.manifest.id) ?? null;
+ const presentation = marketPresentationForInstalledGhost(ghost, marketItem);
return {
- ...toGhostPluginListItem(ghost),
+ ...toGhostPluginListItem(ghost, presentation),
origin: pluginPresentationOrigin(marketItem),
- // 迁移账本(legacy-unresolved)会让 main 把同版本 release 也判成
- // update-available;列表入口只对版本号确实变化的更新亮牌。
- marketUpdate:
- marketItem?.installState === 'update-available' &&
- marketItem.version !== ghost.manifest.version
- ? marketItem
- : null,
+ // 同版本展示刷新由 main 标成 installed;legacy-unresolved 仍保留
+ // update-available,以便用户用市场包替换未验证的本地字节。
+ marketUpdate: pluginUpdateForInstalledVersion(marketItem),
};
}),
[ghosts, marketByGhostId],
@@ -384,12 +388,21 @@ export function GhostPluginPage() {
const selectedGhost = selectedId
? (ghosts.find((ghost) => ghost.manifest.id === selectedId) ?? null)
: null;
- const selectedDetail = selectedGhost ? toGhostPluginDetail(selectedGhost) : null;
+ const selectedPresentation = selectedGhost
+ ? marketPresentationForInstalledGhost(
+ selectedGhost,
+ marketByGhostId.get(selectedGhost.manifest.id),
+ )
+ : null;
+ const selectedDetail = selectedGhost
+ ? toGhostPluginDetail(selectedGhost, selectedPresentation)
+ : null;
const selectedMarketInstall = selectedDetail
? (marketByGhostId.get(selectedDetail.id) ?? null)
: null;
- const selectedMarketUpdate =
- selectedMarketInstall?.installState === 'update-available' ? selectedMarketInstall : null;
+ const selectedMarketUpdate = selectedDetail
+ ? pluginUpdateForInstalledVersion(selectedMarketInstall)
+ : null;
const panelStatus = useMemo(() => {
if (!selectedDetail || selectedDetail.panelMinWidth === null) return null;
@@ -408,7 +421,7 @@ export function GhostPluginPage() {
}, [selectedDetail, t]);
const handleToggle = useCallback(
- async (id: string, enabled: boolean) => {
+ async (id: string, enabled: boolean, displayName: string) => {
try {
const dir = scopeDirRef.current;
if (dir) {
@@ -419,9 +432,7 @@ export function GhostPluginPage() {
enabled
? 'settings.ghosts.toast.projectEnabled'
: 'settings.ghosts.toast.projectDisabled',
- {
- name: ghosts.find((ghost) => ghost.manifest.id === id)?.manifest.name ?? id,
- },
+ { name: displayName },
),
);
} else {
@@ -431,7 +442,7 @@ export function GhostPluginPage() {
toast.error(t(ghostInstallErrorKey(extractIpcError(error)?.code)));
}
},
- [ghosts, t],
+ [t],
);
// 市场更新流程由列表卡片和详情页共用:先取目标 release 的完整 manifest 做
@@ -564,7 +575,7 @@ export function GhostPluginPage() {
}, []);
const handleUseGhost = useCallback(
- async (id: string) => {
+ async (id: string, displayName: string) => {
const ghost = ghosts.find((candidate) => candidate.manifest.id === id);
if (!ghost?.manifest.command) return;
// 使用前置门:点击时现查配置就绪度(main 侧确定性判定),未就绪先
@@ -578,7 +589,7 @@ export function GhostPluginPage() {
}
if (setupStatus && !setupStatus.ready) {
const goConfigure = await confirm({
- title: t('settings.ghosts.setupGate.title', { name: ghost.manifest.name }),
+ title: t('settings.ghosts.setupGate.title', { name: displayName }),
description: formatSetupGateDescription(setupStatus, t),
confirmText: t('settings.ghosts.setupGate.configure'),
cancelText: t('settings.ghosts.setupGate.cancel'),
@@ -608,8 +619,10 @@ export function GhostPluginPage() {
);
const handleUse = useCallback(() => {
- if (selectedGhost) void handleUseGhost(selectedGhost.manifest.id);
- }, [handleUseGhost, selectedGhost]);
+ if (selectedGhost && selectedDetail) {
+ void handleUseGhost(selectedGhost.manifest.id, selectedDetail.name);
+ }
+ }, [handleUseGhost, selectedDetail, selectedGhost]);
const handleUninstall = useCallback(async () => {
if (!selectedDetail) return;
@@ -831,7 +844,7 @@ export function GhostPluginPage() {
: undefined
}
onBack={() => setSelectedId(null)}
- onToggle={(enabled) => void handleToggle(selectedDetail.id, enabled)}
+ onToggle={(enabled) => void handleToggle(selectedDetail.id, enabled, selectedDetail.name)}
onUse={handleUse}
onUpdate={() => void handleUpdate()}
updateLabel={
@@ -840,13 +853,12 @@ export function GhostPluginPage() {
: undefined
}
updateVersion={
- selectedMarketUpdate && selectedMarketUpdate.version !== selectedDetail.version
- ? selectedMarketUpdate.version
- : undefined
+ selectedMarketUpdate?.version
}
updateBusy={selectedMarketUpdate !== null && marketBusyId !== null}
onUninstall={() => void handleUninstall()}
toggleDisabled={scopeDir !== null && selectedGhost !== null && !selectedGhost.enabled}
+ onIconLoadError={handleMarketIconLoadError}
/>
);
}
@@ -921,6 +933,7 @@ export function GhostPluginPage() {
expanded={installedExpanded}
onExpandedChange={setInstalledExpanded}
onSelect={setSelectedId}
+ onIconLoadError={handleMarketIconLoadError}
/>
</section>
) : null}
@@ -999,7 +1012,9 @@ export function GhostPluginPage() {
item={catalogItem.item}
sourceLabel={t(`settings.ghosts.page.origin.${catalogItem.item.origin}`)}
onSelect={() => setSelectedId(catalogItem.item.id)}
- onAction={() => void handleUseGhost(catalogItem.item.id)}
+ onAction={() =>
+ void handleUseGhost(catalogItem.item.id, catalogItem.item.name)
+ }
updateVersion={catalogItem.item.marketUpdate?.version}
updateBusy={catalogItem.item.marketUpdate !== null && marketBusyId !== null}
onUpdate={
@@ -1012,7 +1027,10 @@ export function GhostPluginPage() {
catalogItem.item.enabled,
)}
toggleDisabled={scopeDir !== null && !catalogItem.item.enabled}
- onToggle={(enabled) => void handleToggle(catalogItem.item.id, enabled)}
+ onToggle={(enabled) =>
+ void handleToggle(catalogItem.item.id, enabled, catalogItem.item.name)
+ }
+ onIconLoadError={handleMarketIconLoadError}
/>
) : (
<MarketPluginCard
@@ -1269,6 +1287,7 @@ export function GhostPluginCard({
onToggle,
effectiveEnabled,
toggleDisabled = false,
+ onIconLoadError,
}: {
item: GhostPluginListItem;
sourceLabel?: string;
@@ -1281,6 +1300,7 @@ export function GhostPluginCard({
onToggle?: (enabled: boolean) => void;
effectiveEnabled?: boolean;
toggleDisabled?: boolean;
+ onIconLoadError?: () => void;
}) {
const { t } = useTranslation();
return (
@@ -1300,7 +1320,12 @@ export function GhostPluginCard({
className="flex min-w-0 flex-1 items-start gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
aria-label={item.name}
>
- <GhostPluginIcon iconDataUrl={item.iconDataUrl} iconId={item.id} iconName={item.name} />
+ <GhostPluginIcon
+ iconDataUrl={item.iconDataUrl}
+ iconId={item.id}
+ iconName={item.name}
+ onIconLoadError={onIconLoadError}
+ />
<span className="flex min-w-0 flex-1 flex-col self-stretch pt-0.5">
<span className="flex min-w-0 items-center gap-2">
<span className="truncate text-15 font-medium text-[var(--text-primary)]">
@@ -1378,9 +1403,11 @@ export function GhostPluginCard({
export function InstalledGhostShortcut({
item,
onSelect,
+ onIconLoadError,
}: {
item: GhostPluginListItem;
onSelect: (id: string) => void;
+ onIconLoadError?: () => void;
}) {
return (
<Tip text={item.name} side="bottom" delay={250}>
@@ -1395,7 +1422,12 @@ export function InstalledGhostShortcut({
)}
aria-label={item.name}
>
- <GhostPluginIcon iconDataUrl={item.iconDataUrl} iconId={item.id} iconName={item.name} />
+ <GhostPluginIcon
+ iconDataUrl={item.iconDataUrl}
+ iconId={item.id}
+ iconName={item.name}
+ onIconLoadError={onIconLoadError}
+ />
</button>
</Tip>
);
@@ -1407,11 +1439,13 @@ export function InstalledGhostQueue({
expanded,
onExpandedChange,
onSelect,
+ onIconLoadError,
}: {
items: readonly GhostPluginListItem[];
expanded: boolean;
onExpandedChange: (expanded: boolean) => void;
onSelect: (id: string) => void;
+ onIconLoadError?: () => void;
}) {
const { t } = useTranslation();
const hasOverflow = items.length > MAX_VISIBLE_INSTALLED_GHOSTS;
@@ -1426,7 +1460,12 @@ export function InstalledGhostQueue({
)}
>
{visibleItems.map((item) => (
- <InstalledGhostShortcut key={item.id} item={item} onSelect={onSelect} />
+ <InstalledGhostShortcut
+ key={item.id}
+ item={item}
+ onSelect={onSelect}
+ onIconLoadError={onIconLoadError}
+ />
))}
{hasOverflow ? (
<button
@@ -1465,6 +1504,7 @@ export function InstalledGhostQueue({
iconId={item.id}
iconName={item.name}
size="mini"
+ onIconLoadError={onIconLoadError}
/>
</span>
))}
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 710795ed89..a5528cb774 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -127,6 +127,37 @@ describe('GhostPluginCard', () => {
expect(onAction).not.toHaveBeenCalled();
});
+ it('routes projected icon failures from installed cards and shortcuts to market recovery', () => {
+ const onIconLoadError = vi.fn();
+ const projected = {
+ ...installedPlugin,
+ iconDataUrl: 'https://plugins.example.invalid/icon.png?signature=current',
+ };
+ const { container, rerender } = render(
+ <GhostPluginCard
+ item={projected}
+ onSelect={vi.fn()}
+ onAction={vi.fn()}
+ onIconLoadError={onIconLoadError}
+ />,
+ );
+
+ fireEvent.error(container.querySelector('img') as HTMLImageElement);
+ expect(onIconLoadError).toHaveBeenCalledTimes(1);
+
+ rerender(
+ <InstalledGhostQueue
+ items={[projected]}
+ expanded={false}
+ onExpandedChange={vi.fn()}
+ onSelect={vi.fn()}
+ onIconLoadError={onIconLoadError}
+ />,
+ );
+ fireEvent.error(container.querySelector('img') as HTMLImageElement);
+ expect(onIconLoadError).toHaveBeenCalledTimes(2);
+ });
+
it('surfaces the market update state with a badge and a direct update action', () => {
const onAction = vi.fn();
const onUpdate = vi.fn();
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 36e257bd13..9caf4ab337 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -163,6 +163,73 @@ describe('Ghost plugin detail sections', () => {
expect(detailActions?.className).toContain('flex-nowrap');
});
+ it('routes a projected detail icon failure to market recovery', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const onIconLoadError = vi.fn();
+ const { container } = render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={{
+ ...detail,
+ iconDataUrl: 'https://plugins.example.invalid/icon.png?signature=current',
+ }}
+ panelStatus="Docked"
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ onIconLoadError={onIconLoadError}
+ />,
+ );
+
+ fireEvent.error(container.querySelector('img') as HTMLImageElement);
+
+ expect(onIconLoadError).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the market replacement action for a same-version legacy install', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const onUpdate = vi.fn();
+ render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={detail}
+ panelStatus="Docked"
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={onUpdate}
+ updateVersion={detail.version}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ const updateButton = screen.getByRole('button', {
+ name: 'settings.ghosts.market.update',
+ });
+ fireEvent.click(updateButton);
+
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.market.updateTo' })).toBeNull();
+ });
+
it('disables every market update entry while an update is busy', async () => {
vi.stubGlobal(
'ResizeObserver',
diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
index 1be58c46fa..5461987c1a 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
import type { PluginMarketItem } from '../../../../../shared/pluginMarket';
-import { orderPluginCatalogItems, pluginPresentationOrigin } from '../pluginMarketPresentation';
+import {
+ orderPluginCatalogItems,
+ pluginPresentationOrigin,
+ pluginUpdateForInstalledVersion,
+} from '../pluginMarketPresentation';
function marketItem(
pluginId: string,
@@ -43,6 +47,30 @@ describe('pluginPresentationOrigin', () => {
});
});
+describe('pluginUpdateForInstalledVersion', () => {
+ it('surfaces a real version update', () => {
+ const update = marketItem('plugin-update', 'example', 'update-available');
+ update.version = '2.0.0';
+
+ expect(pluginUpdateForInstalledVersion(update)).toBe(update);
+ });
+
+ it.each([
+ ['same-version metadata refresh', marketItem('plugin-same', 'same', 'installed')],
+ ['already installed', marketItem('plugin-installed', 'installed', 'installed')],
+ ['conflict', marketItem('plugin-conflict', 'conflict', 'conflict')],
+ ['missing market record', null],
+ ] as const)('does not surface %s as a package update', (_label, item) => {
+ expect(pluginUpdateForInstalledVersion(item)).toBeNull();
+ });
+
+ it('keeps a same-version legacy-adopted install updateable', () => {
+ const legacy = marketItem('plugin-legacy', 'legacy', 'update-available');
+
+ expect(pluginUpdateForInstalledVersion(legacy)).toBe(legacy);
+ });
+});
+
describe('orderPluginCatalogItems', () => {
it('renders installed and available cards in the server response order', () => {
const first = marketItem('plugin-first', 'first', 'not-installed');
diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketForegroundRefresh.test.tsx b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketForegroundRefresh.test.tsx
new file mode 100644
index 0000000000..922a78986c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketForegroundRefresh.test.tsx
@@ -0,0 +1,96 @@
+/**
+ * Regression coverage for foreground market refresh deduplication and outage throttling.
+ * @vitest-environment jsdom
+ */
+
+import { act, fireEvent, render } from '@testing-library/react';
+import { useRef } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { usePluginMarketForegroundRefresh } from '../usePluginMarketForegroundRefresh';
+
+function Harness({ refresh }: { refresh: () => void | Promise<void> }) {
+ const lastRefreshAtRef = useRef(0);
+ usePluginMarketForegroundRefresh(refresh, lastRefreshAtRef);
+ return null;
+}
+
+async function flushForegroundEvent(target: Window | Document, event: Event): Promise<void> {
+ await act(async () => {
+ fireEvent(target, event);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ Reflect.deleteProperty(document, 'visibilityState');
+});
+
+describe('usePluginMarketForegroundRefresh', () => {
+ it('deduplicates paired focus and visibility events while a refresh is in flight', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-07-28T00:00:00.000Z'));
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'visible',
+ });
+ let finishRefresh: (() => void) | null = null;
+ const refresh = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishRefresh = resolve;
+ }),
+ );
+ render(<Harness refresh={refresh} />);
+
+ fireEvent.focus(window);
+ fireEvent(document, new Event('visibilitychange'));
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(refresh).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ finishRefresh?.();
+ await Promise.resolve();
+ });
+ });
+
+ it('throttles repeated foreground events after a failed refresh', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-07-28T00:00:00.000Z'));
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'visible',
+ });
+ const refresh = vi.fn().mockRejectedValue(new Error('market unavailable'));
+ render(<Harness refresh={refresh} />);
+
+ await flushForegroundEvent(window, new FocusEvent('focus'));
+ await flushForegroundEvent(window, new FocusEvent('focus'));
+ expect(refresh).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(29_999);
+ await flushForegroundEvent(window, new FocusEvent('focus'));
+ expect(refresh).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(1);
+ await flushForegroundEvent(window, new FocusEvent('focus'));
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not refresh while the document is hidden', async () => {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ value: 'hidden',
+ });
+ const refresh = vi.fn();
+ render(<Harness refresh={refresh} />);
+
+ await flushForegroundEvent(window, new FocusEvent('focus'));
+
+ expect(refresh).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index 26e8642d25..9d2e0703e7 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -14,6 +14,7 @@ import {
type GhostToolDecl,
type InstalledGhost,
} from '../../../../shared/ghost';
+import type { PluginMarketItem } from '../../../../shared/pluginMarket';
export interface GhostPluginListItem {
id: string;
@@ -37,6 +38,50 @@ export interface GhostPluginDetail extends GhostPluginListItem {
installDir: string | null;
}
+/**
+ * 展示投影只覆盖用户能看到的四个字段;运行时仍完全来自本地安装包。
+ *
+ * `iconDataUrl` 是有意要求存在的字段:市场项的 `icon: null` 也必须覆盖本地
+ * 包图标,而不是因为缺少 URL 又显示旧图标。
+ */
+export interface GhostPluginMarketPresentation {
+ name: string;
+ description: string;
+ author: string | null;
+ iconDataUrl: string | undefined;
+}
+
+/**
+ * Returns a market presentation only when the installed package is the exact
+ * market-owned version. A local install, a conflicting ghostId, an unavailable
+ * market item, or a pending version update must keep using its local manifest.
+ */
+export function marketPresentationForInstalledGhost(
+ ghost: Pick<InstalledGhost, 'manifest'>,
+ marketItem:
+ | Pick<
+ PluginMarketItem,
+ 'ghostId' | 'installState' | 'version' | 'name' | 'description' | 'author' | 'icon'
+ >
+ | null
+ | undefined,
+): GhostPluginMarketPresentation | null {
+ if (
+ !marketItem ||
+ marketItem.ghostId !== ghost.manifest.id ||
+ marketItem.installState !== 'installed' ||
+ marketItem.version !== ghost.manifest.version
+ ) {
+ return null;
+ }
+ return {
+ name: marketItem.name,
+ description: marketItem.description ?? '',
+ author: marketItem.author,
+ iconDataUrl: marketItem.icon?.url,
+ };
+}
+
export type GhostFallbackIconKind =
'diagram' | 'media' | 'search' | 'communication' | 'code' | 'calendar' | 'generic';
@@ -101,12 +146,20 @@ export function sortGhostPluginItemsByRecentUse<T extends Pick<GhostPluginListIt
* 这里刻意不加入安装量、使用量、认证徽章等旧原型字段;这些字段在 Ghost
* runtime 中没有事实来源,页面不应继续展示伪数据。
*/
-export function toGhostPluginListItem(ghost: InstalledGhost): GhostPluginListItem {
+export function toGhostPluginListItem(
+ ghost: InstalledGhost,
+ presentation?: GhostPluginMarketPresentation | null,
+): GhostPluginListItem {
const { manifest } = ghost;
- return {
- id: manifest.id,
+ const display = presentation ?? {
name: manifest.name,
description: manifest.description ?? '',
+ iconDataUrl: ghost.iconDataUrl,
+ };
+ return {
+ id: manifest.id,
+ name: display.name,
+ description: display.description,
version: manifest.version,
enabled: ghost.enabled,
canUse: Boolean(manifest.command),
@@ -116,7 +169,7 @@ export function toGhostPluginListItem(ghost: InstalledGhost): GhostPluginListIte
publisherVerified: false,
reviewed: false,
},
- ...(ghost.iconDataUrl !== undefined ? { iconDataUrl: ghost.iconDataUrl } : {}),
+ ...(display.iconDataUrl !== undefined ? { iconDataUrl: display.iconDataUrl } : {}),
};
}
@@ -124,13 +177,16 @@ export function toGhostPluginListItem(ghost: InstalledGhost): GhostPluginListIte
* 详情页复用列表 adapter 的基础字段,再补充 manifest 明确声明的权限与工具。
* 权限与详情卡共用 shared/ghost.ts 的纯推导函数,不在 renderer 复制规则。
*/
-export function toGhostPluginDetail(ghost: InstalledGhost): GhostPluginDetail {
- const listItem = toGhostPluginListItem(ghost);
+export function toGhostPluginDetail(
+ ghost: InstalledGhost,
+ presentation?: GhostPluginMarketPresentation | null,
+): GhostPluginDetail {
+ const listItem = toGhostPluginListItem(ghost, presentation);
const { manifest } = ghost;
return {
...listItem,
trust: listItem.trust!,
- author: manifest.author ?? null,
+ author: presentation ? presentation.author : manifest.author ?? null,
contents: ghostContentKeys(manifest),
permissions: ghostPermissionItems(manifest),
tools: manifest.tools ?? [],
diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
index e30b19707f..09964e33ad 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
@@ -26,6 +26,20 @@ export function pluginPresentationOrigin(
return 'local';
}
+/**
+ * Main's install state is authoritative for the update affordance.
+ *
+ * A same-version `update-available` item can be a legacy-adopted install whose
+ * bytes have not been verified against the market release. Version equality
+ * alone cannot suppress that replacement path; same-release metadata refreshes
+ * are already reported as `installed` by Main.
+ */
+export function pluginUpdateForInstalledVersion(
+ item: PluginMarketItem | null | undefined,
+): PluginMarketItem | null {
+ return item?.installState === 'update-available' ? item : null;
+}
+
/**
* Keeps the complete catalog in server order while rendering an installed card
* for market records already owned by this client. Local-only installs have no
diff --git a/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketForegroundRefresh.ts b/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketForegroundRefresh.ts
new file mode 100644
index 0000000000..9d0c612950
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketForegroundRefresh.ts
@@ -0,0 +1,43 @@
+import { useEffect, useRef } from 'react';
+
+const FOREGROUND_REFRESH_THROTTLE_MS = 30_000;
+
+/**
+ * Refreshes market presentation after Cindy returns to the foreground.
+ *
+ * Electron can emit focus and visibilitychange as a pair. Claiming the throttle
+ * window before dispatch and sharing one in-flight request keeps that pair, and
+ * repeated foreground events during an outage, from creating request storms.
+ */
+export function usePluginMarketForegroundRefresh(
+ refresh: () => void | Promise<void>,
+ lastRefreshAtRef: { current: number },
+): void {
+ const refreshRef = useRef(refresh);
+ refreshRef.current = refresh;
+ const inFlightRef = useRef(false);
+
+ useEffect(() => {
+ const refreshWhenVisible = () => {
+ if (document.visibilityState !== 'visible' || inFlightRef.current) return;
+ const now = Date.now();
+ if (now - lastRefreshAtRef.current < FOREGROUND_REFRESH_THROTTLE_MS) return;
+
+ lastRefreshAtRef.current = now;
+ inFlightRef.current = true;
+ void Promise.resolve()
+ .then(() => refreshRef.current())
+ .catch(() => undefined)
+ .finally(() => {
+ inFlightRef.current = false;
+ });
+ };
+
+ window.addEventListener('focus', refreshWhenVisible);
+ document.addEventListener('visibilitychange', refreshWhenVisible);
+ return () => {
+ window.removeEventListener('focus', refreshWhenVisible);
+ document.removeEventListener('visibilitychange', refreshWhenVisible);
+ };
+ }, [lastRefreshAtRef]);
+}