Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): renew expiring plugin icons (#359)
xxxcc34886fbb6649
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsxindex cebbba2ea7..af02d48b46 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx@@ -61,11 +61,13 @@ export function GhostPluginIcon({iconDataUrl,iconId,iconName,+ onIconLoadError,size = 'md',}: {iconDataUrl?: string;iconId: string;iconName: string;+ onIconLoadError?: () => void;size?: GhostPluginIconSize;}) {const [failedSrc, setFailedSrc] = useState<string | null>(null);@@ -93,7 +95,10 @@ export function GhostPluginIcon({alt=""draggable={false}referrerPolicy="no-referrer"- onError={() => setFailedSrc(resolvedIconDataUrl)}+ onError={() => {+ setFailedSrc(resolvedIconDataUrl);+ onIconLoadError?.();+ }}className={cn(svg ? SVG_ICON_CLASSES[size] : 'size-full object-cover',iconId === 'cindy-github' && 'plugin-icon--github',diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 4410486bc2..5d1b4e2b69 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -67,6 +67,7 @@ import {type PluginPresentationOrigin,} from './lib/pluginMarketPresentation';import { pluginMarketErrorKey } from './lib/pluginMarketErrorKey';+import { usePluginIconRefresh } from './lib/usePluginIconRefresh';import './plugin-motion.css';const MAX_VISIBLE_INSTALLED_GHOSTS = 5;@@ -104,18 +105,31 @@ export function GhostPluginPage() {const [marketBusyId, setMarketBusyId] = useState<string | null>(null);const marketRefreshRequestRef = useRef(0);const marketDetailRequestRef = useRef(0);- const refreshMarket = useCallback(async () => {+ const refreshMarket = useCallback(async (preserveOnError = false) => {const requestId = ++marketRefreshRequestRef.current;try {const snapshot = await window.electronAPI.pluginMarket.snapshot();- if (requestId === marketRefreshRequestRef.current) setMarketSnapshot(snapshot);- } catch (error) {- if (requestId === marketRefreshRequestRef.current) {- setMarketSnapshot({- items: [],- unavailableReason: error instanceof Error ? error.message : String(error),- });+ if (requestId !== marketRefreshRequestRef.current) return;+ // Main intentionally represents market outages as data so the initial page can render a+ // non-blocking empty state. During icon renewal, convert that fulfilled unavailable result+ // back into a failure: the catch path preserves the visible snapshot and the hook retries.+ if (preserveOnError && snapshot.unavailableReason !== null) {+ throw new Error(snapshot.unavailableReason);}+ setMarketSnapshot(snapshot);+ } catch (error) {+ if (requestId !== marketRefreshRequestRef.current) return;+ setMarketSnapshot((current) =>+ preserveOnError && current+ ? current+ : {+ items: [],+ unavailableReason: error instanceof Error ? error.message : String(error),+ },+ );+ // Background icon renewal keeps the current snapshot visible, but must still report+ // failure to the renewal hook so it can schedule a bounded retry.+ if (preserveOnError) throw error;}}, []);useEffect(() => {@@ -510,6 +524,35 @@ export function GhostPluginPage() {[t],);+ const refreshVisibleMarketDetail = useCallback(async (pluginId: string) => {+ // A background icon renewal may observe navigation, but must never invalidate a+ // user-initiated detail request by advancing its request generation.+ const requestId = marketDetailRequestRef.current;+ try {+ const detail = await window.electronAPI.pluginMarket.detail(pluginId);+ if (requestId !== marketDetailRequestRef.current) return;+ setMarketDetail((current) => (current?.pluginId === pluginId ? detail : current));+ } catch (error) {+ // A background URL renewal must not close an otherwise usable detail page.+ if (requestId === marketDetailRequestRef.current) throw error;+ }+ }, []);+ const visibleMarketIcons = useMemo(+ () => [...marketItems.map((item) => item.icon), marketDetail?.icon],+ [marketDetail?.icon, marketItems],+ );+ const refreshVisibleMarketIcons = useCallback(async () => {+ const refreshes: Promise<void>[] = [refreshMarket(true)];+ if (marketDetail?.pluginId) {+ refreshes.push(refreshVisibleMarketDetail(marketDetail.pluginId));+ }+ await Promise.all(refreshes);+ }, [marketDetail?.pluginId, refreshMarket, refreshVisibleMarketDetail]);+ const handleMarketIconLoadError = usePluginIconRefresh(+ visibleMarketIcons,+ refreshVisibleMarketIcons,+ );+const handleInstallFromMarket = useCallback(async () => {if (!marketDetail) return;const confirmed = await confirm({@@ -550,6 +593,7 @@ export function GhostPluginPage() {setMarketDetail(null);}}onInstall={() => void handleInstallFromMarket()}+ onIconLoadError={handleMarketIconLoadError}/>);}@@ -777,6 +821,7 @@ export function GhostPluginPage() {item={item}busy={marketBusyId === item.pluginId}onSelect={() => void handleSelectMarket(item.pluginId)}+ onIconLoadError={handleMarketIconLoadError}/>))}</div>@@ -805,10 +850,12 @@ function MarketPluginCard({item,busy,onSelect,+ onIconLoadError,}: {item: PluginMarketItem;busy: boolean;onSelect: () => void;+ onIconLoadError: () => void;}) {const { t } = useTranslation();return (@@ -831,6 +878,7 @@ function MarketPluginCard({iconDataUrl={item.icon?.url}iconId={item.ghostId}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">diff --git a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsxindex 2f102428f7..69676a580b 100644--- a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx@@ -13,6 +13,7 @@ interface MarketPluginDetailViewProps {busy: boolean;onBack: () => void;onInstall: () => void;+ onIconLoadError: () => void;}/** 尚未安装的市场 Plugin 详情;只展示协议事实,不创建 renderer 侧安装逻辑。 */export function MarketPluginDetailView({@@ -20,6 +21,7 @@ export function MarketPluginDetailView({busy,onBack,onInstall,+ onIconLoadError,}: MarketPluginDetailViewProps) {const { t } = useTranslation();const permissions = ghostPermissionItems(detail.manifest);@@ -54,6 +56,7 @@ export function MarketPluginDetailView({iconDataUrl={detail.icon?.url}iconId={detail.ghostId}iconName={detail.name}+ onIconLoadError={onIconLoadError}size="detail"/><div className="min-w-0">diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginIcon.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginIcon.test.tsxnew file mode 100644index 0000000000..d8155b32f7--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginIcon.test.tsx@@ -0,0 +1,39 @@+/**+ * Regression coverage for signed Plugin icon failure and recovery.+ * @vitest-environment jsdom+ */++import { fireEvent, render } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { GhostPluginIcon } from '../GhostPluginIcon';++describe('GhostPluginIcon', () => {+ it('requests metadata renewal after a signed URL fails and accepts the replacement URL', () => {+ const onIconLoadError = vi.fn();+ const { container, rerender } = render(+ <GhostPluginIcon+ iconDataUrl="https://oss.example/old-icon?signature=old"+ iconId="cindy-github"+ iconName="Cindy GitHub"+ onIconLoadError={onIconLoadError}+ />,+ );++ fireEvent.error(container.querySelector('img')!);+ expect(onIconLoadError).toHaveBeenCalledTimes(1);+ expect(container.querySelector('img')).toBeNull();++ rerender(+ <GhostPluginIcon+ iconDataUrl="https://oss.example/new-icon?signature=new"+ iconId="cindy-github"+ iconName="Cindy GitHub"+ onIconLoadError={onIconLoadError}+ />,+ );+ expect(container.querySelector('img')?.getAttribute('src')).toBe(+ 'https://oss.example/new-icon?signature=new',+ );+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginIconRefresh.test.tsx b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginIconRefresh.test.tsxnew file mode 100644index 0000000000..71a9eafdec--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginIconRefresh.test.tsx@@ -0,0 +1,136 @@+/**+ * Regression coverage for renewing short-lived Plugin market icon URLs.+ * @vitest-environment jsdom+ */++import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { earliestPluginIconRefreshAtMs, usePluginIconRefresh } from '../usePluginIconRefresh';++const START_MS = Date.parse('2026-07-25T00:00:00.000Z');++function icon(expiresAtMs: number): { expiresAt: string } {+ return { expiresAt: new Date(expiresAtMs).toISOString() };+}++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('earliestPluginIconRefreshAtMs', () => {+ it('renews thirty seconds before the earliest valid icon expiry', () => {+ expect(+ earliestPluginIconRefreshAtMs([+ icon(START_MS + 300_000),+ icon(START_MS + 120_000),+ { expiresAt: 'invalid' },+ null,+ ]),+ ).toBe(START_MS + 90_000);+ });++ it('returns null when no signed icon is visible', () => {+ expect(earliestPluginIconRefreshAtMs([null, undefined])).toBeNull();+ });+});++describe('usePluginIconRefresh', () => {+ it('uses one timer to renew visible icons before expiry', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(START_MS);+ const refresh = vi.fn().mockResolvedValue(undefined);++ renderHook(() => usePluginIconRefresh([icon(START_MS + 300_000)], refresh));++ await act(async () => {+ vi.advanceTimersByTime(269_999);+ await Promise.resolve();+ });+ expect(refresh).not.toHaveBeenCalled();++ await act(async () => {+ vi.advanceTimersByTime(1);+ await Promise.resolve();+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ });++ it('renews an overdue icon when the renderer becomes visible again', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(START_MS);+ const refresh = vi.fn().mockResolvedValue(undefined);+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');++ renderHook(() => usePluginIconRefresh([icon(START_MS + 60_000)], refresh));+ vi.setSystemTime(START_MS + 31_000);++ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'));+ await Promise.resolve();+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ });++ it('retries a failed scheduled renewal after a bounded delay', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(START_MS);+ const refresh = vi+ .fn()+ .mockRejectedValueOnce(new Error('temporary failure'))+ .mockResolvedValue(undefined);++ renderHook(() => usePluginIconRefresh([icon(START_MS + 60_000)], refresh));++ await act(async () => {+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(refresh).toHaveBeenCalledTimes(1);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(29_999);+ });+ expect(refresh).toHaveBeenCalledTimes(1);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });+ expect(refresh).toHaveBeenCalledTimes(2);+ });++ it('deduplicates concurrent image failures and cools down retries', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(START_MS);+ let finishRefresh: (() => void) | undefined;+ const refresh = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finishRefresh = resolve;+ }),+ );+ const { result } = renderHook(() => usePluginIconRefresh([], refresh));++ await act(async () => {+ result.current();+ result.current();+ await Promise.resolve();+ });+ expect(refresh).toHaveBeenCalledTimes(1);++ await act(async () => {+ finishRefresh?.();+ await Promise.resolve();+ });+ result.current();+ await Promise.resolve();+ expect(refresh).toHaveBeenCalledTimes(1);++ vi.setSystemTime(START_MS + 30_001);+ await act(async () => {+ result.current();+ await Promise.resolve();+ });+ expect(refresh).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/usePluginIconRefresh.ts b/apps/desktop/src/renderer/features/plugin/lib/usePluginIconRefresh.tsnew file mode 100644index 0000000000..6c383bb7e4--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/usePluginIconRefresh.ts@@ -0,0 +1,79 @@+import type { PluginIconMetadata } from '@cindy/plugin-protocol';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';++const ICON_REFRESH_LEAD_MS = 30_000;+const ICON_REFRESH_MIN_DELAY_MS = 1_000;+const ICON_ERROR_RECOVERY_COOLDOWN_MS = 30_000;+const ICON_REFRESH_RETRY_DELAY_MS = 30_000;++type ExpiringPluginIcon = Pick<PluginIconMetadata, 'expiresAt'> | null | undefined;++/**+ * Finds the first time at which any visible signed icon should be renewed.+ * Invalid timestamps are ignored defensively; protocol parsing normally rejects them earlier.+ */+export function earliestPluginIconRefreshAtMs(icons: readonly ExpiringPluginIcon[]): number | null {+ let earliestRefreshAt = Number.POSITIVE_INFINITY;+ for (const icon of icons) {+ if (!icon) continue;+ const expiresAt = Date.parse(icon.expiresAt);+ if (!Number.isFinite(expiresAt)) continue;+ earliestRefreshAt = Math.min(earliestRefreshAt, expiresAt - ICON_REFRESH_LEAD_MS);+ }+ return Number.isFinite(earliestRefreshAt) ? earliestRefreshAt : null;+}++/**+ * Keeps short-lived market icon URLs renewed with one page-level timer.+ * The returned error handler shares the same in-flight request and applies a cooldown so a+ * missing OSS object cannot create a refresh loop when each response has a new signature.+ */+export function usePluginIconRefresh(+ icons: readonly ExpiringPluginIcon[],+ refresh: () => void | Promise<void>,+): () => void {+ const refreshRef = useRef(refresh);+ refreshRef.current = refresh;+ const inFlightRef = useRef<Promise<void> | null>(null);+ const lastErrorRecoveryAtRef = useRef(Number.NEGATIVE_INFINITY);+ const [retryAtMs, setRetryAtMs] = useState<number | null>(null);+ const refreshAtMs = useMemo(() => earliestPluginIconRefreshAtMs(icons), [icons]);++ const requestRefresh = useCallback(() => {+ if (inFlightRef.current) return;+ const request = Promise.resolve().then(() => refreshRef.current());+ inFlightRef.current = request;+ void request+ .then(+ () => setRetryAtMs(null),+ () => setRetryAtMs(Date.now() + ICON_REFRESH_RETRY_DELAY_MS),+ )+ .finally(() => {+ if (inFlightRef.current === request) inFlightRef.current = null;+ });+ }, []);++ useEffect(() => {+ if (refreshAtMs === null) return;+ const scheduledAtMs = retryAtMs ?? refreshAtMs;+ const delayMs = Math.max(ICON_REFRESH_MIN_DELAY_MS, scheduledAtMs - Date.now());+ const timer = window.setTimeout(requestRefresh, delayMs);+ const handleVisibilityChange = () => {+ if (document.visibilityState === 'visible' && scheduledAtMs <= Date.now()) {+ requestRefresh();+ }+ };+ document.addEventListener('visibilitychange', handleVisibilityChange);+ return () => {+ window.clearTimeout(timer);+ document.removeEventListener('visibilitychange', handleVisibilityChange);+ };+ }, [refreshAtMs, requestRefresh, retryAtMs]);++ return useCallback(() => {+ const now = Date.now();+ if (now - lastErrorRecoveryAtRef.current < ICON_ERROR_RECOVERY_COOLDOWN_MS) return;+ lastErrorRecoveryAtRef.current = now;+ requestRefresh();+ }, [requestRefresh]);+}