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): 加载自定义市场本地图标 (#1966)

nanaco67bac6ed3a0b
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index db48c71c4c..6a43f8e3fd 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -29,7 +29,22 @@ describe('Plugin Market IPC error boundary', () => {
expect(body).toContain('if (isIpcError(error)) throw error;');
expect(body).toContain("throwIpcError('INTERNAL', 'Plugin market operation failed');");
- expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(12);
+ expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(13);
+ });
+
+ it('validates local icon keys with the same reserved-prefix contract as the service', () => {
+ const start = registerSource.indexOf("ipcMain.handle('plugin-market:local-icons'");
+ const end = registerSource.indexOf("ipcMain.handle(\n 'plugin-market:install'", start);
+ const body = registerSource.slice(start, end);
+
+ expect(body).toContain('isPluginMarketCustomIconKey(expectedIconKey)');
+ expect(registerSource).toContain(
+ "import { isPluginMarketCustomIconKey } from '../../shared/pluginMarket.js';",
+ );
+ expect(body).toContain('localIconRequestGate.tryRun');
+ expect(body).toContain(
+ "throwIpcError('PRECONDITION_FAILED', 'Too many local Plugin icon requests');",
+ );
});
it('guards removal notice consumption and signals trusted app windows only', () => {
diff --git a/apps/desktop/src/main/plugin-market/__tests__/localIconRequestGate.test.ts b/apps/desktop/src/main/plugin-market/__tests__/localIconRequestGate.test.ts
new file mode 100644
index 0000000000..ca1d7876aa
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/__tests__/localIconRequestGate.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ LocalIconRequestGate,
+ MAX_CONCURRENT_LOCAL_ICON_REQUESTS,
+} from '../localIconRequestGate.js';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+describe('LocalIconRequestGate', () => {
+ it('never starts more than two unsettled Main requests', async () => {
+ expect(MAX_CONCURRENT_LOCAL_ICON_REQUESTS).toBe(2);
+ const gate = new LocalIconRequestGate();
+ const first = deferred<string>();
+ const second = deferred<string>();
+ const blockedOperation = vi.fn(async () => 'blocked');
+
+ const firstRun = gate.tryRun(() => first.promise);
+ const secondRun = gate.tryRun(() => second.promise);
+
+ expect(firstRun).not.toBeNull();
+ expect(secondRun).not.toBeNull();
+ expect(gate.tryRun(blockedOperation)).toBeNull();
+ expect(blockedOperation).not.toHaveBeenCalled();
+
+ first.resolve('first');
+ await expect(firstRun).resolves.toBe('first');
+
+ const admittedRun = gate.tryRun(async () => 'admitted');
+ await expect(admittedRun).resolves.toBe('admitted');
+
+ second.resolve('second');
+ await expect(secondRun).resolves.toBe('second');
+ });
+
+ it('releases capacity after rejection and synchronous failure', async () => {
+ const gate = new LocalIconRequestGate();
+ const rejected = deferred<void>();
+ const rejectedRun = gate.tryRun(() => rejected.promise);
+ rejected.reject(new Error('failed'));
+ await expect(rejectedRun).rejects.toThrow('failed');
+
+ expect(() =>
+ gate.tryRun(() => {
+ throw new Error('sync failed');
+ }),
+ ).toThrow('sync failed');
+
+ await expect(gate.tryRun(async () => 'available')).resolves.toBe('available');
+ });
+});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
index fde0d646b9..ffd9cbc724 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
@@ -12,7 +12,8 @@ const runtime = vi.hoisted(() => ({
enabled: boolean;
}>,
/** 测试可注入:每次 list() 调用返回不同快照(模拟打包窗口内运行时变动)。 */
- listSequence: null as null | (() => Array<{ manifest: Record<string, unknown>; dir: string; enabled: boolean }>),
+ listSequence: null as
+ null | (() => Array<{ manifest: Record<string, unknown>; dir: string; enabled: boolean }>),
install: vi.fn(),
uninstall: vi.fn(),
builtinRemoved: new Set<string>(),
@@ -70,9 +71,17 @@ vi.mock('../download.js', () => ({
import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';
-import { customMarketPluginId, customMarketReleaseId, marketSourceKey } from '../../../shared/pluginMarket';
+import {
+ customMarketPluginId,
+ customMarketReleaseId,
+ marketSourceKey,
+ pluginMarketCustomIconProjectionToken,
+ pluginMarketCustomIconSourceToken,
+} from '../../../shared/pluginMarket';
+import { GHOST_ICON_MAX_BYTES, type GhostManifest } from '../../../shared/ghost';
import { PluginMarketLedger, ghostManifestDigest } from '../ledger';
import { PluginMarketService } from '../service';
+import { MarketSourceManager } from '../sources';
import { MarketSourceStore } from '../sources/store';
import type { PluginMarketApi } from '../api';
@@ -92,7 +101,7 @@ afterEach(() => {
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
});
-function ghostManifest(id: string, version = '1.0.0') {
+function ghostManifest(id: string, version = '1.0.0', overrides: Record<string, unknown> = {}) {
return {
schemaVersion: 2 as const,
id,
@@ -103,6 +112,7 @@ function ghostManifest(id: string, version = '1.0.0') {
kind: 'chip' as const,
entry: 'main.js',
slots: ['notify' as const],
+ ...overrides,
};
}
@@ -132,7 +142,14 @@ function serverSummary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePl
function writeLocalMarket(
root: string,
marketName: string,
- plugins: Array<{ rel: string; id: string; version?: string; minCindyVersion?: string }>,
+ plugins: Array<{
+ rel: string;
+ id: string;
+ version?: string;
+ minCindyVersion?: string;
+ icon?: string;
+ iconBytes?: string | Buffer;
+ }>,
): string {
const dir = path.join(root, marketName);
for (const plugin of plugins) {
@@ -141,13 +158,20 @@ function writeLocalMarket(
fs.writeFileSync(
path.join(pluginDir, 'ghost.json'),
JSON.stringify({
- ...ghostManifest(plugin.id, plugin.version ?? '1.0.0'),
- ...(plugin.minCindyVersion
- ? { minCindyVersion: plugin.minCindyVersion }
- : {}),
+ ...ghostManifest(
+ plugin.id,
+ plugin.version ?? '1.0.0',
+ plugin.icon ? { icon: plugin.icon } : {},
+ ),
+ ...(plugin.minCindyVersion ? { minCindyVersion: plugin.minCindyVersion } : {}),
}),
);
fs.writeFileSync(path.join(pluginDir, 'main.js'), '// entry');
+ if (plugin.icon) {
+ const iconPath = path.join(pluginDir, ...plugin.icon.split('/'));
+ fs.mkdirSync(path.dirname(iconPath), { recursive: true });
+ fs.writeFileSync(iconPath, plugin.iconBytes ?? 'icon-bytes');
+ }
}
fs.mkdirSync(path.join(dir, '.agents', 'plugins'), { recursive: true });
fs.writeFileSync(
@@ -193,11 +217,7 @@ function harness(items: VisiblePluginSummary[], marketDirs: Array<{ name: string
api,
ledger,
sourceStore,
- service: new PluginMarketService(
- api as unknown as PluginMarketApi,
- ledger,
- sourceStore,
- ),
+ service: new PluginMarketService(api as unknown as PluginMarketApi, ledger, sourceStore),
};
}
@@ -385,6 +405,559 @@ describe('PluginMarketService 自定义市场聚合', () => {
});
});
+describe('PluginMarketService 自定义市场图标', () => {
+ it('rejects an unsafe icon path before stat or byte read even if discovery validation is bypassed', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const pluginDir = path.join(root, 'plugin');
+ const outsideIcon = path.join(root, 'outside.png');
+ fs.mkdirSync(pluginDir, { recursive: true });
+ fs.writeFileSync(outsideIcon, 'PRIVATE');
+ const h = harness([], []);
+ const config = {
+ name: 'team-lib',
+ addedAt: '2026-07-30T00:00:00.000Z',
+ lastSyncedAt: '2026-07-30T01:00:00.000Z',
+ lastRevision: null,
+ source: { type: 'local' as const, path: root },
+ };
+ const discovered = {
+ config,
+ result: {
+ ok: true as const,
+ marketplace: {
+ name: 'team-lib',
+ displayName: null,
+ skippedCount: 0,
+ unreadableCount: 0,
+ plugins: [
+ {
+ ghostId: 'alpha',
+ version: '1.0.0',
+ dir: pluginDir,
+ manifest: ghostManifest('alpha', '1.0.0', {
+ icon: '../outside.png',
+ }) as GhostManifest,
+ },
+ ],
+ },
+ },
+ };
+ const forEachSpy = vi
+ .spyOn(MarketSourceManager.prototype, 'forEachDiscoveredSource')
+ .mockImplementation(async (visitor) => visitor(discovered));
+ const withSourceSpy = vi
+ .spyOn(MarketSourceManager.prototype, 'withDiscoveredSource')
+ .mockImplementation(async (_name, visitor) => visitor(discovered));
+ const lstatSpy = vi.spyOn(fs.promises, 'lstat');
+ const openSpy = vi.spyOn(fs.promises, 'open');
+ try {
+ const item = (await h.service.snapshot()).items[0]!;
+ expect(item.ghostId).toBe('alpha');
+ expect(item.customIconKey).toBeUndefined();
+
+ const request = {
+ pluginId: item.pluginId,
+ expectedIconKey: 'a'.repeat(64),
+ };
+ await expect(h.service.localIcons([request])).resolves.toEqual([
+ { ...request, status: 'missing' },
+ ]);
+ expect(lstatSpy.mock.calls.some(([file]) => String(file) === outsideIcon)).toBe(false);
+ expect(openSpy.mock.calls.some(([file]) => String(file) === outsideIcon)).toBe(false);
+ } finally {
+ openSpy.mockRestore();
+ lstatSpy.mockRestore();
+ withSourceSpy.mockRestore();
+ forEachSpy.mockRestore();
+ }
+ });
+
+ it('projects opaque icon keys and batches one discovery per marketplace', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'ALPHA' },
+ { rel: 'plugins/beta', id: 'beta', icon: 'assets/icon.webp', iconBytes: 'BETA' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+
+ const snapshot = await h.service.snapshot();
+ const alpha = snapshot.items.find((item) => item.ghostId === 'alpha');
+ const beta = snapshot.items.find((item) => item.ghostId === 'beta');
+ expect(alpha?.icon).toBeNull();
+ expect(alpha?.customIconKey).toMatch(/^[a-f0-9]{64}$/);
+ expect(beta?.customIconKey).toMatch(/^[a-f0-9]{64}$/);
+ expect(pluginMarketCustomIconSourceToken(alpha!.customIconKey!)).toBe(
+ pluginMarketCustomIconSourceToken(beta!.customIconKey!),
+ );
+ expect(pluginMarketCustomIconProjectionToken(alpha!.customIconKey!)).toBe(
+ pluginMarketCustomIconProjectionToken(beta!.customIconKey!),
+ );
+ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ expect(detail.customIconKey).toBe(alpha?.customIconKey);
+ const repeatedDetail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ expect(repeatedDetail.customIconKey).toBe(detail.customIconKey);
+
+ const discoverSpy = vi.spyOn(MarketSourceManager.prototype, 'withDiscoveredSource');
+ try {
+ const results = await h.service.localIcons([
+ { pluginId: alpha!.pluginId, expectedIconKey: alpha!.customIconKey! },
+ { pluginId: beta!.pluginId, expectedIconKey: beta!.customIconKey! },
+ ]);
+ expect(discoverSpy).toHaveBeenCalledTimes(1);
+ expect(results).toEqual([
+ {
+ pluginId: alpha!.pluginId,
+ expectedIconKey: alpha!.customIconKey,
+ status: 'loaded',
+ dataUrl: `data:image/png;base64,${Buffer.from('ALPHA').toString('base64')}`,
+ },
+ {
+ pluginId: beta!.pluginId,
+ expectedIconKey: beta!.customIconKey,
+ status: 'loaded',
+ dataUrl: `data:image/webp;base64,${Buffer.from('BETA').toString('base64')}`,
+ },
+ ]);
+ } finally {
+ discoverSpy.mockRestore();
+ }
+ });
+
+ it('keeps the source token across refreshes and changes it for a new owner generation', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'AAAA' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+
+ const first = (await h.service.snapshot()).items[0]!;
+ const iconPath = path.join(dir, 'plugins', 'alpha', 'assets', 'icon.png');
+ const before = fs.statSync(iconPath);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ fs.writeFileSync(iconPath, 'BBBB');
+ fs.utimesSync(iconPath, before.atime, before.mtime);
+
+ const second = (await h.service.snapshot()).items[0]!;
+ expect(second.version).toBe(first.version);
+ expect(second.customIconKey).not.toBe(first.customIconKey);
+ expect(pluginMarketCustomIconSourceToken(second.customIconKey!)).toBe(
+ pluginMarketCustomIconSourceToken(first.customIconKey!),
+ );
+ expect(pluginMarketCustomIconProjectionToken(second.customIconKey!)).not.toBe(
+ pluginMarketCustomIconProjectionToken(first.customIconKey!),
+ );
+ await expect(
+ h.service.localIcons([{ pluginId: first.pluginId, expectedIconKey: first.customIconKey! }]),
+ ).resolves.toEqual([
+ { pluginId: first.pluginId, expectedIconKey: first.customIconKey, status: 'missing' },
+ ]);
+
+ runtime.session = { ...runtime.session, generation: 2 };
+ const nextOwner = (await h.service.snapshot()).items[0]!;
+ expect(nextOwner.customIconKey).not.toBe(second.customIconKey);
+ expect(pluginMarketCustomIconSourceToken(nextOwner.customIconKey!)).not.toBe(
+ pluginMarketCustomIconSourceToken(second.customIconKey!),
+ );
+ });
+
+ it('changes the projection key when same-length icon bytes change but stats collide', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'AAAA' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const first = (await h.service.snapshot()).items[0]!;
+ const iconPath = path.join(dir, 'plugins', 'alpha', 'assets', 'icon.png');
+ const stableStat = await fs.promises.stat(iconPath, { bigint: true });
+ await fs.promises.writeFile(iconPath, 'BBBB');
+
+ const realLstat = fs.promises.lstat;
+ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation((async (
+ target: fs.PathLike,
+ options?: fs.StatOptions,
+ ) => {
+ if (String(target).endsWith(path.join('plugins', 'alpha', 'assets', 'icon.png'))) {
+ return stableStat;
+ }
+ return realLstat(target, options as never);
+ }) as typeof fs.promises.lstat);
+ const realOpen = fs.promises.open;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ const handle = await realOpen(...args);
+ if (!String(args[0]).endsWith(path.join('plugins', 'alpha', 'assets', 'icon.png'))) {
+ return handle;
+ }
+ return new Proxy(handle, {
+ get(target, key) {
+ if (key === 'stat') return async () => stableStat;
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }) as typeof fs.promises.open);
+ try {
+ const second = (await h.service.snapshot()).items[0]!;
+ expect(second.customIconKey).not.toBe(first.customIconKey);
+ await expect(
+ h.service.localIcons([
+ { pluginId: second.pluginId, expectedIconKey: second.customIconKey! },
+ ]),
+ ).resolves.toEqual([
+ {
+ pluginId: second.pluginId,
+ expectedIconKey: second.customIconKey,
+ status: 'loaded',
+ dataUrl: `data:image/png;base64,${Buffer.from('BBBB').toString('base64')}`,
+ },
+ ]);
+ } finally {
+ openSpy.mockRestore();
+ lstatSpy.mockRestore();
+ }
+ });
+
+ it('does not attach bytes from a raced file handle to an older icon key', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'AAAA' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const item = (await h.service.snapshot()).items[0]!;
+ const iconPath = await fs.promises.realpath(
+ path.join(dir, 'plugins', 'alpha', 'assets', 'icon.png'),
+ );
+ const backupPath = `${iconPath}.old-generation`;
+ const realOpen = fs.promises.open;
+ let restoredOldGeneration = false;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ if (String(args[0]) !== iconPath) return realOpen(...args);
+ fs.renameSync(iconPath, backupPath);
+ fs.writeFileSync(iconPath, 'BBBB');
+ const handle = await realOpen(...args);
+ const realRead = handle.read.bind(handle);
+ return new Proxy(handle, {
+ get(target, key) {
+ if (key === 'read') {
+ return async (buffer: Buffer, offset: number, length: number, position: number) => {
+ const result = await realRead(buffer, offset, length, position);
+ if (!restoredOldGeneration) {
+ fs.rmSync(iconPath);
+ fs.renameSync(backupPath, iconPath);
+ restoredOldGeneration = true;
+ }
+ return result;
+ };
+ }
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }) as typeof fs.promises.open);
+ try {
+ const results = await h.service.localIcons([
+ { pluginId: item.pluginId, expectedIconKey: item.customIconKey! },
+ ]);
+ expect(results).toHaveLength(1);
+ expect(results[0]).toMatchObject({
+ pluginId: item.pluginId,
+ expectedIconKey: item.customIconKey,
+ });
+ expect(['missing', 'retryable']).toContain(results[0]?.status);
+ expect(results[0]?.status).not.toBe('loaded');
+ expect(restoredOldGeneration).toBe(true);
+ } finally {
+ openSpy.mockRestore();
+ if (fs.existsSync(backupPath)) {
+ fs.rmSync(iconPath, { force: true });
+ fs.renameSync(backupPath, iconPath);
+ }
+ }
+ });
+
+ it('treats missing, oversized and invalid-extension icons as deterministic absence', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/missing', id: 'missing', icon: 'assets/icon.png' },
+ {
+ rel: 'plugins/oversized',
+ id: 'oversized',
+ icon: 'assets/icon.png',
+ iconBytes: Buffer.alloc(GHOST_ICON_MAX_BYTES + 1),
+ },
+ { rel: 'plugins/svg', id: 'svg', icon: 'assets/icon.svg', iconBytes: '<svg />' },
+ ]);
+ fs.rmSync(path.join(dir, 'plugins', 'missing', 'assets', 'icon.png'));
+ const h = harness([], [{ name: 'team-lib', dir }]);
+
+ const snapshot = await h.service.snapshot();
+ expect(snapshot.items.some((item) => item.ghostId === 'svg')).toBe(false);
+ const requests = snapshot.items.map((item) => ({
+ pluginId: item.pluginId,
+ expectedIconKey: item.customIconKey!,
+ }));
+ expect(requests).toHaveLength(2);
+ await expect(h.service.localIcons(requests)).resolves.toEqual(
+ requests.map((request) => ({ ...request, status: 'missing' })),
+ );
+ });
+
+ it('returns retryable for uncertain icon I/O and failed marketplace rediscovery', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'ALPHA' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const item = (await h.service.snapshot()).items[0]!;
+ const request = { pluginId: item.pluginId, expectedIconKey: item.customIconKey! };
+ const iconPath = await fs.promises.realpath(
+ path.join(dir, 'plugins', 'alpha', 'assets', 'icon.png'),
+ );
+ const realOpen = fs.promises.open;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ if (String(args[0]) === iconPath) {
+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' });
+ }
+ return realOpen(...args);
+ }) as typeof fs.promises.open);
+ try {
+ await expect(h.service.localIcons([request])).resolves.toEqual([
+ { ...request, status: 'retryable' },
+ ]);
+ } finally {
+ openSpy.mockRestore();
+ }
+
+ fs.rmSync(path.join(dir, '.agents', 'plugins', 'marketplace.json'));
+ await expect(h.service.localIcons([request])).resolves.toEqual([
+ { ...request, status: 'retryable' },
+ ]);
+ });
+
+ it('returns retryable when the icon changes during the verified read', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'ALPHA' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const item = (await h.service.snapshot()).items[0]!;
+ const request = { pluginId: item.pluginId, expectedIconKey: item.customIconKey! };
+ const iconPath = await fs.promises.realpath(
+ path.join(dir, 'plugins', 'alpha', 'assets', 'icon.png'),
+ );
+ const realOpen = fs.promises.open;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ const handle = await realOpen(...args);
+ if (String(args[0]) !== iconPath) return handle;
+ const realStat = handle.stat.bind(handle);
+ let statCalls = 0;
+ return new Proxy(handle, {
+ get(target, key) {
+ if (key === 'stat') {
+ return async (options?: fs.StatOptions) => {
+ const stat = (await realStat(options as never)) as unknown as fs.BigIntStats;
+ statCalls += 1;
+ if (statCalls !== 2) return stat;
+ return new Proxy(stat, {
+ get(statTarget, statKey) {
+ if (statKey === 'mtimeNs') return statTarget.mtimeNs + 1n;
+ const value = Reflect.get(statTarget, statKey);
+ return typeof value === 'function' ? value.bind(statTarget) : value;
+ },
+ }) as fs.BigIntStats;
+ };
+ }
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }) as typeof fs.promises.open);
+ try {
+ await expect(h.service.localIcons([request])).resolves.toEqual([
+ { ...request, status: 'retryable' },
+ ]);
+ } finally {
+ openSpy.mockRestore();
+ }
+ });
+
+ it('keeps discovery and projection uncertainty retryable', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'ALPHA' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const item = (await h.service.snapshot()).items[0]!;
+ const request = { pluginId: item.pluginId, expectedIconKey: item.customIconKey! };
+
+ const discoverSpy = vi
+ .spyOn(MarketSourceManager.prototype, 'withDiscoveredSource')
+ .mockImplementationOnce(async (_name, consume) =>
+ consume({
+ config: {
+ name: 'team-lib',
+ source: { type: 'local', path: dir },
+ addedAt: '2026-07-30T00:00:00.000Z',
+ lastRevision: null,
+ lastSyncedAt: null,
+ },
+ result: {
+ ok: true,
+ marketplace: {
+ name: 'team-lib',
+ displayName: null,
+ plugins: [],
+ skippedCount: 0,
+ unreadableCount: 1,
+ },
+ },
+ }),
+ );
+ await expect(h.service.localIcons([request])).resolves.toEqual([
+ { ...request, status: 'retryable' },
+ ]);
+ discoverSpy.mockRestore();
+
+ const realLstat = fs.promises.lstat;
+ const currentProjectionSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation((async (
+ target: fs.PathLike,
+ options?: fs.StatOptions,
+ ) => {
+ if (String(target).endsWith(path.join('plugins', 'alpha', 'assets', 'icon.png'))) {
+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' });
+ }
+ return realLstat(target, options as never);
+ }) as typeof fs.promises.lstat);
+ try {
+ await expect(h.service.localIcons([request])).resolves.toEqual([
+ { ...request, status: 'retryable' },
+ ]);
+ } finally {
+ currentProjectionSpy.mockRestore();
+ }
+
+ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation((async (
+ target: fs.PathLike,
+ options?: fs.StatOptions,
+ ) => {
+ if (String(target).endsWith(path.join('plugins', 'alpha', 'assets', 'icon.png'))) {
+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' });
+ }
+ return realLstat(target, options as never);
+ }) as typeof fs.promises.lstat);
+ const uncertainItem = (await h.service.snapshot()).items[0]!;
+ lstatSpy.mockRestore();
+ await expect(
+ h.service.localIcons([
+ { pluginId: uncertainItem.pluginId, expectedIconKey: uncertainItem.customIconKey! },
+ ]),
+ ).resolves.toEqual([
+ {
+ pluginId: uncertainItem.pluginId,
+ expectedIconKey: uncertainItem.customIconKey,
+ status: 'retryable',
+ },
+ ]);
+ });
+
+ it.runIf(process.platform !== 'win32')(
+ 'does not stat an icon through a parent-directory symlink outside the plugin directory',
+ async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'ALPHA' },
+ ]);
+ const externalAssets = path.join(root, 'external-assets');
+ fs.mkdirSync(externalAssets);
+ fs.writeFileSync(path.join(externalAssets, 'icon.png'), 'PRIVATE');
+ const assetsDir = path.join(dir, 'plugins', 'alpha', 'assets');
+ fs.rmSync(assetsDir, { recursive: true });
+ fs.symlinkSync(externalAssets, assetsDir, 'dir');
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const lstatSpy = vi.spyOn(fs.promises, 'lstat');
+ try {
+ const item = (await h.service.snapshot()).items[0]!;
+ expect(item.customIconKey).toBeUndefined();
+ expect(
+ lstatSpy.mock.calls.some(([file]) => String(file) === path.join(assetsDir, 'icon.png')),
+ ).toBe(false);
+ } finally {
+ lstatSpy.mockRestore();
+ }
+ },
+ );
+
+ it.runIf(process.platform !== 'win32')(
+ 'does not follow a marketplace icon symlink outside the plugin directory',
+ async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'ALPHA' },
+ ]);
+ const secret = path.join(root, 'secret.txt');
+ fs.writeFileSync(secret, 'PRIVATE');
+ const iconPath = path.join(dir, 'plugins', 'alpha', 'assets', 'icon.png');
+ fs.rmSync(iconPath);
+ fs.symlinkSync(secret, iconPath);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const item = (await h.service.snapshot()).items[0]!;
+ expect(item.customIconKey).toBeUndefined();
+ const request = { pluginId: item.pluginId, expectedIconKey: 'a'.repeat(64) };
+
+ const results = await h.service.localIcons([request]);
+ expect(results).toEqual([{ ...request, status: 'missing' }]);
+ expect(JSON.stringify(results)).not.toContain(Buffer.from('PRIVATE').toString('base64'));
+ },
+ );
+
+ it('does not return bytes from a marketplace icon hard-linked to a file outside the plugin directory', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', icon: 'assets/icon.png', iconBytes: 'ALPHA' },
+ ]);
+ const secret = path.join(root, 'secret.txt');
+ fs.writeFileSync(secret, 'PRIVATE');
+ const iconPath = path.join(dir, 'plugins', 'alpha', 'assets', 'icon.png');
+ fs.rmSync(iconPath);
+ try {
+ fs.linkSync(secret, iconPath);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EPERM' || code === 'ENOTSUP' || code === 'EOPNOTSUPP') return;
+ throw error;
+ }
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const item = (await h.service.snapshot()).items[0]!;
+
+ const results = await h.service.localIcons([
+ { pluginId: item.pluginId, expectedIconKey: item.customIconKey! },
+ ]);
+ expect(results).toEqual([
+ { pluginId: item.pluginId, expectedIconKey: item.customIconKey, status: 'missing' },
+ ]);
+ expect(JSON.stringify(results)).not.toContain(Buffer.from('PRIVATE').toString('base64'));
+ });
+});
+
describe('PluginMarketService 自定义市场 snapshot 账户作用域', () => {
it('rejects the snapshot when the account switches during custom discovery', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
@@ -431,10 +1004,14 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
expect(detail.manifest?.id).toBe('alpha');
expect(detail.sourceType).toBe('local-market');
- await expect(h.service.detail(customMarketPluginId('team-lib', 'missing'))).rejects.toMatchObject({
+ await expect(
+ h.service.detail(customMarketPluginId('team-lib', 'missing')),
+ ).rejects.toMatchObject({
code: 'NOT_FOUND',
});
- await expect(h.service.detail(customMarketPluginId('no-such-market', 'alpha'))).rejects.toMatchObject({
+ await expect(
+ h.service.detail(customMarketPluginId('no-such-market', 'alpha')),
+ ).rejects.toMatchObject({
code: 'NOT_FOUND',
});
});
@@ -475,9 +1052,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
it('custom market 即使自报 cindy-github 也不会获得 server-market 官方标记', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-github-'));
roots.push(root);
- const dir = writeLocalMarket(root, 'team-lib', [
- { rel: 'plugins/github', id: 'cindy-github' },
- ]);
+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/github', id: 'cindy-github' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
runtime.install.mockResolvedValue({
manifest: ghostManifest('cindy-github'),
@@ -653,9 +1228,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
- runtime.ghosts = [
- { manifest: ghostManifest('alpha'), dir: '/ghosts/alpha', enabled: true },
- ];
+ runtime.ghosts = [{ manifest: ghostManifest('alpha'), dir: '/ghosts/alpha', enabled: true }];
// 服务端市场装过同 id 插件
h.ledger.upsertInstallation({
pluginId: PLUGIN_ID,
@@ -685,10 +1258,13 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const rival = writeLocalMarket(root, 'rival-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
- const h = harness([], [
- { name: 'team-lib', dir },
- { name: 'rival-lib', dir: rival },
- ]);
+ const h = harness(
+ [],
+ [
+ { name: 'team-lib', dir },
+ { name: 'rival-lib', dir: rival },
+ ],
+ );
runtime.install.mockResolvedValue({
manifest: ghostManifest('alpha'),
@@ -754,9 +1330,9 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
});
const snapshot = await h.service.snapshot();
- expect(
- snapshot.items.find((entry) => entry.sourceType === 'server')?.installState,
- ).toBe('not-installed');
+ expect(snapshot.items.find((entry) => entry.sourceType === 'server')?.installState).toBe(
+ 'not-installed',
+ );
await expect(
h.service.install(item.id, {
@@ -814,12 +1390,12 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const realList = MarketSourceStore.prototype.list;
let reads = 0;
- const listSpy = vi
- .spyOn(MarketSourceStore.prototype, 'list')
- .mockImplementation(function (this: MarketSourceStore) {
- reads += 1;
- return realList.call(this);
- });
+ const listSpy = vi.spyOn(MarketSourceStore.prototype, 'list').mockImplementation(function (
+ this: MarketSourceStore,
+ ) {
+ reads += 1;
+ return realList.call(this);
+ });
try {
await expect(
@@ -951,13 +1527,14 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
// 提交点必须确认来源仍在,否则会装出一个没有对应来源的包并写孤儿账本记录。
const realGet = MarketSourceStore.prototype.get;
let gets = 0;
- const spy = vi
- .spyOn(MarketSourceStore.prototype, 'get')
- .mockImplementation(function (this: MarketSourceStore, name: string) {
- gets += 1;
- if (gets > 1) return null;
- return realGet.call(this, name);
- });
+ const spy = vi.spyOn(MarketSourceStore.prototype, 'get').mockImplementation(function (
+ this: MarketSourceStore,
+ name: string,
+ ) {
+ gets += 1;
+ if (gets > 1) return null;
+ return realGet.call(this, name);
+ });
try {
await expect(
h.service.install(pluginId, {
@@ -1029,14 +1606,15 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
// MARKET_SOURCE_INVALID。切号发生在 operation 已启动、错误尚未抛出之间——
// 用 store.get 作时序钩子(refreshSource 第一步就是读配置)。
const realGet = MarketSourceStore.prototype.get;
- const spy = vi
- .spyOn(MarketSourceStore.prototype, 'get')
- .mockImplementation(function (this: MarketSourceStore, name: string) {
- const config = realGet.call(this, name);
- fs.rmSync(dir, { recursive: true, force: true });
- runtime.session = { ...runtime.session, generation: runtime.session.generation + 1 };
- return config;
- });
+ const spy = vi.spyOn(MarketSourceStore.prototype, 'get').mockImplementation(function (
+ this: MarketSourceStore,
+ name: string,
+ ) {
+ const config = realGet.call(this, name);
+ fs.rmSync(dir, { recursive: true, force: true });
+ runtime.session = { ...runtime.session, generation: runtime.session.generation + 1 };
+ return config;
+ });
try {
// 失败出口若不校验代际,git/discover 类错误的 detail(刻意保留仓库地址等
// 上一账号私有信息)会被交给切号后的 Renderer。必须统一换成代际错误。
@@ -1165,9 +1743,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
it('does not let official market take over an installed custom plugin when its source is unreadable', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
- const dir = writeLocalMarket(root, 'team-lib', [
- { rel: 'plugins/x', id: 'server-plugin' },
- ]);
+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
runtime.ghosts = [
{ manifest: ghostManifest('server-plugin'), dir: '/ghosts/server-plugin', enabled: true },
diff --git a/apps/desktop/src/main/plugin-market/localIconRequestGate.ts b/apps/desktop/src/main/plugin-market/localIconRequestGate.ts
new file mode 100644
index 0000000000..0ae1a2fc84
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/localIconRequestGate.ts
@@ -0,0 +1,26 @@
+export const MAX_CONCURRENT_LOCAL_ICON_REQUESTS = 2;
+
+/**
+ * Main-side hard cap for the privileged work behind plugin-market:local-icons.
+ * Renderer throttling is only a performance hint and cannot be a security boundary.
+ */
+export class LocalIconRequestGate {
+ private inFlight = 0;
+
+ tryRun<T>(operation: () => Promise<T>): Promise<T> | null {
+ if (this.inFlight >= MAX_CONCURRENT_LOCAL_ICON_REQUESTS) return null;
+ this.inFlight += 1;
+
+ let request: Promise<T>;
+ try {
+ request = operation();
+ } catch (error) {
+ this.inFlight -= 1;
+ throw error;
+ }
+
+ return request.finally(() => {
+ this.inFlight -= 1;
+ });
+ }
+}
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 7b293c8563..e87be5c89d 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -4,6 +4,7 @@ import { ipcMain, type WebContents } from 'electron';
import { isIpcError } from '../../shared/ipc-errors.js';
import type { GhostManifest } from '../../shared/ghost.js';
+import { isPluginMarketCustomIconKey } from '../../shared/pluginMarket.js';
import {
sendToTrustedAppWindows,
setGhostUninstallLedgerPreparer,
@@ -12,6 +13,7 @@ import { createLogger } from '../logger.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';
import { parseMarketSource } from './sources/parse.js';
+import { LocalIconRequestGate } from './localIconRequestGate.js';
import { PluginMarketPackagePermissionReviewBridge } from './packagePermissionReviewBridge.js';
import { PluginMarketService } from './service.js';
@@ -23,6 +25,7 @@ const UPGRADE_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:upgrade-notice-available
const PACKAGE_PERMISSION_REVIEW_CHANNEL = 'plugin-market:package-permission-review';
const trackedReviewRequesters = new WeakSet<WebContents>();
const packagePermissionReviewBridge = new PluginMarketPackagePermissionReviewBridge();
+const localIconRequestGate = new LocalIconRequestGate();
function service(): PluginMarketService {
serviceSingleton ??= new PluginMarketService();
@@ -122,6 +125,28 @@ export function registerPluginMarketIpc(): void {
service().detail(requireString(pluginId, 'pluginId')),
);
});
+ ipcMain.handle('plugin-market:local-icons', (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (!Array.isArray(raw) || raw.length > 8) {
+ throwIpcError('INVALID_PARAMS', 'local icon requests must contain at most 8 entries');
+ }
+ const requests = raw.map((entry) => {
+ const payload = requireObject(entry);
+ const pluginId = requireString(payload.pluginId, 'pluginId');
+ const expectedIconKey = requireString(payload.expectedIconKey, 'expectedIconKey');
+ if (pluginId.length > 1024 || !isPluginMarketCustomIconKey(expectedIconKey)) {
+ throwIpcError('INVALID_PARAMS', 'Invalid local Plugin icon request');
+ }
+ return { pluginId, expectedIconKey };
+ });
+ return invokePluginMarket(() => {
+ const request = localIconRequestGate.tryRun(() => service().localIcons(requests));
+ if (!request) {
+ throwIpcError('PRECONDITION_FAILED', 'Too many local Plugin icon requests');
+ }
+ return request;
+ });
+ });
ipcMain.handle(
'plugin-market:install',
(event, pluginId: unknown, options: unknown) => {
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 738956121e..8d5054dcab 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -13,12 +13,16 @@ import { app, dialog } from 'electron';
import {
diffGhostPermissionItems,
+ GHOST_ICON_MAX_BYTES,
ghostPermissionBaselineKey,
+ ghostIconMimeType,
+ isSafeGhostRelativePath,
isOfficialGhostId,
validateGhostManifest,
type GhostManifest,
type InstalledGhost,
} from '../../shared/ghost.js';
+import { isIpcError } from '../../shared/ipc-errors.js';
import type {
MarketSourceConfig,
MarketSourceSummary,
@@ -26,6 +30,8 @@ import type {
PluginMarketInstallOptions,
PluginMarketInstallResult,
PluginMarketItem,
+ PluginMarketLocalIconRequest,
+ PluginMarketLocalIconResult,
PluginMarketPackageReviewFacts,
PluginMarketSnapshot,
PluginRemovalUserNotice,
@@ -37,6 +43,9 @@ import {
customMarketReleaseId,
marketSourceKey,
parseCustomMarketPluginId,
+ PLUGIN_MARKET_CUSTOM_ICON_PROJECTION_TOKEN_LENGTH,
+ PLUGIN_MARKET_CUSTOM_ICON_SOURCE_TOKEN_LENGTH,
+ pluginMarketCustomIconProjectionToken,
} from '../../shared/pluginMarket.js';
import { getCurrentUserId } from '../authManager.js';
import {
@@ -61,6 +70,7 @@ import { createLogger } from '../logger.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import {
GHOST_MANIFEST_MAX_BYTES,
+ readBoundedFileNoFollowWithStat,
readBoundedFileNoFollowSync,
} from '../utils/readBoundedFile.js';
import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';
@@ -80,9 +90,7 @@ import { MarketSourceStore } from './sources/store.js';
const log = createLogger('plugin-market');
-type PackagePermissionReviewer = (
- facts: PluginMarketPackageReviewFacts,
-) => Promise<boolean>;
+type PackagePermissionReviewer = (facts: PluginMarketPackageReviewFacts) => Promise<boolean>;
class SilentUpgradeBusyError extends Error {}
class SilentUpgradeStaleBaselineError extends Error {}
@@ -103,6 +111,7 @@ class SilentDefaultInstallCancelledError extends Error {}
* 放宽正确性的理由。
*/
const SOURCE_MUTATION_KEY = 'market-sources';
+const CUSTOM_ICON_PROJECTION_TOKEN_RE = /^[a-f0-9]{16}$/;
/**
* 扩权批准的原子复核:Renderer 的 allowPermissionExpansion 只代表「用户对
@@ -158,8 +167,7 @@ function visiblePluginsForOwner(
): VisiblePluginSummary[] {
return owner.mode === 'local'
? plugins.filter(
- (plugin) =>
- plugin.scope === 'public' && isGhostAvailableForActiveSession(plugin.ghostId),
+ (plugin) => plugin.scope === 'public' && isGhostAvailableForActiveSession(plugin.ghostId),
)
: [...plugins];
}
@@ -238,9 +246,7 @@ function legacyRecordFrom(
};
}
-function ghostIdCounts(
- plugins: readonly VisiblePluginSummary[],
-): Map<string, number> {
+function ghostIdCounts(plugins: readonly VisiblePluginSummary[]): Map<string, number> {
const counts = new Map<string, number>();
for (const plugin of plugins) {
counts.set(plugin.ghostId, (counts.get(plugin.ghostId) ?? 0) + 1);
@@ -256,6 +262,7 @@ function manifestSupportsCurrentCindy(manifest: GhostManifest): boolean {
interface CustomMarketEntry {
config: MarketSourceConfig;
plugin: DiscoveredMarketPlugin;
+ iconKey: string | null;
}
/**
@@ -270,10 +277,14 @@ interface CustomMarketEntry {
* 展示投影用:剥掉控制字符(保留换行/制表)与双向文本控制符。只作用于送往
* Renderer 的市场条目字段,不改动 manifest 本体(校验/摘要仍以原文为准)。
*/
+/* eslint-disable no-control-regex */
function stripDirectionalControls(text: string): string {
- // eslint-disable-next-line no-control-regex
- return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
+ return text.replace(
+ /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,
+ '',
+ );
}
+/* eslint-enable no-control-regex */
function installedGhostRawManifest(dir: string): GhostManifest | null {
try {
@@ -297,6 +308,113 @@ function installedGhostRawManifestDigest(dir: string): string | null {
return manifest ? ghostManifestDigest(manifest) : null;
}
+/**
+ * 自定义市场图标的不可逆投影键。Renderer 只拿摘要,不拿来源路径;每次新的
+ * 市场快照都会换 projection token。它是快照级缓存代际,不是预读全部图标得出的
+ * 内容 hash:localIcons 会重新核对当前投影事实并稳定读取;Renderer 可丢弃字节缓存
+ * 后按同一代际重新物化,而刷新市场快照一定换 token 并触发新读取。
+ */
+function customMarketIconPath(plugin: DiscoveredMarketPlugin): string | null {
+ const icon = plugin.manifest.icon;
+ if (!isSafeGhostRelativePath(icon)) return null;
+ return path.join(plugin.dir, ...icon.split('/'));
+}
+
+/**
+ * 自定义市场的不透明传输身份。不包含 revision 或 projection,因此同一
+ * 来源在当前会话内的刷新仍共享一个槽;来源命名空间、会话或重加的同名来源
+ * 不会被旧来源的挂起 IPC 误阻塞。Renderer 只能看到摘要 token。
+ */
+function customMarketIconSourceToken(owner: ActiveAppSession, config: MarketSourceConfig): string {
+ return crypto
+ .createHash('sha256')
+ .update(
+ JSON.stringify([
+ owner.mode,
+ owner.dataOwnerId,
+ owner.generation,
+ config.name,
+ marketSourceKey(config.source),
+ config.addedAt,
+ ]),
+ )
+ .digest('hex')
+ .slice(0, PLUGIN_MARKET_CUSTOM_ICON_SOURCE_TOKEN_LENGTH);
+}
+
+async function customMarketIconKey(
+ owner: ActiveAppSession,
+ config: MarketSourceConfig,
+ plugin: DiscoveredMarketPlugin,
+ projectionToken: string,
+ openedIconStat?: fs.BigIntStats,
+): Promise<string | null> {
+ const iconPath = customMarketIconPath(plugin);
+ if (iconPath === null || !CUSTOM_ICON_PROJECTION_TOKEN_RE.test(projectionToken)) {
+ return null;
+ }
+ let iconFingerprint: string;
+ let projectionUncertain = false;
+ try {
+ // plugin.dir 是发现阶段得到的 realpath。先解析完整图标路径并确认仍在该根内,
+ // 再做 lstat;否则父目录 symlink 会让投影阶段探测并摘要根外文件元数据。
+ const realIconPath = await fs.promises.realpath(iconPath);
+ const relativeToPlugin = path.relative(plugin.dir, realIconPath);
+ if (
+ relativeToPlugin === '..' ||
+ relativeToPlugin.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(relativeToPlugin)
+ ) {
+ return null;
+ }
+ const stat = openedIconStat ?? (await fs.promises.lstat(iconPath, { bigint: true }));
+ iconFingerprint = `${stat.dev}:${stat.ino}:${stat.mode}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
+ } catch (error) {
+ projectionUncertain = !isDeterministicLocalIconReadFailure(error);
+ iconFingerprint = `unreadable:${(error as NodeJS.ErrnoException)?.code ?? 'unknown'}`;
+ }
+ const digest = crypto
+ .createHash('sha256')
+ .update(
+ JSON.stringify([
+ owner.mode,
+ owner.dataOwnerId,
+ owner.generation,
+ config.name,
+ marketSourceKey(config.source),
+ config.addedAt,
+ config.lastRevision,
+ plugin.ghostId,
+ plugin.version,
+ ghostManifestDigest(plugin.manifest),
+ iconFingerprint,
+ projectionToken,
+ ]),
+ )
+ .digest('hex');
+ const digestHead = digest[0] ?? '2';
+ const stableHead = projectionUncertain
+ ? '1'
+ : digestHead === '0' || digestHead === '1'
+ ? '2'
+ : digestHead;
+ return `${stableHead}${customMarketIconSourceToken(owner, config)}${projectionToken}${digest.slice(0, 31)}`;
+}
+
+function localIconMissing(request: PluginMarketLocalIconRequest): PluginMarketLocalIconResult {
+ return { ...request, status: 'missing' };
+}
+
+function localIconRetryable(request: PluginMarketLocalIconRequest): PluginMarketLocalIconResult {
+ return { ...request, status: 'retryable' };
+}
+
+/** 文件不存在/路径形状非法是确定性缺失;权限、锁和其它 I/O 留给 Renderer 重试。 */
+function isDeterministicLocalIconReadFailure(error: unknown): boolean {
+ const code = (error as NodeJS.ErrnoException)?.code;
+ return code === 'ENOENT' || code === 'ENOTDIR' || code === 'EISDIR' || code === 'ELOOP';
+}
+
/** 官方市场是否仍拥有当前落地包;带摘要的新记录必须与磁盘事实一致。 */
function serverMarketOwnsInstalledGhost(
pluginId: string,
@@ -373,6 +491,13 @@ export class PluginMarketService {
private ledgerMutation: Promise<void> = Promise.resolve();
private readonly pendingRemovalNotices = new Map<string, PluginRemovalUserNotice>();
private readonly pendingUpgradeNotices = new Map<string, PluginUpgradeUserNotice>();
+ /**
+ * Renderer 把 customIconKey 当不可变缓存 generation。每次重新投影市场都换代,
+ * 使低精度文件系统上的同长度、同 stat 原地改写也会在刷新后重新按需读取。
+ */
+ private customIconProjectionGeneration = crypto
+ .randomBytes(PLUGIN_MARKET_CUSTOM_ICON_PROJECTION_TOKEN_LENGTH / 2)
+ .toString('hex');
constructor(
private readonly api = new PluginMarketApi(undefined, () => app.getVersion()),
@@ -408,7 +533,8 @@ export class PluginMarketService {
customSourceNames: [],
};
}
- const customEntries = await this.discoverCustomEntriesSafe(owner);
+ const iconProjectionGeneration = this.nextCustomIconProjectionGeneration();
+ const customEntries = await this.discoverCustomEntriesSafe(owner, iconProjectionGeneration);
const customSourceNames = this.customSourceNamesSafe(owner);
requireSameMarketOwner(owner);
if (!getClientEndpoint('pluginApiBaseUrl')) {
@@ -536,6 +662,157 @@ export class PluginMarketService {
});
}
+ /**
+ * 批量按需读取自定义市场图标。一次调用只捕获一个 owner,并按市场分组,保证
+ * 同一来源至多发现一次;路径与字节始终留在 Main,Renderer 只得到 data URL。
+ */
+ async localIcons(
+ requests: readonly PluginMarketLocalIconRequest[],
+ ): Promise<PluginMarketLocalIconResult[]> {
+ return this.runForOwner(async (owner) => {
+ const manager = this.sourceManagerForOwner(owner);
+ const results = new Array<PluginMarketLocalIconResult>(requests.length);
+ const groups = new Map<
+ string,
+ Array<{
+ index: number;
+ request: PluginMarketLocalIconRequest;
+ ref: { marketName: string; ghostId: string };
+ }>
+ >();
+
+ requests.forEach((request, index) => {
+ const ref = parseCustomMarketPluginId(request.pluginId);
+ if (!ref) {
+ results[index] = localIconMissing(request);
+ return;
+ }
+ const group = groups.get(ref.marketName) ?? [];
+ group.push({ index, request, ref });
+ groups.set(ref.marketName, group);
+ });
+
+ for (const [marketName, group] of groups) {
+ try {
+ await manager.withDiscoveredSource(marketName, async (discovered) => {
+ if (!discovered.result.ok) {
+ for (const entry of group) {
+ // 该 key 来自此前成功的快照;二次发现失败时无法可靠区分清单被删
+ // 与 exists/stat 的暂时不可访问。只有来源配置已移除的 NOT_FOUND 才在
+ // 外层 catch 固化为 missing,其余发现失败都交给 Renderer 重试。
+ results[entry.index] = localIconRetryable(entry.request);
+ }
+ return;
+ }
+ const pluginsByGhostId = new Map(
+ discovered.result.marketplace.plugins.map((plugin) => [plugin.ghostId, plugin]),
+ );
+ for (const entry of group) {
+ const plugin = pluginsByGhostId.get(entry.ref.ghostId);
+ if (!plugin) {
+ results[entry.index] =
+ discovered.result.marketplace.unreadableCount > 0
+ ? localIconRetryable(entry.request)
+ : localIconMissing(entry.request);
+ continue;
+ }
+ const expectedProjectionToken = pluginMarketCustomIconProjectionToken(
+ entry.request.expectedIconKey,
+ );
+ if (expectedProjectionToken === null) {
+ results[entry.index] = localIconMissing(entry.request);
+ continue;
+ }
+ const currentIconKey = await customMarketIconKey(
+ owner,
+ discovered.config,
+ plugin,
+ expectedProjectionToken,
+ );
+ if (currentIconKey?.startsWith('1')) {
+ results[entry.index] = localIconRetryable(entry.request);
+ continue;
+ }
+ if (
+ currentIconKey !== entry.request.expectedIconKey &&
+ !entry.request.expectedIconKey.startsWith('1')
+ ) {
+ results[entry.index] = localIconMissing(entry.request);
+ continue;
+ }
+ const icon = plugin.manifest.icon;
+ const iconPath = customMarketIconPath(plugin);
+ const mime = icon === undefined ? null : ghostIconMimeType(icon);
+ if (iconPath === null || mime === null) {
+ results[entry.index] = localIconMissing(entry.request);
+ continue;
+ }
+ try {
+ const read = await readBoundedFileNoFollowWithStat(iconPath, GHOST_ICON_MAX_BYTES, {
+ containWithin: plugin.dir,
+ nonBlocking: true,
+ rejectHardLinks: true,
+ verifyContentStability: true,
+ });
+ if (read === null) {
+ results[entry.index] =
+ discovered.result.marketplace.unreadableCount > 0
+ ? localIconRetryable(entry.request)
+ : localIconMissing(entry.request);
+ } else if (
+ (await customMarketIconKey(
+ owner,
+ discovered.config,
+ plugin,
+ expectedProjectionToken,
+ read.stat,
+ )) !== entry.request.expectedIconKey
+ ) {
+ results[entry.index] = entry.request.expectedIconKey.startsWith('1')
+ ? localIconRetryable(entry.request)
+ : localIconMissing(entry.request);
+ } else {
+ results[entry.index] = {
+ ...entry.request,
+ status: 'loaded',
+ dataUrl: `data:${mime};base64,${read.bytes.toString('base64')}`,
+ };
+ }
+ } catch (error) {
+ results[entry.index] = isDeterministicLocalIconReadFailure(error)
+ ? localIconMissing(entry.request)
+ : localIconRetryable(entry.request);
+ if (!isDeterministicLocalIconReadFailure(error)) {
+ log.warn('custom marketplace icon read failed', {
+ market: marketName,
+ ghostId: entry.ref.ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+ });
+ } catch (error) {
+ if (isIpcError(error) && error.code === 'PRECONDITION_FAILED') throw error;
+ const status = isIpcError(error) && error.code === 'NOT_FOUND' ? 'missing' : 'retryable';
+ for (const entry of group) {
+ results[entry.index] =
+ status === 'missing'
+ ? localIconMissing(entry.request)
+ : localIconRetryable(entry.request);
+ }
+ if (status === 'retryable') {
+ log.warn('custom marketplace icon source unavailable', {
+ market: marketName,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+ return results;
+ });
+ }
+
async install(
pluginId: string,
options: PluginMarketInstallOptions,
@@ -559,19 +836,14 @@ export class PluginMarketService {
if (!selected) {
throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
}
- if (
- catalog.filter((plugin) => plugin.ghostId === selected.ghostId).length !== 1
- ) {
+ if (catalog.filter((plugin) => plugin.ghostId === selected.ghostId).length !== 1) {
throwIpcError('ALREADY_EXISTS', 'Multiple market Plugins use the same Plugin ID');
}
const plugin = await this.api.detail(pluginId);
requireSameMarketOwner(owner);
assertDetailMatchesSummary(selected, plugin);
if (plugin.currentRelease.id !== options.expectedReleaseId) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin release changed after permission review',
- );
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after permission review');
}
const compatible = validateGhostManifest(plugin.currentRelease.manifest);
const reviewed = validateGhostManifest(options.expectedManifest);
@@ -580,10 +852,7 @@ export class PluginMarketService {
!reviewed.ok ||
ghostManifestDigest(compatible.manifest) !== ghostManifestDigest(reviewed.manifest)
) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin manifest changed after permission review',
- );
+ throwIpcError('PRECONDITION_FAILED', 'Plugin manifest changed after permission review');
}
if (!manifestSupportsCurrentCindy(compatible.manifest)) {
throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');
@@ -611,10 +880,7 @@ export class PluginMarketService {
async uninstall(pluginId: string): Promise<{ ok: true }> {
// 自定义市场插件的卸载走同一账本路径,仅跳过服务端 CUID 形状校验。
- if (
- !parseCustomMarketPluginId(pluginId) &&
- !isValidPluginResourceId(pluginId)
- ) {
+ if (!parseCustomMarketPluginId(pluginId) && !isValidPluginResourceId(pluginId)) {
throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');
}
const owner = captureMarketOwner();
@@ -747,27 +1013,38 @@ export class PluginMarketService {
ghostId: string;
}): Promise<PluginMarketDetail> {
return this.runForOwner(async (owner) => {
+ const iconProjectionGeneration = this.customIconProjectionGeneration;
const manager = this.sourceManagerForOwner(owner);
- const discovered = await manager.discoverSource(ref.marketName);
- if (!discovered.result.ok) {
- throwIpcError(discovered.result.code, discovered.result.detail ?? discovered.result.code);
- }
- const plugin = discovered.result.marketplace.plugins.find(
- (candidate) => candidate.ghostId === ref.ghostId,
- );
- if (!plugin) {
- throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');
- }
- if (!manifestSupportsCurrentCindy(plugin.manifest)) {
- throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');
- }
- return {
- ...this.customToItem(
- { config: discovered.config, plugin },
- this.localInstallSnapshot(this.ledgerForOwner(owner)),
- ),
- manifest: plugin.manifest,
- };
+ return manager.withDiscoveredSource(ref.marketName, async (discovered) => {
+ if (!discovered.result.ok) {
+ throwIpcError(discovered.result.code, discovered.result.detail ?? discovered.result.code);
+ }
+ const plugin = discovered.result.marketplace.plugins.find(
+ (candidate) => candidate.ghostId === ref.ghostId,
+ );
+ if (!plugin) {
+ throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');
+ }
+ if (!manifestSupportsCurrentCindy(plugin.manifest)) {
+ throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');
+ }
+ return {
+ ...this.customToItem(
+ {
+ config: discovered.config,
+ plugin,
+ iconKey: await customMarketIconKey(
+ owner,
+ discovered.config,
+ plugin,
+ iconProjectionGeneration,
+ ),
+ },
+ this.localInstallSnapshot(this.ledgerForOwner(owner)),
+ ),
+ manifest: plugin.manifest,
+ };
+ });
});
}
@@ -812,10 +1089,7 @@ export class PluginMarketService {
const pluginId = customMarketPluginId(ref.marketName, plugin.ghostId);
const releaseId = customMarketReleaseId(ref.marketName, plugin.ghostId, plugin.version);
if (releaseId !== options.expectedReleaseId) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin release changed after permission review',
- );
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after permission review');
}
const existing = getGhostManager()
.list()
@@ -832,11 +1106,11 @@ export class PluginMarketService {
: null;
const ownsInstall = Boolean(
existing &&
- currentRecord?.installed &&
- currentRecord.pluginId === pluginId &&
- currentRecord.sourceKey === sourceKey &&
- currentRecord.manifestDigest != null &&
- currentRecord.manifestDigest === reviewInstalledDigest,
+ currentRecord?.installed &&
+ currentRecord.pluginId === pluginId &&
+ currentRecord.sourceKey === sourceKey &&
+ currentRecord.manifestDigest != null &&
+ currentRecord.manifestDigest === reviewInstalledDigest,
);
// 收养:运行时已装内容的声明与本来源候选**完全一致**(原始 manifest 摘要
// 相等)时,允许在没有有效账本记录的情况下重装并补写溯源。这是"包已落位
@@ -845,8 +1119,8 @@ export class PluginMarketService {
// 确认框审阅过同一份 manifest;声明有任何差异都收养不了。
const adoptable = Boolean(
existing &&
- !ownsInstall &&
- reviewInstalledDigest === ghostManifestDigest(plugin.manifest),
+ !ownsInstall &&
+ reviewInstalledDigest === ghostManifestDigest(plugin.manifest),
);
if (existing && !ownsInstall && !adoptable) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
@@ -906,9 +1180,7 @@ export class PluginMarketService {
// 按 id 互斥,beforeCommit 的 runtime 复核到 installOrUpdate 落位之间,
// 同 id 的本地装入/卸载插不进来(否则复核仍会在落位前过期)。
withCommitLock: (fn) =>
- this.withMutation(SOURCE_MUTATION_KEY, () =>
- withGhostInstallLock(plugin.ghostId, fn),
- ),
+ this.withMutation(SOURCE_MUTATION_KEY, () => withGhostInstallLock(plugin.ghostId, fn)),
// 溯源写入仍在上面那把 ghost 锁内(afterCommit 由 commit 段调用):
// 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。
// 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation。
@@ -958,25 +1230,26 @@ export class PluginMarketService {
}
/** 快照聚合用:发现全部自定义市场条目。任何失败都降级为空,不拖垮快照。 */
+ private nextCustomIconProjectionGeneration(): string {
+ return (this.customIconProjectionGeneration = crypto
+ .randomBytes(PLUGIN_MARKET_CUSTOM_ICON_PROJECTION_TOKEN_LENGTH / 2)
+ .toString('hex'));
+ }
+
private async discoverCustomEntriesSafe(
- owner?: ActiveAppSession,
+ owner: ActiveAppSession,
+ iconProjectionGeneration: string,
): Promise<CustomMarketEntry[]> {
try {
- const manager = owner
- ? this.sourceManagerForOwner(owner)
- : new MarketSourceManager({
- store: this.sourceStore,
- cloneRoot: ownerScopedUserDataPath('plugin-market', 'sources'),
- });
- const discovered = await manager.discoverAll();
+ const manager = this.sourceManagerForOwner(owner);
const entries: CustomMarketEntry[] = [];
- for (const { config, result } of discovered) {
+ await manager.forEachDiscoveredSource(async ({ config, result }) => {
if (!result.ok) {
log.warn('custom marketplace discovery failed', {
market: config.name,
code: result.code,
});
- continue;
+ return;
}
if (result.marketplace.unreadableCount > 0) {
log.warn('custom marketplace has unreadable plugin entries', {
@@ -986,9 +1259,13 @@ export class PluginMarketService {
}
for (const plugin of result.marketplace.plugins) {
if (!manifestSupportsCurrentCindy(plugin.manifest)) continue;
- entries.push({ config, plugin });
+ entries.push({
+ config,
+ plugin,
+ iconKey: await customMarketIconKey(owner, config, plugin, iconProjectionGeneration),
+ });
}
- }
+ });
return entries;
} catch (error) {
log.warn('custom marketplace enumeration failed', {
@@ -1007,10 +1284,7 @@ export class PluginMarketService {
}
/** 自定义市场项的状态机与服务端 toItem 完全一致(冲突 / 首装 / 更新 / 已装)。 */
- private customToItem(
- entry: CustomMarketEntry,
- local: LocalInstallSnapshot,
- ): PluginMarketItem {
+ private customToItem(entry: CustomMarketEntry, local: LocalInstallSnapshot): PluginMarketItem {
const { config, plugin } = entry;
const pluginId = customMarketPluginId(config.name, plugin.ghostId);
const releaseId = customMarketReleaseId(config.name, plugin.ghostId, plugin.version);
@@ -1021,19 +1295,19 @@ export class PluginMarketService {
// conflict 而不是 update-available。
const ownsInstall = Boolean(
ghost &&
- record?.installed &&
- record.pluginId === pluginId &&
- record.sourceKey === marketSourceKey(config.source) &&
- record.manifestDigest != null &&
- record.manifestDigest === local.rawDigestByGhostId.get(plugin.ghostId),
+ record?.installed &&
+ record.pluginId === pluginId &&
+ record.sourceKey === marketSourceKey(config.source) &&
+ record.manifestDigest != null &&
+ record.manifestDigest === local.rawDigestByGhostId.get(plugin.ghostId),
);
// 收养口径与 customInstall 一致:运行时内容声明与候选完全一致时不标 conflict,
// 投影成可安装——这是账本写失败后的自愈入口(conflict 在 UI 被禁用,没有它
// 用户连重试的按钮都没有)。
const adoptable = Boolean(
ghost &&
- !ownsInstall &&
- local.rawDigestByGhostId.get(plugin.ghostId) === ghostManifestDigest(plugin.manifest),
+ !ownsInstall &&
+ local.rawDigestByGhostId.get(plugin.ghostId) === ghostManifestDigest(plugin.manifest),
);
// 市场目录只用于发现,不声明未安装 ghostId 的所有权。只有运行时已经存在
// 同 id 且不属于当前来源时才冲突,避免官方或其它市场接管用户已装插件。
@@ -1045,6 +1319,7 @@ export class PluginMarketService {
: record?.releaseId === releaseId
? 'installed'
: 'update-available';
+ const iconKey = entry.iconKey;
return {
pluginId,
ghostId: plugin.ghostId,
@@ -1052,12 +1327,12 @@ export class PluginMarketService {
// 显示成另一副样子(视觉欺骗),控制字符可撑破布局。展示投影一律剥掉
// (保留换行);市场名闸在 discover,这里补齐插件侧同一口径。
name: stripDirectionalControls(plugin.manifest.name),
- description: plugin.manifest.description != null
- ? stripDirectionalControls(plugin.manifest.description)
- : null,
- author: plugin.manifest.author != null
- ? stripDirectionalControls(plugin.manifest.author)
- : null,
+ description:
+ plugin.manifest.description != null
+ ? stripDirectionalControls(plugin.manifest.description)
+ : null,
+ author:
+ plugin.manifest.author != null ? stripDirectionalControls(plugin.manifest.author) : null,
// scope 是服务端授权概念,自定义市场项无服务端身份;展示层按 sourceType 分流。
scope: 'public',
organizationId: null,
@@ -1066,6 +1341,7 @@ export class PluginMarketService {
version: plugin.version,
publishedAt: config.lastSyncedAt ?? config.addedAt,
icon: null,
+ ...(iconKey !== null ? { customIconKey: iconKey } : {}),
installState,
enabled: ownsInstall ? (ghost?.enabled ?? null) : null,
sourceType: config.source.type === 'git' ? 'git-market' : 'local-market',
@@ -1080,9 +1356,7 @@ export class PluginMarketService {
* 写操作落在错误账户。新增 owner-bound 方法只允许经此入口,从结构上
* 杜绝逐路径漏加 generation 校验。
*/
- private async runForOwner<T>(
- operation: (owner: ActiveAppSession) => Promise<T>,
- ): Promise<T> {
+ private async runForOwner<T>(operation: (owner: ActiveAppSession) => Promise<T>): Promise<T> {
const owner = captureMarketOwner();
let result: T;
try {
@@ -1101,9 +1375,7 @@ export class PluginMarketService {
private sourceManagerForOwner(owner: ActiveAppSession): MarketSourceManager {
requireSameMarketOwner(owner);
return new MarketSourceManager({
- store: this.sourceStore.bind(
- ownerScopedUserDataPath('plugin-market', 'sources.v1.json'),
- ),
+ store: this.sourceStore.bind(ownerScopedUserDataPath('plugin-market', 'sources.v1.json')),
cloneRoot: ownerScopedUserDataPath('plugin-market', 'sources'),
});
}
@@ -1178,9 +1450,7 @@ export class PluginMarketService {
plugin,
{
expectedInstalled: options.expectedInstalled,
- ...(reviewedManifest?.ok
- ? { reviewedManifest: reviewedManifest.manifest }
- : {}),
+ ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),
allowPermissionExpansion: options.allowPermissionExpansion,
reviewedBaseline: options.reviewedBaseline,
beforeCommitInLock: options.beforeCommitInLock,
@@ -1200,9 +1470,7 @@ export class PluginMarketService {
plugin,
{
expectedInstalled: options.expectedInstalled,
- ...(reviewedManifest?.ok
- ? { reviewedManifest: reviewedManifest.manifest }
- : {}),
+ ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),
allowPermissionExpansion: options.allowPermissionExpansion,
reviewedBaseline: options.reviewedBaseline,
approvedPackageSha256: error.review.packageSha256,
@@ -1269,8 +1537,7 @@ export class PluginMarketService {
const permissionBaselineManifest =
installedRawManifest &&
currentRecordNow?.installed &&
- (currentRecordNow.source === 'market' ||
- currentRecordNow.source === 'legacy-adopted') &&
+ (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&
currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)
? installedRawManifest
: null;
@@ -1281,9 +1548,7 @@ export class PluginMarketService {
...(options.reviewedManifest
? {
reviewedManifest: options.reviewedManifest,
- ...(permissionBaselineManifest
- ? { permissionBaselineManifest }
- : {}),
+ ...(permissionBaselineManifest ? { permissionBaselineManifest } : {}),
}
: {}),
...(options.approvedPackageSha256 !== undefined
@@ -1417,7 +1682,9 @@ export class PluginMarketService {
): Promise<void> {
const record = ledger.installationForGhost('cindy-github');
requireSameMarketOwner(owner);
- const installed = getGhostManager().list().find((ghost) => ghost.manifest.id === 'cindy-github');
+ const installed = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === 'cindy-github');
if (!record || !installed || !canBackfillOfficialCindyGithubTrust(record, installed)) return;
const tempPath = path.join(
app.getPath('temp'),
@@ -1522,7 +1789,9 @@ export class PluginMarketService {
if (reason) return skip(removal, reason);
ghostsById ??= new Map(
- getGhostManager().list().map((ghost) => [ghost.manifest.id, ghost]),
+ getGhostManager()
+ .list()
+ .map((ghost) => [ghost.manifest.id, ghost]),
);
const installed = ghostsById.get(removal.ghostId);
if (!installed) return skip(removal, 'runtime-not-installed');
@@ -1563,8 +1832,7 @@ export class PluginMarketService {
}
if (removedNames.length === 0) return;
const key = removalNoticeKey(owner);
- const count =
- (this.pendingRemovalNotices.get(key)?.count ?? 0) + removedNames.length;
+ const count = (this.pendingRemovalNotices.get(key)?.count ?? 0) + removedNames.length;
this.pendingRemovalNotices.set(key, {
count,
name: count === 1 ? (removedNames[0] ?? null) : null,
@@ -1579,9 +1847,7 @@ export class PluginMarketService {
const installSubject = defaultInstallSubject(owner);
const counts = ghostIdCounts(plugins);
const uniqueGhostIds = new Set(
- plugins
- .filter((plugin) => counts.get(plugin.ghostId) === 1)
- .map((plugin) => plugin.ghostId),
+ plugins.filter((plugin) => counts.get(plugin.ghostId) === 1).map((plugin) => plugin.ghostId),
);
const ledgerData = ledger.read();
const local = this.localInstallSnapshot(ledger, ledgerData.installations);
@@ -1781,9 +2047,7 @@ export class PluginMarketService {
private ledgerForOwner(owner: ActiveAppSession): PluginMarketLedger {
requireSameMarketOwner(owner);
- return this.ledger.bind(
- ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),
- );
+ return this.ledger.bind(ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'));
}
private withLedgerMutation<T>(
@@ -1822,9 +2086,7 @@ export class PluginMarketService {
private withMutation<T>(pluginId: string, operation: () => Promise<T>): Promise<T> {
const previous = this.mutations.get(pluginId) ?? Promise.resolve();
- const current = previous
- .catch(() => undefined)
- .then(operation);
+ const current = previous.catch(() => undefined).then(operation);
this.mutations.set(pluginId, current);
const cleanup = () => {
if (this.mutations.get(pluginId) === current) this.mutations.delete(pluginId);
diff --git a/apps/desktop/src/main/plugin-market/sources/index.ts b/apps/desktop/src/main/plugin-market/sources/index.ts
index 014d123113..f04f73cb7c 100644
--- a/apps/desktop/src/main/plugin-market/sources/index.ts
+++ b/apps/desktop/src/main/plugin-market/sources/index.ts
@@ -55,12 +55,7 @@ import {
settleCachePathRemovals,
} from './cacheLease.js';
import { discoverMarketplace, type DiscoveredMarketplace, type DiscoverError } from './discover.js';
-import {
- MarketGitError,
- cloneMarketplace,
- fetchMarketplace,
- type GitExecutor,
-} from './git.js';
+import { MarketGitError, cloneMarketplace, fetchMarketplace, type GitExecutor } from './git.js';
import { checkGitPreflight as checkGitPreflightImpl } from './preflight.js';
import { parseMarketSource } from './parse.js';
import { MarketSourceStore } from './store.js';
@@ -176,7 +171,13 @@ export class MarketSourceManager {
try {
const version = (readAtomicFileSync(pointer) ?? '').trim();
// 版本名必须是 versions/ 下的直接子目录名,拒绝绝对路径与穿越。
- if (version && !version.includes('/') && !version.includes('\\') && version !== '..' && version !== '.') {
+ if (
+ version &&
+ !version.includes('/') &&
+ !version.includes('\\') &&
+ version !== '..' &&
+ version !== '.'
+ ) {
const dir = path.join(this.versionsDir(slot), version);
if (fs.existsSync(dir)) return dir;
}
@@ -445,7 +446,11 @@ export class MarketSourceManager {
let revision: string;
try {
revision = await cloneMarketplace(
- { url: source.url, ...(source.ref ? { ref: source.ref } : {}), sparsePaths: source.sparsePaths },
+ {
+ url: source.url,
+ ...(source.ref ? { ref: source.ref } : {}),
+ sparsePaths: source.sparsePaths,
+ },
incoming,
this.deps.gitExecutor,
);
@@ -592,10 +597,7 @@ export class MarketSourceManager {
// 两条路径(快进成功 / 重克隆)都会赋值或抛出,此处仅满足 TS 的确定性赋值分析。
let revision = '';
let stagedDir = fastForwardDir;
- let discovered: Extract<
- Awaited<ReturnType<typeof discoverMarketplace>>,
- { ok: true }
- >;
+ let discovered: Extract<Awaited<ReturnType<typeof discoverMarketplace>>, { ok: true }>;
try {
let fastForwarded = false;
if (current) {
@@ -752,6 +754,36 @@ export class MarketSourceManager {
);
}
+ /**
+ * 在每个来源的读取租约内消费发现结果。回调返回前,result 中的 plugin.dir
+ * 仍然受缓存租约保护;需要从目录读取派生事实的投影层必须使用此入口。
+ */
+ async forEachDiscoveredSource(fn: (entry: DiscoveredSource) => Promise<void>): Promise<void> {
+ const configs = this.deps.store.list();
+ for (const config of configs) {
+ await this.withMarketRoot(config, async (root) => {
+ if (!root || !fs.existsSync(root)) {
+ await fn({
+ config,
+ result: { ok: false, code: 'MARKET_SOURCE_INVALID', detail: 'market root missing' },
+ });
+ return;
+ }
+ const discovered = await discoverMarketplace(root);
+ await fn({
+ config,
+ result: discovered.ok
+ ? { ok: true, marketplace: discovered.marketplace }
+ : {
+ ok: false,
+ code: discovered.code,
+ ...(discovered.detail ? { detail: discovered.detail } : {}),
+ },
+ });
+ });
+ }
+ }
+
/** 快照聚合用:全部来源的发现结果(含失败)。 */
async discoverAll(): Promise<DiscoveredSource[]> {
const configs = this.deps.store.list();
diff --git a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
index d3de6490e2..fdac202496 100644
--- a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
+++ b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts
@@ -3,6 +3,7 @@
* 重点:符号链接一律拒(POSIX 走 O_NOFOLLOW,无该 flag 的平台走
* lstat+dev/ino 回退闸),超限/非普通文件返回 null。
*/
+import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -10,6 +11,8 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ BoundedFileReadChangedError,
+ BoundedFileReadUncertainError,
GHOST_MANIFEST_MAX_BYTES,
readBoundedFileNoFollow,
readBoundedFileNoFollowSync,
@@ -36,6 +39,58 @@ describe('readBoundedFileNoFollow', () => {
expect(await readBoundedFileNoFollow(big, GHOST_MANIFEST_MAX_BYTES)).toBeNull();
});
+ it('rejectHardLinks:拒绝已有硬链接的文件', async () => {
+ const original = path.join(workDir, 'outside-secret.png');
+ const linked = path.join(workDir, 'market-icon.png');
+ await fs.promises.writeFile(original, 'PRIVATE');
+ await fs.promises.link(original, linked);
+
+ expect(await readBoundedFileNoFollow(linked, 1024, { rejectHardLinks: true })).toBeNull();
+ });
+
+ it('rejectHardLinks:读取后链接计数变化时按内容变化拒绝', async () => {
+ const file = path.join(workDir, 'linked-during-read.png');
+ await fs.promises.writeFile(file, 'SAFE');
+ const realOpen = fs.promises.open;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ const handle = await realOpen(...args);
+ const realStat = handle.stat.bind(handle);
+ let statCalls = 0;
+ return new Proxy(handle, {
+ get(target, key) {
+ if (key === 'stat') {
+ return async (options?: fs.StatOptions) => {
+ const stat = (await realStat(options as never)) as unknown as fs.BigIntStats;
+ statCalls += 1;
+ if (statCalls === 1) return stat;
+ return new Proxy(stat, {
+ get(statTarget, statKey) {
+ if (statKey === 'nlink') return 2n;
+ const value = Reflect.get(statTarget, statKey);
+ return typeof value === 'function' ? value.bind(statTarget) : value;
+ },
+ }) as fs.BigIntStats;
+ };
+ }
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }) as typeof fs.promises.open);
+ try {
+ await expect(
+ readBoundedFileNoFollow(file, 1024, {
+ rejectHardLinks: true,
+ verifyContentStability: true,
+ }),
+ ).rejects.toBeInstanceOf(BoundedFileReadChangedError);
+ } finally {
+ openSpy.mockRestore();
+ }
+ });
+
it.runIf(process.platform !== 'win32')('POSIX:符号链接在 open 处被 O_NOFOLLOW 拒绝', async () => {
const target = path.join(workDir, 'target.json');
await fs.promises.writeFile(target, '{"ok":true}');
@@ -59,7 +114,9 @@ describe('readBoundedFileNoFollow', () => {
it('无 O_NOFOLLOW 的平台:普通文件不被回退闸误伤', async () => {
const file = path.join(workDir, 'plain.json');
await fs.promises.writeFile(file, '{"ok":1}');
- expect((await readBoundedFileNoFollow(file, 1024, { noFollowFlag: null }))?.toString('utf8')).toBe('{"ok":1}');
+ expect(
+ (await readBoundedFileNoFollow(file, 1024, { noFollowFlag: null }))?.toString('utf8'),
+ ).toBe('{"ok":1}');
});
it('无 O_NOFOLLOW 的平台:lstat 报告符号链接时拒绝,不依赖宿主 symlink 权限', async () => {
@@ -120,6 +177,31 @@ describe('readBoundedFileNoFollow', () => {
},
);
+ it.runIf(process.platform !== 'win32')('nonBlocking: FIFO 不阻塞并被拒绝', async () => {
+ const fifo = path.join(workDir, 'icon');
+ if (spawnSync('mkfifo', [fifo]).status !== 0) return;
+ const started = Date.now();
+ await expect(readBoundedFileNoFollow(fifo, 1024, { nonBlocking: true })).resolves.toBeNull();
+ expect(Date.now() - started).toBeLessThan(2_000);
+ });
+
+ it('根内复核暂时失败时报告不确定读取,不伪装成缺失', async () => {
+ const file = path.join(workDir, 'uncertain.json');
+ await fs.promises.writeFile(file, '{"ok":true}');
+ const statSpy = vi
+ .spyOn(fs.promises, 'stat')
+ .mockRejectedValueOnce(Object.assign(new Error('EACCES'), { code: 'EACCES' }));
+ try {
+ const error = await readBoundedFileNoFollow(file, 1024, { containWithin: workDir }).catch(
+ (value: unknown) => value,
+ );
+ expect(error).toBeInstanceOf(BoundedFileReadUncertainError);
+ expect(error).toMatchObject({ code: 'EACCES' });
+ } finally {
+ statSpy.mockRestore();
+ }
+ });
+
it('网络盘短读:单次 read 未填满时循环读满已校验长度', async () => {
const file = path.join(workDir, 'short.json');
const payload = `{"key":"${'a'.repeat(64)}"}`;
@@ -150,6 +232,85 @@ describe('readBoundedFileNoFollow', () => {
}
});
+ it('开启内容稳定性校验时,读取期间版本变化返回可重试错误', async () => {
+ const file = path.join(workDir, 'changed.json');
+ await fs.promises.writeFile(file, '{"ok":true}');
+ const realOpen = fs.promises.open;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ const handle = await realOpen(...args);
+ const realStat = handle.stat.bind(handle);
+ let statCalls = 0;
+ return new Proxy(handle, {
+ get(target, key) {
+ if (key === 'stat') {
+ return async (options?: fs.StatOptions) => {
+ const stat = (await realStat(options as never)) as unknown as fs.BigIntStats;
+ statCalls += 1;
+ if (statCalls !== 2) return stat;
+ return new Proxy(stat, {
+ get(statTarget, statKey) {
+ if (statKey === 'mtimeNs') return statTarget.mtimeNs + 1n;
+ const value = Reflect.get(statTarget, statKey);
+ return typeof value === 'function' ? value.bind(statTarget) : value;
+ },
+ }) as fs.BigIntStats;
+ };
+ }
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }) as typeof fs.promises.open);
+ try {
+ await expect(
+ readBoundedFileNoFollow(file, 1024, { verifyContentStability: true }),
+ ).rejects.toBeInstanceOf(BoundedFileReadChangedError);
+ } finally {
+ openSpy.mockRestore();
+ }
+ });
+
+ it('开启内容稳定性校验时,同 stat 的同长度改写会在复读时返回可重试错误', async () => {
+ const file = path.join(workDir, 'same-stat-changed.json');
+ await fs.promises.writeFile(file, 'AAAA');
+ const stableStat = await fs.promises.stat(file, { bigint: true });
+ const realOpen = fs.promises.open;
+ let rewritten = false;
+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (
+ ...args: Parameters<typeof fs.promises.open>
+ ) => {
+ const handle = await realOpen(...args);
+ const realRead = handle.read.bind(handle);
+ return new Proxy(handle, {
+ get(target, key) {
+ if (key === 'stat') return async () => stableStat;
+ if (key === 'read') {
+ return async (buffer: Buffer, offset: number, length: number, position: number) => {
+ const result = await realRead(buffer, offset, length, position);
+ if (!rewritten) {
+ await fs.promises.writeFile(file, 'BBBB');
+ rewritten = true;
+ }
+ return result;
+ };
+ }
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ }) as typeof fs.promises.open);
+ try {
+ await expect(
+ readBoundedFileNoFollow(file, 1024, { verifyContentStability: true }),
+ ).rejects.toBeInstanceOf(BoundedFileReadChangedError);
+ expect(rewritten).toBe(true);
+ } finally {
+ openSpy.mockRestore();
+ }
+ });
+
it.runIf(process.platform !== 'win32')(
'回退闸:dev/ino 为 0(网络盘/无标识 FS)时拒绝,不退化成只看 isSymbolicLink',
async () => {
@@ -184,12 +345,16 @@ describe('readBoundedFileNoFollow', () => {
});
}) as typeof fs.promises.open);
const realLstat = fs.promises.lstat;
- const lstatSpy = vi
- .spyOn(fs.promises, 'lstat')
- .mockImplementation((async (p: fs.PathLike, opts?: fs.StatOptions) => {
- const st = (await (realLstat as (...a: unknown[]) => Promise<fs.BigIntStats>)(p, opts)) as fs.BigIntStats;
- return zero(st);
- }) as typeof fs.promises.lstat);
+ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation((async (
+ p: fs.PathLike,
+ opts?: fs.StatOptions,
+ ) => {
+ const st = (await (realLstat as (...a: unknown[]) => Promise<fs.BigIntStats>)(
+ p,
+ opts,
+ )) as fs.BigIntStats;
+ return zero(st);
+ }) as typeof fs.promises.lstat);
try {
expect(await readBoundedFileNoFollow(file, 1024, { noFollowFlag: null })).toBeNull();
} finally {
@@ -205,19 +370,24 @@ describe('readBoundedFileNoFollowSync', () => {
const file = path.join(workDir, 'plain.json');
await fs.promises.writeFile(file, '{"ok":1}');
expect(readBoundedFileNoFollowSync(file, 1024)?.toString('utf8')).toBe('{"ok":1}');
- expect(readBoundedFileNoFollowSync(file, 1024, { noFollowFlag: null })?.toString('utf8')).toBe('{"ok":1}');
+ expect(readBoundedFileNoFollowSync(file, 1024, { noFollowFlag: null })?.toString('utf8')).toBe(
+ '{"ok":1}',
+ );
const big = path.join(workDir, 'big.json');
await fs.promises.writeFile(big, 'x'.repeat(2048));
expect(readBoundedFileNoFollowSync(big, 1024)).toBeNull();
});
- it.runIf(process.platform !== 'win32')('符号链接:O_NOFOLLOW 拒于 open,回退闸拒于 lstat', async () => {
- const target = path.join(workDir, 'target.json');
- await fs.promises.writeFile(target, '{"ok":true}');
- const link = path.join(workDir, 'link.json');
- await fs.promises.symlink(target, link);
- expect(() => readBoundedFileNoFollowSync(link, 1024)).toThrow();
- expect(readBoundedFileNoFollowSync(link, 1024, { noFollowFlag: null })).toBeNull();
- });
+ it.runIf(process.platform !== 'win32')(
+ '符号链接:O_NOFOLLOW 拒于 open,回退闸拒于 lstat',
+ async () => {
+ const target = path.join(workDir, 'target.json');
+ await fs.promises.writeFile(target, '{"ok":true}');
+ const link = path.join(workDir, 'link.json');
+ await fs.promises.symlink(target, link);
+ expect(() => readBoundedFileNoFollowSync(link, 1024)).toThrow();
+ expect(readBoundedFileNoFollowSync(link, 1024, { noFollowFlag: null })).toBeNull();
+ },
+ );
});
diff --git a/apps/desktop/src/main/utils/readBoundedFile.ts b/apps/desktop/src/main/utils/readBoundedFile.ts
index 1a844e9301..ae4bb5de03 100644
--- a/apps/desktop/src/main/utils/readBoundedFile.ts
+++ b/apps/desktop/src/main/utils/readBoundedFile.ts
@@ -29,8 +29,49 @@ export interface ReadBoundedFileOptions {
/**
* 已 realpath 的根目录。传入时在 open 之后复核:路径此刻 stat 的 dev/ino
* 与句柄一致,且 realpath(filePath) 落在该根内;任一不成立返回 null。
+ * 根内复核遇到无法确定的 I/O 错误时可能抛出 BoundedFileReadUncertainError。
*/
containWithin?: string;
+ /** 特殊文件场景使用非阻塞打开,避免 FIFO 在 Main 中永久等待。 */
+ nonBlocking?: boolean;
+ /** 拒绝链接计数不为 1 的文件,并在读取后再次复核。 */
+ rejectHardLinks?: boolean;
+ /** 复读同一句柄并比较字节;内容或版本变化时抛出可重试错误。 */
+ verifyContentStability?: boolean;
+}
+
+type ReadBoundedFileNoFollowSyncOptions = Pick<
+ ReadBoundedFileOptions,
+ 'noFollowFlag' | 'containWithin'
+>;
+
+export interface BoundedFileRead {
+ bytes: Buffer;
+ /** 与 bytes 来自同一已打开句柄,且读取前后版本字段保持不变。 */
+ stat: fs.BigIntStats;
+}
+
+export class BoundedFileReadUncertainError extends Error {
+ readonly code: string;
+
+ constructor(cause?: unknown) {
+ super('File could not be safely verified');
+ this.name = 'BoundedFileReadUncertainError';
+ this.code =
+ typeof (cause as NodeJS.ErrnoException | undefined)?.code === 'string'
+ ? ((cause as NodeJS.ErrnoException).code as string)
+ : 'FILE_READ_UNCERTAIN';
+ if (cause !== undefined) this.cause = cause;
+ }
+}
+
+export class BoundedFileReadChangedError extends Error {
+ readonly code = 'FILE_CONTENT_CHANGED';
+
+ constructor() {
+ super('File content changed while it was being read');
+ this.name = 'BoundedFileReadChangedError';
+ }
}
/** realpath 产物是否落在同为 realpath 产物的根内(含根本身)。 */
@@ -52,15 +93,24 @@ function sameInode(a: fs.BigIntStats, b: fs.BigIntStats): boolean {
return a.dev === b.dev && a.ino === b.ino;
}
+/** 同一打开句柄在读取前后是否仍是同一内容版本。 */
+function sameHandleVersion(a: fs.BigIntStats, b: fs.BigIntStats): boolean {
+ return (
+ a.dev === b.dev &&
+ a.ino === b.ino &&
+ a.mode === b.mode &&
+ a.size === b.size &&
+ a.mtimeNs === b.mtimeNs &&
+ a.ctimeNs === b.ctimeNs
+ );
+}
+
/**
* 在已打开句柄上循环读满已校验的长度。网络盘/FUSE 上单次 read() 不保证填满
- * 请求区间,单次读会把合法文件截断成解析失败。EOF 早于已校验长度(并发截断)
- * 时按实际读到的字节返回,交由上层解析/校验自然拒绝。
+ * 请求区间,单次读会把合法文件截断成解析失败。EOF 提前时这里只返回实际字节;
+ * 调用方随后用句柄版本复核(及可选复读)拒绝并发截断或改写。
*/
-async function readToLength(
- handle: fs.promises.FileHandle,
- size: number,
-): Promise<Buffer> {
+async function readToLength(handle: fs.promises.FileHandle, size: number): Promise<Buffer> {
const buffer = Buffer.alloc(size);
let offset = 0;
while (offset < size) {
@@ -71,7 +121,7 @@ async function readToLength(
return buffer.subarray(0, offset);
}
-/** open 之后的根内复核(异步侧),失败一律按不可信拒绝。 */
+/** open 后根内复核:确定性路径失败返回 false,无法判定的 I/O 错误抛出。 */
async function verifyStillWithinRoot(
handleStat: fs.BigIntStats,
filePath: string,
@@ -84,7 +134,11 @@ async function verifyStillWithinRoot(
]);
if (!sameInode(pathStat, handleStat)) return false;
return isWithinRoot(realFilePath, realRoot);
- } catch {
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException)?.code;
+ if (code !== 'ENOENT' && code !== 'ENOTDIR' && code !== 'ELOOP') {
+ throw new BoundedFileReadUncertainError(error);
+ }
return false;
}
}
@@ -92,7 +146,8 @@ async function verifyStillWithinRoot(
/**
* 读取一个"必须是普通文件"的文件,拒绝符号链接,限量读取。
*
- * - 非普通文件 / 超过 maxBytes / 符号链接或根内复核不过 → 返回 null;
+ * - 非普通文件 / 超过 maxBytes / 符号链接或确定性根内复核不过 → 返回 null;
+ * - 根内复核遇到无法判定的 I/O 错误 → 抛出 BoundedFileReadUncertainError;
* - open 失败(含 O_NOFOLLOW 平台对 symlink 的 ELOOP 拒绝、ENOENT)→ 抛出,
* 由调用方决定语义。
*
@@ -101,28 +156,31 @@ async function verifyStillWithinRoot(
* 打开的 inode,堵"open 之后换文件"的窗口。语义与 POSIX 侧一致:该文件不允许
* 是符号链接,无论目标指向哪里。
*/
-export async function readBoundedFileNoFollow(
+export async function readBoundedFileNoFollowWithStat(
filePath: string,
maxBytes: number,
options?: ReadBoundedFileOptions,
-): Promise<Buffer | null> {
+): Promise<BoundedFileRead | null> {
const noFollow =
- options?.noFollowFlag !== undefined
- ? options.noFollowFlag
- : (fs.constants.O_NOFOLLOW ?? null);
- const handle = await fs.promises.open(
- filePath,
- fs.constants.O_RDONLY | (noFollow ?? 0),
- );
+ options?.noFollowFlag !== undefined ? options.noFollowFlag : (fs.constants.O_NOFOLLOW ?? null);
+ const openFlags =
+ fs.constants.O_RDONLY |
+ (noFollow ?? 0) |
+ (options?.nonBlocking ? (fs.constants.O_NONBLOCK ?? 0) : 0);
+ const handle = await fs.promises.open(filePath, openFlags);
try {
const stat = await handle.stat({ bigint: true });
if (!stat.isFile() || Number(stat.size) > maxBytes) return null;
+ if (options?.rejectHardLinks && stat.nlink !== 1n) return null;
if (noFollow === null) {
let linkStat: fs.BigIntStats;
try {
linkStat = await fs.promises.lstat(filePath, { bigint: true });
- } catch {
- // 路径条目已消失,无从证明句柄对应目录项 → 按不可信拒绝。
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException)?.code;
+ if (code !== 'ENOENT' && code !== 'ENOTDIR' && code !== 'ELOOP') {
+ throw new BoundedFileReadUncertainError(error);
+ }
return null;
}
if (linkStat.isSymbolicLink()) return null;
@@ -131,12 +189,43 @@ export async function readBoundedFileNoFollow(
if (options?.containWithin !== undefined) {
if (!(await verifyStillWithinRoot(stat, filePath, options.containWithin))) return null;
}
- return await readToLength(handle, Number(stat.size));
+ const bytes = await readToLength(handle, Number(stat.size));
+ const finalStat = await handle.stat({ bigint: true });
+ if (options?.rejectHardLinks && finalStat.nlink !== 1n) {
+ if (options.verifyContentStability) throw new BoundedFileReadChangedError();
+ return null;
+ }
+ if (!sameHandleVersion(stat, finalStat)) {
+ if (options?.verifyContentStability) throw new BoundedFileReadChangedError();
+ return null;
+ }
+ if (options?.verifyContentStability) {
+ const verificationBytes = await readToLength(handle, Number(stat.size));
+ const verificationStat = await handle.stat({ bigint: true });
+ if (
+ (options.rejectHardLinks && verificationStat.nlink !== 1n) ||
+ !sameHandleVersion(finalStat, verificationStat) ||
+ bytes.length !== verificationBytes.length ||
+ !bytes.equals(verificationBytes)
+ ) {
+ throw new BoundedFileReadChangedError();
+ }
+ return { bytes, stat: verificationStat };
+ }
+ return { bytes, stat: finalStat };
} finally {
await handle.close();
}
}
+export async function readBoundedFileNoFollow(
+ filePath: string,
+ maxBytes: number,
+ options?: ReadBoundedFileOptions,
+): Promise<Buffer | null> {
+ return (await readBoundedFileNoFollowWithStat(filePath, maxBytes, options))?.bytes ?? null;
+}
+
/**
* 跟随符号链接的变体:仅供"路径已经是 realpath 产物、链接目标已被根包含校验
* 管住"的调用方使用(市场清单 marketplace.json)。类型与大小闸、根内复核、
@@ -167,12 +256,10 @@ export async function readBoundedFileFollowLinks(
export function readBoundedFileNoFollowSync(
filePath: string,
maxBytes: number,
- options?: ReadBoundedFileOptions,
+ options?: ReadBoundedFileNoFollowSyncOptions,
): Buffer | null {
const noFollow =
- options?.noFollowFlag !== undefined
- ? options.noFollowFlag
- : (fs.constants.O_NOFOLLOW ?? null);
+ options?.noFollowFlag !== undefined ? options.noFollowFlag : (fs.constants.O_NOFOLLOW ?? null);
const fd = fs.openSync(filePath, fs.constants.O_RDONLY | (noFollow ?? 0));
try {
const stat = fs.fstatSync(fd, { bigint: true });
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index dd09baab81..83853b133a 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1199,6 +1199,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('plugin-market:snapshot'),
detail: (pluginId: string): Promise<import('../shared/pluginMarket').PluginMarketDetail> =>
ipcRenderer.invoke('plugin-market:detail', pluginId),
+ localIcons: (
+ requests: import('../shared/pluginMarket').PluginMarketLocalIconRequest[],
+ ): Promise<import('../shared/pluginMarket').PluginMarketLocalIconResult[]> =>
+ ipcRenderer.invoke('plugin-market:local-icons', requests),
install: (
pluginId: string,
options: import('../shared/pluginMarket').PluginMarketInstallOptions,
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx
index af02d48b46..c3bf194056 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx
@@ -14,7 +14,7 @@ import {
Workflow,
type LucideIcon,
} from 'lucide-react';
-import { useEffect, useState } from 'react';
+import { useEffect, useState, type Ref } from 'react';
import { cn } from '@/lib/utils';
import { ghostFallbackIconKind, type GhostFallbackIconKind } from './lib/ghostPluginViewModel';
@@ -61,12 +61,16 @@ export function GhostPluginIcon({
iconDataUrl,
iconId,
iconName,
+ iconContainerRef,
+ onIconLoad,
onIconLoadError,
size = 'md',
}: {
iconDataUrl?: string;
iconId: string;
iconName: string;
+ iconContainerRef?: Ref<HTMLSpanElement>;
+ onIconLoad?: () => void;
onIconLoadError?: () => void;
size?: GhostPluginIconSize;
}) {
@@ -81,6 +85,7 @@ export function GhostPluginIcon({
return (
<span
+ ref={iconContainerRef}
className={cn(
'inline-flex shrink-0 items-center justify-center overflow-hidden border-[0.5px] border-[var(--border-default)]',
resolvedIconDataUrl
@@ -95,6 +100,7 @@ export function GhostPluginIcon({
alt=""
draggable={false}
referrerPolicy="no-referrer"
+ onLoad={onIconLoad}
onError={() => {
setFailedSrc(resolvedIconDataUrl);
onIconLoadError?.();
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 21a222c207..aef4315386 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -125,6 +125,7 @@ import {
import { AddMarketplaceDialog } from './AddMarketplaceDialog';
import { pluginMarketErrorKey } from './lib/pluginMarketErrorKey';
import { usePluginIconRefresh } from './lib/usePluginIconRefresh';
+import { usePluginMarketIcon } from './lib/usePluginMarketIcon';
import { usePluginMarketForegroundRefresh } from './lib/usePluginMarketForegroundRefresh';
import { usePluginMarketLocaleRefresh } from './lib/usePluginMarketLocaleRefresh';
import './plugin-motion.css';
@@ -1716,6 +1717,7 @@ export function MarketPluginCard({
onIconLoadError: () => void;
}) {
const { t } = useTranslation();
+ const marketIcon = usePluginMarketIcon(item, { deferUntilVisible: true });
const unavailable = busy || item.installState === 'conflict';
const conflictDescriptionId = useId();
const conflictDescription =
@@ -1748,10 +1750,12 @@ export function MarketPluginCard({
)}
>
<GhostPluginIcon
- iconDataUrl={item.icon?.url}
+ iconContainerRef={marketIcon.containerRef}
+ iconDataUrl={marketIcon.iconDataUrl}
iconId={item.ghostId}
iconName={item.name}
- onIconLoadError={onIconLoadError}
+ onIconLoad={marketIcon.onIconLoad}
+ onIconLoadError={() => marketIcon.onIconLoadError(onIconLoadError)}
/>
<span className="flex min-w-0 flex-1 flex-col self-stretch pt-0.5">
<span className="truncate text-15 font-medium text-[var(--text-primary)]">
diff --git a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
index 9c93ffd6af..c2d212bf8f 100644
--- a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
@@ -6,6 +6,7 @@ import { cn } from '@/lib/utils';
import { ghostPermissionItems } from '../../../shared/ghost';
import type { PluginMarketDetail } from '../../../shared/pluginMarket';
import { GhostPluginIcon } from './GhostPluginIcon';
+import { usePluginMarketIcon } from './lib/usePluginMarketIcon';
import { pluginPresentationOrigin } from './lib/pluginMarketPresentation';
import { PluginDetailTopBar, usePluginDetailScrolled } from './PluginDetailTopBar';
@@ -26,6 +27,7 @@ export function MarketPluginDetailView({
}: MarketPluginDetailViewProps) {
const { t } = useTranslation();
const { scrolled, onScroll } = usePluginDetailScrolled();
+ const marketIcon = usePluginMarketIcon(detail, { deferUntilVisible: false });
const presentationOrigin = pluginPresentationOrigin(detail);
// 自定义市场(Git/本地源)的包字节未经服务端校验,安全说明必须如实区分。
const isCustomSource = detail.sourceType !== 'server';
@@ -62,10 +64,12 @@ export function MarketPluginDetailView({
<header>
<div className="plugin-detail-hero grid grid-cols-[64px_minmax(0,1fr)_auto] items-center gap-3">
<GhostPluginIcon
- iconDataUrl={detail.icon?.url}
+ iconContainerRef={marketIcon.containerRef}
+ iconDataUrl={marketIcon.iconDataUrl}
iconId={detail.ghostId}
iconName={detail.name}
- onIconLoadError={onIconLoadError}
+ onIconLoad={marketIcon.onIconLoad}
+ onIconLoadError={() => marketIcon.onIconLoadError(onIconLoadError)}
size="detail"
/>
<div className="min-w-0">
diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketIcon.test.tsx b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketIcon.test.tsx
new file mode 100644
index 0000000000..a5a0b4160f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/usePluginMarketIcon.test.tsx
@@ -0,0 +1,697 @@
+/**
+ * Regression coverage for custom marketplace icon batching, viewport loading and cache bounds.
+ * @vitest-environment jsdom
+ */
+
+import { act, render, renderHook, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type {
+ PluginMarketItem,
+ PluginMarketLocalIconRequest,
+ PluginMarketLocalIconResult,
+} from '../../../../../shared/pluginMarket';
+import {
+ __pluginMarketIconStoreStatsForTest,
+ __resetPluginMarketIconStoreForTest,
+ usePluginMarketIcon,
+} from '../usePluginMarketIcon';
+
+function testHex(value: string, length: number): string {
+ const encoded = [...value]
+ .map((character) => character.codePointAt(0)!.toString(16).padStart(2, '0'))
+ .join('');
+ return (encoded || 'a').repeat(Math.ceil(length / Math.max(encoded.length, 1))).slice(0, length);
+}
+
+function testCustomIconKey(source: string, projection: string, digest: string): string {
+ return `2${testHex(source, 16)}${testHex(projection, 16)}${testHex(digest, 31)}`;
+}
+
+function customItem(
+ id: string,
+ key?: string,
+ market = 'team-lib',
+ source = market,
+): PluginMarketItem {
+ const iconKey = key ?? testCustomIconKey(source, 'snapshot', id);
+ return {
+ pluginId: `custom:${market}/${id}`,
+ ghostId: id,
+ name: id,
+ description: null,
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: false,
+ releaseId: `custom:${market}/${id}:1.0.0`,
+ version: '1.0.0',
+ publishedAt: '2026-08-06T00:00:00.000Z',
+ icon: null,
+ customIconKey: iconKey,
+ installState: 'not-installed',
+ enabled: null,
+ sourceType: 'local-market',
+ sourceMarketName: market,
+ };
+}
+
+let localIcons: ReturnType<typeof vi.fn>;
+
+function ConsumerForSourceSplit({ item }: { item: PluginMarketItem }) {
+ const icon = usePluginMarketIcon(item, { deferUntilVisible: false });
+ return <span>{icon.iconDataUrl ? 'loaded' : 'pending'}</span>;
+}
+
+beforeEach(() => {
+ __resetPluginMarketIconStoreForTest();
+ localIcons = vi.fn();
+ (window as unknown as { electronAPI: { pluginMarket: { localIcons: typeof localIcons } } })
+ .electronAPI = { pluginMarket: { localIcons } };
+});
+
+afterEach(() => {
+ __resetPluginMarketIconStoreForTest();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ Reflect.deleteProperty(globalThis, 'IntersectionObserver');
+ Reflect.deleteProperty(window, 'electronAPI');
+});
+
+describe('usePluginMarketIcon', () => {
+ it('merges same-frame consumers into one request and reuses the shared cache', async () => {
+ const alpha = customItem('alpha');
+ const beta = customItem('beta');
+ localIcons.mockImplementation(async (requests: PluginMarketLocalIconRequest[]) =>
+ requests.map(
+ (request): PluginMarketLocalIconResult => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: `data:image/png;base64,${request.pluginId}`,
+ }),
+ ),
+ );
+
+ const first = renderHook(() => [
+ usePluginMarketIcon(alpha, { deferUntilVisible: false }),
+ usePluginMarketIcon(beta, { deferUntilVisible: false }),
+ ]);
+ await waitFor(() => expect(first.result.current.every((entry) => entry.iconDataUrl)).toBe(true));
+ expect(localIcons).toHaveBeenCalledTimes(1);
+ expect(localIcons.mock.calls[0]?.[0]).toEqual([
+ { pluginId: alpha.pluginId, expectedIconKey: alpha.customIconKey },
+ { pluginId: beta.pluginId, expectedIconKey: beta.customIconKey },
+ ]);
+
+ first.unmount();
+ const cached = renderHook(() => usePluginMarketIcon(alpha, { deferUntilVisible: false }));
+ expect(cached.result.current.iconDataUrl).toContain(alpha.pluginId);
+ expect(localIcons).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back without IPC retries when a custom icon key is invalid', async () => {
+ const item = customItem('invalid-key', '0'.repeat(64));
+ const hook = renderHook(() => usePluginMarketIcon(item, { deferUntilVisible: false }));
+ await act(async () => Promise.resolve());
+
+ expect(hook.result.current.iconDataUrl).toBeUndefined();
+ expect(localIcons).not.toHaveBeenCalled();
+ hook.unmount();
+ });
+
+ it('reloads cached bytes when Main publishes a new icon projection generation', async () => {
+ const first = customItem('alpha', testCustomIconKey('team-source', 'projection-a', 'old'));
+ const next = customItem('alpha', testCustomIconKey('team-source', 'projection-b', 'new'));
+ localIcons
+ .mockResolvedValueOnce([
+ {
+ pluginId: first.pluginId,
+ expectedIconKey: first.customIconKey!,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,OLD',
+ },
+ ])
+ .mockResolvedValueOnce([
+ {
+ pluginId: next.pluginId,
+ expectedIconKey: next.customIconKey!,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,NEW',
+ },
+ ]);
+
+ const hook = renderHook(
+ ({ item }: { item: PluginMarketItem }) =>
+ usePluginMarketIcon(item, { deferUntilVisible: false }),
+ { initialProps: { item: first } },
+ );
+ await waitFor(() => expect(hook.result.current.iconDataUrl).toContain('OLD'));
+ expect(localIcons).toHaveBeenCalledTimes(1);
+
+ hook.rerender({ item: next });
+ await waitFor(() => expect(hook.result.current.iconDataUrl).toContain('NEW'));
+ expect(localIcons).toHaveBeenCalledTimes(2);
+ expect(localIcons.mock.calls[1]?.[0]).toEqual([
+ { pluginId: next.pluginId, expectedIconKey: next.customIconKey },
+ ]);
+ hook.unmount();
+ });
+
+ it('does not read a card icon until its container approaches the viewport', async () => {
+ let callback: IntersectionObserverCallback | null = null;
+ const observe = vi.fn();
+ const disconnect = vi.fn();
+ class TestIntersectionObserver {
+ constructor(next: IntersectionObserverCallback) {
+ callback = next;
+ }
+ observe = observe;
+ disconnect = disconnect;
+ unobserve = vi.fn();
+ takeRecords = vi.fn(() => []);
+ readonly root = null;
+ readonly rootMargin = '240px';
+ readonly thresholds = [0];
+ }
+ globalThis.IntersectionObserver =
+ TestIntersectionObserver as unknown as typeof IntersectionObserver;
+ localIcons.mockImplementation(async (requests: PluginMarketLocalIconRequest[]) =>
+ requests.map(
+ (request): PluginMarketLocalIconResult => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ }),
+ ),
+ );
+
+ const item = customItem('alpha');
+ const hook = renderHook(() => usePluginMarketIcon(item, { deferUntilVisible: true }));
+ const target = document.createElement('span');
+ act(() => hook.result.current.containerRef(target));
+ await waitFor(() => expect(observe).toHaveBeenCalledWith(target));
+ expect(localIcons).not.toHaveBeenCalled();
+
+ act(() => {
+ callback?.(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ {} as IntersectionObserver,
+ );
+ });
+ await waitFor(() => expect(hook.result.current.iconDataUrl).toContain('AAAA'));
+ expect(localIcons).toHaveBeenCalledTimes(1);
+ hook.unmount();
+ expect(disconnect).toHaveBeenCalled();
+ });
+
+ it('retries uncertain failures while visible and stops once bytes load', async () => {
+ vi.useFakeTimers();
+ const item = customItem('alpha');
+ localIcons
+ .mockResolvedValueOnce([
+ {
+ pluginId: item.pluginId,
+ expectedIconKey: item.customIconKey!,
+ status: 'retryable',
+ },
+ ])
+ .mockResolvedValueOnce([
+ {
+ pluginId: item.pluginId,
+ expectedIconKey: item.customIconKey!,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ },
+ ]);
+
+ const hook = renderHook(() => usePluginMarketIcon(item, { deferUntilVisible: false }));
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ expect(localIcons).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_000);
+ });
+ expect(localIcons).toHaveBeenCalledTimes(2);
+ expect(hook.result.current.iconDataUrl).toContain('AAAA');
+ });
+
+ it('serializes batches so one source discovery finishes before the next batch starts', async () => {
+ const items = Array.from({ length: 17 }, (_, index) => customItem(`icon-${index}`));
+ const pending: Array<{
+ requests: PluginMarketLocalIconRequest[];
+ resolve: (results: PluginMarketLocalIconResult[]) => void;
+ }> = [];
+ localIcons.mockImplementation(
+ (requests: PluginMarketLocalIconRequest[]) =>
+ new Promise<PluginMarketLocalIconResult[]>((resolve) => {
+ pending.push({ requests, resolve });
+ }),
+ );
+
+ function Consumer({ item }: { item: PluginMarketItem }) {
+ const icon = usePluginMarketIcon(item, { deferUntilVisible: false });
+ return <span data-testid="serialized-icon">{icon.iconDataUrl ? 'loaded' : 'pending'}</span>;
+ }
+
+ const view = render(
+ <>
+ {items.map((item) => (
+ <Consumer key={item.pluginId} item={item} />
+ ))}
+ </>,
+ );
+ await waitFor(() => expect(localIcons).toHaveBeenCalledTimes(1));
+ const firstBatch = pending[0]!;
+ expect(firstBatch.requests).toHaveLength(8);
+
+ await act(async () => {
+ firstBatch.resolve(
+ firstBatch.requests.map((request) => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ })),
+ );
+ });
+ await waitFor(() => expect(localIcons).toHaveBeenCalledTimes(2));
+ const secondBatch = pending[1]!;
+ expect(secondBatch.requests).toHaveLength(8);
+
+ await act(async () => {
+ secondBatch.resolve(
+ secondBatch.requests.map((request) => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ })),
+ );
+ });
+ await waitFor(() => expect(localIcons).toHaveBeenCalledTimes(3));
+ const thirdBatch = pending[2]!;
+ expect(thirdBatch.requests).toHaveLength(1);
+
+ await act(async () => {
+ thirdBatch.resolve(
+ thirdBatch.requests.map((request) => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ })),
+ );
+ });
+ await waitFor(() =>
+ expect(
+ screen.getAllByTestId('serialized-icon').every((node) => node.textContent === 'loaded'),
+ ).toBe(true),
+ );
+ view.unmount();
+ });
+
+ it('does not mix different marketplace sources in one IPC batch', async () => {
+ const teamItems = Array.from({ length: 5 }, (_, index) => customItem(`team-${index}`));
+ const otherItems = Array.from({ length: 4 }, (_, index) =>
+ customItem(`other-${index}`, undefined, 'other-market'),
+ );
+ const pending: Array<{
+ requests: PluginMarketLocalIconRequest[];
+ resolve: (results: PluginMarketLocalIconResult[]) => void;
+ }> = [];
+ localIcons.mockImplementation(
+ (requests: PluginMarketLocalIconRequest[]) =>
+ new Promise<PluginMarketLocalIconResult[]>((resolve) =>
+ pending.push({ requests, resolve }),
+ ),
+ );
+
+ const view = render(
+ <>
+ {[...teamItems, ...otherItems].map((item) => (
+ <span key={item.pluginId}>
+ <ConsumerForSourceSplit item={item} />
+ </span>
+ ))}
+ </>,
+ );
+ await waitFor(() => expect(localIcons).toHaveBeenCalledTimes(1));
+ expect(
+ pending[0]!.requests.every((request) => request.pluginId.startsWith('custom:team-lib/')),
+ ).toBe(true);
+ await act(async () =>
+ pending[0]!.resolve(
+ pending[0]!.requests.map((request) => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ })),
+ ),
+ );
+ await waitFor(() => expect(localIcons).toHaveBeenCalledTimes(2));
+ expect(
+ pending[1]!.requests.every((request) => request.pluginId.startsWith('custom:other-market/')),
+ ).toBe(true);
+ await act(async () =>
+ pending[1]!.resolve(
+ pending[1]!.requests.map((request) => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ })),
+ ),
+ );
+ view.unmount();
+ });
+
+ it('releases a hung IPC batch after its timeout and ignores late results', async () => {
+ vi.useFakeTimers();
+ const items = [
+ ...Array.from({ length: 8 }, (_, index) => customItem(`timeout-${index}`)),
+ customItem('healthy-after-timeout', undefined, 'other-market'),
+ ];
+ localIcons
+ .mockImplementationOnce(
+ () => new Promise<PluginMarketLocalIconResult[]>(() => undefined),
+ )
+ .mockImplementation(async (requests: PluginMarketLocalIconRequest[]) =>
+ requests.map(
+ (request): PluginMarketLocalIconResult => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: 'data:image/png;base64,AAAA',
+ }),
+ ),
+ );
+
+ function Consumer({ item }: { item: PluginMarketItem }) {
+ const icon = usePluginMarketIcon(item, { deferUntilVisible: false });
+ return <span data-testid="timeout-icon">{icon.iconDataUrl ? 'loaded' : 'pending'}</span>;
+ }
+
+ const view = render(
+ <>
+ {items.map((item) => (
+ <Consumer key={item.pluginId} item={item} />
+ ))}
+ </>,
+ );
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(localIcons).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000);
+ });
+ expect(localIcons.mock.calls.length).toBeGreaterThan(1);
+ expect(
+ localIcons.mock.calls.slice(1).some((call) =>
+ (call[0] as PluginMarketLocalIconRequest[]).some(
+ (request) => request.pluginId === items[8]!.pluginId,
+ ),
+ ),
+ ).toBe(true);
+ view.unmount();
+ });
+
+ it('does not exceed the global unsettled request cap', async () => {
+ vi.useFakeTimers();
+ localIcons.mockImplementation(
+ () => new Promise<PluginMarketLocalIconResult[]>(() => undefined),
+ );
+ const first = renderHook(() =>
+ usePluginMarketIcon(customItem('cap-a'), { deferUntilVisible: false }),
+ );
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ const second = renderHook(() =>
+ usePluginMarketIcon(customItem('cap-b', undefined, 'other-market'), {
+ deferUntilVisible: false,
+ }),
+ );
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ expect(__pluginMarketIconStoreStatsForTest().unsettledRequests).toBe(2);
+ expect(localIcons).toHaveBeenCalledTimes(2);
+ first.unmount();
+ second.unmount();
+ });
+
+ it('keeps one transport slot per opaque source across projection generations', async () => {
+ vi.useFakeTimers();
+ localIcons.mockImplementation(
+ () => new Promise<PluginMarketLocalIconResult[]>(() => undefined),
+ );
+ const first = renderHook(() =>
+ usePluginMarketIcon(
+ customItem('same-source-a', testCustomIconKey('source-a', 'projection-a', 'a')),
+ { deferUntilVisible: false },
+ ),
+ );
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+
+ const second = renderHook(() =>
+ usePluginMarketIcon(
+ customItem('same-source-b', testCustomIconKey('source-a', 'projection-b', 'b')),
+ { deferUntilVisible: false },
+ ),
+ );
+ await act(async () => Promise.resolve());
+
+ expect(localIcons).toHaveBeenCalledTimes(1);
+ expect(__pluginMarketIconStoreStatsForTest().unsettledRequests).toBe(1);
+ first.unmount();
+ second.unmount();
+ });
+
+ it('does not let a hung same-name source block a replacement source', async () => {
+ vi.useFakeTimers();
+ localIcons.mockImplementation(
+ () => new Promise<PluginMarketLocalIconResult[]>(() => undefined),
+ );
+ const oldSource = renderHook(() =>
+ usePluginMarketIcon(
+ customItem('old-source', testCustomIconKey('source-old', 'projection-a', 'a')),
+ { deferUntilVisible: false },
+ ),
+ );
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+
+ const replacement = customItem(
+ 'replacement-source',
+ testCustomIconKey('source-new', 'projection-b', 'b'),
+ );
+ const nextSource = renderHook(() =>
+ usePluginMarketIcon(replacement, { deferUntilVisible: false }),
+ );
+ await act(async () => Promise.resolve());
+
+ expect(localIcons).toHaveBeenCalledTimes(2);
+ expect(localIcons.mock.calls[1]?.[0]).toEqual([
+ {
+ pluginId: replacement.pluginId,
+ expectedIconKey: replacement.customIconKey,
+ },
+ ]);
+ expect(__pluginMarketIconStoreStatsForTest().unsettledRequests).toBe(2);
+ oldSource.unmount();
+ nextSource.unmount();
+ });
+
+ it('does not let one hung marketplace consume both transport slots', async () => {
+ vi.useFakeTimers();
+ let resolveHealthy: ((results: PluginMarketLocalIconResult[]) => void) | undefined;
+ localIcons
+ .mockImplementationOnce(() => new Promise<PluginMarketLocalIconResult[]>(() => undefined))
+ .mockImplementationOnce(
+ () =>
+ new Promise<PluginMarketLocalIconResult[]>((resolve) => {
+ resolveHealthy = resolve;
+ }),
+ );
+ const hung = renderHook(() =>
+ usePluginMarketIcon(customItem('hung-a'), { deferUntilVisible: false }),
+ );
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ await act(async () => vi.advanceTimersByTimeAsync(1_000));
+ expect(localIcons).toHaveBeenCalledTimes(1);
+
+ const healthyMarketItem = customItem('healthy-b', undefined, 'other-market');
+ const healthy = renderHook(() =>
+ usePluginMarketIcon(healthyMarketItem, { deferUntilVisible: false }),
+ );
+ await act(async () => Promise.resolve());
+
+ expect(localIcons).toHaveBeenCalledTimes(2);
+ expect(localIcons.mock.calls[1]?.[0]).toEqual([
+ {
+ pluginId: healthyMarketItem.pluginId,
+ expectedIconKey: healthyMarketItem.customIconKey,
+ },
+ ]);
+ expect(__pluginMarketIconStoreStatsForTest().unsettledRequests).toBe(2);
+
+ await act(async () =>
+ resolveHealthy?.([
+ {
+ pluginId: healthyMarketItem.pluginId,
+ expectedIconKey: healthyMarketItem.customIconKey!,
+ status: 'loaded',
+ dataUrl: `data:image/png;base64,${healthyMarketItem.pluginId}`,
+ },
+ ]),
+ );
+ expect(healthy.result.current.iconDataUrl).toContain(healthyMarketItem.pluginId);
+ expect(__pluginMarketIconStoreStatsForTest().unsettledRequests).toBe(1);
+ expect(localIcons).toHaveBeenCalledTimes(2);
+
+ hung.unmount();
+ healthy.unmount();
+ });
+
+ it('wakes transport-blocked icons when a slot settles without consuming retry budget', async () => {
+ vi.useFakeTimers();
+ const pending: Array<{
+ requests: PluginMarketLocalIconRequest[];
+ resolve: (results: PluginMarketLocalIconResult[]) => void;
+ }> = [];
+ localIcons.mockImplementation(
+ (requests: PluginMarketLocalIconRequest[]) =>
+ new Promise<PluginMarketLocalIconResult[]>((resolve) => {
+ pending.push({ requests, resolve });
+ }),
+ );
+
+ const first = renderHook(() =>
+ usePluginMarketIcon(customItem('blocked-a'), { deferUntilVisible: false }),
+ );
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ const second = renderHook(() =>
+ usePluginMarketIcon(customItem('blocked-b', undefined, 'other-market'), {
+ deferUntilVisible: false,
+ }),
+ );
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ const thirdItem = customItem('blocked-c', undefined, 'third-market');
+ const third = renderHook(() => usePluginMarketIcon(thirdItem, { deferUntilVisible: false }));
+ await act(async () => Promise.resolve());
+
+ expect(localIcons).toHaveBeenCalledTimes(2);
+ await act(async () => vi.advanceTimersByTimeAsync(60_000));
+ expect(localIcons).toHaveBeenCalledTimes(2);
+
+ first.unmount();
+ second.unmount();
+ await act(async () => pending[0]!.resolve([]));
+ expect(localIcons).toHaveBeenCalledTimes(3);
+ const recovery = pending[2]!;
+ expect(recovery.requests.some((request) => request.pluginId === thirdItem.pluginId)).toBe(true);
+ await act(async () =>
+ recovery.resolve(
+ recovery.requests.map((request) => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: `data:image/png;base64,${request.pluginId}`,
+ })),
+ ),
+ );
+ expect(third.result.current.iconDataUrl).toContain(thirdItem.pluginId);
+
+ third.unmount();
+ });
+
+ it('bounds unmounted record metadata and cancels pending retries', async () => {
+ const items = Array.from({ length: 136 }, (_, index) => customItem(`record-${index}`));
+ localIcons.mockImplementation(async (requests: PluginMarketLocalIconRequest[]) =>
+ requests.map(
+ (request): PluginMarketLocalIconResult => ({ ...request, status: 'missing' }),
+ ),
+ );
+
+ function Consumer({ item }: { item: PluginMarketItem }) {
+ usePluginMarketIcon(item, { deferUntilVisible: false });
+ return null;
+ }
+
+ const view = render(
+ <>
+ {items.map((item) => (
+ <Consumer key={item.pluginId} item={item} />
+ ))}
+ </>,
+ );
+ await waitFor(() => expect(localIcons).toHaveBeenCalledTimes(17));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ view.unmount();
+ expect(__pluginMarketIconStoreStatsForTest().records).toBeLessThanOrEqual(128);
+ __resetPluginMarketIconStoreForTest();
+
+ vi.useFakeTimers();
+ const retryItem = customItem('retry-after-unmount');
+ localIcons.mockReset();
+ localIcons.mockResolvedValue([
+ {
+ pluginId: retryItem.pluginId,
+ expectedIconKey: retryItem.customIconKey!,
+ status: 'retryable',
+ },
+ ]);
+ const hook = renderHook(() => usePluginMarketIcon(retryItem, { deferUntilVisible: false }));
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ expect(localIcons).toHaveBeenCalledTimes(1);
+ hook.unmount();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_000);
+ });
+ expect(localIcons).toHaveBeenCalledTimes(1);
+ });
+
+ it('evicts unmounted image data once the shared cache exceeds its byte budget', async () => {
+ const items = Array.from({ length: 25 }, (_, index) => customItem(`icon-${index}`));
+ const payload = `data:image/png;base64,${'A'.repeat(700_000)}`;
+ localIcons.mockImplementation(async (requests: PluginMarketLocalIconRequest[]) =>
+ requests.map(
+ (request): PluginMarketLocalIconResult => ({
+ ...request,
+ status: 'loaded',
+ dataUrl: payload,
+ }),
+ ),
+ );
+
+ function Consumer({ item }: { item: PluginMarketItem }) {
+ const icon = usePluginMarketIcon(item, { deferUntilVisible: false });
+ return <span data-testid="market-icon-state">{icon.iconDataUrl ? 'loaded' : 'pending'}</span>;
+ }
+
+ const view = render(
+ <>
+ {items.map((item) => (
+ <Consumer key={item.pluginId} item={item} />
+ ))}
+ </>,
+ );
+ await waitFor(() =>
+ expect(screen.getAllByTestId('market-icon-state').every((node) => node.textContent === 'loaded')).toBe(
+ true,
+ ),
+ );
+ expect(__pluginMarketIconStoreStatsForTest().loadedDataSize).toBeGreaterThan(16 * 1024 * 1024);
+
+ view.unmount();
+ expect(__pluginMarketIconStoreStatsForTest().loadedDataSize).toBeLessThanOrEqual(
+ 16 * 1024 * 1024,
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketIcon.ts b/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketIcon.ts
new file mode 100644
index 0000000000..1ca1c439d8
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/usePluginMarketIcon.ts
@@ -0,0 +1,491 @@
+/**
+ * Custom marketplace icon loader.
+ *
+ * Main owns discovery and filesystem access. Renderer batches visible requests, keeps bytes in a
+ * bounded shared LRU, and treats customIconKey as a snapshot cache generation rather than a byte
+ * content hash. Main verifies every materialized read; a refreshed projection gets a new key.
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ */
+
+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';
+
+import type {
+ PluginMarketItem,
+ PluginMarketLocalIconRequest,
+ PluginMarketLocalIconResult,
+} from '../../../../shared/pluginMarket';
+import {
+ isPluginMarketCustomIconKey,
+ pluginMarketCustomIconSourceToken,
+} from '../../../../shared/pluginMarket';
+
+type LocalIconStatus = 'idle' | 'queued' | 'loading' | 'loaded' | 'missing' | 'retryable';
+
+interface LocalIconSnapshot {
+ status: LocalIconStatus;
+ dataUrl?: string;
+}
+
+interface LocalIconRecord {
+ request: PluginMarketLocalIconRequest;
+ snapshot: LocalIconSnapshot;
+ listeners: Set<() => void>;
+ pinCount: number;
+ lastUsed: number;
+ dataSize: number;
+ retryCount: number;
+ retryTimer: ReturnType<typeof setTimeout> | null;
+ loadAttempt: number;
+}
+
+interface LocalIconBatchEntry {
+ record: LocalIconRecord;
+ attempt: number;
+}
+
+const EMPTY_SNAPSHOT: LocalIconSnapshot = Object.freeze({ status: 'idle' });
+const BATCH_SIZE = 8;
+const RECORD_CACHE_LIMIT = 128;
+const DATA_URL_CACHE_BUDGET = 16 * 1024 * 1024;
+const LOCAL_ICON_REQUEST_TIMEOUT_MS = 10_000;
+const MAX_UNSETTLED_LOCAL_ICON_REQUESTS = 2;
+const RETRY_DELAYS_MS = [1_000, 5_000, 30_000] as const;
+const records = new Map<string, LocalIconRecord>();
+const queuedKeys = new Set<string>();
+const transportBlockedKeys = new Set<string>();
+const unsettledLocalIconRequests = new Map<object, string>();
+let flushScheduled = false;
+let flushInFlight = false;
+let pruneScheduled = false;
+let totalDataSize = 0;
+
+function requestKey(request: PluginMarketLocalIconRequest): string {
+ return `${request.pluginId}:${request.expectedIconKey}`;
+}
+
+function requestSourceKey(request: PluginMarketLocalIconRequest): string {
+ return pluginMarketCustomIconSourceToken(request.expectedIconKey) ?? request.pluginId;
+}
+
+function hasUnsettledRequestForSource(sourceKey: string): boolean {
+ for (const unsettledSourceKey of unsettledLocalIconRequests.values()) {
+ if (unsettledSourceKey === sourceKey) return true;
+ }
+ return false;
+}
+
+function recordFor(request: PluginMarketLocalIconRequest): LocalIconRecord {
+ const key = requestKey(request);
+ const existing = records.get(key);
+ if (existing) return existing;
+ const created: LocalIconRecord = {
+ request,
+ snapshot: EMPTY_SNAPSHOT,
+ listeners: new Set(),
+ pinCount: 0,
+ lastUsed: Date.now(),
+ dataSize: 0,
+ retryCount: 0,
+ retryTimer: null,
+ loadAttempt: 0,
+ };
+ records.set(key, created);
+ scheduleRecordPrune();
+ return created;
+}
+
+function canRemoveRecord(record: LocalIconRecord): boolean {
+ return (
+ record.pinCount === 0 &&
+ record.listeners.size === 0 &&
+ record.snapshot.status !== 'queued' &&
+ record.snapshot.status !== 'loading'
+ );
+}
+
+function removeRecord(record: LocalIconRecord): void {
+ if (!canRemoveRecord(record)) return;
+ if (record.retryTimer !== null) {
+ clearTimeout(record.retryTimer);
+ record.retryTimer = null;
+ }
+ queuedKeys.delete(requestKey(record.request));
+ transportBlockedKeys.delete(requestKey(record.request));
+ if (record.dataSize > 0) {
+ totalDataSize -= record.dataSize;
+ record.dataSize = 0;
+ }
+ records.delete(requestKey(record.request));
+}
+
+function pruneRecords(): void {
+ if (records.size <= RECORD_CACHE_LIMIT) return;
+ const candidates = [...records.values()]
+ .filter(canRemoveRecord)
+ .sort((a, b) => a.lastUsed - b.lastUsed);
+ for (const record of candidates) {
+ removeRecord(record);
+ if (records.size <= RECORD_CACHE_LIMIT) break;
+ }
+}
+
+function scheduleRecordPrune(): void {
+ if (pruneScheduled) return;
+ pruneScheduled = true;
+ queueMicrotask(() => {
+ pruneScheduled = false;
+ pruneRecords();
+ });
+}
+
+function publish(record: LocalIconRecord, snapshot: LocalIconSnapshot): void {
+ if (record.dataSize > 0) {
+ totalDataSize -= record.dataSize;
+ record.dataSize = 0;
+ }
+ record.snapshot = snapshot;
+ if (snapshot.status === 'loaded' && snapshot.dataUrl) {
+ record.dataSize = snapshot.dataUrl.length;
+ totalDataSize += record.dataSize;
+ }
+ record.lastUsed = Date.now();
+ for (const listener of record.listeners) listener();
+}
+
+function evictUnpinnedData(): void {
+ if (totalDataSize <= DATA_URL_CACHE_BUDGET) return;
+ const candidates = [...records.values()]
+ .filter((record) => record.pinCount === 0 && record.snapshot.status === 'loaded')
+ .sort((a, b) => a.lastUsed - b.lastUsed);
+ for (const record of candidates) {
+ publish(record, EMPTY_SNAPSHOT);
+ if (totalDataSize <= DATA_URL_CACHE_BUDGET) break;
+ }
+}
+
+function scheduleFlush(): void {
+ if (flushScheduled) return;
+ flushScheduled = true;
+ queueMicrotask(() => void flushQueue());
+}
+
+function queueRecord(record: LocalIconRecord): void {
+ if (record.snapshot.status !== 'idle' && record.snapshot.status !== 'retryable') {
+ return;
+ }
+ if (record.retryTimer !== null) return;
+ transportBlockedKeys.delete(requestKey(record.request));
+ publish(record, { status: 'queued' });
+ queuedKeys.add(requestKey(record.request));
+ scheduleFlush();
+}
+
+function scheduleRetry(record: LocalIconRecord): void {
+ if (record.pinCount === 0 || record.retryTimer !== null) return;
+ const delay = RETRY_DELAYS_MS[record.retryCount];
+ if (delay === undefined) {
+ publish(record, { status: 'missing' });
+ return;
+ }
+ record.retryCount += 1;
+ record.retryTimer = setTimeout(() => {
+ record.retryTimer = null;
+ queueRecord(record);
+ }, delay);
+}
+
+function markRetryable(record: LocalIconRecord): void {
+ publish(record, { status: 'retryable' });
+ scheduleRetry(record);
+}
+
+function parkForTransportCapacity(record: LocalIconRecord): void {
+ publish(record, { status: 'retryable' });
+ transportBlockedKeys.add(requestKey(record.request));
+}
+
+function wakeTransportBlockedRecords(): void {
+ for (const key of [...transportBlockedKeys]) {
+ const record = records.get(key);
+ transportBlockedKeys.delete(key);
+ if (record?.pinCount && record.snapshot.status === 'retryable' && record.retryTimer === null) {
+ queueRecord(record);
+ }
+ }
+ pruneRecords();
+}
+
+function localIconsWithinTimeoutFromPromise(
+ request: Promise<PluginMarketLocalIconResult[]>,
+): Promise<PluginMarketLocalIconResult[]> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('custom marketplace icon request timed out')),
+ LOCAL_ICON_REQUEST_TIMEOUT_MS,
+ );
+ });
+ // Electron invoke cannot be cancelled from Renderer. Promise.race only releases this batch;
+ // loadAttempt below prevents a late response from overwriting a retried record.
+ return Promise.race([request, timeout]).finally(() => {
+ if (timer !== undefined) clearTimeout(timer);
+ }) as Promise<PluginMarketLocalIconResult[]>;
+}
+
+function trackUnsettledLocalIconRequest(
+ request: Promise<PluginMarketLocalIconResult[]>,
+ marketKey: string,
+): void {
+ const token = {};
+ unsettledLocalIconRequests.set(token, marketKey);
+ const release = () => {
+ if (!unsettledLocalIconRequests.delete(token)) return;
+ wakeTransportBlockedRecords();
+ };
+ void request.then(
+ () => release(),
+ () => release(),
+ );
+}
+function applyResult(record: LocalIconRecord, result: PluginMarketLocalIconResult): void {
+ if (result.status === 'loaded') {
+ publish(record, { status: 'loaded', dataUrl: result.dataUrl });
+ evictUnpinnedData();
+ pruneRecords();
+ return;
+ }
+ if (result.status === 'missing') {
+ publish(record, { status: 'missing' });
+ pruneRecords();
+ return;
+ }
+ markRetryable(record);
+ pruneRecords();
+}
+
+async function flushQueue(): Promise<void> {
+ flushScheduled = false;
+ if (flushInFlight) return;
+ const batch: LocalIconBatchEntry[] = [];
+ if (unsettledLocalIconRequests.size >= MAX_UNSETTLED_LOCAL_ICON_REQUESTS) {
+ for (const key of queuedKeys) {
+ queuedKeys.delete(key);
+ const record = records.get(key);
+ if (!record || record.snapshot.status !== 'queued') continue;
+ // 这批还没有发出 IPC,不能消耗内容读取的重试预算。旧请求
+ // settle 释放槽位后会唤醒仍在可视区的记录。
+ parkForTransportCapacity(record);
+ }
+ pruneRecords();
+ return;
+ }
+ const pendingKeys = [...queuedKeys];
+ const firstPendingRecord = pendingKeys
+ .map((key) => records.get(key))
+ .find(
+ (record): record is LocalIconRecord =>
+ record?.snapshot.status === 'queued' &&
+ !hasUnsettledRequestForSource(requestSourceKey(record.request)),
+ );
+ if (!firstPendingRecord) {
+ for (const key of pendingKeys) {
+ queuedKeys.delete(key);
+ const record = records.get(key);
+ if (record?.snapshot.status === 'queued') parkForTransportCapacity(record);
+ }
+ pruneRecords();
+ return;
+ }
+ const batchSource = requestSourceKey(firstPendingRecord.request);
+ for (const key of pendingKeys) {
+ queuedKeys.delete(key);
+ const record = records.get(key);
+ if (!record || record.snapshot.status !== 'queued') continue;
+ if (requestSourceKey(record.request) !== batchSource) {
+ queuedKeys.add(key);
+ continue;
+ }
+ publish(record, { status: 'loading' });
+ batch.push({ record, attempt: (record.loadAttempt += 1) });
+ if (batch.length === BATCH_SIZE) break;
+ }
+ if (batch.length === 0) return;
+
+ let ipcRequest: Promise<PluginMarketLocalIconResult[]>;
+ try {
+ ipcRequest = window.electronAPI.pluginMarket.localIcons(
+ batch.map(({ record }) => record.request),
+ );
+ } catch {
+ for (const { record, attempt } of batch) {
+ if (record.loadAttempt === attempt) markRetryable(record);
+ }
+ if (queuedKeys.size > 0) scheduleFlush();
+ return;
+ }
+
+ // Raw Electron invoke 是不可取消的 transport 资源:全局最多 2 个,且同一不透明
+ // 来源身份最多占 1 个槽;同名但不同来源不会被旧请求误阻塞。
+ trackUnsettledLocalIconRequest(ipcRequest, batchSource);
+ flushInFlight = true;
+ try {
+ const results = await localIconsWithinTimeoutFromPromise(ipcRequest);
+ const byKey = new Map(results.map((result) => [requestKey(result), result]));
+ for (const { record, attempt } of batch) {
+ if (record.loadAttempt !== attempt) continue;
+ const result = byKey.get(requestKey(record.request));
+ if (result) applyResult(record, result);
+ else markRetryable(record);
+ }
+ } catch {
+ for (const { record, attempt } of batch) {
+ if (record.loadAttempt === attempt) markRetryable(record);
+ }
+ } finally {
+ // Timeout 只释放逻辑批次(flushInFlight),不会释放不可取消 raw invoke 的 transport
+ // 槽位;后者必须等真实 settle,才能维持“底层未完成请求严格 <= 2”的硬上界。
+ // 迟到结果由 loadAttempt 隔离,不能覆盖新尝试。
+ flushInFlight = false;
+ pruneRecords();
+ if (queuedKeys.size > 0) scheduleFlush();
+ }
+}
+
+function subscribe(request: PluginMarketLocalIconRequest | null, listener: () => void): () => void {
+ if (!request) return () => undefined;
+ const record = recordFor(request);
+ record.listeners.add(listener);
+ return () => {
+ record.listeners.delete(listener);
+ pruneRecords();
+ };
+}
+
+function snapshot(request: PluginMarketLocalIconRequest | null): LocalIconSnapshot {
+ return request ? recordFor(request).snapshot : EMPTY_SNAPSHOT;
+}
+
+function pin(request: PluginMarketLocalIconRequest): () => void {
+ const record = recordFor(request);
+ record.pinCount += 1;
+ record.lastUsed = Date.now();
+ queueRecord(record);
+ return () => {
+ record.pinCount = Math.max(0, record.pinCount - 1);
+ if (record.pinCount === 0 && record.retryTimer !== null) {
+ clearTimeout(record.retryTimer);
+ record.retryTimer = null;
+ }
+ evictUnpinnedData();
+ pruneRecords();
+ };
+}
+
+function reportDecodeFailure(request: PluginMarketLocalIconRequest): void {
+ const record = recordFor(request);
+ markRetryable(record);
+}
+
+function reportDecodeSuccess(request: PluginMarketLocalIconRequest): void {
+ const record = recordFor(request);
+ record.retryCount = 0;
+}
+
+export function usePluginMarketIcon(
+ item: Pick<PluginMarketItem, 'pluginId' | 'icon' | 'customIconKey' | 'sourceType'>,
+ { deferUntilVisible }: { deferUntilVisible: boolean },
+) {
+ const request = useMemo<PluginMarketLocalIconRequest | null>(
+ () =>
+ item.sourceType !== 'server' &&
+ item.customIconKey &&
+ isPluginMarketCustomIconKey(item.customIconKey)
+ ? { pluginId: item.pluginId, expectedIconKey: item.customIconKey }
+ : null,
+ [item.customIconKey, item.pluginId, item.sourceType],
+ );
+ const [target, setTarget] = useState<HTMLElement | null>(null);
+ const [nearViewport, setNearViewport] = useState(
+ () => !deferUntilVisible || typeof IntersectionObserver === 'undefined',
+ );
+
+ useEffect(() => {
+ if (!request || !deferUntilVisible) {
+ setNearViewport(true);
+ return;
+ }
+ if (!target || typeof IntersectionObserver === 'undefined') {
+ setNearViewport(typeof IntersectionObserver === 'undefined');
+ return;
+ }
+ setNearViewport(false);
+ const observer = new IntersectionObserver(
+ (entries) => setNearViewport(entries.some((entry) => entry.isIntersecting)),
+ { rootMargin: '240px' },
+ );
+ observer.observe(target);
+ return () => observer.disconnect();
+ }, [deferUntilVisible, request, target]);
+
+ const subscribeToRequest = useCallback(
+ (listener: () => void) => subscribe(request, listener),
+ [request],
+ );
+ const getSnapshot = useCallback(() => snapshot(request), [request]);
+ const current = useSyncExternalStore(subscribeToRequest, getSnapshot, getSnapshot);
+
+ useEffect(() => {
+ if (!request || !nearViewport) return;
+ return pin(request);
+ }, [nearViewport, request]);
+
+ const onIconLoadError = useCallback(
+ (fallback?: () => void) => {
+ if (request) reportDecodeFailure(request);
+ else fallback?.();
+ },
+ [request],
+ );
+ const onIconLoad = useCallback(() => {
+ if (request) reportDecodeSuccess(request);
+ }, [request]);
+
+ return {
+ containerRef: setTarget,
+ iconDataUrl:
+ request && current.status === 'loaded'
+ ? current.dataUrl
+ : request
+ ? undefined
+ : item.icon?.url,
+ onIconLoad,
+ onIconLoadError,
+ };
+}
+
+export function __resetPluginMarketIconStoreForTest(): void {
+ for (const record of records.values()) {
+ if (record.retryTimer !== null) clearTimeout(record.retryTimer);
+ }
+ records.clear();
+ queuedKeys.clear();
+ transportBlockedKeys.clear();
+ unsettledLocalIconRequests.clear();
+
+ flushScheduled = false;
+ flushInFlight = false;
+ pruneScheduled = false;
+ totalDataSize = 0;
+}
+
+export function __pluginMarketIconStoreStatsForTest(): {
+ records: number;
+ loadedDataSize: number;
+ unsettledRequests: number;
+} {
+ return {
+ records: records.size,
+ loadedDataSize: totalDataSize,
+ unsettledRequests: unsettledLocalIconRequests.size,
+ };
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index bf42020f82..c772c3d0d7 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1503,6 +1503,9 @@ interface ElectronAPI {
pluginMarket: {
snapshot: () => Promise<import('../shared/pluginMarket').PluginMarketSnapshot>;
detail: (pluginId: string) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;
+ localIcons: (
+ requests: import('../shared/pluginMarket').PluginMarketLocalIconRequest[],
+ ) => Promise<import('../shared/pluginMarket').PluginMarketLocalIconResult[]>;
install: (
pluginId: string,
options: import('../shared/pluginMarket').PluginMarketInstallOptions,
diff --git a/apps/desktop/src/shared/__tests__/pluginMarket.test.ts b/apps/desktop/src/shared/__tests__/pluginMarket.test.ts
new file mode 100644
index 0000000000..dc4e8c2524
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/pluginMarket.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ isPluginMarketCustomIconKey,
+ pluginMarketCustomIconProjectionToken,
+ pluginMarketCustomIconSourceToken,
+} from '../pluginMarket';
+
+describe('Plugin Market shared contract', () => {
+ it('accepts generated custom icon keys and reserves a leading zero', () => {
+ expect(isPluginMarketCustomIconKey(`1${'0'.repeat(63)}`)).toBe(true);
+ expect(isPluginMarketCustomIconKey(`a${'f'.repeat(63)}`)).toBe(true);
+ expect(isPluginMarketCustomIconKey('0'.repeat(64))).toBe(false);
+ expect(isPluginMarketCustomIconKey('A'.repeat(64))).toBe(false);
+ expect(isPluginMarketCustomIconKey('a'.repeat(63))).toBe(false);
+ expect(isPluginMarketCustomIconKey('a'.repeat(65))).toBe(false);
+ });
+
+ it('extracts opaque source and projection tokens from the stable key layout', () => {
+ const key = `2${'a'.repeat(16)}${'b'.repeat(16)}${'c'.repeat(31)}`;
+ expect(pluginMarketCustomIconSourceToken(key)).toBe('a'.repeat(16));
+ expect(pluginMarketCustomIconProjectionToken(key)).toBe('b'.repeat(16));
+ expect(pluginMarketCustomIconSourceToken('0'.repeat(64))).toBeNull();
+ expect(pluginMarketCustomIconProjectionToken('invalid')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.ts
index e6ec89e3a6..7b87fcf46f 100644
--- a/apps/desktop/src/shared/pluginMarket.ts
+++ b/apps/desktop/src/shared/pluginMarket.ts
@@ -25,6 +25,12 @@ export interface PluginMarketItem {
version: string;
publishedAt: string;
icon: PluginIconMetadata | null;
+ /**
+ * 自定义市场图标的本地身份键。它是 Main 根据当前来源事实计算的本地投影身份,
+ * 不包含本地路径或字节;读取失败或事实不确定时也可能携带该键并由 localIcons
+ * 返回 missing/retryable。服务端市场与未声明 icon 的自定义插件不携带。
+ */
+ customIconKey?: string;
installState: PluginMarketInstallState;
enabled: boolean | null;
/** 来源类型;服务端市场项为 'server'。 */
@@ -68,6 +74,39 @@ export interface PluginMarketDetail extends PluginMarketItem {
manifest: GhostManifest;
}
+/** Main 生成并接受的自定义市场图标身份键形状;首位 0 为保留值。 */
+export const PLUGIN_MARKET_CUSTOM_ICON_KEY_RE = /^[1-9a-f][a-f0-9]{63}$/;
+export const PLUGIN_MARKET_CUSTOM_ICON_SOURCE_TOKEN_LENGTH = 16;
+export const PLUGIN_MARKET_CUSTOM_ICON_PROJECTION_TOKEN_LENGTH = 16;
+
+export function isPluginMarketCustomIconKey(value: string): boolean {
+ return PLUGIN_MARKET_CUSTOM_ICON_KEY_RE.test(value);
+}
+
+/** Renderer 只用这个不透明 token 做同来源传输限流,不解析 Main 侧身份事实。 */
+export function pluginMarketCustomIconSourceToken(value: string): string | null {
+ if (!isPluginMarketCustomIconKey(value)) return null;
+ return value.slice(1, 1 + PLUGIN_MARKET_CUSTOM_ICON_SOURCE_TOKEN_LENGTH);
+}
+
+/** Main 从图标键恢复快照投影代际,用于读取时重算并核对完整键。 */
+export function pluginMarketCustomIconProjectionToken(value: string): string | null {
+ if (!isPluginMarketCustomIconKey(value)) return null;
+ const start = 1 + PLUGIN_MARKET_CUSTOM_ICON_SOURCE_TOKEN_LENGTH;
+ return value.slice(start, start + PLUGIN_MARKET_CUSTOM_ICON_PROJECTION_TOKEN_LENGTH);
+}
+
+/** Renderer 请求 Main 按当前自定义市场事实读取一个本地图标。 */
+export interface PluginMarketLocalIconRequest {
+ pluginId: string;
+ expectedIconKey: string;
+}
+
+/** Main 的批量图标读取结果;请求身份原样带回,供 Renderer 安全归并。 */
+export type PluginMarketLocalIconResult =
+ | (PluginMarketLocalIconRequest & { status: 'loaded'; dataUrl: string })
+ | (PluginMarketLocalIconRequest & { status: 'missing' | 'retryable' });
+
/** Main 从已验证真实包中提取的权限复核事实。 */
export interface PluginMarketPackageReviewFacts {
/** 已按当前界面语言本地化,仅用于展示;安全指纹由 Main 基于原始清单计算。 */