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(skillhub): 统一详情页并支持作者发布更新与市场一键更新 (#4749)

boboed4bef88b48d
diff --git a/apps/desktop/src/main/skillhub/__tests__/fixtures/published-content.json b/apps/desktop/src/main/skillhub/__tests__/fixtures/published-content.json
new file mode 100644
index 0000000000..97c0a51429
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/fixtures/published-content.json
@@ -0,0 +1,26 @@
+[
+ {
+ "path": "SKILL.md",
+ "size": 79,
+ "sha256": "25ff5356351bcb9fec49c3f417e93dee6176eb5baa69ddf64d667d1370ef89db",
+ "base64": "LS0tCm5hbWU6IGdvbGRlbi1za2lsbApkZXNjcmlwdGlvbjogR29sZGVuIGZpeHR1cmUKdmVyc2lvbjogMS4wLjAKLS0tCiMg56S65L6LCg=="
+ },
+ {
+ "path": "scripts/run.py",
+ "size": 15,
+ "sha256": "b80792336156c7b0f7fe02eeef24610d2d52a10d1810397744471d1dc5738180",
+ "base64": "cHJpbnQoImhlbGxvIikK"
+ },
+ {
+ "path": "assets/icon.bin",
+ "size": 5,
+ "sha256": "6d1dc71fb8c1d9f7786ddddd833d3f60835dd60e3b86b652e4458f780c6532f6",
+ "base64": "AP8BgAo="
+ },
+ {
+ "path": "empty.txt",
+ "size": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "base64": ""
+ }
+]
diff --git a/apps/desktop/src/main/skillhub/__tests__/infoMapping.test.ts b/apps/desktop/src/main/skillhub/__tests__/infoMapping.test.ts
index 60162673d5..81973271ba 100644
--- a/apps/desktop/src/main/skillhub/__tests__/infoMapping.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/infoMapping.test.ts
@@ -133,7 +133,7 @@ describe('mapHubSkillInfoToDesktopInfo', () => {
});
});
- it('maps Hub fileHash to folderHash when provided', () => {
+ it('does not confuse archive bytes with a local folder digest', () => {
const info = mapHubSkillInfoToDesktopInfo({
slug: 'review-helper',
displayName: 'Review Helper',
@@ -147,6 +147,6 @@ describe('mapHubSkillInfoToDesktopInfo', () => {
categories: [],
});
- expect(info.folderHash).toBe('server-folder-hash');
+ expect(info.folderHash).toBeUndefined();
});
});
diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
index 2531a8d530..f71e322f87 100644
--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
@@ -578,6 +578,35 @@ describe('skillhub/installService', () => {
expect(shell.trashItem).toHaveBeenCalledOnce();
});
+ it.each([
+ { scope: undefined, origin: 'published', expectedOrigin: 'published' },
+ { scope: 'market', origin: 'published', expectedOrigin: 'installed' },
+ { scope: undefined, origin: 'installed', expectedOrigin: 'installed' },
+ ] as const)('preserves publication provenance only when updating the same catalog ($scope/$origin)', async ({ scope, origin, expectedOrigin }) => {
+ const name = 'google-play-console';
+ const finalDir = path.join(TEST_ROOT, 'skills', name);
+ fs.mkdirSync(finalDir, { recursive: true });
+ fs.writeFileSync(path.join(finalDir, 'SKILL.md'), 'old content');
+ const zipBuf = await makeZip({ 'SKILL.md': 'new content' });
+ await setupInstallDownload(name, zipBuf);
+ const { registryService } = await import('../registry');
+ const { serverApiFetch } = await import('../../serverApiClient');
+ const fetch = vi.mocked(serverApiFetch).getMockImplementation()!;
+ vi.mocked(serverApiFetch).mockImplementation(async (url, options) => url.includes('/batch-detail')
+ ? { items: [{ slug: name, owner: { slug: 'org-owner' }, isMine: true }] }
+ : fetch(url, options));
+ vi.mocked(registryService.getInstall).mockResolvedValue({
+ version: '1.0.0', origin, authorId: 'org-owner', folderHash: 'old-hash', installedAt: 1, updatedAt: 1,
+ });
+ const { install } = await import('../installService');
+ expect(await install({ name, installPath: finalDir, version: '1.0.1', catalogScope: scope, force: true, skipBackup: false }, () => {}))
+ .toMatchObject({ success: true, version: '1.0.1' });
+ expect(registryService.addInstall).toHaveBeenCalledWith(name, finalDir, expect.objectContaining({
+ version: '1.0.1', origin: expectedOrigin, authorId: 'org-owner', ...(scope ? { catalogScope: scope } : {}),
+ }));
+ expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf8')).toBe('new content');
+ });
+
it('keeps the previous install intact when extraction fails during forced update', async () => {
const finalDir = path.join(TEST_ROOT, 'skills', 'broken-skill');
fs.mkdirSync(finalDir, { recursive: true });
diff --git a/apps/desktop/src/main/skillhub/__tests__/publishedComparison.test.ts b/apps/desktop/src/main/skillhub/__tests__/publishedComparison.test.ts
new file mode 100644
index 0000000000..a99762fbfb
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/publishedComparison.test.ts
@@ -0,0 +1,234 @@
+import { createHash } from 'node:crypto';
+import nodeFs from 'node:fs';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { Readable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fixture from './fixtures/published-content.json';
+import { comparePublishedSkill, localComparisonFiles, publishedManifest } from '../publishedComparison';
+import type { SkillhubMarketService } from '../marketService';
+import type { Skill } from '../scanner';
+import { pack } from '../zipPacker';
+
+vi.mock('../../logger', () => ({ createLogger: () => ({ info: vi.fn() }) }));
+
+let root: string;
+let skill: Pick<Skill, 'name' | 'absolutePath' | 'registryEntry' | 'registrySkillName'>;
+const info = { isCreator: true, canManage: true, authorId: 'owner', ownerType: 'personal', latestVersion: '1.0.0' };
+const market = {
+ info: vi.fn(),
+ getPublishedFiles: vi.fn(),
+ readPublishedFile: vi.fn(),
+};
+const compare = (diff = false) => comparePublishedSkill(skill, market as unknown as SkillhubMarketService, diff);
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'skill-compare-'));
+ for (const file of fixture) {
+ await fs.mkdir(path.dirname(path.join(root, file.path)), { recursive: true });
+ await fs.writeFile(path.join(root, file.path), Buffer.from(file.base64, 'base64'));
+ }
+ skill = { name: 'golden-skill', absolutePath: root, registryEntry: null };
+ market.info.mockReset().mockResolvedValue({ success: true, info });
+ market.getPublishedFiles.mockReset().mockResolvedValue({ version: '1.0.0', files: fixture });
+ market.readPublishedFile.mockReset().mockImplementation(async ({ path: name }) => ({
+ file: { content: Buffer.from(fixture.find((file) => file.path === name)!.base64, 'base64').toString('utf8'), truncated: false },
+ }));
+});
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+describe('published content comparison', () => {
+ it('matches the server golden bytes, including binary and empty files, without a registry snapshot', async () => {
+ const local = await localComparisonFiles(root, false);
+ const { manifest } = await pack(root);
+ expect(manifest.files.map(({ relPath, ...file }) => ({ path: relPath, ...file })))
+ .toEqual([...local].sort((a, b) => a.path.localeCompare(b.path)));
+ expect(local.sort((a, b) => a.path.localeCompare(b.path))).toEqual(
+ fixture.map(({ path, size, sha256 }) => ({ path, size, sha256 })).sort((a, b) => a.path.localeCompare(b.path)),
+ );
+ expect(await compare()).toEqual({ status: 'same', version: '1.0.0', pending: false });
+ expect(market.getPublishedFiles).toHaveBeenCalledWith({ name: 'golden-skill', version: '1.0.0', includeHashes: true });
+ });
+
+ it.each(['unchanged', 'modified', 'unknown'] as const)('distinguishes %s local content from a newer remote release', async (localChanges) => {
+ skill.registryEntry = { version: '1.0.0' } as Skill['registryEntry'];
+ market.info.mockResolvedValue({ info: { ...info, latestVersion: '2.0.0' } });
+ const newer = fixture.map((file) => file.path === 'SKILL.md' ? { ...file, sha256: 'a'.repeat(64) } : file);
+ market.getPublishedFiles.mockImplementation(async ({ version }) => {
+ if (version === '1.0.0' && localChanges === 'unknown') throw new Error('Historical manifest unavailable');
+ return { version, files: version === '2.0.0' ? newer : fixture };
+ });
+ if (localChanges === 'modified') await fs.writeFile(path.join(root, 'scripts/run.py'), 'local edit');
+ expect(await compare()).toMatchObject({ status: 'different', version: '2.0.0', localChanges });
+ expect(market.getPublishedFiles).toHaveBeenCalledWith({ name: 'golden-skill', version: '1.0.0', includeHashes: true });
+ });
+
+ it.each(['learned', 'imported'] as const)('does not assume %s version numbers identify a downloaded baseline', async (origin) => {
+ skill.registryEntry = { version: '0.1.0', origin } as Skill['registryEntry'];
+ await fs.writeFile(path.join(root, 'scripts/run.py'), 'locally authored');
+ expect(await compare()).toEqual({ status: 'different', version: '1.0.0', pending: false });
+ expect(market.getPublishedFiles).toHaveBeenCalledTimes(1);
+ });
+
+ it('counts version-only edits and compares with the remote text', async () => {
+ const original = Buffer.from(fixture[0].base64, 'base64').toString('utf8');
+ await fs.writeFile(path.join(root, 'SKILL.md'), original.replace('1.0.0', '1.0.1'));
+ expect(await compare(true)).toMatchObject({ status: 'different', changes: [{
+ path: 'SKILL.md', kind: 'modified', isBinary: false, oldContent: original, newContent: original.replace('1.0.0', '1.0.1'),
+ }] });
+ });
+
+ it('detects added scripts, removed files and changed binary bytes', async () => {
+ await fs.writeFile(path.join(root, 'scripts/new.py'), 'new');
+ await fs.unlink(path.join(root, 'empty.txt'));
+ await fs.writeFile(path.join(root, 'assets/icon.bin'), Buffer.from([0, 1]));
+ const result = await compare(true);
+ expect(result).toMatchObject({ status: 'different', changes: [
+ { path: 'assets/icon.bin', kind: 'modified', isBinary: true, oldSize: 5, newSize: 2 },
+ { path: 'empty.txt', kind: 'removed' },
+ { path: 'scripts/new.py', kind: 'added', newContent: 'new' },
+ ] });
+ });
+
+ it.each(['pending', 'scanning', 'machine_reviewing', 'manual_reviewing', 'quarantine', 'warning', 'warn', ' MANUAL_REVIEWING ', undefined])(
+ 'uses the submitted version during review (%s)', async (status) => {
+ market.info.mockResolvedValue({ info: { ...info, moderationStatus: 'published', pendingVersion: { version: '1.1.0', status } } });
+ market.getPublishedFiles.mockResolvedValue({ version: '1.1.0', files: fixture });
+ expect(await compare()).toEqual({ status: 'same', version: '1.1.0', pending: true });
+ await fs.writeFile(path.join(root, 'scripts/run.py'), 'changed again');
+ expect(await compare(true)).toMatchObject({ status: 'different', version: '1.1.0', pending: true });
+ expect(market.readPublishedFile).toHaveBeenCalledWith({ name: 'golden-skill', version: '1.1.0', path: 'scripts/run.py' });
+ });
+
+ it.each(['pending', 'scanning', 'machine_reviewing', 'manual_reviewing', 'quarantine', 'warning', 'warn'])(
+ 'recognizes a first publication under review (%s)', async (moderationStatus) => {
+ market.info.mockResolvedValue({ info: { ...info, moderationStatus } });
+ expect(await compare()).toEqual({ status: 'same', version: '1.0.0', pending: true });
+ });
+
+ it.each(['rejected', 'failed', 'blocked'])('compares with the published version after rejection (%s)', async (status) => {
+ market.info.mockResolvedValue({ info: { ...info, moderationStatus: 'published', pendingVersion: { version: '1.1.0', status } } });
+ expect(await compare()).toEqual({ status: 'same', version: '1.0.0', pending: false });
+ });
+
+ it.each([false, undefined])('does not infer authorship from management rights (%s)', async (isCreator) => {
+ market.info.mockResolvedValue({ info: { ...info, isCreator } });
+ expect(await compare()).toEqual({ status: isCreator === false ? 'not-owner' : 'unavailable' });
+ expect(market.getPublishedFiles).not.toHaveBeenCalled();
+ });
+
+ it('does not cross catalog identities with the same slug', async () => {
+ skill.registryEntry = { catalogScope: 'team' } as Skill['registryEntry'];
+ market.info.mockResolvedValueOnce({ info }).mockResolvedValueOnce({ info: { ...info, authorId: 'different-owner' } });
+ expect(await compare()).toEqual({ status: 'not-owner' });
+ expect(market.getPublishedFiles).not.toHaveBeenCalled();
+ });
+
+ it('fails rather than treating a missing digest, changing version, or unreadable tree as clean', async () => {
+ market.getPublishedFiles.mockResolvedValueOnce({ version: '1.0.0', files: fixture.map(({ sha256, ...file }) => file) });
+ await expect(compare()).rejects.toThrow('Missing file digest');
+ market.getPublishedFiles.mockResolvedValueOnce({ version: '2.0.0', files: fixture });
+ await expect(compare()).rejects.toThrow('Published version changed');
+ await fs.rename(root, root + '-moved');
+ try { await expect(compare()).rejects.toThrow(); }
+ finally { await fs.rename(root + '-moved', root); }
+ });
+
+ it('skips packaging exclusions and symlinks without reading their targets', async () => {
+ await fs.mkdir(path.join(root, '.git'));
+ await fs.writeFile(path.join(root, '.git/config'), 'ignore');
+ await fs.writeFile(path.join(root, '.DS_Store'), 'ignore');
+ await fs.symlink(os.tmpdir(), path.join(root, 'external'), process.platform === 'win32' ? 'junction' : 'dir');
+ expect(await compare()).toMatchObject({ status: 'same' });
+ });
+
+ it('accepts 2,000 packaged files with directories and symlinks, but rejects an extra file', async () => {
+ // Exercise both production walkers at the real quota without thousands of
+ // disk operations competing with other unit workers. The golden test above
+ // verifies the same pack/compare contract against real filesystem handles.
+ const files = new Map<string, Buffer>([
+ [path.join(root, 'SKILL.md'), Buffer.from(fixture[0].base64, 'base64')],
+ ...Array.from({ length: 1_999 }, (_, index): [string, Buffer] =>
+ [path.join(root, 'nested', `${index}.txt`), Buffer.from('content')]),
+ ]);
+ const entry = (name: string, kind: 'file' | 'dir' | 'link') => ({
+ name, isFile: () => kind === 'file', isDirectory: () => kind === 'dir',
+ });
+ const directories = new Map([
+ [root, [entry('SKILL.md', 'file'), entry('nested', 'dir'), entry('external', 'link')]],
+ [path.join(root, 'nested'), [entry('empty', 'dir'),
+ ...Array.from({ length: 1_999 }, (_, index) => entry(`${index}.txt`, 'file'))]],
+ [path.join(root, 'nested', 'empty'), []],
+ ]);
+ const stat = (file: string) => ({
+ ino: 1, dev: 1, mtimeMs: 1, ctimeMs: 1,
+ size: files.get(file)?.length ?? 0, isFile: () => files.has(file),
+ });
+ const bytes = (file: string) => {
+ const content = files.get(file);
+ if (!content) throw new Error(`Unexpected file read: ${file}`);
+ return content;
+ };
+ vi.spyOn(fs, 'realpath').mockImplementation(async (file) => String(file));
+ vi.spyOn(fs, 'readdir').mockImplementation(async (dir) => {
+ const entries = directories.get(String(dir));
+ if (!entries) throw new Error(`Unexpected directory read: ${dir}`);
+ return entries as never;
+ });
+ vi.spyOn(fs, 'stat').mockImplementation(async (file) => stat(String(file)) as never);
+ vi.spyOn(fs, 'readFile').mockImplementation(async (file) => Buffer.from(bytes(String(file))));
+ vi.spyOn(fs, 'open').mockImplementation(async (file) => ({
+ stat: async () => stat(String(file)),
+ createReadStream: () => Readable.from([bytes(String(file))]),
+ close: async () => {},
+ }) as Awaited<ReturnType<typeof fs.open>>);
+ vi.spyOn(nodeFs, 'createReadStream').mockImplementation((file) =>
+ Readable.from([bytes(String(file))]) as ReturnType<typeof nodeFs.createReadStream>);
+ const { manifest } = await pack(root);
+ expect(manifest.files).toHaveLength(2_000);
+ market.getPublishedFiles.mockResolvedValue({
+ version: '1.0.0', files: manifest.files.map(({ relPath, ...file }) => ({ path: relPath, ...file })),
+ });
+ expect(await compare()).toEqual({ status: 'same', version: '1.0.0', pending: false });
+ files.set(path.join(root, 'extra.txt'), Buffer.from('one too many'));
+ directories.get(root)!.push(entry('extra.txt', 'file'));
+ await expect(compare()).rejects.toThrow('Skill exceeds comparison limit');
+ });
+
+ it('shows summaries for truncated or unverifiable remote text', async () => {
+ await fs.writeFile(path.join(root, 'scripts/run.py'), 'new');
+ market.readPublishedFile.mockResolvedValue({ file: { content: 'wrong', truncated: false } });
+ expect(await compare(true)).toMatchObject({ changes: [{ path: 'scripts/run.py', isBinary: true, oldContent: '', newContent: '' }] });
+ market.readPublishedFile.mockResolvedValue({ file: { content: 'print("hello")\n', truncated: true } });
+ expect(await compare(true)).toMatchObject({ changes: [{ isBinary: true }] });
+ });
+
+ it('never downloads large files just to preview them', async () => {
+ const content = Buffer.alloc(2 * 1024 * 1024, 'a');
+ const sha256 = createHash('sha256').update(content).digest('hex');
+ market.getPublishedFiles.mockResolvedValue({ version: '1.0.0', files: [...fixture, { path: 'large.txt', size: content.length, sha256 }] });
+ expect(await compare(true)).toMatchObject({ changes: [{ path: 'large.txt', kind: 'removed', isBinary: true }] });
+ expect(market.readPublishedFile).not.toHaveBeenCalled();
+ });
+
+ it.each(['../escape', '/etc/passwd', 'C:/secret', 'a//b', 'a/./b', 'a\\b'])('rejects invalid remote paths: %s', (name) => {
+ expect(() => publishedManifest([...fixture, { ...fixture[0], path: name }])).toThrow('Invalid published path');
+ });
+ it('applies the file limit after package exclusions, while enforcing the retained limit', () => {
+ const ignored = Array.from({ length: 2_100 }, (_, i) => ({ path: `node_modules/package/${i}.js` }));
+ const retained = [fixture[0], ...Array.from({ length: 1_999 }, (_, i) => ({ ...fixture[0], path: `scripts/${i}.js` }))];
+ expect(publishedManifest([...ignored, ...retained])).toHaveLength(2_000);
+ expect(() => publishedManifest([...ignored, ...retained, { ...fixture[0], path: 'extra.js' }]))
+ .toThrow('Skill exceeds comparison limit');
+ expect(() => publishedManifest([...ignored, ...retained, { path: 'node_modules/../escape' }]))
+ .toThrow('Invalid published path');
+ });
+
+ it('rejects duplicated and incomplete remote manifests', () => {
+ expect(() => publishedManifest([...fixture, fixture[0]])).toThrow('Invalid published path');
+ expect(() => publishedManifest(fixture.slice(1))).toThrow('Missing Skill manifest');
+ });
+});
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 383a0b65c3..b6e5cb9770 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -17,6 +17,8 @@ vi.mock('../activationPreferences', () => ({
}));
const handlers = new Map<string, (...args: unknown[]) => unknown>();
+const comparePublishedSkill = vi.fn();
+vi.mock('../publishedComparison', () => ({ comparePublishedSkill }));
const showOpenDialog = vi.fn();
const showMessageBox = vi.fn();
vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
@@ -158,6 +160,7 @@ describe('registerSkillhubIpc usage handlers', () => {
isCindyLearnSkillEnabled.mockReturnValue(true);
handlers.clear();
vi.clearAllMocks();
+ comparePublishedSkill.mockReset().mockResolvedValue({ status: 'same', version: '1.0.0', pending: false });
renameLocalSkill.mockReset();
getManagedSkillRoots.mockReturnValue([]);
getCurrentDataOwnerId.mockReturnValue('local-v1');
@@ -189,6 +192,48 @@ describe('registerSkillhubIpc usage handlers', () => {
});
});
+ it.each(['unchanged', 'generation', 'revoked', 'failure', '429', '503', 'network', '404'] as const)(
+ 'binds publication comparison to the scanned local identity and original account: %s', async (transition) => {
+ const sender = { id: 75, on: vi.fn(), once: vi.fn() };
+ const source = fs.mkdtempSync(path.join(fixtureRoot, 'compare-'));
+ const absolutePath = fs.realpathSync.native(source);
+ getAllowedProjectRoots.mockResolvedValue([source]);
+ const scannedSkill = {
+ id: 'demo', kind: 'skill', name: 'local-name', registrySkillName: 'registered-slug',
+ absolutePath, discoveredPath: source,
+ scope: 'project', projectRoot: source,
+ };
+ scanAllSkills.mockResolvedValueOnce({ skills: [scannedSkill], sources: [] });
+ await handlers.get('skillhub:scan')!({ sender }, { projects: [] });
+ const params = { absolutePath, skillId: 'demo', includeDiff: true };
+ await expect(handlers.get('skillhub:compare-published')!({ sender: { id: 76 } }, params))
+ .rejects.toThrow('Refresh the Skill list');
+ await expect(handlers.get('skillhub:compare-published')!({ sender }, { ...params, skillId: 'other' }))
+ .rejects.toThrow('Refresh the Skill list');
+ expect(comparePublishedSkill).not.toHaveBeenCalled();
+ comparePublishedSkill.mockImplementationOnce(async () => {
+ if (transition === 'generation') ownerState.generation++;
+ if (transition === 'revoked') getAllowedProjectRoots.mockResolvedValueOnce([]);
+ if (transition === 'failure') throw new Error('unreadable local directory');
+ if (['429', '503', 'network', '404'].includes(transition)) {
+ const { ServerApiError } = await import('../../serverApiClient');
+ throw new ServerApiError('TEST_ERROR', transition === 'network' ? 0 : Number(transition), 'remote failure');
+ }
+ return { status: 'different', version: '1.0.0', pending: false, changes: [{ oldContent: 'private content' }] };
+ });
+ const response = await Promise.resolve(handlers.get('skillhub:compare-published')!({ sender }, params))
+ .catch((error) => ({ error }));
+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledWith({ sender });
+ expect(comparePublishedSkill).toHaveBeenCalledWith(scannedSkill, marketService, true);
+ if (transition === 'unchanged') expect(response).toMatchObject({ status: 'different' });
+ else {
+ if (transition === 'generation' || transition === 'revoked') expect(response).toMatchObject({ error: expect.any(Error) });
+ else expect(response).toEqual({ status: 'unavailable', ...(['429', '503', 'network'].includes(transition) ? { reason: 'service' } : {}) });
+ expect(JSON.stringify(response)).not.toContain('private content');
+ }
+ },
+ );
+
it('delivers private publication feedback only to currently trusted app windows', async () => {
const { BrowserWindow } = await import('electron');
const { registerSkillhubIpc } = await import('../registerIpc');
diff --git a/apps/desktop/src/main/skillhub/infoMapping.ts b/apps/desktop/src/main/skillhub/infoMapping.ts
index be6620711a..8db30227aa 100644
--- a/apps/desktop/src/main/skillhub/infoMapping.ts
+++ b/apps/desktop/src/main/skillhub/infoMapping.ts
@@ -25,6 +25,7 @@ export interface HubSkillInfoForDesktop {
moderationStatus?: string;
updatedAt: string;
isMine?: boolean;
+ isCreator?: boolean;
canManage?: boolean;
categories?: Array<{ slug: string; name: string; source?: 'platform' }>;
tags?: Array<{ slug: string; name: string; source?: 'platform' }>;
@@ -51,8 +52,9 @@ export function mapHubSkillInfoToDesktopInfo(hub: HubSkillInfoForDesktop, opts?:
authorAvatarUrl: null as string | null,
isMine: opts?.forceMine === true || hub.isMine === true,
canManage: hub.canManage === true,
+ isCreator: hub.isCreator,
latestVersion: hub.version,
- folderHash: hub.folderHash ?? hub.fileHash,
+ folderHash: hub.folderHash, // fileHash is the ZIP checksum, never a directory digest.
visibility: (hub.visibility === 'public' ? 'PUBLIC' : 'DEPARTMENT_SCOPED') as 'PUBLIC' | 'DEPARTMENT_SCOPED',
publishedVisibility: (hub.visibility === 'private' || hub.visibility === 'shared' || hub.visibility === 'public'
? hub.visibility
diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.ts
index cf3eae241f..29ea4f35ea 100644
--- a/apps/desktop/src/main/skillhub/installService.ts
+++ b/apps/desktop/src/main/skillhub/installService.ts
@@ -744,8 +744,7 @@ export async function install(
}
// 拉 hub 元数据 — 落盘 authorId 给渲染层兜底用(离线 fallback)。
- // isMine=true 时存当前 userId(与 renderer 的 currentUserId 同命名空间),
- // 否则存 slug(不会与 currentUserId 匹配 → 正确识别为 foreign)。
+ // 与 info / batch sync 使用同一 owner slug,组织归属不能换成当前成员 ID。
let authorId = '';
try {
const resp = await skillhubApiFetch<{
@@ -756,7 +755,7 @@ export async function install(
body: { slugs: [p.name] },
});
const matched = resp.items?.find((i) => i.slug === p.name);
- authorId = matched?.isMine ? userId : (matched?.owner.slug ?? '');
+ authorId = matched?.owner.slug ?? '';
} catch (err) {
log.warn('[skillInstall] batch-detail after install warn:', err);
}
@@ -777,6 +776,11 @@ export async function install(
!pathTextEquals(path.normalize(installPath), path.normalize(logicalFinalDir)),
);
const existingRegistryEntry = logicalRegistrySnapshot?.entry ?? physicalRegistrySnapshots[0]?.entry ?? null;
+ // Replacing the same catalog record updates its content baseline, not its publication provenance.
+ // This local metadata never grants publish rights; those still require fresh server authority.
+ const preservePublication = existingRegistryEntry?.origin === 'published'
+ && existingRegistryEntry.catalogScope === p.catalogScope;
+ if (preservePublication && !authorId) authorId = existingRegistryEntry.authorId;
const previousRegistrySnapshots = registrySnapshots;
const mutatedRegistryPaths = uniqueNormalizedPaths([
logicalFinalDir,
@@ -803,7 +807,7 @@ export async function install(
folderHash,
installedAt: nowSec,
updatedAt: nowSec,
- origin: 'installed',
+ origin: preservePublication ? 'published' : 'installed',
autoSynced: nextAutoSynced,
...(p.catalogScope ? { catalogScope: p.catalogScope } : {}),
});
diff --git a/apps/desktop/src/main/skillhub/marketService.ts b/apps/desktop/src/main/skillhub/marketService.ts
index 3c3cea8ea8..a4652f9903 100644
--- a/apps/desktop/src/main/skillhub/marketService.ts
+++ b/apps/desktop/src/main/skillhub/marketService.ts
@@ -190,12 +190,15 @@ export class SkillhubMarketService {
return { success: true as const, info };
}
- async getPublishedFiles({ name, version, catalogScope }: { name: string; version?: string; catalogScope?: SkillhubCatalogScope }) {
- const qs = version ? `?version=${encodeURIComponent(version)}` : '';
+ async getPublishedFiles({ name, version, catalogScope, includeHashes }: { name: string; version?: string; catalogScope?: SkillhubCatalogScope; includeHashes?: boolean }) {
+ const search = new URLSearchParams();
+ if (version) search.set('version', version);
+ if (includeHashes) search.set('includeHashes', '1');
+ const qs = search.size ? `?${search}` : '';
const result = await this.fetch<{
slug: string;
version: string;
- files: Array<{ path: string; size: number; language: string; truncated: boolean }>;
+ files: Array<{ path: string; size: number; language: string; truncated: boolean; sha256?: string }>;
}>(withSkillhubCatalogScope(`/api/skills-hub/skills/${encodeURIComponent(name)}/files${qs}`, catalogScope));
return { success: true as const, ...result };
}
diff --git a/apps/desktop/src/main/skillhub/publishedComparison.ts b/apps/desktop/src/main/skillhub/publishedComparison.ts
new file mode 100644
index 0000000000..10e6b950fc
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/publishedComparison.ts
@@ -0,0 +1,190 @@
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import type { SkillhubContentChange, SkillhubPublishComparison } from '../../shared/skillhubPublishComparison';
+import type { Skill } from './scanner';
+import type { SkillhubMarketService } from './marketService';
+import { isIgnoredSkillPackagePath } from './packageIgnore';
+import { activePublishedReviewVersion } from '../../shared/skillhubPublishedStatus';
+
+const MAX_FILES = 2_000;
+const MAX_BYTES = 50 * 1024 * 1024;
+const MAX_TEXT_BYTES = 1024 * 1024;
+const MAX_DIFF_BYTES = 4 * 1024 * 1024;
+const MAX_REMOTE_PREVIEWS = 16;
+const HASH_RE = /^[a-f0-9]{64}$/;
+interface ContentFile { path: string; size: number; sha256: string; text?: string }
+
+function safeRelativePath(value: string): boolean {
+ return value.length > 0 && value.length <= 512 && !/[\\\x00-\x1f]/.test(value)
+ && !value.startsWith('/') && !/^[A-Za-z]:/.test(value)
+ && value.split('/').every((part) => part !== '' && part !== '.' && part !== '..');
+}
+
+/** Uses the exact local packaging exclusions, including on archives uploaded by other clients. */
+export function publishedManifest(value: unknown): ContentFile[] {
+ if (!Array.isArray(value)) throw new Error('Incomplete published manifest');
+ const files: ContentFile[] = [];
+ const paths = new Set<string>();
+ let bytes = 0;
+ for (const file of value) {
+ if (!file || typeof file.path !== 'string' || !safeRelativePath(file.path) || paths.has(file.path)) {
+ throw new Error('Invalid published path');
+ }
+ paths.add(file.path);
+ if (isIgnoredSkillPackagePath(file.path)) continue;
+ if (files.length >= MAX_FILES) throw new Error('Skill exceeds comparison limit');
+ if (typeof file.sha256 !== 'string' || !HASH_RE.test(file.sha256)
+ || !Number.isSafeInteger(file.size) || file.size < 0) throw new Error('Missing file digest');
+ bytes += file.size;
+ if (bytes > MAX_BYTES) throw new Error('Skill exceeds comparison limit');
+ files.push({ path: file.path, size: file.size, sha256: file.sha256 });
+ }
+ if (!files.some((file) => file.path === 'SKILL.md')) throw new Error('Missing Skill manifest');
+ return files;
+}
+
+function textContent(bytes: Buffer): string | undefined {
+ if (bytes.includes(0)) return undefined;
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { return undefined; }
+}
+
+/** Fail on unreadable/changing files instead of silently treating a partial scan as clean. */
+export async function localComparisonFiles(root: string, includeText: boolean): Promise<ContentFile[]> {
+ const canonical = await fs.promises.realpath(root);
+ const files: ContentFile[] = [];
+ let bytes = 0;
+ let retainedText = 0;
+ async function assertInside(file: string) {
+ const real = await fs.promises.realpath(file);
+ const rel = path.relative(canonical, real);
+ if (path.isAbsolute(rel) || rel === '..' || rel.startsWith(`..${path.sep}`)) throw new Error('Skill path changed');
+ return real;
+ }
+ async function walk(dir: string): Promise<void> {
+ const dirBefore = await fs.promises.stat(await assertInside(dir));
+ for (const entry of await fs.promises.readdir(dir, { withFileTypes: true })) {
+ const file = path.join(dir, entry.name);
+ const relative = path.relative(canonical, file).split(path.sep).join('/');
+ if (isIgnoredSkillPackagePath(relative)) continue;
+ if (entry.isDirectory()) { await walk(file); continue; }
+ if (!entry.isFile()) continue;
+ // Match the package manifest: directories and symlinks are not published files.
+ if (files.length >= MAX_FILES) throw new Error('Skill exceeds comparison limit');
+ if (!safeRelativePath(relative)) throw new Error('Invalid local package path');
+ const real = await assertInside(file);
+ const handle = await fs.promises.open(real, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
+ try {
+ const before = await handle.stat();
+ if (!before.isFile() || before.size + bytes > MAX_BYTES) throw new Error('Skill exceeds comparison limit');
+ const hash = crypto.createHash('sha256');
+ const keepText = includeText && before.size <= MAX_TEXT_BYTES && retainedText + before.size <= MAX_DIFF_BYTES;
+ const chunks: Buffer[] = [];
+ let size = 0;
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
+ size += chunk.length;
+ if (bytes + size > MAX_BYTES) throw new Error('Skill exceeds comparison limit');
+ hash.update(chunk);
+ if (keepText && size <= MAX_TEXT_BYTES) chunks.push(chunk);
+ }
+ const after = await handle.stat();
+ const current = await fs.promises.stat(await assertInside(file));
+ if (before.ino !== current.ino || before.dev !== current.dev || before.mtimeMs !== after.mtimeMs
+ || before.ctimeMs !== after.ctimeMs || before.size !== size || after.mtimeMs !== current.mtimeMs
+ || after.ctimeMs !== current.ctimeMs || after.size !== current.size) throw new Error('Skill changed during comparison');
+ bytes += size;
+ const text = keepText ? textContent(Buffer.concat(chunks)) : undefined;
+ if (text !== undefined) retainedText += size;
+ files.push({ path: relative, size, sha256: hash.digest('hex'), ...(text !== undefined ? { text } : {}) });
+ } finally { await handle.close(); }
+ }
+ const dirAfter = await fs.promises.stat(await assertInside(dir));
+ if (dirBefore.ino !== dirAfter.ino || dirBefore.dev !== dirAfter.dev
+ || dirBefore.mtimeMs !== dirAfter.mtimeMs || dirBefore.ctimeMs !== dirAfter.ctimeMs) {
+ throw new Error('Skill changed during comparison');
+ }
+ }
+ await walk(canonical);
+ return files;
+}
+
+export async function comparePublishedSkill(
+ skill: Pick<Skill, 'name' | 'registrySkillName' | 'registryEntry' | 'absolutePath'>,
+ market: Pick<SkillhubMarketService, 'info' | 'getPublishedFiles' | 'readPublishedFile'>,
+ includeDiff = false,
+): Promise<SkillhubPublishComparison> {
+ const name = skill.registrySkillName ?? skill.name;
+ const scope = skill.registryEntry?.catalogScope;
+ const source = await market.info(name, scope);
+ if (!source.info) return { status: 'not-owner' };
+ if (typeof source.info.isCreator !== 'boolean') return { status: 'unavailable' };
+ if (source.info.isCreator !== true || !source.info.canManage) return { status: 'not-owner' };
+ // Publication always targets native management reads. Never cross same-slug catalog identities.
+ const native = scope ? await market.info(name) : source;
+ if (!native.info || native.info.isCreator !== true || !native.info.canManage
+ || native.info.authorId !== source.info.authorId || native.info.ownerType !== source.info.ownerType) {
+ return { status: 'not-owner' };
+ }
+ const info = native.info;
+ const reviewVersion = activePublishedReviewVersion(info);
+ const pending = reviewVersion !== null;
+ const version = reviewVersion ?? info.latestVersion;
+ const remote = await market.getPublishedFiles({ name, version, includeHashes: true });
+ if (remote.version !== version) throw new Error('Published version changed');
+ const published = publishedManifest(remote.files);
+ const local = await localComparisonFiles(skill.absolutePath, includeDiff);
+ const oldByPath = new Map(published.map((file) => [file.path, file]));
+ const newByPath = new Map(local.map((file) => [file.path, file]));
+ const changedPaths = [...new Set([...oldByPath.keys(), ...newByPath.keys()])].sort()
+ .filter((file) => oldByPath.get(file)?.sha256 !== newByPath.get(file)?.sha256);
+ const installedVersion = skill.registryEntry?.version;
+ let localChanges: 'modified' | 'unchanged' | 'unknown' | undefined;
+ const installedOrigin = skill.registryEntry?.origin;
+ if (changedPaths.length && installedVersion && installedVersion !== version
+ && installedOrigin !== 'learned' && installedOrigin !== 'imported') {
+ // A difference from the latest release may just be an older, unedited copy.
+ // Compare with the immutable installed release, never a ZIP hash or guessed author.
+ try {
+ const baseline = await market.getPublishedFiles({ name, version: installedVersion, includeHashes: true });
+ if (baseline.version !== installedVersion) throw new Error('Installed version changed');
+ const original = publishedManifest(baseline.files);
+ localChanges = original.length === local.length
+ && original.every((file) => newByPath.get(file.path)?.sha256 === file.sha256)
+ ? 'unchanged' : 'modified';
+ } catch {
+ localChanges = 'unknown';
+ }
+ }
+ const result = {
+ status: changedPaths.length ? 'different' as const : 'same' as const, version, pending,
+ ...(localChanges ? { localChanges } : {}),
+ };
+ if (!includeDiff) return result;
+ const changes: SkillhubContentChange[] = [];
+ let previewBytes = 0;
+ let previewRequests = 0;
+ for (const file of changedPaths) {
+ const oldFile = oldByPath.get(file);
+ const newFile = newByPath.get(file);
+ let oldContent = oldFile ? undefined : '';
+ const newContent = newFile ? newFile.text : '';
+ if (oldFile && oldFile.size <= MAX_TEXT_BYTES && newContent !== undefined
+ && previewRequests < MAX_REMOTE_PREVIEWS
+ && previewBytes + oldFile.size + (newFile?.size ?? 0) <= MAX_DIFF_BYTES) {
+ previewRequests++;
+ const response = await market.readPublishedFile({ name, version, path: file });
+ const preview = response.file;
+ if (!preview.truncated && typeof preview.content === 'string' && Buffer.byteLength(preview.content) === oldFile.size
+ && crypto.createHash('sha256').update(preview.content).digest('hex') === oldFile.sha256) {
+ oldContent = textContent(Buffer.from(preview.content));
+ }
+ }
+ const isBinary = oldContent === undefined || newContent === undefined
+ || previewBytes + (oldFile?.size ?? 0) + (newFile?.size ?? 0) > MAX_DIFF_BYTES;
+ if (!isBinary) previewBytes += (oldFile?.size ?? 0) + (newFile?.size ?? 0);
+ changes.push({ path: file, kind: !oldFile ? 'added' : !newFile ? 'removed' : 'modified', isBinary,
+ oldContent: isBinary ? '' : oldContent ?? '', newContent: isBinary ? '' : newContent ?? '',
+ oldSize: oldFile?.size ?? 0, newSize: newFile?.size ?? 0 });
+ }
+ return { ...result, changes };
+}
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index f70b4cd13a..17c4050e7d 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -21,9 +21,12 @@ import { assertTrustedAppRendererEvent, isTrustedAppRendererWindow } from '../se
import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import { isSkillhubCatalogScope } from '../../shared/skillhubCatalog.js';
import { computeFolderHashDetailed } from './folderHash';
+import { comparePublishedSkill } from './publishedComparison';
+import type { SkillhubPublishComparisonParams, SkillhubPublishComparison } from '../../shared/skillhubPublishComparison';
import { type MdKind, parseAndValidateFrontmatter } from './frontmatterValidation';
import * as importLocalSkill from './importLocalSkill';
import * as installService from './installService';
+import { ServerApiError } from '../serverApiClient';
import { SkillhubMarketService, skillhubIpcError } from './marketService';
import type { PublishParams, PublishProgressEvent } from './publishService';
import { SkillPublishService } from './publishService';
@@ -892,6 +895,38 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
},
);
+ ipcMain.handle('skillhub:compare-published', async (event, params: SkillhubPublishComparisonParams): Promise<SkillhubPublishComparison> => {
+ assertTrustedAppRendererEvent(event);
+ if (!params || typeof params !== 'object' || typeof params.absolutePath !== 'string'
+ || params.absolutePath.length > 32768 || (params.skillId !== undefined && (typeof params.skillId !== 'string' || params.skillId.length > 512))
+ || (params.includeDiff !== undefined && typeof params.includeDiff !== 'boolean')) {
+ throwIpcError('INVALID_PARAMS', 'Invalid Skill comparison request');
+ }
+ const owner = activeOwnerScopeKey();
+ const record = await requireLocalSkill(event, params.absolutePath, params.skillId);
+ assertReviewOwnerCurrent(owner);
+ if (record.skill.kind !== 'skill' || record.skill.builtIn) return { status: 'not-owner' };
+ let result: SkillhubPublishComparison;
+ try {
+ result = await comparePublishedSkill(record.skill, marketService, params.includeDiff);
+ } catch (error) {
+ // Local filesystem/identity/manifest failures must not throttle unrelated skills.
+ const serviceFailure = error instanceof ServerApiError
+ && (error.statusCode === 0 || error.statusCode === 408 || error.statusCode === 429 || error.statusCode >= 500);
+ result = { status: 'unavailable', ...(serviceFailure ? { reason: 'service' as const } : {}) };
+ }
+ assertReviewOwnerCurrent(owner);
+ const current = await requireLocalSkill(event, params.absolutePath, params.skillId);
+ assertReviewOwnerCurrent(owner);
+ if (current.physicalIdentity !== record.physicalIdentity
+ || current.skill.kind !== record.skill.kind || current.skill.builtIn !== record.skill.builtIn
+ || (current.skill.registrySkillName ?? current.skill.name) !== (record.skill.registrySkillName ?? record.skill.name)
+ || current.skill.registryEntry?.catalogScope !== record.skill.registryEntry?.catalogScope) {
+ return { status: 'unavailable' };
+ }
+ return result;
+ });
+
// 计算本地 skill 文件夹 hash(进入 DetailView 时触发)
// 返回 hash + manifest(文件清单 + 各自 sha256),manifest 用于 renderer 端
// 排查"我没改但 dirty" — 直接 console.table 即可看到本地参与 hash 的全部文件。
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index cb279e781f..7cddae746a 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3307,6 +3307,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 计算本地 skill 文件夹 hash(30s 缓存在 renderer 侧)
// manifest 是参与 hash 的文件清单(path + sha256),用于 dirty 排查
+ comparePublished: (params: import('../shared/skillhubPublishComparison').SkillhubPublishComparisonParams): Promise<import('../shared/skillhubPublishComparison').SkillhubPublishComparison> => ipcRenderer.invoke('skillhub:compare-published', params),
+
getFolderHash: (
absolutePath: string,
): Promise<{
diff --git a/apps/desktop/src/renderer/components/diff-panel/FileChangeGroup.tsx b/apps/desktop/src/renderer/components/diff-panel/FileChangeGroup.tsx
index 80f974bc6d..4a6181eb77 100644
--- a/apps/desktop/src/renderer/components/diff-panel/FileChangeGroup.tsx
+++ b/apps/desktop/src/renderer/components/diff-panel/FileChangeGroup.tsx
@@ -30,10 +30,12 @@ export interface FileChange {
export function FileChangeGroup({
change,
defaultExpanded = false,
+ summaryOnly = false,
}: {
change: FileChange;
/** 默认展开(learn 提案审查这类"内容即主体"的场景传 true;快照 diff 保持折叠)。 */
defaultExpanded?: boolean;
+ summaryOnly?: boolean;
}) {
const { t } = useTranslation();
// 默认折叠 — 用户先扫一眼哪些文件变了,再展开关心的那个
@@ -94,7 +96,7 @@ export function FileChangeGroup({
<span className="flex shrink-0 items-center gap-2 text-xs tabular-nums">
{change.isBinary ? (
<span className="rounded bg-muted px-1.5 py-0.5 text-10 text-muted-foreground">
- {t('skillhub.diffPanel.binaryBadge')}
+ {t(summaryOnly ? 'skillhub.publishComparison.summaryBadge' : 'skillhub.diffPanel.binaryBadge')}
</span>
) : stats ? (
<>
@@ -108,7 +110,7 @@ export function FileChangeGroup({
{expanded && (
<div className="border-t border-border p-2">
{change.isBinary ? (
- <BinaryChangedView change={change} />
+ <BinaryChangedView change={change} summaryOnly={summaryOnly} />
) : (
// contextLines=3:整文件对比时只显示变化前后 3 行,中间折叠,
// 避免一改一行铺出整屏。
@@ -124,7 +126,7 @@ export function FileChangeGroup({
);
}
-function BinaryChangedView({ change }: { change: FileChange }) {
+function BinaryChangedView({ change, summaryOnly }: { change: FileChange; summaryOnly: boolean }) {
const { t } = useTranslation();
const fmtSize = (n: number) => {
if (n < 1024) return `${n} B`;
@@ -133,7 +135,7 @@ function BinaryChangedView({ change }: { change: FileChange }) {
};
return (
<div className="flex flex-col gap-1 px-2 py-3 text-xs text-muted-foreground">
- <span>{t('skillhub.diffPanel.binaryNote')}</span>
+ <span>{t(summaryOnly ? 'skillhub.publishComparison.summaryNote' : 'skillhub.diffPanel.binaryNote')}</span>
<span className="tabular-nums">
{change.kind === 'added'
? t('skillhub.diffPanel.binarySizeNew', { size: fmtSize(change.newSize) })
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillPublishUpdateHint.tsx b/apps/desktop/src/renderer/features/skillhub/SkillPublishUpdateHint.tsx
new file mode 100644
index 0000000000..92387fb408
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/SkillPublishUpdateHint.tsx
@@ -0,0 +1,30 @@
+import { useTranslation } from 'react-i18next';
+import { useSkillPublishComparison, type PublishComparisonState } from './hooks/useSkillPublishComparison';
+import { hasPublishableChanges } from './lib/publishUpdateState';
+
+export function SkillPublishUpdateHint({ skill, knownCreator }: { skill: SkillhubSkill; knownCreator?: boolean }) {
+ const { t } = useTranslation();
+ const { comparison } = useSkillPublishComparison(knownCreator ? skill : null);
+ if (comparison.status !== 'different' && comparison.status !== 'unavailable') return null;
+ if (comparison.status === 'different' && !hasPublishableChanges(comparison)) return null;
+ if (comparison.status === 'unavailable' && !knownCreator) return null;
+ return (
+ <span className="text-12 leading-4 text-[var(--text-secondary)]">
+ {t(comparison.status === 'unavailable' ? 'skillhub.publishComparison.unavailable'
+ : comparison.pending ? 'skillhub.publishComparison.pendingChanges' : 'skillhub.publishComparison.updateAvailable')}
+ </span>
+ );
+}
+
+export function SkillPublishComparisonNotice({ comparison, isCreator }: {
+ comparison: PublishComparisonState;
+ isCreator?: boolean;
+}) {
+ const { t } = useTranslation();
+ if (comparison.status !== 'unavailable' || isCreator !== true) return null;
+ return (
+ <p className="shrink-0 px-4 pt-4 text-sm text-[var(--text-secondary)]">
+ {t('skillhub.publishComparison.unavailable')}
+ </p>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx
new file mode 100644
index 0000000000..051b9b32ca
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx
@@ -0,0 +1,167 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Navigate, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Select } from '@/components/ui/select';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { SkillhubDetailView } from './SkillhubDetailView';
+import { SkillhubMarketDetailView } from './SkillhubMarketDetailView';
+import { SkillDetailHeader, SkillDetailPage } from './components/SkillDetailLayout';
+import { LocalSkillControls } from './components/LocalSkillControls';
+import { InstallTargetPicker } from './components/InstallTargetPicker';
+import { MarketManagementDialogs, useMarketManagement } from './hooks/useMarketManagement';
+import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
+import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
+import { deriveLocalInstall, type MarketSkill } from './hooks/useMarketList';
+import { refresh, useSkillhub } from './hooks/useSkillhub';
+import { buildLocalSkillRoute, findLocalSkillRouteEntry } from './lib/localRoutes';
+import { buildMarketSkillRoute, skillDetailCatalog, skillDetailLocalParams, skillDetailReturnRoute, withSkillDetailReturn } from './lib/detailRoutes';
+import { marketLocalCopies } from './lib/marketLocalCopies';
+
+function marketViewModel(info: SkillhubInfoResult, local: SkillhubSkill | null, catalogScope: MarketSkill['catalogScope']): MarketSkill {
+ const primary = local ? {
+ version: local.registryEntry?.version ?? null, absolutePath: local.absolutePath, hasRegistryEntry: !!local.registryEntry,
+ } : undefined;
+ const installed = deriveLocalInstall(info, primary ? { global: primary, projects: [] } : undefined);
+ return {
+ ...info, icon: info.icon ?? undefined, catalogScope, ...installed,
+ authorAvatarUrl: null, avatarInitial: info.authorName.slice(0, 1),
+ categories: info.categories ?? [], tags: info.tags ?? [], githubUrl: info.githubUrl ?? null,
+ relativeTime: '', latestPublishedFromDeviceId: null,
+ cardState: installed.updateAvailable ? 'installed-outdated' : installed.installedLocally ? 'installed-latest' : 'not-installed',
+ };
+}
+
+/** Both list entry points resolve identity here; content readers retain their own authority. */
+export function SkillhubDetailRoute() {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const [search] = useSearchParams();
+ const { user } = useAuth();
+ const identity = useSkillhubIdentityPolicy(user);
+ const owner = getDataOwnerGeneration();
+ const { skills, bootstrapped, loading, learnSkillEnabled } = useSkillhub();
+ const explicitLocal = findLocalSkillRouteEntry(skills, skillDetailLocalParams(search), search);
+ const remoteName = search.get('remote')
+ ?? (explicitLocal?.kind === 'skill' && !explicitLocal.builtIn ? explicitLocal.registrySkillName ?? explicitLocal.name : null);
+ const catalogScope = search.has('remote') ? skillDetailCatalog(search) : explicitLocal?.registryEntry?.catalogScope;
+ const targetKey = JSON.stringify([owner, remoteName, catalogScope]);
+ const [remote, setRemote] = useState<{ key: string; info: SkillhubInfoResult | null; failed: boolean } | null>(null);
+ const [revision, setRevision] = useState(0);
+ const reload = useCallback(() => setRevision((value) => value + 1), []);
+ const returnTo = skillDetailReturnRoute(search);
+ const showingMarket = search.get('view') === 'market';
+ const marketUpdate = useMarketSkillUpdate();
+ const [pickerOpen, setPickerOpen] = useState(false);
+
+ const commandPath = search.get('path');
+ useEffect(() => { if (commandPath) void refresh(); }, [commandPath]);
+ useEffect(() => {
+ if (!remoteName) return;
+ let cancelled = false;
+ setRemote(null);
+ void window.electronAPI.skillhub.info(remoteName, catalogScope).then((result) => {
+ if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
+ setRemote({ key: targetKey, info: result.success && result.info ? result.info : null, failed: !result.success });
+ }, () => {
+ if (!cancelled && isDataOwnerGenerationCurrent(owner)) setRemote({ key: targetKey, info: null, failed: true });
+ });
+ return () => { cancelled = true; };
+ }, [remoteName, catalogScope, targetKey, owner, revision, showingMarket]);
+
+ // A same-name market record is not an association for an unregistered local author folder.
+ const info = remote?.key === targetKey && remote.info
+ && (search.has('remote') || explicitLocal?.registryEntry || remote.info.isCreator === true)
+ ? remote.info : null;
+ const copies = useMemo(() => info
+ ? marketLocalCopies(skills, { ...info, isMine: info.isCreator === true, catalogScope })
+ : explicitLocal ? [explicitLocal] : [], [info, skills, explicitLocal, catalogScope]);
+ const selected = copies.find((copy) => copy.id === explicitLocal?.id) ?? copies[0] ?? null;
+ const market = info ? marketViewModel(info, selected, catalogScope) : null;
+
+ const selectSource = (view: 'local' | 'market', local: SkillhubSkill | null = selected, action?: 'publish') => {
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ let route = view === 'local' && local
+ ? withSkillDetailReturn(buildLocalSkillRoute(local), returnTo)
+ : buildMarketSkillRoute({ name: remoteName ?? '', catalogScope }, returnTo);
+ const query = new URLSearchParams(route.split('?')[1]);
+ if (info) { query.set('remote', info.name); query.set('catalog', catalogScope ?? 'native'); }
+ if (local) {
+ const localQuery = new URLSearchParams(buildLocalSkillRoute(local).split('?')[1]);
+ for (const [key, value] of localQuery) if (key !== 'view') query.set(key, value);
+ }
+ if (action) query.set('action', action);
+ route = `/skillhub/detail?${query}`;
+ navigate(route, { replace: true });
+ };
+ const management = useMarketManagement({
+ active: !!info?.canManage, reload, onClone: () => setPickerOpen(true),
+ onDeleted: () => selected ? selectSource('local') : navigate(returnTo),
+ });
+
+ const navigation = (beforeLeave: () => Promise<boolean> = async () => true, disabled = false) => (
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-[var(--border-default)] px-4 py-2">
+ <div className="flex items-center gap-1" role="group" aria-label={t('skillhub.unifiedDetail.contentSource')}>
+ {selected && <Button variant={showingMarket ? 'secondary' : 'primary'} disabled={disabled} aria-pressed={!showingMarket}
+ onClick={() => { if (showingMarket) void beforeLeave().then((ok) => { if (ok) selectSource('local'); }); }}>{t('skillhub.unifiedDetail.local')}</Button>}
+ {(info || showingMarket) && <Button variant={showingMarket ? 'primary' : 'secondary'} disabled={disabled} aria-pressed={showingMarket}
+ onClick={() => { if (!showingMarket) void beforeLeave().then((ok) => { if (ok) selectSource('market'); }); }}>{t('skillhub.unifiedDetail.market')}</Button>}
+ </div>
+ {copies.length > 1 && (
+ <Select label={t('skillhub.sidebar.marketInstalledHeading')} value={selected?.id ?? ''} disabled={disabled}
+ className="max-w-sm"
+ onValueChange={(value) => {
+ const next = copies.find((copy) => copy.id === value);
+ if (next && next.id !== selected?.id) void beforeLeave().then((ok) => { if (ok) selectSource(showingMarket ? 'market' : 'local', next); });
+ }} options={copies.map((copy) => ({ value: copy.id, label: `${copy.scope === 'global' ? t('skillhub.detail.scopeGlobal') : copy.projectRoot} · ${copy.discoveredPath ?? copy.absolutePath}` }))} />
+ )}
+ {showingMarket && selected && <span className="min-w-0 truncate text-xs text-[var(--text-secondary)]" title={selected.absolutePath}>{selected.absolutePath}</span>}
+ </div>
+ );
+
+ return <>
+ {!showingMarket && selected ? (
+ <SkillhubDetailView key={`${owner.generation}:${selected.id}`} entryOverride={selected} renderNavigation={navigation}
+ onUninstalled={() => info ? selectSource('market', null) : navigate(returnTo)} />
+ ) : showingMarket && market ? (
+ <SkillhubMarketDetailView key={`${owner.generation}:${remoteName}:${catalogScope}`} skill={market} onClose={() => navigate(returnTo)}
+ navigation={navigation()} primaryAction={user ? info?.canManage && identity.canWrite ? 'manage' : 'clone' : 'none'}
+ onClone={() => setPickerOpen(true)} onManageAction={management.handleManageAction} learnSkillEnabled={learnSkillEnabled}
+ onUpdate={user ? marketUpdate.update : undefined} updating={marketUpdate.updatingNames.has(market.name)}
+ localActions={selected ? <LocalSkillControls key={selected.id} skill={selected} disabled={marketUpdate.updatingNames.has(market.name)} /> : null} />
+ ) : (
+ <SkillDetailPage>
+ <SkillDetailHeader title={remoteName ?? t('skillhub.home.title')} backLabel={t('skillhub.detail.backToSkillhub')} onBack={() => navigate(returnTo)} />
+ {navigation()}
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 text-sm text-[var(--text-secondary)]">
+ {!bootstrapped || loading || (showingMarket && remoteName && remote?.key !== targetKey)
+ ? t('skillhub.detail.loadingContent') : t(remote?.failed ? 'skillhub.unifiedDetail.marketUnavailable' : 'skillhub.detail.notFound')}
+ {remote?.key === targetKey && remote.failed && <Button onClick={reload}>{t('skillhub.unifiedDetail.retry')}</Button>}
+ </div>
+ </SkillDetailPage>
+ )}
+ <InstallTargetPicker open={pickerOpen && !!market} skill={market} onClose={() => setPickerOpen(false)}
+ onInstallComplete={() => { setPickerOpen(false); void refresh(); reload(); }} />
+ <MarketManagementDialogs controller={management} />
+ </>;
+}
+
+/** Preserve existing bookmarks, command-palette links, and older market URLs. */
+export function LegacySkillDetailRedirect({ market = false }: { market?: boolean }) {
+ const params = useParams();
+ const location = useLocation();
+ const search = new URLSearchParams(location.search);
+ search.set('view', market ? 'market' : 'local');
+ if (market) {
+ search.set('remote', params.name ?? '');
+ if (!search.has('catalog')) search.set('catalog', location.pathname.startsWith('/skillhub/market/manage/') ? 'native' : 'market');
+ if (!search.has('returnTo')) search.set('returnTo', '/skillhub/market');
+ } else {
+ if (params.kind) search.set('kind', params.kind);
+ if (params.name) search.set('name', params.name);
+ if (params.projectHash) search.set('project', params.projectHash);
+ if (!search.has('scope') && params.kind) search.set('scope', params.projectHash ? 'project' : 'global');
+ }
+ return <Navigate to={`/skillhub/detail?${search}`} replace state={location.state} />;
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
index 435ad913d5..29253d4844 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
@@ -1,7 +1,5 @@
-import { LocalSkillControls } from './components/LocalSkillControls';
-import { OfficialSkillBadge } from './components/OfficialSkillBadge';
/**
- * SkillhubDetailView — route for /skillhub/{kind}/{global|project}/[hash]/:name.
+ * SkillhubDetailView — local content controller inside the shared /skillhub/detail page.
*
* Layout (per prod spec v0.5 F4):
* ┌ Top toolbar (h-16) ─────────────────────────────────────────────┐
@@ -17,14 +15,20 @@ import { OfficialSkillBadge } from './components/OfficialSkillBadge';
* - agent → single .md file, FILES section hidden
*/
+import { SkillDetailResizeHandle, SkillDetailPage, SkillDetailHeader, SkillDetailColumns, SkillDetailSidebar, SkillDetailContent } from './components/SkillDetailLayout';
+import { skillDetailReturnRoute, withSkillDetailReturn } from './lib/detailRoutes';
+import { hasPublishableChanges } from './lib/publishUpdateState';
+import { LocalSkillControls } from './components/LocalSkillControls';
+import { OfficialSkillBadge } from './components/OfficialSkillBadge';
+
import * as Dialog from '@radix-ui/react-dialog';
-import { AlertCircle, AlertTriangle, ArrowLeft, ArrowUp, Bot, CheckCircle, ChevronDown, ChevronRight, Clock3, FileText, Folder, FolderOpen, Globe, type LucideIcon, Package, Pencil, Save, Search, SquareTerminal, Upload, X } from 'lucide-react';
+import { AlertCircle, AlertTriangle, ArrowUp, Bot, CheckCircle, ChevronDown, ChevronRight, Clock3, FileText, Folder, FolderOpen, Globe, type LucideIcon, Package, Pencil, Save, Search, SquareTerminal, Upload, X } from 'lucide-react';
import { type CSSProperties, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
-import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { PlaintextEditor, type PlaintextEditorHandle } from '@/components/markdown/PlaintextEditor';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { Spinner } from '@/components/ui/spinner';
@@ -39,8 +43,8 @@ import { getDataOwnerGeneration, isDataOwnerIdCurrent } from '@/contexts/dataOwn
import { cn } from '@/lib/utils';
import { getDraft, getFastModeForModel } from '@/state/newMakerDraft';
import { useMetaColumnResize } from './hooks/useMetaColumnResize';
-import { useSkillhubHomeNavigation } from './hooks/useSkillhubHomeNavigation';
import { invalidateHash, useSkillFolderHash } from './hooks/useSkillFolderHash';
+import { useSkillPublishComparison } from './hooks/useSkillPublishComparison';
import {
clearHistory,
clearLastEntryId,
@@ -51,6 +55,7 @@ import {
import { triggerIncrementalSync } from './hooks/useSkillSync';
import { type DetailState, deriveDetailActionState, deriveDetailState } from './lib/detailButtons';
import {
+ buildLocalSkillRoute,
findLocalSkillByPath,
findLocalSkillRouteEntry,
} from './lib/localRoutes';
@@ -81,6 +86,7 @@ import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
import { usePublicationFeedback, useRejectionFeedback } from './hooks/useRejectionFeedback';
import { shouldHandlePublishProgressEvent } from './lib/publishProgressFilter';
import { SkillhubDiffPanel } from './SkillhubDiffPanel';
+import { SkillPublishComparisonNotice } from './SkillPublishUpdateHint';
const log = createLogger('SkillhubDetailView');
@@ -978,15 +984,18 @@ function FileTreeRow({ entry, parentDir, depth, currentPath, onSelectFile }: Fil
);
}
-export function SkillhubDetailView() {
+export function SkillhubDetailView({ entryOverride, renderNavigation, onUninstalled }: {
+ entryOverride?: SkillhubSkill;
+ renderNavigation?: (beforeLeave: () => Promise<boolean>, disabled: boolean) => ReactNode;
+ onUninstalled?: () => void;
+} = {}) {
const { t } = useTranslation();
const { user } = useAuth();
const identityPolicy = useSkillhubIdentityPolicy(user);
const params = useParams();
- const [searchParams] = useSearchParams();
+ const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const location = useLocation();
- const { backToCatalog, replaceLocalSkill } = useSkillhubHomeNavigation();
const { skills, bootstrapped, loading: skillsLoading } = useSkillhub();
const commandPath = searchParams.get('path');
useEffect(() => {
@@ -996,8 +1005,9 @@ export function SkillhubDetailView() {
const { createSession } = useCCSessions();
// 入口来源:market 卡片会带 state.from。详情页返回不走浏览器式历史,
// 而是退出到 SkillHub 一级页:market 来源回 market,其它入口回 local 欢迎页。
- const navState = location.state as { from?: string; resetHistory?: boolean } | null;
+ const navState = location.state as { from?: string; resetHistory?: boolean; skillhubHome?: unknown } | null;
const fromRoute = navState?.from ?? '/skillhub';
+ const backTargetRoute = skillDetailReturnRoute(searchParams, fromRoute === '/skillhub/market' ? '/skillhub/market' : '/skillhub/local');
// 兼容旧 sessionStorage 栈:从外部入口进入时先清掉,避免老版本留下的
// detail 链影响后续返回语义。
const shouldResetHistory = navState?.resetHistory === true;
@@ -1006,12 +1016,12 @@ export function SkillhubDetailView() {
const metaResize = useMetaColumnResize();
const entry = useMemo(() => {
- return findLocalSkillRouteEntry(
+ return entryOverride ?? findLocalSkillRouteEntry(
skills,
params as Record<string, string | undefined>,
searchParams,
);
- }, [params, searchParams, skills]);
+ }, [entryOverride, params, searchParams, skills]);
// 记录最近访问项供下次打开 SkillHub 时恢复;返回按钮会清掉它,避免用户
// 主动退出详情页后又被 welcome 自动带回同一条记录。
@@ -1045,7 +1055,7 @@ export function SkillhubDetailView() {
}
clearLastEntryId();
clearHistory();
- backToCatalog();
+ navigate(backTargetRoute, { state: { skillhubHome: navState?.skillhubHome } });
};
// ── v0.2.1: 4-state detection for kind === 'skill' ────────────────────────
@@ -1061,16 +1071,20 @@ export function SkillhubDetailView() {
// 拉新数据;publish 完成后通过 invalidateInfo + bump infoFetchTrigger 强刷。
// detailState 完全基于 infoResult 派生(不再用批量 syncResults),保证按钮永远
// 反映「这个 skill 在服务器上的真实状态」。
+ const entryMarketName = entry?.registrySkillName ?? entry?.name;
+ const publishSkill = useMemo(() => entry && entryMarketName
+ ? { ...entry, name: entryMarketName } : entry, [entry, entryMarketName]);
const entryCatalogScope = entry?.registryEntry?.catalogScope;
const [infoResult, setInfoResult] = useState<SkillhubInfoResult | null>(
- () => (entry?.name ? getCachedInfo(entry.name, entryCatalogScope) : null),
+ () => (entryMarketName ? getCachedInfo(entryMarketName, entryCatalogScope) : null),
);
const [infoLoading, setInfoLoading] = useState(false);
const [publishTargetInfo, setPublishTargetInfo] = useState<SkillhubInfoResult | null>(
- () => (entry?.name && entryCatalogScope === 'team' ? getCachedInfo(entry.name) : null),
+ () => (entryMarketName && entryCatalogScope === 'team' ? getCachedInfo(entryMarketName) : null),
);
const [publishTargetLoading, setPublishTargetLoading] = useState(false);
const [infoFetchTrigger, setInfoFetchTrigger] = useState(0);
+ const { comparison: publishComparison, refresh: comparisonRefresh } = useSkillPublishComparison(infoResult?.isCreator === true ? entry : null);
// 同步重置:entry.name 变化时立刻把 infoResult 切到新 name 的缓存值。
// FadeSwitcher 按 feature 段(/skillhub)聚合 key,同 feature 内切 skill 不重挂,
@@ -1079,15 +1093,15 @@ export function SkillhubDetailView() {
// 关键升级:不再无脑置 null(那会让按钮闪过一次"无版本号 → 有版本号"),
// 改成同步从 SWR 缓存取上次结果,缓存命中(常见的重访场景)时直接渲染最终态,
// 完全不闪;缓存 miss(首访)时才退回到 null + loading=true。
- const entryInfoKey = entry?.name ? `${entryCatalogScope ?? 'default'}:${entry.name}` : null;
+ const entryInfoKey = entryMarketName ? `${entryCatalogScope ?? 'default'}:${entryMarketName}` : null;
const { result: scanResult, setResult: setScanResult } = usePublicationFeedback(entryInfoKey);
const [trackedEntryInfoKey, setTrackedEntryInfoKey] = useState<string | null>(entryInfoKey);
if (entryInfoKey !== trackedEntryInfoKey) {
setTrackedEntryInfoKey(entryInfoKey);
- const cached = entry?.name ? getCachedInfo(entry.name, entryCatalogScope) : null;
+ const cached = entryMarketName ? getCachedInfo(entryMarketName, entryCatalogScope) : null;
setInfoResult(cached);
setPublishTargetInfo(
- entry?.name && entryCatalogScope === 'team' ? getCachedInfo(entry.name) : null,
+ entryMarketName && entryCatalogScope === 'team' ? getCachedInfo(entryMarketName) : null,
);
setLiveScanStatus(null);
// 有缓存就不显示 loading(SWR 后台静默刷),没缓存才进 loading 态
@@ -1134,11 +1148,11 @@ export function SkillhubDetailView() {
return { info, liveScanStatus: null };
}, []);
- const remoteInfoName = isSkill ? (entry?.name ?? null) : null;
+ const remoteInfoName = isSkill ? (entryMarketName ?? null) : null;
const remoteInfoRequest = useMemo(() => {
if (!remoteInfoName) return null;
- return { name: remoteInfoName, catalogScope: entryCatalogScope, refreshKey: infoFetchTrigger };
- }, [remoteInfoName, entryCatalogScope, infoFetchTrigger]);
+ return { name: remoteInfoName, catalogScope: entryCatalogScope, refreshKey: infoFetchTrigger, comparisonRefresh };
+ }, [remoteInfoName, entryCatalogScope, infoFetchTrigger, comparisonRefresh]);
useEffect(() => {
if (!remoteInfoRequest) {
@@ -1205,7 +1219,7 @@ export function SkillhubDetailView() {
const previousPublishOpenRef = useRef(publishOpen);
const deferredDoneRef = useRef(false);
publishOpenRef.current = publishOpen;
- const publishProgressName = isSkill ? (entry?.name ?? null) : null;
+ const publishProgressName = isSkill ? (entryMarketName ?? null) : null;
const publishProgressAbsolutePath = isSkill ? (entry?.absolutePath ?? null) : null;
const publishProgressTarget = useMemo(() => {
if (!publishProgressName || !publishProgressAbsolutePath) return null;
@@ -1290,17 +1304,19 @@ export function SkillhubDetailView() {
// 按钮区/banner 数据就绪:info 落定 + hash 算完即可,不再依赖批量 sync。
// 仅 isSkill 场景需要 hash;command/agent 直接视为 ready。
- const hashReady = !isSkill || (!hashLoading && localFolderHash !== null);
+ const hashReady = !isSkill || (!hashLoading && localFolderHash !== null)
+ || publishComparison.status === 'same' || publishComparison.status === 'different'
+ || publishComparison.status === 'unavailable';
const detailReady = !isSkill || (!infoLoading && !effectivePublishLoading && hashReady);
// 三维度 detail state
- const marketDeleted = !infoLoading && checkMarketDeleted(entry?.name ?? '', entryCatalogScope);
+ const marketDeleted = !infoLoading && checkMarketDeleted(entryMarketName ?? '', entryCatalogScope);
const detailState = useMemo<DetailState | null>(() => {
const state = deriveDetailState(isSkill ? entry : null, infoResult, marketDeleted);
return state;
}, [isSkill, entry, infoResult, marketDeleted]);
const publishTargetDeleted = !effectivePublishLoading
- && checkMarketDeleted(entry?.name ?? '', entryCatalogScope === 'team' ? undefined : entryCatalogScope);
+ && checkMarketDeleted(entryMarketName ?? '', entryCatalogScope === 'team' ? undefined : entryCatalogScope);
const publishDetailState = useMemo<DetailState | null>(() => (
deriveDetailState(isSkill ? entry : null, effectivePublishInfo, publishTargetDeleted)
), [isSkill, entry, effectivePublishInfo, publishTargetDeleted]);
@@ -1315,8 +1331,9 @@ export function SkillhubDetailView() {
publishedStatus,
identityPolicy.canWrite && entry?.builtIn !== true,
publishDetailState,
+ publishComparison,
),
- [detailState, registryEntry, localFolderHash, publishedStatus, identityPolicy.canWrite, entry?.builtIn, publishDetailState],
+ [detailState, registryEntry, localFolderHash, publishedStatus, identityPolicy.canWrite, entry?.builtIn, publishDetailState, publishComparison],
);
const detailAction = detailActionState?.status ?? null;
const isOutdated = detailActionState?.isOutdated ?? false;
@@ -1325,7 +1342,7 @@ export function SkillhubDetailView() {
const rejectionFeedback = useRejectionFeedback({
entryKey: entryInfoKey,
- name: entry?.name ?? null,
+ name: entryMarketName ?? null,
version: publishedStatus === 'rejected' ? effectivePublishedStatusVersion(publishedStatusSource) : null,
canManage: publishDetailState?.canManage === true,
});
@@ -1374,6 +1391,14 @@ export function SkillhubDetailView() {
setPublishOpen(true);
}, [entry, identityPolicy.canWrite, isPublishedReviewing, confirm, t]);
+ useEffect(() => {
+ if (searchParams.get('action') !== 'publish' || !detailReady
+ || !hasPublishableChanges(publishComparison) || effectivePublishInfo?.isCreator !== true
+ || !identityPolicy.canWrite || entry?.builtIn) return;
+ setSearchParams((previous) => { const next = new URLSearchParams(previous); next.delete('action'); return next; }, { replace: true });
+ void openPublish();
+ }, [searchParams, setSearchParams, detailReady, publishComparison, effectivePublishInfo?.isCreator, identityPolicy.canWrite, entry?.builtIn, openPublish]);
+
// installed-from-market 视图的卸载/更新动作。
// 跟 SkillhubMarketListView 走同一条 IPC,保持后端逻辑唯一。
const [marketActionRunning, setMarketActionRunning] = useState(false);
@@ -1395,7 +1420,7 @@ export function SkillhubDetailView() {
setMarketActionRunning(true);
try {
const res = await window.electronAPI.skillhub.install({
- name: entry.name,
+ name: entry.registrySkillName ?? entry.name,
installPath: entry.absolutePath,
version: latestVersion,
catalogScope: entry.registryEntry?.catalogScope,
@@ -1410,7 +1435,7 @@ export function SkillhubDetailView() {
// 抓着旧 hash 不放——不主动 invalidate,按钮区会用旧 localHash 跟新
// serverHash 比对,误命中 isMineDirty 分支显示「发布新版本」。
invalidateHash(entry.absolutePath);
- invalidateInfo(entry.name);
+ invalidateInfo(entry.registrySkillName ?? entry.name);
setInfoFetchTrigger((n) => n + 1);
void refreshSkillhub();
} else if (res.errorCode !== 'CANCELLED') {
@@ -1811,7 +1836,7 @@ export function SkillhubDetailView() {
onClick={() => {
clearLastEntryId();
clearHistory();
- backToCatalog();
+ navigate(backTargetRoute, { state: { skillhubHome: navState?.skillhubHome } });
}}
className="text-[var(--msg-assistant-text)] underline-offset-2 hover:underline"
>
@@ -1839,48 +1864,10 @@ export function SkillhubDetailView() {
(!!entry.frontmatter && Object.keys(entry.frontmatter).length > 0);
return (
- <div
- className="flex h-full w-full flex-col motion-safe:animate-[detail-soft-in_220ms_ease-out]"
- style={{
- // 内层 fade — 叠在 MainLayout FadeSwitcher 的 220ms 0→1 之上,
- // 专门软化 detail 数据加载完成那一刻的"硬切"感:
- // FadeSwitcher 让外壳渐入,这里让填入的内容也带一点透明度起步,
- // 两层组合后用户感知到的是"逐渐浮现",不是"啪一下出现"。
- // motion-safe: 尊重 prefers-reduced-motion,无障碍偏好关闭后直接显示。
- }}
- >
- {/* ─── Top toolbar ─────────────────────────────────────────
- Detail Top Bar 规格:
- height: 72 → h-[72px]
- padding: [0,24,0,16] → pl-4 pr-6
- gap: 16 → gap-4
- chips + path 在 72px 高度内对齐,与「编辑 / 发布」按钮 (h-9) 视觉协调。
- mac 上本页不渲染通用 ContentHeader,toolbar 行承担窗口拖拽,行内交互
- 元素各自 no-drag(windowDrag.tsx 约定)。 */}
- <div
- className="flex h-[72px] w-full shrink-0 items-center gap-4 border-b border-[var(--cmd-palette-border)] pl-4 pr-6"
- style={WINDOW_DRAG_STYLE}
- >
- <Tip text={backLabel}>
- <button
- type="button"
- onClick={goBack}
- className={cn(
- 'flex h-9 w-9 items-center justify-center rounded-full',
- 'text-[var(--settings-section-desc)] hover:bg-[var(--surface-hover)]',
- )}
- style={WINDOW_NO_DRAG_STYLE}
- aria-label={backLabel}
- >
- <ArrowLeft size={18} />
- </button>
- </Tip>
-
- <div className="flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden">
- <div className="flex min-w-0 items-center gap-2">
- <h2 className="min-w-0 truncate text-lg font-medium leading-none text-[var(--msg-assistant-text)]">
- {(entry.frontmatter?.displayName as string) || (entry.frontmatter?.name as string) || entry.name}
- </h2>
+ <SkillDetailPage>
+ <SkillDetailHeader
+ title={(entry.frontmatter?.displayName as string) || (entry.frontmatter?.name as string) || entry.name}
+ badges={<>
{entry.builtIn && <OfficialSkillBadge />}
<KindChip kind={entry.kind} />
<ScopeChip scope={entry.scope} />
@@ -1924,7 +1911,8 @@ export function SkillhubDetailView() {
</button>
</Tip>
)}
- </div>
+ </>}
+ subtitle={
<button
type="button"
onClick={() => {
@@ -1949,9 +1937,11 @@ export function SkillhubDetailView() {
>
{entry.absolutePath}
</button>
- </div>
-
- {/* v0.2.2 edit-mode actions: when editMode is on, show Cancel + Save
+ }
+ backLabel={backLabel}
+ onBack={() => { void goBack(); }}
+ actions={<>
+ {/* v0.2.2 edit-mode actions: when editMode is on, show Cancel + Save
and hide everything else (publish UI / tag) to avoid ambiguity.
View-mode actions live in the else-branch below. */}
{editMode ? (
@@ -2021,7 +2011,8 @@ export function SkillhubDetailView() {
onUninstalled={() => {
clearLastEntryId();
clearHistory();
- backToCatalog();
+ if (onUninstalled) onUninstalled();
+ else navigate(backTargetRoute, { state: { skillhubHome: navState?.skillhubHome } });
}} />}
{/* 编辑入口 */}
{!editButtonState.hidden && (
@@ -2196,7 +2187,9 @@ export function SkillhubDetailView() {
)}
</div>
)}
- </div>
+ </>}
+ />
+ {renderNavigation?.(requestLeaveEditMode, saving || marketActionRunning)}
{/* v0.2.2: save-error banner — only in edit mode after a failed save.
Stays put while user retries (doesn't auto-dismiss).
@@ -2219,6 +2212,7 @@ export function SkillhubDetailView() {
detailState is null until skill+infoResult arrive (detailReady guard). */}
{!editMode && isSkill && detailReady && detailState && (
<>
+ <SkillPublishComparisonNotice comparison={publishComparison} isCreator={effectivePublishInfo?.isCreator} />
{/* mine + dirty: local changes not yet published */}
{isMineDirty && (
<div className="shrink-0 pl-3 pr-3 pt-4">
@@ -2234,14 +2228,16 @@ export function SkillhubDetailView() {
>
<AlertTriangle size={16} className="shrink-0 text-[var(--settings-section-desc)]" />
<span className="flex-1 text-sm font-medium text-[var(--msg-assistant-text)]">
- {t('skillhub.detail.bannerLocalChanges')}
+ {t(publishComparison.status === 'different' && publishComparison.pending
+ ? 'skillhub.publishComparison.pendingChanges'
+ : 'skillhub.publishComparison.updateAvailable')}
</span>
<span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">{t('skillhub.detail.bannerSeeChanges')}</span>
</button>
</div>
)}
{/* outdated: 另一台设备发布了新版,本地版本号已落后 */}
- {isOutdated && publishDetailState?.canManage && entry.registryEntry && (
+ {isOutdated && effectivePublishInfo?.isCreator && entry.registryEntry && (
<div className="shrink-0 pl-3 pr-3 pt-4">
<button
type="button"
@@ -2308,14 +2304,7 @@ export function SkillhubDetailView() {
- command / agent: single-pane — frontmatter folds into the top
of the markdown column, since there are no sibling files to
list and the meta is small enough to coexist with the body. */}
- <div
- className={cn(
- // relative: 锚点。变更面板(floating 浮卡)挂在本容器内,贴正文区
- // inset 浮出 —— 不再写死 top 像素,顶栏多高都不会错位。
- 'relative flex min-h-0 flex-1 w-full',
- showFiles && !editMode && metaResize.isDragging && 'select-none cursor-col-resize',
- )}
- >
+ <SkillDetailColumns resizing={showFiles && !editMode && metaResize.isDragging}>
{/* Left aside (Files + Usage) — hidden in edit mode so the
text editor takes the full main area. Frontmatter stays in the
same source buffer instead of occupying a separate left column. */}
@@ -2323,10 +2312,7 @@ export function SkillhubDetailView() {
// 可调宽左栏。Frontmatter 已经移到右侧正文上方;这里保留文件树
// 和本机使用表现,让用户先定位文件,再看这个 skill 的实际表现。
// px-3 让文件树文字贴近 resize handle,左栏读起来更像紧凑导航。
- <aside
- className="relative flex h-full shrink-0 select-text flex-col gap-4 overflow-y-auto border-r border-[var(--cmd-palette-border)] px-3 py-4"
- style={{ width: metaResize.width }}
- >
+ <SkillDetailSidebar width={metaResize.width}>
<section className="flex flex-col gap-1">
<h3 className="mb-2 text-xs font-medium uppercase tracking-wider text-[var(--cmd-palette-item-meta)]">
{t('skillhub.detail.filesTitle')}
@@ -2370,30 +2356,8 @@ export function SkillhubDetailView() {
{/* Resize handle — same pattern as the main sidebar: 4px transparent
hit area, 1px highlight line on hover, double-click to reset. */}
- <hr
- aria-orientation="vertical"
- aria-valuemin={metaResize.minWidth}
- aria-valuemax={metaResize.maxWidth}
- aria-valuenow={metaResize.width}
- aria-label={t('skillhub.detail.resizeUsageFilesColumn')}
- tabIndex={0}
- className="absolute right-0 top-0 z-10 m-0 h-full w-[4px] cursor-col-resize border-0 bg-transparent p-0 transition-colors hover:bg-[var(--file-chip-bg)] focus-visible:bg-[var(--file-chip-bg)] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--settings-theme-icon)]"
- onPointerDown={metaResize.handleDragStart}
- onDoubleClick={metaResize.resetWidth}
- onKeyDown={(event) => {
- if (event.key === 'ArrowLeft') {
- event.preventDefault();
- metaResize.resizeByKeyboard(-1, event.shiftKey);
- } else if (event.key === 'ArrowRight') {
- event.preventDefault();
- metaResize.resizeByKeyboard(1, event.shiftKey);
- } else if (event.key === 'Enter') {
- event.preventDefault();
- metaResize.resetWidth();
- }
- }}
- />
- </aside>
+ <SkillDetailResizeHandle resize={metaResize} />
+ </SkillDetailSidebar>
)}
{/* Right pane: file content (and the frontmatter strip prepended
@@ -2401,20 +2365,7 @@ export function SkillhubDetailView() {
dispatch as TextLightbox (see lib/textPreview.ts). In edit mode
the pane drops its padding + scroll handling so PlaintextEditor can
use its own flex-fill layout and internal scrolling. */}
- <div
- className={cn(
- 'flex min-w-0 flex-1 flex-col',
- editMode
- ? 'overflow-hidden'
- : cn(
- 'overflow-y-auto px-8 pb-8',
- // No inline frontmatter → drop the top padding so a single
- // .md without frontmatter sits flush against the toolbar
- // instead of floating below empty space.
- showInlineFrontmatter || showFiles ? 'pt-8' : 'pt-2',
- ),
- )}
- >
+ <SkillDetailContent editing={editMode} compact={!showInlineFrontmatter && !showFiles}>
{/* In single-pane (command / agent) layout the frontmatter strip
only earns its real estate if it actually has something to
show — empty frontmatter just becomes wasted vertical space
@@ -2524,7 +2475,7 @@ export function SkillhubDetailView() {
</pre>
);
})()}
- </div>
+ </SkillDetailContent>
{/* Diff panel — 浮层卡片(market 详情浮层同款),锚定在本 body 的
relative 容器内、贴正文区 inset 浮出,不吃顶栏高度。始终挂载让
滑入动画生效;切换 entry 时 DetailView 走 FadeSwitcher 整体重挂,
@@ -2533,18 +2484,20 @@ export function SkillhubDetailView() {
<SkillhubDiffPanel
open={diffPanelOpen}
onClose={() => setDiffPanelOpen(false)}
- skillName={entry.name}
+ skillName={entryMarketName ?? entry.name}
absolutePath={entry.absolutePath}
+ skillId={entry.id}
+ published={effectivePublishInfo?.isCreator === true}
/>
)}
- </div>
+ </SkillDetailColumns>
{/* v0.2.1: PublishDialog — only rendered for skill kind */}
{isSkill && entry && (
<PublishDialog
open={publishOpen}
onOpenChange={setPublishOpen}
- skill={entry}
+ skill={publishSkill ?? entry}
isFirstPublish={!publishDetailState || detailAction?.kind === 'publish-to-market'}
autoCleanName={
detailState?.origin === null &&
@@ -2567,14 +2520,14 @@ export function SkillhubDetailView() {
// 最后导航到新 URL。先 await refresh 才 navigate,确保新 URL 落地时
// skills 已包含新 entry,免得短暂闪一下"未找到"。
const owner = getDataOwnerGeneration();
- invalidateInfo(entry.name);
+ invalidateInfo(entry.registrySkillName ?? entry.name);
invalidateHash(newAbsolutePath);
void refreshSkillhub().then((scannedSkills) => {
if (!isDataOwnerIdCurrent(owner)) return;
const renamed = findLocalSkillByPath(scannedSkills, newAbsolutePath);
if (!renamed) return;
setLastEntryId(renamed.id);
- replaceLocalSkill(renamed);
+ navigate(withSkillDetailReturn(buildLocalSkillRoute(renamed), backTargetRoute), { replace: true, state: location.state });
});
}}
onScanResult={setScanResult}
@@ -2593,6 +2546,6 @@ export function SkillhubDetailView() {
onClose={() => { rejectionFeedback.dismiss(); setScanResult(null); }}
result={rejectionFeedback.result ?? scanResult}
/>
- </div>
+ </SkillDetailPage>
);
}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDiffPanel.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDiffPanel.tsx
index a0c56cb8f4..86bc62dc23 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDiffPanel.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDiffPanel.tsx
@@ -1,5 +1,5 @@
/**
- * SkillhubDiffPanel — 右侧滑入面板,展示当前 skill 与上次发布快照的文件级 diff。
+ * SkillhubDiffPanel — 原作者比较线上具体版本;其他本地修改保留安装快照 diff。
*
* 触发:DetailView 里点 mine-dirty banner → setOpen(true)。
*
@@ -22,6 +22,7 @@ import { FileDiff as FileDiffIcon } from 'lucide-react';
import { DiffPanelShell } from '@/components/diff-panel/DiffPanelShell';
import { FileChangeGroup, type FileChange } from '@/components/diff-panel/FileChangeGroup';
import { computeDiffStats } from '@/lib/agent-actions/diffStats';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
interface SkillhubDiffPanelProps {
open: boolean;
@@ -30,6 +31,8 @@ interface SkillhubDiffPanelProps {
skillName: string;
/** Skill 在本机的绝对路径 — IPC 用它读当前文件。 */
absolutePath: string;
+ skillId?: string;
+ published?: boolean;
}
type LoadState =
@@ -37,9 +40,9 @@ type LoadState =
| { kind: 'loading' }
| { kind: 'no-snapshot' }
| { kind: 'error'; message: string }
- | { kind: 'ready'; changes: FileChange[] };
+ | { kind: 'ready'; changes: FileChange[]; version?: string };
-export function SkillhubDiffPanel({ open, onClose, skillName, absolutePath }: SkillhubDiffPanelProps) {
+export function SkillhubDiffPanel({ open, onClose, skillName, absolutePath, skillId, published }: SkillhubDiffPanelProps) {
const { t } = useTranslation();
const [state, setState] = useState<LoadState>({ kind: 'idle' });
@@ -50,11 +53,29 @@ export function SkillhubDiffPanel({ open, onClose, skillName, absolutePath }: Sk
return;
}
let cancelled = false;
+ const owner = getDataOwnerGeneration();
setState({ kind: 'loading' });
+ if (published) {
+ window.electronAPI.skillhub.comparePublished({ absolutePath, skillId, includeDiff: true })
+ .then((res) => {
+ if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
+ if (res.status !== 'same' && res.status !== 'different') {
+ setState({ kind: 'error', message: t('skillhub.publishComparison.unavailable') });
+ return;
+ }
+ setState({ kind: 'ready', version: res.version, changes: res.changes ?? [] });
+ })
+ .catch(() => {
+ if (!cancelled && isDataOwnerGenerationCurrent(owner)) {
+ setState({ kind: 'error', message: t('skillhub.publishComparison.unavailable') });
+ }
+ });
+ return () => { cancelled = true; };
+ }
window.electronAPI.skillhub
.getSnapshotDiff({ absolutePath, name: skillName })
.then((res) => {
- if (cancelled) return;
+ if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
if (!res.success) {
setState({ kind: 'error', message: res.error ?? 'unknown error' });
return;
@@ -66,7 +87,7 @@ export function SkillhubDiffPanel({ open, onClose, skillName, absolutePath }: Sk
setState({ kind: 'ready', changes: res.changes ?? [] });
})
.catch((err: unknown) => {
- if (cancelled) return;
+ if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
setState({
kind: 'error',
message: err instanceof Error ? err.message : String(err),
@@ -75,7 +96,7 @@ export function SkillhubDiffPanel({ open, onClose, skillName, absolutePath }: Sk
return () => {
cancelled = true;
};
- }, [open, absolutePath, skillName]);
+ }, [open, absolutePath, skillName, skillId, published, t]);
// 汇总 +/- 计数(只对 ready 状态算)
const totals = useMemo(() => {
@@ -97,7 +118,9 @@ export function SkillhubDiffPanel({ open, onClose, skillName, absolutePath }: Sk
onClose={onClose}
variant="floating"
ariaLabel={t('skillhub.diffPanel.ariaLabel')}
- title={t('skillhub.diffPanel.title')}
+ title={state.kind === 'ready' && state.version
+ ? t('skillhub.publishComparison.diffTitle', { version: state.version })
+ : t('skillhub.diffPanel.title')}
defaultWidth={560}
storageKey="diff-panel-shell:skillhub-width"
rightHeader={
@@ -119,7 +142,7 @@ export function SkillhubDiffPanel({ open, onClose, skillName, absolutePath }: Sk
) : (
<ul className="flex flex-col gap-2 p-3">
{state.changes.map((c) => (
- <FileChangeGroup key={c.path} change={c} />
+ <FileChangeGroup key={c.path} change={c} summaryOnly={published && c.isBinary} />
))}
</ul>
))}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
index 68977bf366..c2c600b08c 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx
@@ -71,7 +71,9 @@ export function useSkillhubStoreSync(): void {
const itemKeys: Array<{ name: string; key: string }> = [];
for (const s of skills) {
if (s.kind !== 'skill') continue;
- const sync = syncResults.get(skillhubCatalogKey(s.name, s.registryEntry?.catalogScope));
+ const name = s.registrySkillName ?? s.name;
+ const catalogKey = skillhubCatalogKey(name, s.registryEntry?.catalogScope);
+ const sync = syncResults.get(catalogKey);
if (!sync?.exists || !sync.isMine) continue;
const serverAuthorId = sync.authorId ?? '';
if (!serverAuthorId) continue; // server 没回 authorId 就别回填
@@ -88,10 +90,10 @@ export function useSkillhubStoreSync(): void {
);
if (!needsAuthorId && !needsOrigin) continue;
}
- const key = `${s.name}\u0000${s.absolutePath}\u0000${serverAuthorId}`;
+ const key = `${catalogKey}\u0000${s.absolutePath}\u0000${serverAuthorId}`;
if (reconciledKeysRef.current.has(key)) continue;
items.push({
- name: s.name,
+ name,
absolutePath: s.absolutePath,
version: latestVersion,
authorId: serverAuthorId,
@@ -99,7 +101,7 @@ export function useSkillhubStoreSync(): void {
? { folderHash: sync.folderHash }
: {}),
});
- itemKeys.push({ name: s.name, key });
+ itemKeys.push({ name, key });
}
if (items.length === 0) {
return;
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
index 322e52f8e9..3f0d2d7f57 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
@@ -6,8 +6,10 @@
* 公开、可选的组织目录和本地技能在同一行切换;“更多”进入完整 Market。
*/
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useNavigate, type Location } from 'react-router-dom';
+import { buildMarketSkillRoute, withSkillDetailReturn } from './lib/detailRoutes';
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useNavigate, useSearchParams, type Location } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { skillhubCatalogKey } from '../../../shared/skillhubCatalog';
import { CATEGORY_ALL } from '../../../shared/skillhubCategory';
@@ -30,23 +32,20 @@ import {
PluginManagementLayout,
PluginManagementPage,
} from '@/features/plugin/PluginManagementLayout';
-import { findLocalSkillByPath } from './lib/localRoutes';
+import { buildLocalSkillRoute, findLocalSkillByPath } from './lib/localRoutes';
import {
builtInSkillDescriptionKey,
prioritizeCindyBuiltInSkills,
} from './lib/builtInSkillPresentation';
import { refresh as refreshSkillhub, useSkillhub } from './hooks/useSkillhub';
-import { useSkillhubHomeNavigation } from './hooks/useSkillhubHomeNavigation';
import {
MARKET_PAGE_SIZE,
useCategoryList,
useMarketList,
type MarketSkill,
} from './hooks/useMarketList';
-import { MarketManagementDialogs, useMarketManagement } from './hooks/useMarketManagement';
import { basename, deriveProjectWorkingDir } from './lib/pathDerivations';
import { projectHash } from './lib/projectHash';
-import { marketCardPrimaryAction } from './lib/marketDetailViewModel';
import {
homeMarketQuery,
isHomeMarketResponseCurrent,
@@ -56,11 +55,13 @@ import {
import { deriveSkillSource } from './lib/skillSource';
import { InstallTargetPicker, type InstallTargetSkill } from './components/InstallTargetPicker';
import { SkillCategoryFilterBar } from './components/SkillCategoryFilterBar';
+import { MarketListError } from './components/MarketListError';
import { HomeMarketCard } from './components/HomeMarketCard';
import { SkillIcon } from './components/SkillIcon';
+import { SkillPublishUpdateHint } from './SkillPublishUpdateHint';
import { OfficialSkillBadge } from './components/OfficialSkillBadge';
-import { SkillhubMarketPreviewPanel } from './SkillhubMarketPreviewPanel';
-import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
+import { useSkillhubHomeNavigation } from './hooks/useSkillhubHomeNavigation';
+import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
const KIND_ICON: Record<string, LucideIcon> = {
skill: Package,
@@ -86,13 +87,14 @@ export function SkillhubHomeView({
} = {}) {
const { t } = useTranslation();
const navigate = useNavigate();
- const { skills, projects, bootstrapped, learnSkillEnabled, syncResults } = useSkillhub();
- const { catalogTab, query, setCatalogTab, setQuery, openLocalSkill } = useSkillhubHomeNavigation(navigationLocation);
+ const [initialSearch] = useSearchParams();
+ const { skills, projects, bootstrapped, syncResults } = useSkillhub();
+ const { catalogTab, query, setCatalogTab, setQuery } = useSkillhubHomeNavigation(navigationLocation);
const normalizedQuery = query.trim().toLocaleLowerCase();
// 未登录也请求公开 Skill 目录;登录身份只扩大服务端可见范围。
const { user } = useAuth();
- const identityPolicy = useSkillhubIdentityPolicy(user);
+ const marketUpdate = useMarketSkillUpdate();
const showOrganization = user?.membershipKind === 'org';
const marketFilter: HomeMarketFilter = catalogTab === 'organization' ? 'organization' : 'public';
const marketRequest = useMemo(() => homeMarketQuery(marketFilter), [marketFilter]);
@@ -102,6 +104,8 @@ export function SkillhubHomeView({
items: marketItems,
loading: marketLoading,
loadingMore: marketLoadingMore,
+ error: marketError,
+ reload: reloadMarket,
hasMore: marketHasMore,
resolvedScope,
resolvedMine,
@@ -112,26 +116,29 @@ export function SkillhubHomeView({
setCategoryFilter,
setVisibility,
loadMore: loadMoreMarket,
- reload: reloadMarket,
} = useMarketList('all', {
- enabled: catalogTab !== 'local',
+ enabled: active && catalogTab !== 'local',
initialScope: 'market',
initialSort: 'trending',
+ initialSearchQuery: initialSearch.get('q') ?? '',
+ initialCategoryFilter: initialSearch.get('category') ?? CATEGORY_ALL,
});
const categoryScope = marketRequest.scope === 'team' ? 'team' : 'market';
const { categories } = useCategoryList(categoryScope);
+ const previousMarketRequest = useRef(marketRequest);
useEffect(() => {
setCatalogScope(marketRequest.scope);
setVisibility(marketRequest.visibility);
setSortBy(marketRequest.sort);
- setCategoryFilter(CATEGORY_ALL);
+ if (previousMarketRequest.current !== marketRequest) setCategoryFilter(CATEGORY_ALL);
+ previousMarketRequest.current = marketRequest;
}, [marketRequest, setCatalogScope, setCategoryFilter, setSortBy, setVisibility]);
useEffect(() => {
setSearchQuery(query);
}, [query, setSearchQuery]);
useEffect(() => {
- if (active && !showOrganization && catalogTab === 'organization') setCatalogTab('public');
- }, [active, catalogTab, setCatalogTab, showOrganization]);
+ if (!showOrganization && catalogTab === 'organization') setCatalogTab('public');
+ }, [catalogTab, showOrganization]);
const marketResponseCurrent = isHomeMarketResponseCurrent(marketRequest, {
scope: resolvedScope,
mine: resolvedMine,
@@ -204,32 +211,19 @@ export function SkillhubHomeView({
? visibleLocalCount > 0
: catalogItems.length > 0;
- // 推荐技能的预览浮层 + 安装选择器(复用 Market 那套):点推荐卡 = 下一步直接
- // 进入该技能的预览;关闭 = 回退到首页。
- const [previewSkill, setPreviewSkill] = useState<MarketSkill | null>(null);
- const [pickerSkill, setPickerSkill] = useState<MarketSkill | null>(null);
- const [pickerOpen, setPickerOpen] = useState(false);
-
// 本地导入:main 选择并检查文件 → 安装位置选择器 → 凭授权导入
const [importGrantToken, setImportGrantToken] = useState<string | null>(null);
const [importTarget, setImportTarget] = useState<InstallTargetSkill | null>(null);
const [importPickerOpen, setImportPickerOpen] = useState(false);
const [importBusy, setImportBusy] = useState(false);
- const openMarket = () => navigate('/skillhub/market');
- const openCatalogSkill = (skill: MarketSkill) => setPreviewSkill(skill);
- const handleClone = (skill: MarketSkill) => {
- setPickerSkill(skill);
- setPickerOpen(true);
+ const returnTo = `/skillhub/local?${new URLSearchParams({ tab: catalogTab, q: query, category: categoryFilter })}`;
+ const openLocal = (local: SkillhubSkill) => {
+ const route = withSkillDetailReturn(buildLocalSkillRoute(local), returnTo);
+ navigate(route, { state: { from: '/skillhub/local', resetHistory: true, skillhubHome: { catalogTab, query } } });
};
- const management = useMarketManagement({
- active: false,
- reload: reloadMarket,
- onClone: handleClone,
- onDeleted: (skill) => {
- if (previewSkill?.name === skill.name) setPreviewSkill(null);
- },
- });
+ const openMarket = () => navigate('/skillhub/market');
+ const openCatalogSkill = (skill: MarketSkill) => navigate(buildMarketSkillRoute(skill, returnTo));
const homeCatalogTabs = visibleHomeCatalogTabs(showOrganization);
const handleImportSkill = useCallback(async () => {
@@ -263,14 +257,6 @@ export function SkillhubHomeView({
setImportTarget(null);
}, []);
- useEffect(() => {
- if (active) return;
- setPreviewSkill(null);
- setPickerSkill(null);
- setPickerOpen(false);
- closeImportPicker();
- }, [active, closeImportPicker]);
-
return (
<PluginManagementLayout
activeTab="skills"
@@ -326,7 +312,6 @@ export function SkillhubHomeView({
optionClassName="px-3.5 text-12"
value={catalogTab}
onValueChange={(tab) => {
- setPreviewSkill(null);
setCatalogTab(tab);
}}
options={homeCatalogTabs.map((tab) => ({
@@ -353,7 +338,7 @@ export function SkillhubHomeView({
</header>
{/* ① 当前云端目录摘要 */}
- {catalogTab !== 'local' && (!normalizedQuery || catalogItems.length > 0 || marketLoading) ? (
+ {catalogTab !== 'local' && (!normalizedQuery || catalogItems.length > 0 || marketLoading || marketError) ? (
<section className="plugin-motion-page-section min-w-0">
{categories.length > 0 ? (
<SkillCategoryFilterBar
@@ -370,6 +355,7 @@ export function SkillhubHomeView({
/>
) : null}
+ <MarketListError error={marketError} loading={marketLoading} onRetry={reloadMarket} />
{(marketLoading || !marketResponseCurrent) && catalogItems.length === 0 ? (
// 占位骨架:与真实卡片同栅格、同行数、同高度,内容到位后原地替换不跳动。
<div className={PLUGIN_MANAGEMENT_CARD_GRID_CLASS} aria-hidden>
@@ -388,14 +374,20 @@ export function SkillhubHomeView({
</div>
))}
</div>
- ) : catalogItems.length === 0 ? (
+ ) : marketError && catalogItems.length === 0 ? null : catalogItems.length === 0 ? (
<div className="rounded-[12px] border-[0.5px] border-[var(--border-default)] px-4 py-5 text-13 leading-5 text-[var(--text-secondary)]">
{t('skillhub.home.catalogEmpty')}
</div>
) : (
<div className={cn('plugin-motion-stagger', PLUGIN_MANAGEMENT_CARD_GRID_CLASS)}>
{catalogItems.map((s) => (
- <HomeMarketCard key={skillhubCatalogKey(s.name, s.catalogScope)} skill={s} onClick={openCatalogSkill} />
+ <HomeMarketCard
+ key={skillhubCatalogKey(s.name, s.catalogScope)}
+ skill={s}
+ onClick={openCatalogSkill}
+ onUpdate={user ? marketUpdate.update : undefined}
+ updating={marketUpdate.updatingNames.has(s.name)}
+ />
))}
{marketResponseCurrent && marketHasMore ? (
<div className="col-span-full flex justify-center pt-1">
@@ -435,7 +427,8 @@ export function SkillhubHomeView({
<LocalGroup
skills={globalSkills}
syncResults={syncResults}
- onOpen={openLocalSkill}
+ active={active}
+ onOpen={openLocal}
/>
)}
{projectGroups.map((g) => (
@@ -444,7 +437,8 @@ export function SkillhubHomeView({
label={g.label}
skills={g.skills}
syncResults={syncResults}
- onOpen={openLocalSkill}
+ active={active}
+ onOpen={openLocal}
/>
))}
</div>
@@ -460,93 +454,59 @@ export function SkillhubHomeView({
</PluginManagementPage>
</main>
- {/* Keep the preview outside the list scroller so it stays anchored to the viewport. */}
- {active && (
- <>
- <SkillhubMarketPreviewPanel
- open={previewSkill !== null}
- skill={previewSkill}
- onClose={() => setPreviewSkill(null)}
- primaryAction={
- previewSkill && user
- ? (() => {
- const action = marketCardPrimaryAction({
- isMine: previewSkill.isMine,
- listVisibility: 'all',
- cardState: previewSkill.cardState,
- });
- return action === 'manage' && !identityPolicy.canWrite ? 'clone' : action;
- })()
- : 'none'
- }
- onClone={handleClone}
- onManageAction={management.handleManageAction}
- learnSkillEnabled={learnSkillEnabled}
- />
- <MarketManagementDialogs controller={management} />
- <InstallTargetPicker
- open={pickerOpen}
- skill={pickerSkill}
- onClose={() => setPickerOpen(false)}
- onInstallComplete={() => {
- void refreshSkillhub();
- setPickerOpen(false);
- // 安装后关掉预览浮层:否则它仍持有 stale previewSkill、CTA 继续显示「安装/克隆」,
- // 可被重复点安装(PR #246 review)。
- setPreviewSkill(null);
- }}
- />
- <InstallTargetPicker
- open={importPickerOpen}
- skill={importTarget}
- onClose={closeImportPicker}
- titleKey="skillhub.home.importPickerTitle"
- subtitleKey="skillhub.home.importPickerSubtitle"
- successToastKey="skillhub.home.importSuccess"
- failedToastKey="skillhub.home.importFailed"
- runAction={async ({ installPath, force }) => {
- if (!importGrantToken) {
- return {
- success: false,
- errorCode: 'INVALID_FILE',
- message: t('skillhub.home.importFailed'),
- };
- }
- return window.electronAPI.skillhub.importLocal({
- grantToken: importGrantToken,
- installPath,
- force,
- });
- }}
- onInstallComplete={(result) => {
- closeImportPicker();
- if (!result?.name) return;
- void refreshSkillhub().then((scannedSkills) => {
- const imported = result.absolutePath
- ? findLocalSkillByPath(scannedSkills, result.absolutePath)
- : undefined;
- if (imported) {
- openLocalSkill(imported);
- return;
- }
- const projectRoot = result.absolutePath
- ? deriveProjectWorkingDir(result.absolutePath)
- : null;
- const fallback = {
- id: '',
- absolutePath: result.absolutePath ?? '',
- engine: 'claude-code' as const,
- kind: 'skill' as const,
- scope: projectRoot ? ('project' as const) : ('global' as const),
- projectHash: projectRoot ? projectHash(projectRoot) : undefined,
- name: result.name,
- };
- openLocalSkill(fallback);
+ <InstallTargetPicker
+ open={active && importPickerOpen}
+ skill={importTarget}
+ onClose={closeImportPicker}
+ titleKey="skillhub.home.importPickerTitle"
+ subtitleKey="skillhub.home.importPickerSubtitle"
+ successToastKey="skillhub.home.importSuccess"
+ failedToastKey="skillhub.home.importFailed"
+ runAction={async ({ installPath, force }) => {
+ if (!importGrantToken) {
+ return {
+ success: false,
+ errorCode: 'INVALID_FILE',
+ message: t('skillhub.home.importFailed'),
+ };
+ }
+ return window.electronAPI.skillhub.importLocal({
+ grantToken: importGrantToken,
+ installPath,
+ force,
+ });
+ }}
+ onInstallComplete={(result) => {
+ closeImportPicker();
+ if (!result?.name) return;
+ void refreshSkillhub().then((scannedSkills) => {
+ const imported = result.absolutePath
+ ? findLocalSkillByPath(scannedSkills, result.absolutePath)
+ : undefined;
+ if (imported) {
+ navigate(buildLocalSkillRoute(imported), {
+ state: { from: '/skillhub/local', resetHistory: true, skillhubHome: { catalogTab, query } },
});
- }}
- />
- </>
- )}
+ return;
+ }
+ const projectRoot = result.absolutePath
+ ? deriveProjectWorkingDir(result.absolutePath)
+ : null;
+ const fallback = {
+ id: '',
+ absolutePath: result.absolutePath ?? '',
+ engine: 'claude-code' as const,
+ kind: 'skill' as const,
+ scope: projectRoot ? ('project' as const) : ('global' as const),
+ projectHash: projectRoot ? projectHash(projectRoot) : undefined,
+ name: result.name,
+ };
+ navigate(buildLocalSkillRoute(fallback), {
+ state: { from: '/skillhub/local', resetHistory: true, skillhubHome: { catalogTab, query } },
+ });
+ });
+ }}
+ />
</div>
</PluginManagementLayout>
);
@@ -556,10 +516,12 @@ function LocalGroup({
label,
skills,
syncResults,
+ active,
onOpen,
}: {
label?: string;
skills: SkillhubSkill[];
+ active: boolean;
/** server 归属结果(含 isMine),用于历史遗留 registry(origin 缺失)的来源推断 */
syncResults: Map<string, SkillhubSyncResult>;
onOpen: (s: SkillhubSkill) => void;
@@ -576,7 +538,7 @@ function LocalGroup({
// 来源:'skillhub' = 从市场安装的副本(填充徽标);'local' = 自己开发/发布、
// 没走 SkillHub 安装的本地副本(弱化文字,不与 SkillHub 抢视觉)。
// origin 缺失的历史 registry 靠 server isMine 兜底判定(见 deriveSkillSource)。
- const sync = syncResults.get(skillhubCatalogKey(s.name, s.registryEntry?.catalogScope));
+ const sync = syncResults.get(skillhubCatalogKey(s.registrySkillName ?? s.name, s.registryEntry?.catalogScope));
const isMine = sync?.exists === true ? sync.isMine : null;
const source = deriveSkillSource(
s.registryEntry?.origin,
@@ -624,6 +586,7 @@ function LocalGroup({
{displayDescription}
</span>
)}
+ <SkillPublishUpdateHint skill={s} knownCreator={active && sync?.exists === true && sync.isCreator === true} />
</span>
<span className="mt-1 flex size-7 shrink-0 items-center justify-center rounded-lg border border-transparent text-[var(--text-secondary)] transition-[background-color,color,transform] group-hover:translate-x-0.5 group-hover:bg-[var(--surface-chip)] group-hover:text-[var(--text-primary)] group-active:translate-x-0 group-active:scale-95">
<ChevronRight size={15} strokeWidth={1.8} />
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx
similarity index 77%
rename from apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx
rename to apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx
index c6d01534ec..306f5b1da6 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx
@@ -1,10 +1,12 @@
+import { SkillDetailPage, SkillDetailHeader, SkillDetailColumns, SkillDetailSidebar, SkillDetailContent, SkillDetailResizeHandle } from './components/SkillDetailLayout';
+import { useMetaColumnResize } from './hooks/useMetaColumnResize';
+import { MarketInstallStatus } from './components/MarketInstallStatus';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { Download, FileText, GraduationCap, X } from 'lucide-react';
+import { Download, FileText, GraduationCap } from 'lucide-react';
import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';
import { Button } from '@/components/ui/button';
-import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { useAuth } from '@/contexts/AuthContext';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, type DataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import { useNavigate } from 'react-router-dom';
@@ -37,9 +39,13 @@ import { ManageMenu, type MarketCardManageAction } from './components/MarketCard
import { ScanResultDialog } from './ScanResultDialog';
import type { ScanResultPayload } from './PublishDialog';
-interface SkillhubMarketPreviewPanelProps {
+interface SkillhubMarketDetailViewProps {
skill: MarketSkill | null;
- open: boolean;
+ open?: boolean;
+ navigation?: ReactNode;
+ localActions?: ReactNode;
+ onUpdate?: (skill: MarketSkill) => void;
+ updating?: boolean;
onClose: () => void;
/** 与卡片同口径的主操作:clone / manage / none。头部据此渲染操作按钮 */
primaryAction?: MarketCardPrimaryAction;
@@ -49,24 +55,26 @@ interface SkillhubMarketPreviewPanelProps {
}
/**
- * Market skill 详情浮层 — 市场内唯一的详情表面(交互原型 v4)。
+ * Market content controller for the shared Skill detail page.
*
* 结构:
* Hero 头部 — 标题行(标题+可见性 chip | 操作按钮),元信息行,描述(满宽)
* 正文 — 左栏(FILES 树) + 右侧 Markdown
- * 遮罩盖整个内容区,sidebar 保持可见可点;头部显示本地安装位置及管理操作。
+ * Local operations are bound to the copy selected by the route.
*/
-export function SkillhubMarketPreviewPanel({
+export function SkillhubMarketDetailView({
skill,
- open,
+ open = true,
+ navigation, localActions, onUpdate, updating,
onClose,
primaryAction = 'none',
onClone,
onManageAction,
learnSkillEnabled = true,
-}: SkillhubMarketPreviewPanelProps) {
+}: SkillhubMarketDetailViewProps) {
const { t } = useTranslation();
const navigate = useNavigate();
+ const metaResize = useMetaColumnResize();
const { dataOwnerId } = useAuth();
const owner = getDataOwnerGeneration();
const skillName = skill?.name ?? null;
@@ -94,16 +102,6 @@ export function SkillhubMarketPreviewPanel({
return () => { scanRequestId.current += 1; };
}, [panelOpen, skillName, reviewVersion, status, skill?.catalogScope, skill?.canManage, dataOwnerId, owner]);
- // ESC 关闭
- useEffect(() => {
- if (!panelOpen) return undefined;
- const onKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape') onClose();
- };
- window.addEventListener('keydown', onKeyDown);
- return () => window.removeEventListener('keydown', onKeyDown);
- }, [panelOpen, onClose]);
-
useEffect(() => {
if (!panelOpen || !skillName) {
setFiles([]);
@@ -175,40 +173,14 @@ export function SkillhubMarketPreviewPanel({
const tree = useMemo(() => buildPreviewTree(files), [files]);
const currentScanResult = scanResultOwner && isDataOwnerGenerationCurrent(scanResultOwner) ? scanResult : null;
+ if (!panelOpen || !skill) return null;
return (
- <>
- {/* 遮罩 — 盖住整个内容区(含顶部筛选工具条),sidebar 保持可用 */}
- <div
- className={cn(
- 'absolute inset-0 z-30 bg-[var(--overlay-modal)] transition-opacity duration-200',
- panelOpen ? 'opacity-100' : 'pointer-events-none opacity-0',
- )}
- onClick={onClose}
- aria-hidden
- />
-
- <aside
- className={cn(
- 'absolute right-3 top-3 bottom-3 z-40 flex flex-col overflow-hidden',
- 'rounded-xl border border-[var(--cmd-palette-border)] bg-[var(--cmd-palette-bg)]',
- 'text-[var(--msg-assistant-text)] shadow-[var(--shadow-menu)]',
- 'transition-transform duration-200 ease-out',
- panelOpen ? 'translate-x-0' : 'pointer-events-none translate-x-[calc(100%+16px)]',
- )}
- style={{ width: 'min(1080px, calc(100% - 24px))', ...WINDOW_NO_DRAG_STYLE }}
- aria-hidden={!panelOpen}
- role="dialog"
- aria-label={t('skillhub.marketPreview.ariaLabel')}
- >
- {skill && (
- <div className="flex h-full min-h-0 flex-col">
- {/* Hero 头部 — 仅标题行与操作同排,元信息/描述满宽 */}
- <header className="shrink-0 border-b border-[var(--cmd-palette-border)] px-6 pb-5 pt-5">
- <div className="flex items-center gap-3">
- <div className="flex min-w-24 flex-1 items-center gap-2.5 overflow-hidden">
- <h2 className="truncate text-lg font-semibold leading-tight">
- {skill.displayName || skill.name}
- </h2>
+ <SkillDetailPage>
+ <SkillDetailHeader
+ title={skill.displayName || skill.name}
+ backLabel={t('skillhub.detail.backToSkillhub')}
+ onBack={onClose}
+ badges={<>
<span
className="inline-flex shrink-0 items-center justify-center rounded-full bg-[var(--chat-input-chip-bg)] text-[var(--settings-section-desc)]"
style={{ height: '20px', padding: '0 8px', fontSize: '11px' }}
@@ -258,9 +230,10 @@ export function SkillhubMarketPreviewPanel({
{t(publishedStatusLabelKey(status))}
</button>
) : null}
- </div>
-
- <div className="flex min-w-0 items-center gap-2 overflow-x-auto py-1">
+ </>}
+ subtitle={<p className="truncate text-xs text-[var(--cmd-palette-item-meta)]">{skillPublisherLabel(skill)} · {skill.name} · v{skill.latestVersion}</p>}
+ actions={<>
+ <MarketInstallStatus skill={skill} onUpdate={onUpdate} updating={updating} />
{primaryAction === 'clone' ? (
<Button
variant="secondary"
@@ -289,7 +262,7 @@ export function SkillhubMarketPreviewPanel({
<span className="leading-none">{t('learn.hub.learnButton')}</span>
</Button>
) : null}
- {primaryAction === 'clone' && onClone ? (
+ {primaryAction === 'clone' && onClone && !skill.updateAvailable && !updating ? (
<Button
variant="cta"
onClick={() => onClone(skill)}
@@ -302,31 +275,12 @@ export function SkillhubMarketPreviewPanel({
{primaryAction === 'manage' && onManageAction ? (
<ManageMenu skill={skill} onAction={onManageAction} />
) : null}
- <MarketLocalSkills key={`${skill.catalogScope}:${skill.name}`} skill={skill} />
- </div>
- <button
- type="button"
- onClick={onClose}
- aria-label={t('diffPanel.shell.closeAria')}
- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-chip)]"
- >
- <X size={16} />
- </button>
- </div>
-
- <p className="mt-1 truncate text-xs text-[var(--cmd-palette-item-meta)]">
- {skillPublisherLabel(skill)} · {skill.name} · v{skill.latestVersion}
- </p>
- {skill.description && (
- <p className="mt-3 text-sm leading-[1.55] text-[var(--text-secondary-mid)]">
- {skill.description}
- </p>
- )}
- </header>
-
- {/* 正文:左栏(文件树) + Markdown */}
- <div className="flex min-h-0 flex-1">
- <nav className="flex w-[230px] shrink-0 flex-col border-r border-[var(--cmd-palette-border)] px-4 py-5">
+ {localActions !== undefined ? localActions : <MarketLocalSkills key={`${skill.catalogScope}:${skill.name}`} skill={skill} />}
+ </>}
+ />
+ {navigation}
+ <SkillDetailColumns resizing={metaResize.isDragging}>
+ <SkillDetailSidebar width={metaResize.width}>
<h3 className="mb-2 shrink-0 text-xs font-medium uppercase tracking-wider text-[var(--cmd-palette-item-meta)]">
{t('skillhub.marketDetail.files')}
</h3>
@@ -343,14 +297,10 @@ export function SkillhubMarketPreviewPanel({
/>
)}
</div>
- </nav>
-
- <main
- className={cn(
- 'flex min-w-0 flex-1 flex-col overflow-y-auto overscroll-contain bg-[hsl(var(--content-area))]',
- 'text-15 font-normal leading-[1.65] text-[var(--text-primary)]',
- )}
- >
+ <SkillDetailResizeHandle resize={metaResize} />
+ </SkillDetailSidebar>
+ <SkillDetailContent>
+ {skill.description && <p className="mb-6 text-sm text-[var(--text-secondary)]">{skill.description}</p>}
{/* 加载中不渲染任何中间态(空白底色保持不动),内容就绪后
一次成型淡入 —— 避免滑入动画期间正文连换多个状态产生闪跳 */}
{filesLoading ? null : filesError && files.length === 0 ? (
@@ -368,7 +318,7 @@ export function SkillhubMarketPreviewPanel({
) : filesError && selectedPath ? (
<p className="px-10 py-8 text-sm text-[var(--cmd-palette-item-meta)]">{filesError}</p>
) : file ? (
- <div key={file.path} className="w-full animate-fade-in px-10 py-8">
+ <div key={file.path} className="w-full animate-fade-in">
<div className="mx-auto w-full min-w-0 max-w-[860px]">
<MarkdownRenderer
workingDir=""
@@ -382,18 +332,14 @@ export function SkillhubMarketPreviewPanel({
{t('skillhub.marketDetail.selectFilePrompt')}
</p>
)}
- </main>
- </div>
- </div>
- )}
- </aside>
-
+ </SkillDetailContent>
+ </SkillDetailColumns>
<ScanResultDialog
open={scanDialogOpen && currentScanResult !== null}
onClose={() => { scanRequestId.current += 1; setScanDialogOpen(false); }}
result={currentScanResult}
/>
- </>
+ </SkillDetailPage>
);
}
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
index 39bb2aa8f8..59a07c63b3 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
@@ -1,3 +1,4 @@
+import { buildMarketSkillRoute } from './lib/detailRoutes';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -19,19 +20,17 @@ import {
type SortBy,
type Visibility,
} from './hooks/useMarketList';
-import { refresh as refreshSkillhub, useSkillhub } from './hooks/useSkillhub';
+import { refresh as refreshSkillhub } from './hooks/useSkillhub';
import { MarketManagementDialogs, useMarketManagement } from './hooks/useMarketManagement';
-import { getMarketSelected, setMarketSelected } from './hooks/useMarketSelection';
+import { MarketListError } from './components/MarketListError';
import { MarketCard } from './components/MarketCard';
import { InstallTargetPicker } from './components/InstallTargetPicker';
-import { SkillhubMarketPreviewPanel } from './SkillhubMarketPreviewPanel';
import { marketCardPrimaryAction } from './lib/marketDetailViewModel';
import { groupMineByOwner } from './lib/mineGrouping';
-import { nextMarketPreviewName } from './lib/marketPreviewSelection';
-import { syncMarketPreviewSelection } from './lib/marketPreviewSync';
import { useAuth } from '@/contexts/AuthContext';
import { CATEGORY_ALL } from '../../../shared/skillhubCategory';
import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
+import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
// Must match the global native scrollbar width in styles/globals.css.
const MARKET_SCROLLBAR_GUTTER_PX = 12;
@@ -50,12 +49,13 @@ export function SkillhubMarketListView() {
function SkillhubMarketListViewInner() {
const { t } = useTranslation();
const { user, isInitializing } = useAuth();
- const { skills: localSkills, learnSkillEnabled } = useSkillhub();
const identityPolicy = useSkillhubIdentityPolicy(user);
+ const { update, updatingNames, isUpdating } = useMarketSkillUpdate();
const location = useLocation();
const navigate = useNavigate();
+ const initialSearch = new URLSearchParams(location.search);
const marketState = location.state as { freshEntry?: boolean; initialVisibility?: Visibility } | null;
- const initialVisibility = marketState?.initialVisibility === 'all' ||
+ const initialVisibility = initialSearch.get('visibility') === 'mine' ? 'mine' : marketState?.initialVisibility === 'all' ||
marketState?.initialVisibility === 'mine'
? marketState.initialVisibility
: undefined;
@@ -75,7 +75,12 @@ function SkillhubMarketListViewInner() {
setVisibility,
loadMore,
reload,
- } = useMarketList(initialVisibility, { initialScope: 'market' });
+ } = useMarketList(initialVisibility, {
+ initialScope: 'market',
+ initialSort: SORT_OPTIONS.find((option) => option.value === initialSearch.get('sort'))?.value,
+ initialSearchQuery: initialSearch.get('q') ?? '',
+ initialCategoryFilter: initialSearch.get('category') ?? CATEGORY_ALL,
+ });
const { categories } = useCategoryList();
// 「我的发布」按归属(个人 / 各团队)分组渲染;空组不显示(groupMineByOwner 只对有 item 的 owner 建组)。
@@ -88,30 +93,10 @@ function SkillhubMarketListViewInner() {
const marketScrollRef = useRef<HTMLDivElement | null>(null);
const [marketHasVerticalOverflow, setMarketHasVerticalOverflow] = useState(false);
- // freshEntry = true(顶部 Market 按钮显式点击)→ 清空 selection,回到状态 A
- // 不带这个标记(detail goBack → navigate(fromRoute='/skillhub/market'))→
- // 保留上次的 module-level selection,sidebar panel + 卡片选中态都自然恢复。
- const isFreshEntry = marketState?.freshEntry === true;
-
- // 当前选中的 Market skill —— 初始值取自模块级 store(detail goBack 回来的场景),
- // freshEntry 时强制 null。
- const [selectedName, setSelectedName] = useState<string | null>(() =>
- isFreshEntry ? null : getMarketSelected()?.name ?? null,
- );
- const [previewSkill, setPreviewSkill] = useState<MarketSkill | null>(null);
-
useEffect(() => {
if (!isInitializing && !user && visibility === 'mine') setVisibility('all');
}, [isInitializing, setVisibility, user, visibility]);
- useEffect(() => {
- if (isFreshEntry) {
- setPreviewSkill(null);
- setMarketSelected(null);
- }
- // 仅 mount 时跑一次:freshEntry 是入口时刻的一次性信号。
- }, []);
-
// Infinite scroll sentinel
const sentinelRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
@@ -154,15 +139,6 @@ function SkillhubMarketListViewInner() {
};
}, [error, hasMore, items.length, loading, loadingMore, visibility]);
- useEffect(() => {
- if (!previewSkill && !selectedName) return;
- const next = syncMarketPreviewSelection({ previewSkill, selectedName }, items);
- if (next.previewSkill === previewSkill && next.selectedName === selectedName) return;
- setPreviewSkill(next.previewSkill);
- setSelectedName(next.selectedName);
- setMarketSelected(next.previewSkill);
- }, [items, previewSkill, selectedName]);
-
// Picker 状态 — Clone 按钮触发
const [pickerOpen, setPickerOpen] = useState(false);
const [pickerSkill, setPickerSkill] = useState<MarketSkill | null>(null);
@@ -173,7 +149,8 @@ function SkillhubMarketListViewInner() {
if (event.phase === 'done') {
void refreshSkillhub();
} else if (event.phase === 'failed') {
- if (event.errorCode !== 'CANCELLED') {
+ // Direct updates report their own result; avoid a second toast from the broadcast.
+ if (event.errorCode !== 'CANCELLED' && !isUpdating(event.name)) {
toast.error(t('skillhub.market.installFailedToast', {
name: event.name,
message: event.message ?? event.errorCode ?? t('skillhub.market.installError'),
@@ -182,24 +159,14 @@ function SkillhubMarketListViewInner() {
}
});
return unsubscribe;
- }, [t]);
+ }, [isUpdating, t]);
const sortLabel = useMemo(() => {
return t(SORT_OPTIONS.find((option) => option.value === sortBy)?.labelKey ?? 'skillhub.market.sortLatest');
}, [sortBy, t]);
- const handleCardClick = (skill: MarketSkill) => {
- const newName = nextMarketPreviewName(previewSkill?.name ?? null, skill.name);
- setSelectedName(newName);
- setMarketSelected(newName ? skill : null);
- setPreviewSkill(newName ? skill : null);
- };
-
- const handlePreviewClose = () => {
- setSelectedName(null);
- setMarketSelected(null);
- setPreviewSkill(null);
- };
+ const returnTo = `/skillhub/market?${new URLSearchParams({ q: searchQuery, sort: sortBy, category: categoryFilter, visibility })}`;
+ const handleCardClick = (skill: MarketSkill) => navigate(buildMarketSkillRoute(skill, returnTo));
const handleClone = (skill: MarketSkill) => {
setPickerSkill(skill);
@@ -209,12 +176,6 @@ function SkillhubMarketListViewInner() {
active: isMineView,
reload,
onClone: handleClone,
- onDeleted: (skill) => {
- if (previewSkill?.name !== skill.name && selectedName !== skill.name) return;
- setPreviewSkill(null);
- setSelectedName(null);
- setMarketSelected(null);
- },
});
const renderCard = (skill: MarketSkill) => (
@@ -233,9 +194,10 @@ function SkillhubMarketListViewInner() {
: 'none'}
allowPrivateVisibilityLabel={visibility === 'mine'}
onClone={handleClone}
+ onUpdate={user ? update : undefined}
+ updating={updatingNames.has(skill.name)}
onManageAction={management.handleManageAction}
onClick={handleCardClick}
- selected={skill.name === selectedName}
/>
);
@@ -250,7 +212,7 @@ function SkillhubMarketListViewInner() {
height: '56px',
padding: '0 24px',
gap: '12px',
- ...(previewSkill ? WINDOW_NO_DRAG_STYLE : WINDOW_DRAG_STYLE),
+ ...WINDOW_DRAG_STYLE,
}}
>
{/* back-to-home — 技能首页(/skillhub/local)。原"返回本地"在已移除的侧栏里,
@@ -384,15 +346,12 @@ function SkillhubMarketListViewInner() {
}
: { width: '100%' }}
>
- {error ? (
- <div className="flex h-full items-center justify-center">
- <p className="text-sm text-[var(--error-fg)]">{t('skillhub.market.loadFailed', { error })}</p>
- </div>
- ) : loading && items.length === 0 ? (
+ <MarketListError error={error} loading={loading} onRetry={reload} />
+ {loading && items.length === 0 ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-[var(--cmd-palette-item-meta)]">{t('skillhub.market.loading')}</p>
</div>
- ) : items.length === 0 ? (
+ ) : error && items.length === 0 ? null : items.length === 0 ? (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-[var(--cmd-palette-item-meta)]">{t('skillhub.market.noResults')}</p>
</div>
@@ -466,24 +425,6 @@ function SkillhubMarketListViewInner() {
setPickerOpen(false);
}}
/>
- <SkillhubMarketPreviewPanel
- open={previewSkill !== null}
- skill={previewSkill}
- onClose={handlePreviewClose}
- primaryAction={previewSkill && user
- ? (() => {
- const action = marketCardPrimaryAction({
- isMine: previewSkill.isMine,
- listVisibility: visibility,
- cardState: previewSkill.cardState,
- });
- return action === 'manage' && !identityPolicy.canWrite ? 'clone' : action;
- })()
- : 'none'}
- onClone={handleClone}
- onManageAction={management.handleManageAction}
- learnSkillEnabled={learnSkillEnabled}
- />
<MarketManagementDialogs controller={management} />
</div>
);
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillPublishUpdateHint.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillPublishUpdateHint.test.tsx
new file mode 100644
index 0000000000..fc49f60cff
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillPublishUpdateHint.test.tsx
@@ -0,0 +1,44 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { SkillPublishComparisonNotice, SkillPublishUpdateHint } from '../SkillPublishUpdateHint';
+import type { PublishComparisonState } from '../hooks/useSkillPublishComparison';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+const compare = vi.hoisted(() => vi.fn(() => ({ comparison: { status: 'unavailable' } })));
+vi.mock('../hooks/useSkillPublishComparison', () => ({ useSkillPublishComparison: compare }));
+afterEach(cleanup);
+
+it.each([false, undefined, true])('shows unavailable hints only for a confirmed creator (%s)', (isCreator) => {
+ // A non-creator may still have canManage; legacy responses omit isCreator entirely.
+ const info = { canManage: true, isCreator };
+ render(<>
+ <SkillPublishComparisonNotice comparison={{ status: 'unavailable' }} isCreator={info.isCreator} />
+ <SkillPublishUpdateHint skill={{} as SkillhubSkill} knownCreator={info.isCreator} />
+ </>);
+ expect(screen.queryAllByText('skillhub.publishComparison.unavailable')).toHaveLength(isCreator === true ? 2 : 0);
+});
+
+it.each<PublishComparisonState>([
+ { status: 'checking' }, { status: 'not-owner' },
+ { status: 'same', version: '1.0.0', pending: false },
+ { status: 'different', version: '1.1.0', pending: true },
+])('does not show an unavailable notice for $status', (comparison) => {
+ render(<SkillPublishComparisonNotice comparison={comparison} isCreator />);
+ expect(screen.queryByText('skillhub.publishComparison.unavailable')).toBeNull();
+});
+
+it('removes the notice when author identity changes', () => {
+ const { rerender } = render(<SkillPublishComparisonNotice comparison={{ status: 'unavailable' }} isCreator />);
+ expect(screen.getByText('skillhub.publishComparison.unavailable')).toBeTruthy();
+ rerender(<SkillPublishComparisonNotice comparison={{ status: 'unavailable' }} isCreator={false} />);
+ expect(screen.queryByText('skillhub.publishComparison.unavailable')).toBeNull();
+});
+
+
+it.each([undefined, false, true])('only schedules list comparison after batch sync confirms the creator (%s)', (knownCreator) => {
+ compare.mockClear();
+ const skill = { id: 'google-play-console' } as SkillhubSkill;
+ render(<SkillPublishUpdateHint skill={skill} knownCreator={knownCreator} />);
+ expect(compare).toHaveBeenLastCalledWith(knownCreator ? skill : null);
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubDetailRoute.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubDetailRoute.test.tsx
new file mode 100644
index 0000000000..c3ae0a8f49
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubDetailRoute.test.tsx
@@ -0,0 +1,159 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+
+const state = vi.hoisted(() => ({ skills: [] as SkillhubSkill[], canWrite: true, leave: vi.fn(), update: vi.fn() }));
+vi.mock('react-i18next', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('react-i18next')>();
+ const t = (key: string) => key;
+ return { ...actual, useTranslation: () => ({ t }) };
+});
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' } }) }));
+vi.mock('../hooks/useSkillhubIdentityPolicy', () => ({ useSkillhubIdentityPolicy: () => ({ canWrite: state.canWrite }) }));
+vi.mock('../hooks/useSkillhub', () => ({
+ useSkillhub: () => ({ skills: state.skills, bootstrapped: true, loading: false, learnSkillEnabled: true }),
+ refresh: vi.fn(async () => state.skills),
+}));
+vi.mock('../hooks/useMarketSkillUpdate', () => ({ useMarketSkillUpdate: () => ({ update: state.update, updatingNames: new Set() }) }));
+vi.mock('../hooks/useMarketManagement', () => ({ useMarketManagement: () => ({}), MarketManagementDialogs: () => null }));
+vi.mock('../components/InstallTargetPicker', () => ({ InstallTargetPicker: () => null }));
+vi.mock('../components/LocalSkillControls', () => ({ LocalSkillControls: ({ skill }: { skill: SkillhubSkill }) => <span data-testid="controls">{skill.id}</span> }));
+vi.mock('@/components/ui/select', () => ({ Select: ({ value, onValueChange, options }: {
+ value: string; onValueChange: (value: string) => void; options: { value: string; label: string }[];
+}) => <select aria-label="copy" value={value} onChange={(event) => onValueChange(event.target.value)}>
+ {options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
+</select> }));
+vi.mock('../SkillhubDetailView', () => ({ SkillhubDetailView: ({ entryOverride, renderNavigation }: {
+ entryOverride: SkillhubSkill; renderNavigation: (leave: () => Promise<boolean>, disabled: boolean) => ReactNode;
+}) => <><div data-testid="local">{entryOverride.id}</div>{renderNavigation(state.leave, false)}</> }));
+vi.mock('../SkillhubMarketDetailView', () => ({ SkillhubMarketDetailView: ({ skill, navigation, localActions, onUpdate, onClose, selectedLocal, onPublishUpdate }: {
+ skill: { installedAbsolutePath: string }; navigation: ReactNode; localActions: ReactNode; onUpdate: (skill: unknown) => void;
+ onClose: () => void; selectedLocal: SkillhubSkill; onPublishUpdate?: (local: SkillhubSkill) => void;
+}) => <><div data-testid="market">{skill.installedAbsolutePath}</div>{navigation}{localActions}
+ <button onClick={() => onUpdate(skill)}>update</button><button onClick={onClose}>back</button>
+ {onPublishUpdate && <button onClick={() => onPublishUpdate(selectedLocal)}>publish</button>}
+</> }));
+
+import { SkillhubDetailRoute, LegacySkillDetailRedirect } from '../SkillhubDetailRoute';
+import { buildMarketSkillRoute } from '../lib/detailRoutes';
+import { buildLocalSkillRoute } from '../lib/localRoutes';
+
+const info = vi.fn();
+const record = { name: 'demo', authorName: 'Owner', isCreator: true, isMine: true, canManage: true, latestVersion: '2.0.0' };
+const local = (id: string, scope: 'global' | 'project', catalogScope: 'market' | 'team' = 'market') => ({
+ id, name: 'demo', engine: 'pi', kind: 'skill', scope, sourceKey: id, projectHash: scope === 'project' ? id : undefined,
+ absolutePath: `/skills/${id}`, projectRoot: scope === 'project' ? `/projects/${id}` : undefined,
+ registryEntry: { version: '1.0.0', catalogScope },
+}) as SkillhubSkill;
+function Location() { const location = useLocation(); return <div data-testid="location">{location.pathname}{location.search}</div>; }
+function mount(path: string) {
+ return render(<MemoryRouter initialEntries={[path]}><Location /><Routes>
+ <Route path="/skillhub/detail" element={<SkillhubDetailRoute />} />
+ <Route path="/skillhub/local/:kind/project/:projectHash/:name" element={<LegacySkillDetailRedirect />} />
+ <Route path="/skillhub/market/:name" element={<LegacySkillDetailRedirect market />} />
+ <Route path="/skillhub/market" element={<div>market list</div>} />
+ </Routes></MemoryRouter>);
+}
+beforeEach(() => {
+ setDataOwnerGeneration('owner', 1);
+ state.skills = [local('project', 'project'), local('global', 'global'), local('team', 'global', 'team')];
+ state.canWrite = true;
+ state.leave.mockReset().mockResolvedValue(true);
+ state.update.mockReset();
+ info.mockReset().mockResolvedValue({ success: true, info: record });
+ vi.stubGlobal('electronAPI', { skillhub: { info } });
+});
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+
+describe('unified Skill details', () => {
+ it('resolves a direct market link, excludes same-slug other catalogs and retains return filters', async () => {
+ const returnTo = '/skillhub/market?q=demo&sort=trending&visibility=mine';
+ mount(buildMarketSkillRoute({ name: 'demo', catalogScope: 'market' }, returnTo));
+ expect(await screen.findByTestId('market')).toHaveProperty('textContent', '/skills/global');
+ expect(screen.getAllByRole('option')).toHaveLength(2);
+ expect(info).toHaveBeenCalledWith('demo', 'market');
+ fireEvent.change(screen.getByLabelText('copy'), { target: { value: 'project' } });
+ await waitFor(() => expect(screen.getByTestId('controls').textContent).toBe('project'));
+ fireEvent.click(screen.getByText('update'));
+ expect(state.update).toHaveBeenCalledWith(expect.objectContaining({ installedAbsolutePath: '/skills/project' }));
+ fireEvent.click(screen.getByText('back'));
+ expect(screen.getByTestId('location').textContent).toBe(returnTo);
+ });
+
+ it('honors the local unsaved-edit guard before switching source or copy', async () => {
+ mount(buildLocalSkillRoute(state.skills[0]!));
+ await screen.findByRole('button', { name: 'skillhub.unifiedDetail.market' });
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.unifiedDetail.local' }));
+ expect(state.leave).not.toHaveBeenCalled();
+ state.leave.mockResolvedValue(false);
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.unifiedDetail.market' }));
+ await waitFor(() => expect(state.leave).toHaveBeenCalledTimes(1));
+ expect(screen.getByTestId('local').textContent).toBe('project');
+ fireEvent.change(screen.getByLabelText('copy'), { target: { value: 'global' } });
+ await waitFor(() => expect(state.leave).toHaveBeenCalledTimes(2));
+ expect(screen.getByTestId('local').textContent).toBe('project');
+ state.leave.mockResolvedValue(true);
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.unifiedDetail.market' }));
+ expect(await screen.findByTestId('market')).toHaveProperty('textContent', '/skills/project');
+ expect(screen.queryByText('publish')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.unifiedDetail.local' }));
+ expect(await screen.findByTestId('local')).toHaveProperty('textContent', 'project');
+ expect(screen.getByTestId('location').textContent).toContain('view=local');
+ });
+
+ it('keeps local unregistered content separate from another creator with the same name', async () => {
+ state.skills = [{ ...state.skills[0]!, registryEntry: null }];
+ info.mockResolvedValue({ success: true, info: { ...record, isCreator: false, isMine: true } });
+ mount(buildLocalSkillRoute(state.skills[0]!));
+ await act(async () => {});
+ expect(screen.getByTestId('local').textContent).toBe('project');
+ expect(screen.queryByRole('button', { name: 'skillhub.unifiedDetail.market' })).toBeNull();
+ });
+
+ it.each([false, true])('does not expose publishing in the market view (canWrite=%s)', async (canWrite) => {
+ state.canWrite = canWrite;
+ mount(buildMarketSkillRoute({ name: 'demo', catalogScope: 'market' }));
+ await screen.findByTestId('market');
+ expect(screen.queryByText('publish')).toBeNull();
+ });
+
+ it('associates the original native publication without merging another owner', async () => {
+ const authored = { ...local('authored', 'global'), name: 'google-play-console', registryEntry: {
+ version: '1.0.0', origin: 'published', authorId: 'creator',
+ } } as SkillhubSkill;
+ state.skills = [authored, { ...authored, id: 'other', registryEntry: { ...authored.registryEntry!, authorId: 'someone-else' } }];
+ info.mockResolvedValue({ success: true, info: { ...record, name: authored.name, authorId: 'creator' } });
+ mount(buildMarketSkillRoute({ name: authored.name, catalogScope: 'market' }));
+ expect(await screen.findByTestId('market')).toHaveProperty('textContent', '/skills/authored');
+ expect(screen.queryByLabelText('copy')).toBeNull();
+ expect(screen.queryByText('publish')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.unifiedDetail.local' }));
+ expect(await screen.findByTestId('local')).toHaveProperty('textContent', 'authored');
+ });
+
+ it('discards an old account response even before React rerenders', async () => {
+ let resolve!: (value: unknown) => void;
+ info.mockReturnValue(new Promise((done) => { resolve = done; }));
+ mount(buildMarketSkillRoute({ name: 'demo', catalogScope: 'market' }));
+ setDataOwnerGeneration('other', 2);
+ await act(async () => { resolve({ success: true, info: record }); });
+ expect(screen.queryByTestId('market')).toBeNull();
+ });
+
+ it('redirects legacy project links without losing engine, source, or copy identity', async () => {
+ mount('/skillhub/local/skill/project/project/demo?engine=pi&source=project');
+ expect(await screen.findByTestId('local')).toHaveProperty('textContent', 'project');
+ expect(screen.getByTestId('location').textContent).toContain('/skillhub/detail?');
+ expect(screen.getByTestId('location').textContent).toContain('source=project');
+ });
+
+ it('redirects legacy market links to a readable market detail', async () => {
+ mount('/skillhub/market/demo');
+ await screen.findByTestId('market');
+ expect(info).toHaveBeenCalledWith('demo', 'market');
+ expect(screen.getByTestId('location').textContent).toContain('/skillhub/detail?');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubDiffPanel.published.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubDiffPanel.published.test.tsx
new file mode 100644
index 0000000000..1877a505a8
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubDiffPanel.published.test.tsx
@@ -0,0 +1,56 @@
+// @vitest-environment jsdom
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { SkillhubDiffPanel } from '../SkillhubDiffPanel';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
+function translate(key: string, params?: { version?: string }) { return params?.version ? key + ':' + params.version : key; }
+vi.mock('@/components/diff-panel/DiffPanelShell', () => ({
+ DiffPanelShell: ({ title, children }: { title: string; children: React.ReactNode }) => <div><h1>{title}</h1>{children}</div>,
+}));
+vi.mock('@/components/diff-panel/FileChangeGroup', () => ({
+ FileChangeGroup: ({ change, summaryOnly }: { change: { path: string; oldContent: string }; summaryOnly: boolean }) =>
+ <li>{change.path}:{summaryOnly ? 'summary' : change.oldContent}</li>,
+}));
+const comparePublished = vi.fn();
+const getSnapshotDiff = vi.fn();
+beforeEach(() => {
+ comparePublished.mockReset();
+ getSnapshotDiff.mockReset();
+ setDataOwnerGeneration('owner-a', 1);
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { skillhub: { comparePublished, getSnapshotDiff } } });
+});
+afterEach(cleanup);
+const props = { open: true, onClose: vi.fn(), skillName: 'demo', skillId: 'skill:demo', absolutePath: '/skills/demo', published: true };
+
+it('shows the exact remote version and file content, without falling back to a local snapshot', async () => {
+ comparePublished.mockResolvedValue({ status: 'different', version: '2.1.0', pending: true, changes: [
+ { path: 'SKILL.md', kind: 'modified', isBinary: false, oldContent: 'online content', newContent: 'local', oldSize: 14, newSize: 5 },
+ { path: 'large.bin', kind: 'added', isBinary: true, oldContent: '', newContent: '', oldSize: 0, newSize: 20 },
+ ] });
+ render(<SkillhubDiffPanel {...props} />);
+ await screen.findByText('skillhub.publishComparison.diffTitle:2.1.0');
+ expect(screen.getByText('SKILL.md:online content')).toBeTruthy();
+ expect(screen.getByText('large.bin:summary')).toBeTruthy();
+ expect(comparePublished).toHaveBeenCalledWith({ absolutePath: '/skills/demo', skillId: 'skill:demo', includeDiff: true });
+ expect(getSnapshotDiff).not.toHaveBeenCalled();
+});
+
+it('reports unavailable instead of a clean comparison when remote contents cannot be read', async () => {
+ comparePublished.mockResolvedValue({ status: 'unavailable' });
+ render(<SkillhubDiffPanel {...props} />);
+ await screen.findByText('skillhub.publishComparison.unavailable');
+ expect(screen.queryByText('skillhub.diffPanel.cleanTitle')).toBeNull();
+ expect(getSnapshotDiff).not.toHaveBeenCalled();
+});
+
+it('discards private preview data returned after switching accounts', async () => {
+ let resolve!: (value: unknown) => void;
+ comparePublished.mockImplementation(() => new Promise((done) => { resolve = done; }));
+ render(<SkillhubDiffPanel {...props} />);
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(1));
+ setDataOwnerGeneration('owner-b', 2);
+ await act(async () => resolve({ status: 'different', version: 'private-version', changes: [] }));
+ expect(screen.queryByText('skillhub.publishComparison.diffTitle:private-version')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubHomeNavigation.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubHomeNavigation.test.tsx
index 4a36c2e67c..067b0cea2b 100644
--- a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubHomeNavigation.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubHomeNavigation.test.tsx
@@ -87,11 +87,14 @@ function CatalogHarness({ entry = '/skillhub/local' }: {
<MemoryRouter initialEntries={['/before', entry]}>
<NavigationControls />
<Routes>
- <Route path="/skillhub/local" element={<SkillhubLocalLayout />}>
+ <Route element={<SkillhubLocalLayout />}>
+ <Route path="/skillhub/detail" element={<DetailNavigation />} />
+ <Route path="/skillhub/local">
<Route index element={null} />
<Route path="by-path" element={<DetailNavigation />} />
<Route path=":kind/global/:name" element={<DetailNavigation />} />
<Route path=":kind/project/:hash/:name" element={<DetailNavigation />} />
+ </Route>
</Route>
<Route path="/settings" element={<SkillhubHomeView embedded />} />
<Route path="*" element={null} />
@@ -148,7 +151,7 @@ describe('Skill home navigation', () => {
list.scrollTop = 720;
fireEvent.click(screen.getByRole('button', { name: /calendar-tools/ }));
expect(screen.queryByRole('radio', { name: 'skillhub.home.local' })).toBeNull();
- expect(screen.getByTestId('location').textContent).toContain(`/skill/${scope}/`);
+ expect(new URLSearchParams(screen.getByTestId('location').textContent!.split('?')[1]).get('scope')).toBe(scope);
expect(list.isConnected).toBe(true);
expect(list.closest('[inert]')?.getAttribute('aria-hidden')).toBe('true');
expect(screen.queryByRole('main')).toBeNull();
@@ -191,8 +194,11 @@ describe('Skill home navigation', () => {
fireEvent.click(screen.getByRole('button', { name: 'Rename skill' }));
const location = screen.getByTestId('location').textContent;
- expect(location).toContain(`/skill/${scope}/`);
- expect(location).toContain('/calendar-renamed?engine=claude-code&source=renamed-source');
+ const query = new URLSearchParams(location!.split('?')[1]);
+ expect(query.get('scope')).toBe(scope);
+ expect(query.get('name')).toBe('calendar-renamed');
+ expect(query.get('engine')).toBe('claude-code');
+ expect(query.get('source')).toBe('renamed-source');
expect(screen.getByTestId('navigation-state').textContent).toBe(detailState);
expect(list.isConnected).toBe(true);
@@ -218,7 +224,7 @@ describe('Skill home navigation', () => {
fireEvent.click(screen.getByRole('button', { name: /calendar-tools/ }));
fireEvent.click(screen.getByRole('button', { name: 'Detail Back' }));
await waitFor(() => expectTab('local'));
- expect(screen.getByTestId('location').textContent).toBe('/skillhub/local');
+ expect(screen.getByTestId('location').textContent?.split('?')[0]).toBe('/skillhub/local');
expect((screen.getByRole('textbox', { name: 'skillhub.home.search' }) as HTMLInputElement).value)
.toBe('calendar');
});
@@ -239,7 +245,7 @@ describe('Skill home navigation', () => {
state: { from: '/skillhub/market', resetHistory: true },
});
fireEvent.click(screen.getByRole('button', { name: 'Rename skill' }));
- expect(screen.getByTestId('location').textContent).toContain('/calendar-renamed?');
+ expect(new URLSearchParams(screen.getByTestId('location').textContent!.split('?')[1]).get('name')).toBe('calendar-renamed');
fireEvent.click(screen.getByRole('button', { name: 'Detail Back' }));
expect(screen.getByTestId('location').textContent).toBe('/skillhub/market');
});
@@ -278,6 +284,7 @@ describe('Skill home navigation', () => {
'/skillhub/local/skill/global/calendar-tools',
'/skillhub/local/skill/project/repo-hash/calendar-tools',
'/skillhub/local/by-path?path=%2Fskills%2Fcalendar-tools',
+ '/skillhub/detail?view=local&kind=skill&scope=global&name=calendar-tools',
])('does not mount a hidden catalog for a direct detail URL: %s', (entry) => {
renderCatalog(entry);
expect(document.querySelector('main')).toBeNull();
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubMarketPreviewPanel.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubMarketDetailView.test.tsx
similarity index 89%
rename from apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubMarketPreviewPanel.test.tsx
rename to apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubMarketDetailView.test.tsx
index e2561b315c..271b62bbf5 100644
--- a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubMarketPreviewPanel.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubMarketDetailView.test.tsx
@@ -22,7 +22,7 @@ vi.mock('../components/MarketCard', () => ({ ManageMenu: () => null }));
vi.mock('../components/MarketLocalSkills', () => ({ MarketLocalSkills: () => null }));
vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
-import { SkillhubMarketPreviewPanel } from '../SkillhubMarketPreviewPanel';
+import { SkillhubMarketDetailView } from '../SkillhubMarketDetailView';
import type { MarketSkill } from '../hooks/useMarketList';
const getScanStatus = vi.fn();
@@ -60,7 +60,7 @@ describe('published Skill rejection feedback', () => {
const publishedSkill = scenario === 'first publication'
? { ...skill, latestVersion: '1.0.1', moderationStatus: 'rejected', pendingVersion: undefined }
: skill;
- render(<SkillhubMarketPreviewPanel skill={publishedSkill} open onClose={vi.fn()} />);
+ render(<SkillhubMarketDetailView skill={publishedSkill} open onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishedStatus.rejected' }));
expect(await screen.findByText(feedback.rejectionReason)).toBeTruthy();
expect(getScanStatus).toHaveBeenCalledWith({ slug: skill.name, version: '1.0.1', catalogScope: undefined });
@@ -70,14 +70,14 @@ describe('published Skill rejection feedback', () => {
let resolve!: (value: typeof feedback) => void;
getScanStatus.mockReturnValue(new Promise<typeof feedback>((done) => { resolve = done; }));
const onClose = vi.fn();
- const { rerender } = render(<SkillhubMarketPreviewPanel skill={skill} open onClose={onClose} />);
+ const { rerender } = render(<SkillhubMarketDetailView skill={skill} open onClose={onClose} />);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishedStatus.rejected' }));
const nextSkill = change === 'skill' ? { ...skill, name: 'another-skill' }
: change === 'version' ? { ...skill, pendingVersion: { version: '1.0.2', status: 'rejected' } }
: change === 'approved' ? { ...skill, latestVersion: '1.0.1', pendingVersion: undefined }
: change === 'permission' ? { ...skill, canManage: false }
: skill;
- rerender(<SkillhubMarketPreviewPanel skill={nextSkill} open={change !== 'close'} onClose={onClose} />);
+ rerender(<SkillhubMarketDetailView skill={nextSkill} open={change !== 'close'} onClose={onClose} />);
await act(async () => { resolve(feedback); });
expect(screen.queryByText(feedback.rejectionReason)).toBeNull();
expect(screen.queryByRole('heading', { name: 'skillhub.scanResult.rejectedTitle' })).toBeNull();
@@ -86,7 +86,7 @@ describe('published Skill rejection feedback', () => {
it.each(['response', 'exception'])('shows unavailable feedback when the scan request fails with a %s', async (failure) => {
if (failure === 'response') getScanStatus.mockResolvedValue({ success: false });
else getScanStatus.mockRejectedValue(new Error('Request failed'));
- render(<SkillhubMarketPreviewPanel skill={skill} open onClose={vi.fn()} />);
+ render(<SkillhubMarketDetailView skill={skill} open onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishedStatus.rejected' }));
expect(await screen.findByRole('dialog', { name: 'skillhub.scanResult.failedTitle' })).toBeTruthy();
expect(screen.getByText('skillhub.scanResult.statusLabel.unavailable')).toBeTruthy();
@@ -97,7 +97,7 @@ describe('published Skill rejection feedback', () => {
let resolve!: (value: typeof feedback) => void;
let reject!: (error: Error) => void;
getScanStatus.mockReturnValue(new Promise<typeof feedback>((done, fail) => { resolve = done; reject = fail; }));
- render(<SkillhubMarketPreviewPanel skill={skill} open onClose={vi.fn()} />);
+ render(<SkillhubMarketDetailView skill={skill} open onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishedStatus.rejected' }));
setDataOwnerGeneration('owner-b', 2);
setDataOwnerGeneration('owner-a', 3);
@@ -113,11 +113,11 @@ describe('published Skill rejection feedback', () => {
it.each(['owner-b', 'owner-a'])('closes visible feedback when the owner generation changes to %s', async (nextOwner) => {
getScanStatus.mockResolvedValue(feedback);
const onClose = vi.fn();
- const { rerender } = render(<SkillhubMarketPreviewPanel skill={skill} open onClose={onClose} />);
+ const { rerender } = render(<SkillhubMarketDetailView skill={skill} open onClose={onClose} />);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishedStatus.rejected' }));
expect(await screen.findByText(feedback.rejectionReason)).toBeTruthy();
setDataOwnerGeneration(nextOwner, 2);
- rerender(<SkillhubMarketPreviewPanel skill={skill} open onClose={onClose} />);
+ rerender(<SkillhubMarketDetailView skill={skill} open onClose={onClose} />);
expect(screen.queryByText(feedback.rejectionReason)).toBeNull();
});
@@ -125,7 +125,7 @@ describe('published Skill rejection feedback', () => {
// Match the server boundary: scoped catalog reads cannot expose unapproved versions.
getScanStatus.mockImplementation(async (request) => request.catalogScope
? { success: false } : feedback);
- render(<SkillhubMarketPreviewPanel skill={{ ...skill, catalogScope }} open onClose={vi.fn()} />);
+ render(<SkillhubMarketDetailView skill={{ ...skill, catalogScope }} open onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishedStatus.rejected' }));
expect(await screen.findByText(feedback.rejectionReason)).toBeTruthy();
expect(getScanStatus).toHaveBeenCalledWith({ slug: skill.name, version: '1.0.1', catalogScope: undefined });
@@ -134,7 +134,7 @@ describe('published Skill rejection feedback', () => {
it.each(['pending', 'rejected'] as const)('preserves the team scope for an ordinary %s catalog read', async (status) => {
getScanStatus.mockResolvedValue({ success: true, status, gates: [] });
const record = { ...skill, canManage: status !== 'rejected', catalogScope: 'team' as const, pendingVersion: { version: '1.0.1', status } };
- render(<SkillhubMarketPreviewPanel skill={record} open onClose={vi.fn()} />);
+ render(<SkillhubMarketDetailView skill={record} open onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: status === 'pending' ? 'skillhub.publishedStatus.waitingReview' : 'skillhub.publishedStatus.rejected' }));
await act(async () => {});
expect(getScanStatus).toHaveBeenCalledWith({ slug: skill.name, version: '1.0.1', catalogScope: 'team' });
@@ -147,7 +147,7 @@ describe('published Skill rejection feedback', () => {
success: true, status, gates: [{ name: 'internal-error', status: 'failed',
issues: [{ severity: 'error', message: 'Unable to process archive' }] }],
});
- render(<SkillhubMarketPreviewPanel skill={{ ...skill, catalogScope, pendingVersion: { version: '1.0.1', status } }} open onClose={vi.fn()} />);
+ render(<SkillhubMarketDetailView skill={{ ...skill, catalogScope, pendingVersion: { version: '1.0.1', status } }} open onClose={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishedStatus.rejected' }));
expect(await screen.findByRole('heading', { name: 'skillhub.scanResult.processingFailedTitle' })).toBeTruthy();
expect(screen.getByText('Unable to process archive')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx
index 079b11c36f..11334a21b4 100644
--- a/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/SkillhubStoreSync.test.tsx
@@ -1,15 +1,15 @@
// @vitest-environment jsdom
-import { cleanup, renderHook } from '@testing-library/react';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
import { projectHash } from '../lib/projectHash';
const mocks = vi.hoisted(() => ({
- sessions: [] as Session[], loading: true, syncProjects: vi.fn(),
- state: { skills: [], syncResults: new Map(), bootstrapped: false },
+ mode: 'local', sessions: [] as Session[], loading: true, syncProjects: vi.fn(),
+ state: { skills: [] as SkillhubSkill[], syncResults: new Map<string, SkillhubSyncResult>(), bootstrapped: false },
}));
vi.mock('@/hooks/useCCSessions', () => ({ useCCSessions: () => ({ sessions: mocks.sessions, isLoading: mocks.loading }) }));
-vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'local', mode: 'local' }) }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'local', mode: mocks.mode }) }));
vi.mock('@/features/cc-agent/useRegisterCCAgentSidebar', () => ({ useRegisterCCAgentSidebar: vi.fn() }));
vi.mock('../hooks/useSkillSync', () => ({ useSkillSync: vi.fn() }));
vi.mock('../hooks/useSkillhub', () => ({
@@ -52,3 +52,26 @@ it('keeps pinned and newly created local project directories in the scan catalog
rerender();
expect(mocks.syncProjects.mock.lastCall![0]).toEqual(projects);
});
+
+
+it.each(['google-play-console-local', 'Google-Play-Console'])('reconciles the registered slug and catalog for folder %s', async (name) => {
+ mocks.mode = 'cloud';
+ mocks.state.bootstrapped = true;
+ const slug = 'google-play-console';
+ const { skillhubCatalogKey } = await import('../../../../shared/skillhubCatalog');
+ const reconcileMineRegistry = vi.fn().mockResolvedValue({ success: true, added: 0, flipped: 0, failures: [] });
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { skillhub: { reconcileMineRegistry } } });
+ mocks.state.skills = [{ kind: 'skill', name, registrySkillName: slug, absolutePath: `/skills/${name}`,
+ registryEntry: { catalogScope: 'market', version: '1.0.0' } } as SkillhubSkill];
+ mocks.state.syncResults = new Map([
+ [skillhubCatalogKey(slug, 'market'), { exists: true, isMine: true, authorId: 'publisher', latestVersion: '2.0.0' } as SkillhubSyncResult],
+ [skillhubCatalogKey(slug, 'team'), { exists: true, isMine: true, authorId: 'other-publisher', latestVersion: '3.0.0' } as SkillhubSyncResult],
+ ]);
+ const hook = renderHook(useSkillhubStoreSync);
+ await waitFor(() => expect(reconcileMineRegistry).toHaveBeenCalledExactlyOnceWith([
+ { name: slug, absolutePath: `/skills/${name}`, authorId: 'publisher', version: '2.0.0' },
+ ]));
+ await act(async () => hook.rerender());
+ expect(reconcileMineRegistry).toHaveBeenCalledTimes(1);
+ mocks.mode = 'local';
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx b/apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx
index 420a2f5135..11e8690ace 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx
@@ -1,53 +1,49 @@
import { Download } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import type { MarketSkill } from '../hooks/useMarketList';
import { skillPublisherLabel } from '../lib/publisherLabel';
import { SkillIcon } from './SkillIcon';
import { SkillTagList } from './SkillTagList';
+import { MarketInstallStatus, type MarketInstallStatusProps } from './MarketInstallStatus';
-export function HomeMarketCard({ skill: s, onClick }: {
- skill: MarketSkill;
+export function HomeMarketCard({ skill: s, onClick, onUpdate, updating }: MarketInstallStatusProps & {
onClick: (skill: MarketSkill) => void;
}) {
- const { t } = useTranslation();
return (
- <button
- type="button"
+ <div
onClick={() => onClick(s)}
className={cn(
- 'group flex min-h-[100px] flex-col gap-1.5 rounded-[12px] border-[0.5px] border-[var(--border-default)]',
+ 'group flex min-h-[100px] cursor-pointer flex-col gap-1.5 rounded-[12px] border-[0.5px] border-[var(--border-default)]',
'bg-[var(--surface-elevated)] p-3 text-left shadow-[var(--plugin-card-shadow)]',
'transition-[background-color,border-color,transform] duration-150 ease-out',
'hover:-translate-y-0.5 hover:border-[var(--text-tertiary)]',
'active:translate-y-0 active:scale-[0.992]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
)}
>
<div className="flex items-center gap-2">
<SkillIcon url={s.icon} />
- <span className="min-w-0 flex-1 truncate text-sm font-medium text-[var(--msg-assistant-text)]">
+ <button
+ type="button"
+ onClick={(event) => { event.stopPropagation(); onClick(s); }}
+ className="min-h-8 min-w-0 flex-1 truncate text-left text-sm font-medium text-[var(--msg-assistant-text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
{s.displayName || s.name}
- </span>
+ </button>
<SkillTagList tags={s.tags} maxVisible={1} className="shrink-0" />
- {s.installedLocally && (
- <span className="shrink-0 rounded-full bg-[var(--chat-input-chip-bg)] px-1.5 py-0.5 text-10 text-[var(--cmd-palette-item-meta)]">
- {t('skillhub.home.installed')}
- </span>
- )}
+ <MarketInstallStatus skill={s} onUpdate={onUpdate} updating={updating} />
</div>
{s.description && (
<p className="line-clamp-2 text-xs text-[var(--cmd-palette-item-meta)]">
{s.description}
</p>
)}
- <div className="flex items-center gap-2 text-11 text-[var(--cmd-palette-item-meta)]">
+ <div className="flex flex-wrap items-center gap-2 text-11 text-[var(--cmd-palette-item-meta)]">
<span className="min-w-0 truncate">{skillPublisherLabel(s)}</span>
<span className="inline-flex shrink-0 items-center gap-0.5">
<Download size={11} />
{s.downloads}
</span>
</div>
- </button>
+ </div>
);
}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx b/apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx
index ba72fc0ba1..8db5c7bdcc 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx
@@ -22,6 +22,7 @@ import {
} from '../lib/publishedStatus';
import { SkillIcon } from './SkillIcon';
import { SkillTagList } from './SkillTagList';
+import { MarketInstallStatus, type MarketInstallStatusProps } from './MarketInstallStatus';
function visibilityLabel(skill: MarketSkill, allowPrivateLabel: boolean): string {
return i18n.t(marketVisibilityLabelKey({
@@ -34,8 +35,7 @@ function visibilityLabel(skill: MarketSkill, allowPrivateLabel: boolean): string
/** 卡片「管理」菜单里的动作(详情统一走浮窗,菜单只收管理类操作) */
export type MarketCardManageAction = 'edit' | 'manageVisibility' | 'clone' | 'delete';
-interface MarketCardProps {
- skill: MarketSkill;
+interface MarketCardProps extends MarketInstallStatusProps {
primaryAction?: MarketCardPrimaryAction;
allowPrivateVisibilityLabel?: boolean;
/** Clone 按钮点击 → 打开 InstallTargetPicker */
@@ -149,6 +149,8 @@ export function MarketCard({
onManageAction,
onClick,
selected,
+ onUpdate,
+ updating,
}: MarketCardProps) {
// useTranslation: subscribe to language change so footer / visibility re-render.
const { t, i18n: i18next } = useTranslation();
@@ -226,7 +228,7 @@ export function MarketCard({
{/* Footer: 时间戳 + 按钮 */}
<div
- className="flex w-full items-center justify-between"
+ className="flex w-full flex-wrap items-center justify-between"
style={{ gap: '8px', minHeight: '36px' }}
>
<div
@@ -252,16 +254,19 @@ export function MarketCard({
<span>{downloads}</span>
</span>
</div>
- {primaryAction === 'manage' && onManageAction ? (
- <ManageMenu skill={skill} onAction={onManageAction} />
- ) : primaryAction === 'clone' ? (
- <CloneButton
- onClick={(e) => {
- e.stopPropagation();
- onClone(skill);
- }}
- />
- ) : null}
+ <div className="flex max-w-full flex-wrap items-center gap-2">
+ <MarketInstallStatus skill={skill} onUpdate={onUpdate} updating={updating} />
+ {primaryAction === 'manage' && onManageAction ? (
+ <ManageMenu skill={skill} onAction={onManageAction} />
+ ) : primaryAction === 'clone' && !skill.updateAvailable && !updating ? (
+ <CloneButton
+ onClick={(e) => {
+ e.stopPropagation();
+ onClone(skill);
+ }}
+ />
+ ) : null}
+ </div>
</div>
</div>
);
diff --git a/apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx b/apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx
new file mode 100644
index 0000000000..e2ddfbf34b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx
@@ -0,0 +1,35 @@
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import type { MarketSkill } from '../hooks/useMarketList';
+
+export interface MarketInstallStatusProps {
+ skill: MarketSkill;
+ onUpdate?: (skill: MarketSkill) => void;
+ updating?: boolean;
+}
+
+export function MarketInstallStatus({ skill, onUpdate, updating = false }: MarketInstallStatusProps) {
+ const { t } = useTranslation();
+ if (skill.updateAvailable || updating) {
+ return (
+ // Keep disabled-button clicks from bubbling into the card's detail action.
+ <span className="inline-flex shrink-0" onClick={(event) => event.stopPropagation()}>
+ <Button
+ variant="secondary"
+ className="px-3"
+ loading={updating}
+ aria-label={updating ? t('skillhub.detail.updating') : undefined}
+ disabled={!onUpdate}
+ onClick={() => onUpdate?.(skill)}
+ >
+ {t('skillhub.marketCard.updateAvailable')}
+ </Button>
+ </span>
+ );
+ }
+ return skill.installedLocally ? (
+ <span className="shrink-0 rounded-full bg-[var(--chat-input-chip-bg)] px-1.5 py-0.5 text-10 text-[var(--cmd-palette-item-meta)]">
+ {t('skillhub.home.installed')}
+ </span>
+ ) : null;
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx b/apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx
new file mode 100644
index 0000000000..b774ceb270
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx
@@ -0,0 +1,11 @@
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+
+export function MarketListError({ error, loading, onRetry }: { error: string | null; loading: boolean; onRetry: () => void }) {
+ const { t } = useTranslation();
+ if (!error) return null;
+ return <div role="alert" className="flex flex-wrap items-center gap-3 p-4">
+ <p className="text-sm text-[var(--error-fg)]">{t('skillhub.market.loadFailed', { error })}</p>
+ <Button variant="secondary" disabled={loading} onClick={onRetry}>{t('skillhub.unifiedDetail.retry')}</Button>
+ </div>;
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx b/apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx
index 8c3e9d0639..367b642cf6 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx
@@ -3,7 +3,7 @@ import { ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { useTranslation } from 'react-i18next';
-import { skillhubCatalogKey } from '../../../../shared/skillhubCatalog';
+import { marketLocalCopies } from '../lib/marketLocalCopies';
import { useSkillhub } from '../hooks/useSkillhub';
import type { MarketSkill } from '../hooks/useMarketList';
import { LocalSkillControls } from './LocalSkillControls';
@@ -15,16 +15,7 @@ export function MarketLocalSkills({ skill }: {
const { t } = useTranslation();
const { skills } = useSkillhub();
const [selectedId, setSelectedId] = useState<string | null>(null);
- const copies = skills.filter((local) => {
- // Use the physically joined registry identity; casing alone cannot prove
- // ownership on case-sensitive volumes. Old scans keep exact-name matching.
- const localName = local.registryEntry ? local.registrySkillName ?? local.name : local.name;
- if (local.kind !== 'skill' || localName !== skill.name) return false;
- return local.registryEntry
- ? skillhubCatalogKey(localName, local.registryEntry.catalogScope)
- === skillhubCatalogKey(skill.name, skill.catalogScope)
- : skill.isMine;
- });
+ const copies = marketLocalCopies(skills, skill);
if (copies.length === 0) return null;
const selected = copies.find((local) => local.id === selectedId) ?? copies[0]!;
diff --git a/apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx b/apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx
new file mode 100644
index 0000000000..3e0373dfe4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx
@@ -0,0 +1,57 @@
+import type { ReactNode } from 'react';
+import { ArrowLeft } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
+import { cn } from '@/lib/utils';
+import { useTranslation } from 'react-i18next';
+import type { useMetaColumnResize } from '../hooks/useMetaColumnResize';
+
+export function SkillDetailPage({ children }: { children: ReactNode }) {
+ return <div className="flex h-full min-h-0 w-full flex-col motion-safe:animate-[detail-soft-in_220ms_ease-out]">{children}</div>;
+}
+
+export function SkillDetailHeader({ title, badges, subtitle, actions, backLabel, onBack }: {
+ title: ReactNode; badges?: ReactNode; subtitle?: ReactNode; actions?: ReactNode;
+ backLabel: string; onBack: () => void;
+}) {
+ return (
+ <header className="flex min-h-[72px] w-full shrink-0 items-center gap-4 border-b border-[var(--cmd-palette-border)] py-3 pl-4 pr-6" style={WINDOW_DRAG_STYLE}>
+ <Button variant="secondary" size="lg" className="w-9 p-0" style={WINDOW_NO_DRAG_STYLE} onClick={onBack} aria-label={backLabel} title={backLabel}>
+ <ArrowLeft size={18} />
+ </Button>
+ <div className="flex min-w-0 flex-1 flex-col gap-1 overflow-hidden">
+ <div className="flex min-w-0 items-center gap-2">
+ <h2 className="min-w-0 truncate text-lg font-medium leading-tight text-[var(--msg-assistant-text)]">{title}</h2>
+ {badges && <span className="flex shrink-0 items-center gap-2" style={WINDOW_NO_DRAG_STYLE}>{badges}</span>}
+ </div>
+ {subtitle}
+ </div>
+ <div className="flex max-w-[60%] shrink-0 items-center gap-2 overflow-x-auto" style={WINDOW_NO_DRAG_STYLE}>{actions}</div>
+ </header>
+ );
+}
+
+export function SkillDetailColumns({ children, resizing = false }: { children: ReactNode; resizing?: boolean }) {
+ return <div className={cn('relative flex min-h-0 w-full flex-1', resizing && 'select-none cursor-col-resize')}>{children}</div>;
+}
+
+export function SkillDetailSidebar({ children, width }: { children: ReactNode; width: number }) {
+ return <aside className="relative flex h-full shrink-0 select-text flex-col gap-4 overflow-y-auto border-r border-[var(--cmd-palette-border)] px-3 py-4" style={{ width }}>{children}</aside>;
+}
+
+export function SkillDetailContent({ children, editing = false, compact = false }: { children: ReactNode; editing?: boolean; compact?: boolean }) {
+ return <div className={cn('flex min-w-0 flex-1 flex-col', editing ? 'overflow-hidden' : 'overflow-y-auto px-8 pb-8', !editing && (compact ? 'pt-2' : 'pt-8'))}>{children}</div>;
+}
+
+export function SkillDetailResizeHandle({ resize }: { resize: ReturnType<typeof useMetaColumnResize> }) {
+ const { t } = useTranslation();
+ return <hr aria-orientation="vertical" aria-valuemin={resize.minWidth} aria-valuemax={resize.maxWidth}
+ aria-valuenow={resize.width} aria-label={t('skillhub.detail.resizeUsageFilesColumn')} tabIndex={0}
+ className="absolute right-0 top-0 z-10 m-0 h-full w-[4px] cursor-col-resize border-0 bg-transparent p-0 transition-colors hover:bg-[var(--file-chip-bg)] focus-visible:bg-[var(--file-chip-bg)] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-[var(--focus-ring-soft)]"
+ onPointerDown={resize.handleDragStart} onDoubleClick={resize.resetWidth}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
+ event.preventDefault(); resize.resizeByKeyboard(event.key === 'ArrowLeft' ? -1 : 1, event.shiftKey);
+ } else if (event.key === 'Enter') { event.preventDefault(); resize.resetWidth(); }
+ }} />;
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx b/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx
index 207431d2ee..19d287fce6 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx
@@ -55,7 +55,7 @@ it('does not dismiss or repeat installation while the selected operation is pend
it('consumes Escape so an underlying window-level handler cannot close the host surface', async () => {
window.electronAPI = { skillhub: { registry: { getByName: vi.fn().mockResolvedValue({ success: false }) } } } as never;
- // SkillhubMarketPreviewPanel keeps a window-level Escape listener mounted
+ // SkillhubMarketDetailView keeps a window-level Escape listener mounted
// while the picker is stacked on top; the picker must consume the key
// itself instead of letting it reach the host surface.
const underlying = vi.fn();
diff --git a/apps/desktop/src/renderer/features/skillhub/components/__tests__/MarketLocalSkills.test.tsx b/apps/desktop/src/renderer/features/skillhub/components/__tests__/MarketLocalSkills.test.tsx
index 3dc5e241c9..54573cee77 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/__tests__/MarketLocalSkills.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/MarketLocalSkills.test.tsx
@@ -24,7 +24,7 @@ import type { MarketSkill } from '../../hooks/useMarketList';
import { MarketCard } from '../MarketCard';
import { HomeMarketCard } from '../HomeMarketCard';
import { MarketLocalSkills } from '../MarketLocalSkills';
-import { SkillhubMarketPreviewPanel } from '../../SkillhubMarketPreviewPanel';
+import { SkillhubMarketDetailView } from '../../SkillhubMarketDetailView';
const market: MarketSkill = {
name: 'gws-calendar', latestVersion: '1.0.2', isMine: false, catalogScope: 'market',
@@ -72,7 +72,7 @@ describe.each(['home', 'card'] as const)('market %s list', (surface) => {
describe('market Skill details', () => {
it('shows gws-calendar 1.0.2 controls and targets the scanned local copy', async () => {
- render(<MemoryRouter><SkillhubMarketPreviewPanel skill={market} open onClose={vi.fn()}
+ render(<MemoryRouter><SkillhubMarketDetailView skill={market} open onClose={vi.fn()}
primaryAction="clone" onClone={vi.fn()} /></MemoryRouter>);
expect(screen.queryByText('skillhub.sidebar.marketInstalledHeading')).toBeNull();
const clone = screen.getByRole('button', { name: 'skillhub.marketCard.clone' });
@@ -87,7 +87,7 @@ describe('market Skill details', () => {
});
it('disables Learn this skill when the built-in Learn Skill is disabled', async () => {
- render(<MemoryRouter><SkillhubMarketPreviewPanel skill={market} open onClose={vi.fn()}
+ render(<MemoryRouter><SkillhubMarketDetailView skill={market} open onClose={vi.fn()}
primaryAction="clone" onClone={vi.fn()} learnSkillEnabled={false} /></MemoryRouter>);
const learn = await screen.findByRole('button', { name: 'learn.hub.learnButton' });
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useMarketList.test.tsx b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useMarketList.test.tsx
new file mode 100644
index 0000000000..b3fd78237d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useMarketList.test.tsx
@@ -0,0 +1,105 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { useMarketList } from '../useMarketList';
+
+const mocks = vi.hoisted(() => ({ skills: [] as SkillhubSkill[], listMarket: vi.fn(), t: (key: string) => key }));
+vi.mock('../useSkillhub', () => ({ useSkillhub: () => ({ skills: mocks.skills }) }));
+vi.mock('react-i18next', async (original) => ({
+ ...await original<typeof import('react-i18next')>(),
+ useTranslation: () => ({ t: mocks.t, i18n: { language: 'en' } }),
+}));
+const item = {
+ name: 'google-play-console', authorId: 'creator', authorName: 'Creator', isMine: true, isCreator: true,
+ canManage: true, catalogScope: 'market', latestVersion: '1.0.1', publishedAt: '2026-09-20T00:00:00Z',
+};
+const page = { success: true, items: [item], nextCursor: 'next' };
+function mount() { return renderHook(() => useMarketList('all', { initialScope: 'market' })); }
+beforeEach(() => {
+ setDataOwnerGeneration('owner-a', 1);
+ mocks.skills = [];
+ mocks.listMarket.mockReset().mockResolvedValue(page);
+ vi.stubGlobal('electronAPI', { skillhub: { listMarket: mocks.listMarket } });
+});
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+
+it.each(['error', 'throw'])('preserves loaded data on refresh failure (%s), then retries without re-entering', async (failure) => {
+ const hook = mount();
+ await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
+ if (failure === 'error') mocks.listMarket.mockResolvedValueOnce({ success: false, error: 'RATE_LIMITED' });
+ else mocks.listMarket.mockRejectedValueOnce(new Error('RATE_LIMITED'));
+ act(() => hook.result.current.reload());
+ await waitFor(() => expect(hook.result.current.error).toBe('RATE_LIMITED'));
+ expect(hook.result.current.items[0]?.name).toBe(item.name);
+ expect(hook.result.current.hasMore).toBe(true);
+ mocks.listMarket.mockResolvedValueOnce({ ...page, items: [{ ...item, latestVersion: '1.0.2' }] });
+ act(() => hook.result.current.reload());
+ await waitFor(() => expect(hook.result.current.items[0]?.latestVersion).toBe('1.0.2'));
+ expect(hook.result.current.error).toBeNull();
+});
+
+it('exposes pagination failures while keeping the current page', async () => {
+ const hook = mount();
+ await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
+ mocks.listMarket.mockResolvedValueOnce({ success: false, error: 'RATE_LIMITED' });
+ await act(() => hook.result.current.loadMore());
+ expect(hook.result.current.error).toBe('RATE_LIMITED');
+ expect(hook.result.current.items).toHaveLength(1);
+});
+
+it('does not retain another filter or account list when the next request fails', async () => {
+ const hook = mount();
+ await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
+ mocks.listMarket.mockResolvedValue({ success: false, error: 'offline' });
+ act(() => hook.result.current.setCategoryFilter('new-category'));
+ await waitFor(() => expect(hook.result.current.error).toBe('offline'));
+ expect(hook.result.current.items).toEqual([]);
+ mocks.listMarket.mockResolvedValue(page);
+ act(() => hook.result.current.reload());
+ await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
+ mocks.listMarket.mockResolvedValue({ success: false, error: 'offline' });
+ setDataOwnerGeneration('owner-b', 2);
+ hook.rerender();
+ expect(hook.result.current.items).toEqual([]);
+ await waitFor(() => expect(hook.result.current.error).toBe('offline'));
+ expect(hook.result.current.items).toEqual([]);
+});
+
+it('ignores a stale reply from a previous account', async () => {
+ let finish!: (value: typeof page) => void;
+ mocks.listMarket.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ const hook = mount();
+ setDataOwnerGeneration('owner-b', 2);
+ await act(async () => finish(page));
+ mocks.listMarket.mockImplementationOnce(() => new Promise(() => {}));
+ hook.rerender();
+ expect(hook.result.current.items).toEqual([]);
+});
+
+it('derives download updates for the native author copy using list metadata only', async () => {
+ mocks.skills = [{
+ id: 'authored', kind: 'skill', name: 'local-folder', registrySkillName: item.name,
+ absolutePath: '/skills/google-play-console', scope: 'global',
+ registryEntry: { version: '1.0.0', origin: 'published', authorId: item.authorId },
+ } as SkillhubSkill];
+ const hook = mount();
+ await waitFor(() => expect(hook.result.current.items[0]).toMatchObject({
+ isCreator: true, updateAvailable: true, installedLocally: true,
+ installedAbsolutePath: '/skills/google-play-console', installedVersion: '1.0.0',
+ }));
+ expect(mocks.listMarket).toHaveBeenCalledTimes(1);
+});
+
+it.each([
+ { isCreator: false }, { isCreator: undefined }, { canManage: false }, { authorId: 'someone-else' },
+])('does not merge an unrelated native author copy (%j)', async (overrides) => {
+ mocks.skills = [{
+ kind: 'skill', name: item.name, absolutePath: '/skills/other', scope: 'global',
+ registryEntry: { version: '1.0.0', origin: 'published', authorId: item.authorId },
+ } as SkillhubSkill];
+ mocks.listMarket.mockResolvedValue({ ...page, items: [{ ...item, ...overrides }] });
+ const hook = mount();
+ await waitFor(() => expect(hook.result.current.items).toHaveLength(1));
+ expect(hook.result.current.items[0]).toMatchObject({ installedLocally: false, updateAvailable: false });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useMarketSkillUpdate.test.tsx b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useMarketSkillUpdate.test.tsx
new file mode 100644
index 0000000000..d27f780ee6
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useMarketSkillUpdate.test.tsx
@@ -0,0 +1,169 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import type { MarketSkill } from '../useMarketList';
+import { useMarketSkillUpdate } from '../useMarketSkillUpdate';
+import { HomeMarketCard } from '../../components/HomeMarketCard';
+import { MarketCard } from '../../components/MarketCard';
+
+const mocks = vi.hoisted(() => ({
+ comparePublished: vi.fn(), refresh: vi.fn(), install: vi.fn(), invalidateHash: vi.fn(), invalidateInfo: vi.fn(),
+ success: vi.fn(), error: vi.fn(), t: (key: string) => key,
+}));
+vi.mock('../useSkillhub', () => ({ refresh: mocks.refresh }));
+vi.mock('../useSkillFolderHash', () => ({ invalidateHash: mocks.invalidateHash }));
+vi.mock('../../lib/infoDedupe', () => ({ invalidate: mocks.invalidateInfo }));
+vi.mock('@/lib/toast', () => ({ toast: { success: mocks.success, error: mocks.error } }));
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
+ useTranslation: () => ({ t: mocks.t, i18n: { language: 'en' } }),
+}));
+
+const skill: MarketSkill = {
+ name: 'calendar', displayName: 'Calendar', description: 'Calendar tools',
+ authorId: 'publisher', authorName: 'Publisher', authorAvatarUrl: null, avatarInitial: 'P',
+ isMine: false, canManage: false, latestVersion: '1.0.2', visibility: 'PUBLIC',
+ catalogScope: 'market', visibleDeptIds: [], categories: [], tags: [], githubUrl: null,
+ publishedAt: '2026-09-01', relativeTime: 'today', downloads: 0,
+ installedLocally: true, installedVersion: '1.0.1', installedAbsolutePath: '/global/calendar',
+ hasAnyInstall: true, latestPublishedFromDeviceId: null, cardState: 'installed-outdated', updateAvailable: true,
+};
+const local = {
+ name: skill.name, kind: 'skill', absolutePath: skill.installedAbsolutePath,
+ registryEntry: { version: '1.0.1', catalogScope: 'market' },
+} as SkillhubSkill;
+const success = { success: true, name: skill.name, version: skill.latestVersion, absolutePath: local.absolutePath };
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ setDataOwnerGeneration('owner');
+ mocks.refresh.mockResolvedValue([local]);
+ mocks.install.mockResolvedValue(success);
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { skillhub: { install: mocks.install, comparePublished: mocks.comparePublished } } });
+});
+afterEach(cleanup);
+
+describe.each(['home', 'market'] as const)('%s direct update action', (surface) => {
+ it('updates in place from the card, blocks repeated clicks, then shows installed', async () => {
+ let finish!: (value: typeof success) => void;
+ mocks.install.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ const onClick = vi.fn();
+ const onClone = vi.fn();
+ function Card({ value }: { value: MarketSkill }) {
+ const { update, updatingNames } = useMarketSkillUpdate();
+ const props = { skill: value, onUpdate: update, updating: updatingNames.has(value.name), onClick };
+ return surface === 'home' ? <HomeMarketCard {...props} /> : <MarketCard {...props} onClone={onClone} />;
+ }
+ const { container, rerender } = render(<Card value={skill} />);
+ const button = screen.getByRole('button', { name: 'skillhub.marketCard.updateAvailable' });
+ expect(container.querySelector('button button')).toBeNull();
+ fireEvent.click(button);
+ fireEvent.click(button);
+ await waitFor(() => expect(mocks.install).toHaveBeenCalledExactlyOnceWith({
+ name: skill.name, version: skill.latestVersion, catalogScope: 'market',
+ installPath: local.absolutePath, force: true, skipBackup: false,
+ }));
+ expect((screen.getByRole('button', { name: 'skillhub.detail.updating' }) as HTMLButtonElement).disabled).toBe(true);
+ expect(onClick).not.toHaveBeenCalled();
+ expect(onClone).not.toHaveBeenCalled();
+ await act(async () => { finish(success); });
+ expect(mocks.refresh).toHaveBeenCalledTimes(2);
+ expect(mocks.invalidateHash).toHaveBeenCalledWith(local.absolutePath);
+ expect(mocks.invalidateInfo).toHaveBeenCalledWith(skill.name, 'market');
+ expect(mocks.success).toHaveBeenCalledOnce();
+ rerender(<Card value={{ ...skill, updateAvailable: false, installedVersion: skill.latestVersion }} />);
+ expect(screen.queryByRole('button', { name: 'skillhub.marketCard.updateAvailable' })).toBeNull();
+ expect(screen.getByText('skillhub.home.installed')).toBeTruthy();
+ });
+
+ it('keeps update and detail keyboard actions separate', async () => {
+ const onUpdate = vi.fn();
+ const onClick = vi.fn();
+ const props = { skill, onUpdate, onClick };
+ render(surface === 'home' ? <HomeMarketCard {...props} /> : <MarketCard {...props} onClone={vi.fn()} />);
+ screen.getByRole('button', { name: 'skillhub.marketCard.updateAvailable' }).focus();
+ await userEvent.keyboard('{Enter}');
+ await userEvent.keyboard(' ');
+ expect(onUpdate).toHaveBeenCalledTimes(2);
+ expect(onClick).not.toHaveBeenCalled();
+ screen.getByRole('button', { name: skill.displayName }).focus();
+ await userEvent.keyboard('{Enter}');
+ expect(onClick).toHaveBeenCalledExactlyOnceWith(skill);
+ });
+});
+
+it.each(['home', 'market'])('never performs publication comparisons on the %s catalog card', async (surface) => {
+ const authored = { ...skill, isCreator: true, isMine: true, canManage: true };
+ render(surface === 'home' ? <HomeMarketCard skill={authored} onClick={vi.fn()} /> : <MarketCard skill={authored} onClone={vi.fn()} />);
+ await act(async () => {});
+ expect(mocks.comparePublished).not.toHaveBeenCalled();
+ expect(screen.queryByText('skillhub.publishComparison.updateAvailable')).toBeNull();
+});
+
+it('updates the original author copy from its public projection with a backup', async () => {
+ const authored = { ...local, registryEntry: { version: '1.0.0', origin: 'published', authorId: skill.authorId } };
+ mocks.refresh.mockResolvedValue([authored]);
+ const { result } = renderHook(useMarketSkillUpdate);
+ await act(() => result.current.update({ ...skill, isCreator: true, isMine: true, canManage: true }));
+ expect(mocks.install).toHaveBeenCalledExactlyOnceWith({
+ name: skill.name, version: skill.latestVersion, catalogScope: 'market',
+ installPath: local.absolutePath, force: true, skipBackup: false,
+ });
+});
+
+it('does not update a same-slug native publication belonging to another owner', async () => {
+ mocks.refresh.mockResolvedValue([{ ...local, registryEntry: { version: '1.0.0', origin: 'published', authorId: 'other' } }]);
+ const { result } = renderHook(useMarketSkillUpdate);
+ await act(() => result.current.update({ ...skill, isCreator: true, isMine: true, canManage: true }));
+ expect(mocks.install).not.toHaveBeenCalled();
+});
+
+describe('direct update registry and owner boundaries', () => {
+ it.each([
+ [],
+ [{ ...local, registryEntry: null }],
+ [{ ...local, registryEntry: { ...local.registryEntry, catalogScope: 'team' } }],
+ [{ ...local, registryEntry: { ...local.registryEntry, version: skill.latestVersion } }],
+ [{ ...local, registryEntry: { ...local.registryEntry, version: '2.0.0' } }],
+ [{ ...local, name: 'another-skill' }],
+ [{ ...local, absolutePath: '/another/calendar' }],
+ ])('does not overwrite a stale or unrelated installation %#', async (...locals) => {
+ mocks.refresh.mockResolvedValue(locals);
+ const { result } = renderHook(useMarketSkillUpdate);
+ await act(() => result.current.update(skill));
+ expect(mocks.install).not.toHaveBeenCalled();
+ expect(result.current.updatingNames.size).toBe(0);
+ });
+
+ it.each(['failure', 'throw'] as const)('recovers from %s and allows retry', async (mode) => {
+ if (mode === 'failure') mocks.install.mockResolvedValueOnce({ success: false, errorCode: 'DOWNLOAD_FAILED' });
+ else mocks.install.mockRejectedValueOnce(new Error('IPC disconnected'));
+ const { result } = renderHook(useMarketSkillUpdate);
+ await act(() => result.current.update(skill));
+ expect(mocks.error).toHaveBeenCalledExactlyOnceWith('skillhub.marketCard.updateFailed');
+ expect(result.current.updatingNames.size).toBe(0);
+ await act(() => result.current.update(skill));
+ expect(mocks.install).toHaveBeenCalledTimes(2);
+ expect(mocks.success).toHaveBeenCalledOnce();
+ });
+
+ it('stops before installation if the owner changes during the rescan', async () => {
+ mocks.refresh.mockImplementationOnce(async () => { setDataOwnerGeneration('other'); return [local]; });
+ const { result } = renderHook(useMarketSkillUpdate);
+ await act(() => result.current.update(skill));
+ expect(mocks.install).not.toHaveBeenCalled();
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ });
+
+ it('ignores completion from a previous owner', async () => {
+ mocks.install.mockImplementationOnce(async () => { setDataOwnerGeneration('other'); return success; });
+ const { result } = renderHook(useMarketSkillUpdate);
+ await act(() => result.current.update(skill));
+ expect(mocks.refresh).toHaveBeenCalledTimes(1);
+ expect(mocks.invalidateHash).not.toHaveBeenCalled();
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillPublishComparison.test.tsx b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillPublishComparison.test.tsx
new file mode 100644
index 0000000000..adf035266f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillPublishComparison.test.tsx
@@ -0,0 +1,144 @@
+// @vitest-environment jsdom
+import { StrictMode } from 'react';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { SkillhubPublishComparison } from '../../../../../shared/skillhubPublishComparison';
+
+let useSkillPublishComparison: typeof import('../useSkillPublishComparison').useSkillPublishComparison;
+let invalidatePublishComparison: typeof import('../useSkillPublishComparison').invalidatePublishComparison;
+let setDataOwnerGeneration: typeof import('@/contexts/dataOwnerGeneration').setDataOwnerGeneration;
+const comparePublished = vi.fn();
+const skill = (name = 'demo') => ({ id: name, kind: 'skill', absolutePath: '/skills/' + name, registryEntry: null }) as SkillhubSkill;
+const same: SkillhubPublishComparison = { status: 'same', version: '1.0.0', pending: false };
+const different: SkillhubPublishComparison = { status: 'different', version: '1.0.0', pending: false };
+
+beforeEach(async () => {
+ vi.resetModules();
+ comparePublished.mockReset().mockResolvedValue(same);
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { skillhub: { comparePublished } } });
+ ({ setDataOwnerGeneration } = await import('@/contexts/dataOwnerGeneration'));
+ setDataOwnerGeneration('owner-a', 1);
+ ({ useSkillPublishComparison, invalidatePublishComparison } = await import('../useSkillPublishComparison'));
+});
+afterEach(() => { cleanup(); vi.restoreAllMocks(); });
+
+it('reuses fresh focus reads, then refreshes after expiry or local mutation without polling', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);
+ const hook = renderHook(() => useSkillPublishComparison(skill()));
+ await waitFor(() => expect(hook.result.current.comparison).toEqual(same));
+ comparePublished.mockResolvedValue(different);
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(hook.result.current.comparison).toEqual(same));
+ expect(comparePublished).toHaveBeenCalledTimes(1);
+ clock.mockReturnValue(131_000);
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(hook.result.current.comparison).toEqual(different));
+ comparePublished.mockResolvedValue(same);
+ act(() => invalidatePublishComparison('/skills/demo'));
+ await waitFor(() => expect(hook.result.current.comparison).toEqual(same));
+ expect(comparePublished).toHaveBeenCalledTimes(3);
+});
+
+it('deduplicates concurrent and StrictMode consumers', async () => {
+ let resolve!: (value: SkillhubPublishComparison) => void;
+ comparePublished.mockImplementation(() => new Promise((done) => { resolve = done; }));
+ const first = renderHook(() => useSkillPublishComparison(skill()), { wrapper: StrictMode });
+ const second = renderHook(() => useSkillPublishComparison(skill()));
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(1));
+ act(() => resolve(different));
+ await waitFor(() => expect(first.result.current.comparison).toEqual(different));
+ expect(second.result.current.comparison).toEqual(different);
+});
+
+it('bounds concurrent scans for a large local list', async () => {
+ const resolves: Array<(value: SkillhubPublishComparison) => void> = [];
+ comparePublished.mockImplementation(() => new Promise((done) => { resolves.push(done); }));
+ for (let n = 0; n < 5; n++) renderHook(() => useSkillPublishComparison(skill(String(n))));
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(3));
+ act(() => resolves[0](same));
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(4));
+ act(() => resolves[1](same));
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(5));
+ await act(async () => resolves.forEach((resolve) => resolve(same)));
+});
+
+it('drops stale results after switching skill, refreshing or changing accounts', async () => {
+ let stale!: (value: SkillhubPublishComparison) => void;
+ comparePublished.mockImplementationOnce(() => new Promise((done) => { stale = done; }));
+ const hook = renderHook(({ name }) => useSkillPublishComparison(skill(name)), { initialProps: { name: 'old' } });
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(1));
+ setDataOwnerGeneration('owner-b', 2);
+ hook.rerender({ name: 'new' });
+ await waitFor(() => expect(hook.result.current.comparison).toEqual(same));
+ await act(async () => stale(different));
+ expect(hook.result.current.comparison).toEqual(same);
+});
+
+it('maps both rejected IPC and error envelopes to unavailable, never clean', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);
+ comparePublished.mockRejectedValueOnce(new Error('offline'));
+ const hook = renderHook(() => useSkillPublishComparison(skill()));
+ await waitFor(() => expect(hook.result.current.comparison.status).toBe('unavailable'));
+ clock.mockReturnValue(131_000);
+ comparePublished.mockResolvedValueOnce({ success: false, error: 'grant revoked' });
+ act(() => invalidatePublishComparison());
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(hook.result.current.comparison.status).toBe('unavailable'));
+});
+
+
+it('cancels queued comparisons when their last consumer leaves', async () => {
+ const resolves: Array<(value: SkillhubPublishComparison) => void> = [];
+ comparePublished.mockImplementation(() => new Promise((done) => { resolves.push(done); }));
+ const hooks = Array.from({ length: 20 }, (_, n) => renderHook(() => useSkillPublishComparison(skill(String(n)))));
+ await waitFor(() => expect(comparePublished).toHaveBeenCalledTimes(3));
+ hooks.forEach((hook) => hook.unmount());
+ await act(async () => resolves.forEach((resolve) => resolve(same)));
+ expect(comparePublished).toHaveBeenCalledTimes(3);
+});
+
+it('shares fresh results across navigation but not across account generations', async () => {
+ const first = renderHook(() => useSkillPublishComparison(skill()));
+ await waitFor(() => expect(first.result.current.comparison).toEqual(same));
+ first.unmount();
+ const second = renderHook(() => useSkillPublishComparison(skill()));
+ await waitFor(() => expect(second.result.current.comparison).toEqual(same));
+ expect(comparePublished).toHaveBeenCalledTimes(1);
+ second.unmount();
+ setDataOwnerGeneration('owner-b', 2);
+ const third = renderHook(() => useSkillPublishComparison(skill()));
+ await waitFor(() => expect(third.result.current.comparison).toEqual(same));
+ expect(comparePublished).toHaveBeenCalledTimes(2);
+});
+
+it('stops draining network requests after failure and permits a later focus retry', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);
+ comparePublished.mockResolvedValue({ status: 'unavailable', reason: 'service' });
+ const hooks = Array.from({ length: 20 }, (_, n) => renderHook(() => useSkillPublishComparison(skill(String(n)))));
+ await waitFor(() => expect(hooks.every((hook) => hook.result.current.comparison.status === 'unavailable')).toBe(true));
+ expect(comparePublished).toHaveBeenCalledTimes(3);
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(hooks.every((hook) => hook.result.current.comparison.status === 'unavailable')).toBe(true));
+ expect(comparePublished).toHaveBeenCalledTimes(3);
+ hooks.slice(1).forEach((hook) => hook.unmount());
+ comparePublished.mockResolvedValue(same);
+ clock.mockReturnValue(131_000);
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(hooks[0].result.current.comparison).toEqual(same));
+ expect(comparePublished).toHaveBeenCalledTimes(4);
+});
+
+
+it('keeps a local comparison failure isolated and retries repaired content immediately', async () => {
+ const broken = skill('broken');
+ comparePublished.mockImplementation(async ({ skillId }) => skillId === broken.id ? { status: 'unavailable' } : same);
+ const first = renderHook(() => useSkillPublishComparison(broken));
+ const healthy = Array.from({ length: 6 }, (_, n) => renderHook(() => useSkillPublishComparison(skill(String(n)))));
+ await waitFor(() => expect(first.result.current.comparison.status).toBe('unavailable'));
+ await waitFor(() => expect(healthy.every((hook) => hook.result.current.comparison.status === 'same')).toBe(true));
+ expect(comparePublished).toHaveBeenCalledTimes(7);
+ comparePublished.mockResolvedValue(same);
+ act(() => invalidatePublishComparison(broken.absolutePath));
+ await waitFor(() => expect(first.result.current.comparison).toEqual(same));
+ expect(comparePublished).toHaveBeenCalledTimes(8);
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
index 357f764b67..2e251abfe2 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketList.ts
@@ -11,8 +11,8 @@
* 2. 把服务端 ListSkillItem 映射成视图模型 MarketSkill。
* 3. 跨引用本地 useSkillhub().skills,标记 "已安装":
* - 别人的 skill:必须 registryEntry !== null 才算"装的"(避免把用户手写的同名 skill 误判为已装)。
- * - 自己的 skill (item.isMine=true):只要本地有同名目录就算"本地有副本",
- * 因为自己上传的 skill 不写 registry(registry 仅由 install 流程写入)。
+ * - 自己的 skill:兼容未注册的本地目录;原作者发布记录通过作者 + slug
+ * 关联同一条记录的公开投影,版本判断不额外请求详情或文件摘要。
* 版本号优先取 registryEntry.version,没有时回落 server 的 latestVersion。
*
* Stale-result guard:每次 fetch 拿一个 requestId,只有最后一次的结果才能
@@ -36,6 +36,7 @@ import { filterAvailableMarketItems } from '../lib/marketDetailViewModel';
import { useSkillhub } from './useSkillhub';
import { semverCompare } from '../versionUtils';
+import { publishedLocalIdentity, publishedMarketIdentity, type MarketLocalIdentity } from '../lib/marketLocalCopies';
export type SortBy = 'trending' | 'downloads' | 'updated_at' | 'created_at';
export type CatalogScope = 'all' | 'market' | 'team';
@@ -73,6 +74,7 @@ export interface MarketSkill {
/** Latin/中文首字符,用于头像 fallback。 */
avatarInitial: string;
isMine: boolean;
+ isCreator?: boolean;
canManage: boolean;
latestVersion: string;
visibility: 'PUBLIC' | 'DEPARTMENT_SCOPED';
@@ -106,6 +108,8 @@ export interface MarketSkill {
installedVersion: string | null;
/** 本地安装的 absolutePath(卸载时需要),未装为 null。 */
installedAbsolutePath: string | null;
+ /** A newer remote version is available for the registry-backed primary copy. */
+ updateAvailable?: boolean;
/** global 或 project 任何位置有安装(用于显示已装 badge + [+] 按钮)。 */
hasAnyInstall: boolean;
/** 跨设备识别:null = pre-feature 历史版本(不亮提示,按 mine 走) */
@@ -126,6 +130,7 @@ interface ServerListItem {
publisherName?: string;
authorAvatarUrl: string | null;
isMine: boolean;
+ isCreator?: boolean;
canManage: boolean;
latestVersion: string;
visibility: 'PUBLIC' | 'DEPARTMENT_SCOPED';
@@ -203,6 +208,7 @@ export interface LocalSkillIndex {
byCatalogKey: Map<string, LocalSkillGroup>;
/** User-authored local folders have no remote scope and only back owned items. */
untrackedByName: Map<string, LocalSkillGroup>;
+ publishedByIdentity?: Map<string, LocalSkillGroup>;
}
function addLocalEntry(
@@ -216,15 +222,20 @@ function addLocalEntry(
group = { global: undefined, projects: [] };
index.set(key, group);
}
- if (scope === 'global') group.global = entry;
+ if (scope === 'global') group.global ??= entry;
else group.projects.push(entry);
}
export function localGroupForItem(
- item: { name: string; isMine: boolean; catalogScope?: SkillhubCatalogScope },
+ item: MarketLocalIdentity,
index: LocalSkillIndex,
): LocalSkillGroup | undefined {
- const tracked = index.byCatalogKey.get(skillhubCatalogKey(item.name, item.catalogScope));
+ const identity = publishedMarketIdentity(item);
+ const authored = identity ? index.publishedByIdentity?.get(identity) : undefined;
+ const exact = index.byCatalogKey.get(skillhubCatalogKey(item.name, item.catalogScope));
+ const tracked = exact && authored ? {
+ global: exact.global ?? authored.global, projects: [...exact.projects, ...authored.projects],
+ } : exact ?? authored;
if (!item.isMine) return tracked;
const untracked = index.untrackedByName.get(item.name);
if (!tracked) return untracked;
@@ -244,7 +255,7 @@ export function deriveCardState(
// 只看 global 位置决定 cardState(影响"可获取"筛选)。
// project-level 安装不改变卡片主状态,用户仍可从 target picker 装到其他位置。
const g = group?.global;
- // 自己发布的 skill 不写 registry —— 改用「全局目录是否存在」判定已装。
+ // 自己发布的 skill 可能没有 registry —— 全局目录存在时仍能判定已装。
// 换机器 / 卸载后本地无目录 → not-installed,进入「可获取」可重新下载(修正 !isMine 排除 bug)。
if (item.isMine) return g ? 'installed-latest' : 'not-installed';
if (!g || !g.hasRegistryEntry) return 'not-installed';
@@ -253,6 +264,25 @@ export function deriveCardState(
return semverCompare(item.latestVersion, g.version) > 0 ? 'installed-outdated' : 'installed-latest';
}
+export function deriveLocalInstall(
+ item: Pick<MarketSkill, 'isMine' | 'latestVersion'>,
+ group: LocalSkillGroup | undefined,
+) {
+ // Keep the badge and update action on the same copy: global, then first project.
+ const primary = group?.global ?? group?.projects[0];
+ const installed = !!primary && (item.isMine || primary.hasRegistryEntry);
+ return {
+ installedLocally: installed,
+ installedVersion: installed ? primary.version : null,
+ installedAbsolutePath: installed ? primary.absolutePath : null,
+ updateAvailable: !!primary?.hasRegistryEntry && !!primary.version
+ && semverCompare(item.latestVersion, primary.version) > 0,
+ hasAnyInstall: !!group && (
+ !!group.global?.hasRegistryEntry || group.projects.some((entry) => entry.hasRegistryEntry)
+ ),
+ };
+}
+
function mapServerToView(
item: ServerListItem,
localIndex: LocalSkillIndex,
@@ -260,15 +290,6 @@ function mapServerToView(
translate: TFunction,
): MarketSkill {
const group = localGroupForItem(item, localIndex);
- // 优先用 global entry 作为"主安装"信息(版本、路径);没有 global 时回落到第一个 project entry。
- const primary = group?.global ?? group?.projects[0];
- // mine:只要本地同名目录存在就算有副本(自己发布的 skill 不写 registry)。
- // 别人的:必须 hasRegistryEntry=true 才算装的(保护用户手写的同名 skill)。
- const isReallyInstalled = !!primary && (item.isMine || primary.hasRegistryEntry);
- const hasAnyInstall = !!group && (
- (!!group.global && group.global.hasRegistryEntry) ||
- group.projects.some((p) => p.hasRegistryEntry)
- );
return {
name: item.name,
icon: item.icon,
@@ -280,6 +301,7 @@ function mapServerToView(
authorAvatarUrl: item.authorAvatarUrl ?? null,
avatarInitial: deriveAvatarInitial(item.authorName),
isMine: item.isMine,
+ isCreator: item.isCreator,
canManage: item.canManage,
latestVersion: item.latestVersion,
visibility: item.visibility,
@@ -295,10 +317,7 @@ function mapServerToView(
publishedAt: item.publishedAt,
relativeTime: formatMarketRelativeTime(item.publishedAt, translate),
downloads: Number.isFinite(item.downloads) ? item.downloads ?? 0 : 0,
- installedLocally: isReallyInstalled,
- installedVersion: isReallyInstalled ? primary.version : null,
- installedAbsolutePath: isReallyInstalled ? primary.absolutePath : null,
- hasAnyInstall,
+ ...deriveLocalInstall(item, group),
latestPublishedFromDeviceId: item.latestPublishedFromDeviceId,
cardState: deriveCardState(item, group, installingNames.has(item.name)),
catalogScope: item.catalogScope,
@@ -306,6 +325,7 @@ function mapServerToView(
}
interface MarketListState {
+ queryKey: string | null;
items: MarketSkill[];
loading: boolean;
loadingMore: boolean;
@@ -316,6 +336,7 @@ interface MarketListState {
}
const INITIAL: MarketListState = {
+ queryKey: null,
items: [],
loading: false,
loadingMore: false,
@@ -350,16 +371,19 @@ export function useMarketList(
initialScope?: CatalogScope;
/** Fixed catalog surfaces can avoid an extra request by declaring their initial sort. */
initialSort?: SortBy;
+ initialSearchQuery?: string;
+ initialCategoryFilter?: CategoryFilter;
},
) {
const enabled = options?.enabled ?? true;
+ const owner = getDataOwnerGeneration();
const { t, i18n: i18next } = useTranslation();
- const [searchQuery, setSearchQueryState] = useState('');
+ const [searchQuery, setSearchQueryState] = useState(options?.initialSearchQuery ?? '');
const [sortBy, setSortByState] = useState<SortBy>(() => options?.initialSort ?? 'updated_at');
const [catalogScope, setCatalogScopeState] = useState<CatalogScope>(
() => options?.initialScope ?? 'all',
);
- const [categoryFilter, setCategoryFilterState] = useState<CategoryFilter>(CATEGORY_ALL);
+ const [categoryFilter, setCategoryFilterState] = useState<CategoryFilter>(options?.initialCategoryFilter ?? CATEGORY_ALL);
// 默认展示当前身份可见的完整目录;“我的管理”由列表页显式切换。
const [visibility, setVisibilityState] = useState<Visibility>(() => initialVisibility);
const [state, setState] = useState<MarketListState>(INITIAL);
@@ -375,6 +399,7 @@ export function useMarketList(
...(() => {
const byCatalogKey = new Map<string, LocalSkillGroup>();
const untrackedByName = new Map<string, LocalSkillGroup>();
+ const publishedByIdentity = new Map<string, LocalSkillGroup>();
for (const s of localSkills) {
if (s.kind !== 'skill') continue;
const entry: LocalSkillEntry = {
@@ -384,11 +409,13 @@ export function useMarketList(
};
const index = s.registryEntry ? byCatalogKey : untrackedByName;
const key = s.registryEntry
- ? skillhubCatalogKey(s.name, s.registryEntry.catalogScope)
+ ? skillhubCatalogKey(s.registrySkillName ?? s.name, s.registryEntry.catalogScope)
: s.name;
addLocalEntry(index, key, s.scope, entry);
+ const identity = publishedLocalIdentity(s);
+ if (identity) addLocalEntry(publishedByIdentity, identity, s.scope, entry);
}
- return { byCatalogKey, untrackedByName };
+ return { byCatalogKey, untrackedByName, publishedByIdentity };
})(),
};
@@ -416,6 +443,7 @@ export function useMarketList(
available: false,
category: params.category,
});
+ if (!isDataOwnerGenerationCurrent(owner)) return { success: false };
if (!res.success) return { success: false, error: res.error };
return {
success: true,
@@ -424,7 +452,7 @@ export function useMarketList(
),
nextCursor: res.nextCursor ?? null,
};
- }, []);
+ }, [owner]);
const collectVisiblePage = useCallback(async (
params: FetchMarketPageInput & { available: boolean },
@@ -469,7 +497,13 @@ export function useMarketList(
category?: string;
}) => {
const myId = ++requestIdRef.current;
- setState((prev) => ({ ...prev, loading: true, error: null }));
+ const queryKey = JSON.stringify([owner, params]);
+ setState((prev) => ({
+ ...(prev.queryKey === queryKey ? prev : INITIAL),
+ queryKey, loading: true, loadingMore: false, error: null,
+ resolvedScope: params.scope, resolvedMine: params.mine,
+ }));
+ const fail = (error: string) => setState((prev) => ({ ...prev, loading: false, loadingMore: false, error }));
try {
const res = await collectVisiblePage({
sort: params.sort,
@@ -479,20 +513,13 @@ export function useMarketList(
available: params.available,
category: params.category,
});
- if (myId !== requestIdRef.current) return; // 旧响应,丢弃
+ if (myId !== requestIdRef.current || !isDataOwnerGenerationCurrent(owner)) return; // 旧响应,丢弃
if (!res.success) {
- setState({
- items: [],
- loading: false,
- loadingMore: false,
- error: res.error ?? i18n.t('skillhub.market.installError'),
- nextCursor: null,
- resolvedScope: params.scope,
- resolvedMine: params.mine,
- });
+ fail(res.error ?? i18n.t('skillhub.market.installError'));
return;
}
setState({
+ queryKey,
items: res.items ?? [],
loading: false,
loadingMore: false,
@@ -502,28 +529,20 @@ export function useMarketList(
resolvedMine: params.mine,
});
} catch (err) {
- if (myId !== requestIdRef.current) return;
- setState({
- items: [],
- loading: false,
- loadingMore: false,
- error: err instanceof Error ? err.message : String(err),
- nextCursor: null,
- resolvedScope: params.scope,
- resolvedMine: params.mine,
- });
+ if (myId !== requestIdRef.current || !isDataOwnerGenerationCurrent(owner)) return;
+ fail(err instanceof Error ? err.message : String(err));
}
},
// installedNames/localIndex 通过 ref 读取最新值;
// fetchPage 自身只由 sort/q/mine 调用方参数驱动。
- [collectVisiblePage],
+ [collectVisiblePage, owner],
);
const loadMore = useCallback(async () => {
const cursor = state.nextCursor;
if (!cursor || state.loadingMore || state.loading) return;
const myId = requestIdRef.current;
- setState((prev) => ({ ...prev, loadingMore: true }));
+ setState((prev) => ({ ...prev, loadingMore: true, error: null }));
try {
const res = await collectVisiblePage({
cursor,
@@ -534,9 +553,9 @@ export function useMarketList(
available: visibility === 'available',
category: categoryFilter !== CATEGORY_ALL ? categoryFilter : undefined,
});
- if (myId !== requestIdRef.current) return;
+ if (myId !== requestIdRef.current || !isDataOwnerGenerationCurrent(owner)) return;
if (!res.success) {
- setState((prev) => ({ ...prev, loadingMore: false }));
+ setState((prev) => ({ ...prev, loadingMore: false, error: res.error ?? i18n.t('skillhub.market.installError') }));
return;
}
setState((prev) => ({
@@ -545,11 +564,11 @@ export function useMarketList(
loadingMore: false,
nextCursor: res.nextCursor ?? null,
}));
- } catch {
- if (myId !== requestIdRef.current) return;
- setState((prev) => ({ ...prev, loadingMore: false }));
+ } catch (err) {
+ if (myId !== requestIdRef.current || !isDataOwnerGenerationCurrent(owner)) return;
+ setState((prev) => ({ ...prev, loadingMore: false, error: err instanceof Error ? err.message : String(err) }));
}
- }, [state.nextCursor, state.loadingMore, state.loading, sortBy, searchQuery, catalogScope, visibility, categoryFilter, collectVisiblePage]);
+ }, [state.nextCursor, state.loadingMore, state.loading, sortBy, searchQuery, catalogScope, visibility, categoryFilter, collectVisiblePage, owner]);
// 外部主动刷新(删除/改可见性后)→ bump tick 触发重拉
const [reloadTick, setReloadTick] = useState(0);
@@ -567,13 +586,14 @@ export function useMarketList(
available: visibility === 'available',
category: categoryFilter !== CATEGORY_ALL ? categoryFilter : undefined,
});
+ return () => { requestIdRef.current++; };
}, [enabled, sortBy, searchQuery, catalogScope, visibility, categoryFilter, fetchPage, reloadTick]);
// 当本地扫描结果或 installing 集合变化时,只重新派生 cardState/installedVersion,不重发请求。
// Include catalog scope so a same-slug install moving between catalogs remaps immediately.
const localKey = localSkills
.filter((s) => s.kind === 'skill')
- .map((s) => `${s.name}@${s.registryEntry?.catalogScope ?? 'native'}@${s.registryEntry?.version ?? '?'}@${s.registryEntry !== null ? 'R' : '_'}@${s.absolutePath}`)
+ .map((s) => `${s.registrySkillName ?? s.name}@${s.registryEntry?.origin}@${s.registryEntry?.authorId}@${s.registryEntry?.catalogScope ?? 'native'}@${s.registryEntry?.version ?? '?'}@${s.registryEntry !== null ? 'R' : '_'}@${s.absolutePath}`)
.join('|');
const installingKey = Array.from(installingNames).sort().join(',');
useEffect(() => {
@@ -581,19 +601,10 @@ export function useMarketList(
if (prev.items.length === 0) return prev;
const remapped = prev.items.map((it) => {
const group = localGroupForItem(it, localIndex);
- const primary = group?.global ?? group?.projects[0];
- const isReallyInstalled = !!primary && (it.isMine || primary.hasRegistryEntry);
- const hasAnyInstall = !!group && (
- (!!group.global && group.global.hasRegistryEntry) ||
- group.projects.some((p) => p.hasRegistryEntry)
- );
return {
...it,
- installedLocally: isReallyInstalled,
+ ...deriveLocalInstall(it, group),
relativeTime: formatMarketRelativeTime(it.publishedAt, translateRef.current),
- installedVersion: isReallyInstalled ? primary.version : null,
- installedAbsolutePath: isReallyInstalled ? primary.absolutePath : null,
- hasAnyInstall,
cardState: deriveCardState(
{
...it,
@@ -637,14 +648,20 @@ export function useMarketList(
});
}, []);
+ const currentQueryKey = JSON.stringify([owner, {
+ sort: sortBy, q: searchQuery, scope: catalogScope,
+ mine: visibility === 'mine', available: visibility === 'available',
+ category: categoryFilter !== CATEGORY_ALL ? categoryFilter : undefined,
+ }]);
+ const visibleState = state.queryKey === currentQueryKey ? state : INITIAL;
return {
- items: state.items,
- loading: state.loading,
- loadingMore: state.loadingMore,
- error: state.error,
- hasMore: state.nextCursor !== null,
- resolvedScope: state.resolvedScope,
- resolvedMine: state.resolvedMine,
+ items: visibleState.items,
+ loading: visibleState.loading,
+ loadingMore: visibleState.loadingMore,
+ error: visibleState.error,
+ hasMore: visibleState.nextCursor !== null,
+ resolvedScope: visibleState.resolvedScope,
+ resolvedMine: visibleState.resolvedMine,
searchQuery,
sortBy,
catalogScope,
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useMarketSkillUpdate.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketSkillUpdate.ts
new file mode 100644
index 0000000000..34ff93e7a9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useMarketSkillUpdate.ts
@@ -0,0 +1,63 @@
+import { useCallback, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { toast } from '@/lib/toast';
+import { marketLocalCopies } from '../lib/marketLocalCopies';
+import { invalidate as invalidateInfo } from '../lib/infoDedupe';
+import { semverCompare } from '../versionUtils';
+import type { MarketSkill } from './useMarketList';
+import { invalidateHash } from './useSkillFolderHash';
+import { refresh } from './useSkillhub';
+
+/** Update the copy represented by the card, without opening the install picker. */
+export function useMarketSkillUpdate() {
+ const { t } = useTranslation();
+ const owner = getDataOwnerGeneration();
+ // The installer serializes by name, including same-name records in other catalogs.
+ const running = useRef(new Set<string>());
+ const [updatingNames, setUpdatingNames] = useState<ReadonlySet<string>>(new Set());
+ const isUpdating = useCallback((name: string) => running.current.has(name), []);
+
+ const update = useCallback(async (skill: MarketSkill) => {
+ if (!skill.updateAvailable || !skill.installedAbsolutePath
+ || running.current.has(skill.name) || !isDataOwnerGenerationCurrent(owner)) return;
+ running.current.add(skill.name);
+ setUpdatingNames(new Set(running.current));
+ try {
+ // Recheck the registry before authorizing replacement of an existing directory.
+ const locals = await refresh();
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ const local = marketLocalCopies(locals, skill).find((entry) =>
+ entry.absolutePath === skill.installedAbsolutePath && entry.registryEntry);
+ if (!local?.registryEntry?.version
+ || semverCompare(skill.latestVersion, local.registryEntry.version) <= 0) return;
+
+ const result = await window.electronAPI.skillhub.install({
+ name: skill.name,
+ version: skill.latestVersion,
+ catalogScope: skill.catalogScope,
+ installPath: local.absolutePath,
+ force: true,
+ skipBackup: false,
+ });
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ if (result.success) {
+ invalidateHash(local.absolutePath);
+ invalidateInfo(skill.name, skill.catalogScope);
+ await refresh();
+ if (isDataOwnerGenerationCurrent(owner)) {
+ toast.success(t('skillhub.detail.updatedToast', { name: skill.name, version: result.version }));
+ }
+ } else if (result.errorCode !== 'CANCELLED') {
+ toast.error(t('skillhub.marketCard.updateFailed'));
+ }
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('skillhub.marketCard.updateFailed'));
+ } finally {
+ running.current.delete(skill.name);
+ setUpdatingNames(new Set(running.current));
+ }
+ }, [owner, t]);
+
+ return { update, updatingNames, isUpdating };
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillFolderHash.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillFolderHash.ts
index 91f1f99ae5..a234447320 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillFolderHash.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillFolderHash.ts
@@ -8,6 +8,7 @@
*/
import { useEffect, useState } from 'react';
+import { invalidatePublishComparison } from './useSkillPublishComparison';
const HASH_TTL_MS = 30_000;
@@ -32,6 +33,7 @@ function notifyInvalidation(absolutePath: string): void {
}
export function invalidateHash(absolutePath: string): void {
+ invalidatePublishComparison(absolutePath);
hashCache.delete(absolutePath);
notifyInvalidation(absolutePath);
}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillPublishComparison.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillPublishComparison.ts
new file mode 100644
index 0000000000..9ef4fe5d89
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillPublishComparison.ts
@@ -0,0 +1,118 @@
+import { useEffect, useState } from 'react';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, type DataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import type { SkillhubPublishComparison } from '../../../../shared/skillhubPublishComparison';
+
+export type PublishComparisonState = SkillhubPublishComparison | { status: 'checking' };
+const FRESH_MS = 30_000;
+const listeners = new Set<(path?: string) => void>();
+let revision = 0;
+const pathRevisions = new Map<string, number>();
+let lastFocusRefresh = 0;
+let active = 0;
+const queue: Array<() => void> = [];
+const inFlight = new Map<string, { promise: Promise<SkillhubPublishComparison>; consumers: Set<() => boolean> }>();
+const cache = new Map<string, { path: string; value: SkillhubPublishComparison; at: number }>();
+let cacheOwner: DataOwnerGeneration | undefined;
+let retryAfter = 0;
+
+export function invalidatePublishComparison(path?: string): void {
+ if (path) pathRevisions.set(path, (pathRevisions.get(path) ?? 0) + 1);
+ else { revision++; pathRevisions.clear(); }
+ for (const [key, entry] of cache) if (!path || entry.path === path) cache.delete(key);
+ listeners.forEach((listener) => listener(path));
+}
+
+function onFocus(): void {
+ if (document.visibilityState === 'hidden' || Date.now() - lastFocusRefresh < 200) return;
+ lastFocusRefresh = Date.now();
+ // Reuse fresh results on rapid focus/navigation; local mutations explicitly invalidate them.
+ listeners.forEach((listener) => listener());
+}
+
+function drain(): void {
+ while (active < 3 && queue.length) queue.shift()?.();
+}
+
+function compare(key: string, skillId: string, absolutePath: string, owner: DataOwnerGeneration, current: () => boolean) {
+ if (cacheOwner !== owner) { cache.clear(); cacheOwner = owner; retryAfter = 0; }
+ const cached = cache.get(key);
+ if (cached && Date.now() - cached.at < FRESH_MS) return Promise.resolve(cached.value);
+ const existing = inFlight.get(key);
+ if (existing) { existing.consumers.add(current); return existing.promise; }
+ const consumers = new Set([current]);
+ const promise = new Promise<SkillhubPublishComparison>((resolve) => {
+ queue.push(() => {
+ // Leaving a page also cancels work that has not reached the IPC yet.
+ if (![...consumers].some((consumer) => consumer())) { resolve({ status: 'unavailable' }); return; }
+ const finish = (value: SkillhubPublishComparison) => {
+ if (isDataOwnerGenerationCurrent(owner)) {
+ if (cache.size >= 256) cache.delete(cache.keys().next().value!);
+ cache.set(key, { path: absolutePath, value, at: Date.now() });
+ }
+ resolve(value);
+ };
+ if (Date.now() < retryAfter) { finish({ status: 'unavailable' }); return; }
+ active++;
+ Promise.resolve().then(() => window.electronAPI.skillhub.comparePublished({ skillId, absolutePath }))
+ .then((result): SkillhubPublishComparison => result && ['same', 'different', 'not-owner', 'unavailable'].includes(result.status)
+ ? result : { status: 'unavailable' }, (): SkillhubPublishComparison => ({ status: 'unavailable' }))
+ .then((value) => {
+ // A failing service must not turn the remaining queue into a request burst.
+ if (value.status === 'unavailable' && value.reason === 'service' && isDataOwnerGenerationCurrent(owner)) retryAfter = Date.now() + FRESH_MS;
+ finish(value);
+ }).finally(() => { active--; drain(); });
+ });
+ }).finally(() => { inFlight.delete(key); });
+ inFlight.set(key, { promise, consumers });
+ // Let StrictMode's cleanup/remount subscribe before evaluating queued consumers.
+ queueMicrotask(drain);
+ return promise;
+}
+
+/** Owner-scoped short-lived results; explicit mutations refresh immediately, with no polling. */
+export function useSkillPublishComparison(skill: SkillhubSkill | null) {
+ const absolutePath = skill?.kind === 'skill' && !skill.builtIn ? skill.absolutePath : null;
+ const skillId = skill?.id ?? '';
+ const [refresh, setRefresh] = useState(0);
+ const owner = getDataOwnerGeneration();
+ const key = JSON.stringify([
+ owner, absolutePath, skillId, skill?.registrySkillName ?? skill?.name,
+ skill?.registryEntry?.catalogScope, skill?.registryEntry?.version,
+ skill?.registryEntry?.folderHash, skill?.registryEntry?.updatedAt,
+ revision, absolutePath ? pathRevisions.get(absolutePath) ?? 0 : 0,
+ ]);
+ const [result, setResult] = useState<{ key: string; refresh: number; value: PublishComparisonState } | null>(null);
+
+ useEffect(() => {
+ if (!absolutePath) return;
+ const listener = (path?: string) => {
+ if (!path || path === absolutePath) setRefresh((value) => value + 1);
+ };
+ if (!listeners.size) {
+ window.addEventListener('focus', onFocus);
+ document.addEventListener('visibilitychange', onFocus);
+ }
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (!listeners.size) {
+ window.removeEventListener('focus', onFocus);
+ document.removeEventListener('visibilitychange', onFocus);
+ }
+ };
+ }, [absolutePath]);
+
+ useEffect(() => {
+ if (!absolutePath) return;
+ let cancelled = false;
+ const current = () => !cancelled && isDataOwnerGenerationCurrent(owner);
+ void compare(key, skillId, absolutePath, owner, current).then((value) => {
+ if (current()) setResult({ key, refresh, value });
+ });
+ return () => { cancelled = true; };
+ }, [key, refresh, absolutePath, skillId, owner]);
+
+ const comparison: PublishComparisonState = !absolutePath ? { status: 'not-owner' }
+ : result?.key === key && result.refresh === refresh ? result.value : { status: 'checking' };
+ return { comparison, refresh };
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillSync.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillSync.ts
index 2935e19f93..9ef98a6f52 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillSync.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillSync.ts
@@ -38,8 +38,9 @@ function uniqueSkillRefs(skills: SkillhubSkill[]): Array<{ slug: string; catalog
for (const skill of skills) {
if (skill.kind !== 'skill') continue;
const catalogScope = skill.registryEntry?.catalogScope;
- byKey.set(skillhubCatalogKey(skill.name, catalogScope), {
- slug: skill.name,
+ const slug = skill.registrySkillName ?? skill.name;
+ byKey.set(skillhubCatalogKey(slug, catalogScope), {
+ slug,
...(catalogScope ? { catalogScope } : {}),
});
}
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhubHomeNavigation.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhubHomeNavigation.ts
index 82019d1246..4a12ba6f1e 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhubHomeNavigation.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhubHomeNavigation.ts
@@ -2,6 +2,7 @@ import { useCallback } from 'react';
import { useLocation, useNavigate, type Location } from 'react-router-dom';
import type { HomeCatalogTab } from '../lib/homeMarketFilter';
+import { skillDetailReturnRoute, withSkillDetailReturn } from '../lib/detailRoutes';
import { buildLocalSkillRoute } from '../lib/localRoutes';
interface HomeViewState {
@@ -21,11 +22,12 @@ export function useSkillhubHomeNavigation(navigationLocation?: Location) {
const location = navigationLocation ?? currentLocation;
const navigate = useNavigate();
const navState = location.state as SkillhubNavigationState | null;
- const savedTab = navState?.skillhubHome?.catalogTab;
+ const search = new URLSearchParams(location.search);
+ const savedTab = navState?.skillhubHome?.catalogTab ?? search.get('tab');
const catalogTab: HomeCatalogTab = savedTab === 'local' || savedTab === 'organization'
? savedTab
: 'public';
- const query = typeof navState?.skillhubHome?.query === 'string' ? navState.skillhubHome.query : '';
+ const query = typeof navState?.skillhubHome?.query === 'string' ? navState.skillhubHome.query : search.get('q') ?? '';
const updateHomeState = useCallback((patch: Partial<HomeViewState>) => {
// Replace the current entry: typing or changing tabs must not add Back steps.
@@ -43,7 +45,7 @@ export function useSkillhubHomeNavigation(navigationLocation?: Location) {
}, [updateHomeState]);
const openLocalSkill = (skill: Parameters<typeof buildLocalSkillRoute>[0]) => {
- navigate(buildLocalSkillRoute(skill), {
+ navigate(withSkillDetailReturn(buildLocalSkillRoute(skill), `${location.pathname}${location.search}`), {
state: {
from: '/skillhub/local',
resetHistory: true,
@@ -54,12 +56,12 @@ export function useSkillhubHomeNavigation(navigationLocation?: Location) {
const replaceLocalSkill = (skill: Parameters<typeof buildLocalSkillRoute>[0]) => {
// A rename replaces the current detail, retaining both its source and list filters.
- navigate(buildLocalSkillRoute(skill), { replace: true, state: location.state });
+ navigate(withSkillDetailReturn(buildLocalSkillRoute(skill), skillDetailReturnRoute(search, navState?.from === '/skillhub/market' ? '/skillhub/market' : '/skillhub/local')), { replace: true, state: location.state });
};
const backToCatalog = () => {
const target = navState?.from === '/skillhub/market' ? '/skillhub/market' : '/skillhub/local';
- navigate(target, { state: { skillhubHome: navState?.skillhubHome } });
+ navigate(skillDetailReturnRoute(search, target), { state: { skillhubHome: navState?.skillhubHome } });
};
return { catalogTab, query, setCatalogTab, setQuery, openLocalSkill, replaceLocalSkill, backToCatalog };
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.ts
index 82694e5c3f..af123d641b 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/deriveCardState.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { deriveCardState, localGroupForItem, type LocalSkillIndex } from '../../hooks/useMarketList';
+import { deriveCardState, deriveLocalInstall, localGroupForItem, type LocalSkillIndex } from '../../hooks/useMarketList';
import { skillhubCatalogKey } from '../../../../../shared/skillhubCatalog';
const item = (over: Record<string, unknown> = {}) => ({
@@ -63,3 +63,34 @@ describe('market install catalog matching', () => {
expect(localGroupForItem({ name: 'same', isMine: false }, index)).toBeUndefined();
});
});
+
+describe('market primary copy update availability', () => {
+ const global = { absolutePath: '/global/x', version: '1.0.0', hasRegistryEntry: true };
+ const project = { ...global, absolutePath: '/project/x' };
+
+ it.each([false, true])('offers an update for a registered copy (isMine=%s)', (isMine) => {
+ expect(deriveLocalInstall({ isMine, latestVersion: '1.0.1' }, { global, projects: [] }))
+ .toMatchObject({ installedLocally: true, updateAvailable: true, installedAbsolutePath: global.absolutePath });
+ });
+
+ it('uses the project copy when there is no global installation', () => {
+ expect(deriveLocalInstall({ isMine: false, latestVersion: '1.0.1' }, { projects: [project] }))
+ .toMatchObject({ updateAvailable: true, installedAbsolutePath: project.absolutePath });
+ });
+
+ it('keeps the status and action on the global copy when multiple locations exist', () => {
+ expect(deriveLocalInstall({ isMine: false, latestVersion: '1.0.1' }, {
+ global: { ...global, version: '1.0.1' }, projects: [project],
+ })).toMatchObject({ updateAvailable: false, installedAbsolutePath: global.absolutePath });
+ });
+
+ it.each(['1.0.0', '0.9.9', 'v1.0.0'])('does not update or downgrade to %s', (latestVersion) => {
+ expect(deriveLocalInstall({ isMine: false, latestVersion }, { global, projects: [] }).updateAvailable).toBe(false);
+ });
+
+ it.each([undefined, { ...global, version: null }, { ...global, hasRegistryEntry: false }])(
+ 'does not replace missing, unversioned or authored copies', (entry) => {
+ expect(deriveLocalInstall({ isMine: true, latestVersion: '2.0.0' }, { global: entry, projects: [] }).updateAvailable).toBe(false);
+ },
+ );
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/detailButtons.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/detailButtons.test.ts
index f0f99dacec..4b917c7ed2 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/detailButtons.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/detailButtons.test.ts
@@ -62,6 +62,57 @@ function makeDetailState(overrides: Partial<DetailState> = {}): DetailState {
}
describe('deriveDetailState — null guards', () => {
+ it('uses verified remote differences without needing a registry', () => {
+ const state = makeDetailState({ canManage: true, isMine: true, latestVersion: '2.0.0' });
+ expect(deriveDetailActionState(state, null, null, 'approved', true, state,
+ { status: 'different', version: '2.0.0', pending: false })).toMatchObject({
+ isMineDirty: true, status: { kind: 'publish-new-version' },
+ });
+ });
+
+ it('suppresses duplicate updates when a pending remote version already matches', () => {
+ const state = makeDetailState({ origin: 'imported', canManage: true, localVersion: '3.0.0', latestVersion: '2.0.0' });
+ expect(deriveDetailActionState(state, makeRegistryEntry(), 'changed-hash', 'pending', true, state,
+ { status: 'same', version: '3.0.0', pending: true })).toMatchObject({
+ isMineDirty: false, status: { kind: 'published-tag' },
+ });
+ });
+
+ it.each(['not-owner', 'unavailable', 'checking'] as const)('does not automatically remind %s, while preserving manual management', (status) => {
+ const state = makeDetailState({ canManage: true, latestVersion: '2.0.0' });
+ expect(deriveDetailActionState(state, makeRegistryEntry(), 'changed-hash', 'approved', true, state,
+ { status })).toMatchObject({ isMineDirty: false, status: { kind: 'publish-new-version' } });
+ });
+
+ it('keeps the remote download choice when local content differs from a newer release', () => {
+ const state = makeDetailState({ origin: 'installed', canManage: true, localVersion: '1.0.0', latestVersion: '2.0.0' });
+ expect(deriveDetailActionState(state, makeRegistryEntry(), 'abc123', 'approved', true, state,
+ { status: 'different', version: '2.0.0', pending: false })).toMatchObject({
+ isOutdated: true, isMineDirty: true, status: { kind: 'publish-new-version' },
+ });
+ });
+ it.each(['unchanged', 'unknown'] as const)('offers download without a publish reminder for %s older content', (localChanges) => {
+ const state = makeDetailState({ origin: 'installed', canManage: true, localVersion: '1.0.0', latestVersion: '2.0.0' });
+ expect(deriveDetailActionState(state, makeRegistryEntry(), 'abc123', 'approved', true, state,
+ { status: 'different', version: '2.0.0', pending: false, localChanges })).toMatchObject({
+ isOutdated: true, isMineDirty: false, status: { kind: 'update', latestVersion: '2.0.0' },
+ });
+ });
+
+ it('preserves manual publication of known local edits when the historical manifest is unavailable', () => {
+ const state = makeDetailState({ origin: 'installed', canManage: true, localVersion: '1.0.0', latestVersion: '2.0.0' });
+ expect(deriveDetailActionState(state, makeRegistryEntry(), 'locally-modified', 'approved', true, state,
+ { status: 'different', version: '2.0.0', pending: false, localChanges: 'unknown' })).toMatchObject({
+ isMineDirty: false, status: { kind: 'publish-new-version' },
+ });
+ });
+
+ it.each(['learned', 'imported'] as const)('keeps %s content outside the download-update path', (origin) => {
+ const state = makeDetailState({ origin, canManage: true, localVersion: '1.0.0', latestVersion: '2.0.0' });
+ expect(deriveDetailActionState(state, makeRegistryEntry(), 'abc123', 'approved', true, state,
+ { status: 'different', version: '2.0.0', pending: false, localChanges: 'unchanged' })?.status.kind).not.toBe('update');
+ });
+
it('returns null when entry is null', () => {
expect(deriveDetailState(null, null, false)).toBeNull();
});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/detailRoutes.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/detailRoutes.test.ts
new file mode 100644
index 0000000000..b2104f58ac
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/detailRoutes.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { buildMarketSkillRoute, skillDetailCatalog, skillDetailLocalParams, skillDetailReturnRoute, withSkillDetailReturn } from '../detailRoutes';
+import { buildLocalSkillRoute, findLocalSkillRouteEntry } from '../localRoutes';
+
+describe('shared detail URL state', () => {
+ it('round-trips literal percent signs and escaped names without losing source identity', () => {
+ const skill = { id: 'source', kind: 'skill' as const, engine: 'pi' as const, scope: 'global' as const,
+ name: '100% a&b', absolutePath: '/skills/special', sourceKey: 'other / source' };
+ const query = new URL(buildLocalSkillRoute(skill), 'https://test.local').searchParams;
+ expect(findLocalSkillRouteEntry([skill], skillDetailLocalParams(query), query)).toBe(skill);
+ });
+ it.each(['market', 'team', undefined] as const)('preserves the %s remote catalog and original list filters', (catalogScope) => {
+ const returnTo = '/skillhub/local?tab=public&q=a%26b&category=tools';
+ const query = new URL(buildMarketSkillRoute({ name: 'demo', catalogScope }, returnTo), 'https://test.local').searchParams;
+ expect(skillDetailCatalog(query)).toBe(catalogScope);
+ expect(skillDetailReturnRoute(query)).toBe(returnTo);
+ });
+ it.each(['https://example.com', '//example.com', '/skillhub/market/other', '/settings'])('rejects an unrelated return URL %s', (returnTo) => {
+ const route = withSkillDetailReturn('/skillhub/detail?view=local', returnTo);
+ expect(skillDetailReturnRoute(new URL(route, 'https://test.local').searchParams)).toBe('/skillhub/local');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts
index 369030d084..a1ac2df455 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/localRoutes.test.ts
@@ -28,7 +28,7 @@ describe('local SkillHub routes', () => {
const other = entry({ scope: 'global', absolutePath: '/home/.agents/skills/demo' });
for (const path of ['/shared/a & b/SKILL.md', '/repo/.claude/skills/demo/skill.md']) {
const url = new URL(buildLocalSkillPathRoute(path), 'https://cindy.local');
- expect(url.pathname).toBe('/skillhub/local/by-path');
+ expect(url.pathname).toBe('/skillhub/detail');
expect(url.searchParams.get('path')).toBe(path);
expect(findLocalSkillRouteEntry([other, target], {}, url.searchParams)).toBe(target);
}
@@ -75,9 +75,9 @@ describe('local SkillHub routes', () => {
)).toBe(renamed);
});
- it('keeps the existing URL shape for an unambiguous skill', () => {
+ it('builds the shared route with the complete local identity', () => {
expect(buildLocalSkillRoute(entry())).toBe(
- '/skillhub/local/skill/project/abcd1234/demo?engine=pi',
+ '/skillhub/detail?view=local&kind=skill&scope=project&name=demo&engine=pi&project=abcd1234',
);
});
@@ -93,7 +93,7 @@ describe('local SkillHub routes', () => {
const search = new URL(route, 'https://cindy.local').searchParams;
expect(route).toBe(
- '/skillhub/local/skill/project/abcd1234/demo?engine=pi&source=pi-source',
+ '/skillhub/detail?view=local&kind=skill&scope=project&name=demo&engine=pi&project=abcd1234&source=pi-source',
);
expect(findLocalSkillRouteEntry(
[addedLater, original],
@@ -113,7 +113,7 @@ describe('local SkillHub routes', () => {
const params = { kind: 'skill', projectHash: 'abcd1234', name: 'demo' };
expect(buildLocalSkillRoute(pi)).toBe(
- '/skillhub/local/skill/project/abcd1234/demo?engine=pi&source=pi-source',
+ '/skillhub/detail?view=local&kind=skill&scope=project&name=demo&engine=pi&project=abcd1234&source=pi-source',
);
expect(
findLocalSkillRouteEntry(
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketManagementAcceptanceCases.md b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketManagementAcceptanceCases.md
index bec4c53208..73a8fab836 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketManagementAcceptanceCases.md
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketManagementAcceptanceCases.md
@@ -4,23 +4,23 @@
## 市场列表范围
-1. 进入 `Skill Hub` 默认在 `可获取`,别人未安装或有更新的 skill 显示 `Clone`。
-2. `可获取` 不显示自己的发布物,不显示 `管理`。
+1. 进入完整市场列表默认显示 `全部`;未安装显示 `Clone`,已安装旧版本显示 `可更新`,点击直接更新原位置并保留备份。
+2. 本人发布物对应的本地副本有修改时显示 `可发布更新`;未修改的旧副本只提示下载更新。
3. `全部` 可以看到自己的公开发布物,但仍显示普通浏览/Clone 行为,不显示 `管理`。
4. `我的发布` 显示自己的云端发布物,卡片主按钮为 `管理`。
5. 可见性标签对齐 SkillHub:公开显示 `公开`、团队可见显示 `团队`、私有显示 `私有`(私有只在我的发布云端管理语境中显示)。
6. 正常已发布/审核通过不显示审核状态 tag;只显示 `机审中`、`人工复核中`、`审核未通过`。
-7. 从云端详情或编辑页返回时,必须回到原来源 tab;从 `我的发布` 进入就回到 `我的发布`,不能回到默认 `可获取`。
+7. 从云端详情或编辑页返回时,必须回到原来源 tab;从 `我的发布` 进入就回到 `我的发布`,保留搜索、分类和排序。
-## 市场预览与云端详情页
+## 统一 Skill 详情页
-1. 市场卡片点击后打开半屏云端预览,不跳转到本地 skill 详情页。
-2. 半屏预览和云端详情都显示云端 FILES 目录,可点 `SKILL.md`、子目录文件并预览内容。
-3. 从 `我的发布` 点击卡片本体打开详情浮窗,不进入 `/skillhub/market/:name`。
+1. 本地与市场卡片都进入 `/skillhub/detail`,URL 保留内容来源、市场范围和本地副本身份;旧链接自动重定向。
+2. 同一布局显示 FILES 目录和正文。市场内容只读;本地内容保留编辑能力。未保存编辑切换来源或副本前须确认。
+3. 从 `我的发布` 点击卡片进入同一详情页。多个本地副本可切换,启用、更新和发布操作均使用所选副本。
4. 顶部展示当前云端版本、归属和市场可见性。
5. 本人云端详情动作统一收口为:编辑信息、管理可见性、Clone、删除。
6. `管理可见性` 打开弹窗回显当前可见团队/部门;保存后走 `set-visibility(shared + visibleSlugs)`,归属变更也在这个弹窗内处理。
-7. 非本人云端详情只显示 `Clone`,不显示 `市场管理`。
+7. 非管理者不显示云端管理。已安装副本可使用本地开关、下载更新;只有确认的原作者且有发布权限才显示 `可发布更新`。
## 管理动作成功体验
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
index fff3392168..10e9dddb13 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/marketRoutes.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -12,8 +12,10 @@ const routerSource = readFileSync(resolve(skillhubDir, '../../router.tsx'), 'utf
const localDetailSource = readFileSync(resolve(skillhubDir, 'SkillhubDetailView.tsx'), 'utf8');
describe('market route scope', () => {
- it('has no fullscreen market detail or manage routes (detail and management live in the preview panel)', () => {
- expect(routerSource).not.toContain('SkillhubMarketDetailView');
+ it('uses one detail route and redirects old detail URLs', () => {
+ expect(routerSource).toContain('<SkillhubDetailRoute />');
+ expect(routerSource).toContain('<LegacySkillDetailRedirect market />');
+ expect(routerSource).toContain('<LegacySkillDetailRedirect />');
expect(routerSource).not.toContain('SkillhubMarketManageView');
});
@@ -48,13 +50,13 @@ describe('market route scope', () => {
expect(acceptanceSource).not.toContain('转到团队库');
});
- it('opens the half-screen cloud preview when a market card is clicked', () => {
+ it('opens the shared detail route with read-only market content', () => {
const listSource = readFileSync(resolve(skillhubDir, 'SkillhubMarketListView.tsx'), 'utf8');
- const previewSource = readFileSync(resolve(skillhubDir, 'SkillhubMarketPreviewPanel.tsx'), 'utf8');
+ const previewSource = readFileSync(resolve(skillhubDir, 'SkillhubMarketDetailView.tsx'), 'utf8');
- expect(listSource).toContain('SkillhubMarketPreviewPanel');
- expect(listSource).toContain('nextMarketPreviewName');
- expect(listSource).toContain('setMarketSelected(newName ? skill : null);');
+ expect(listSource).toContain('navigate(buildMarketSkillRoute(skill, returnTo))');
+ expect(previewSource).toContain('<SkillDetailPage>');
+ expect(localDetailSource).toContain('<SkillDetailPage>');
expect(previewSource).toContain('getPublishedFiles');
expect(previewSource).toContain('readPublishedFile');
expect(previewSource).toContain('allowPrivilegedLinks={false}');
@@ -132,7 +134,7 @@ describe('market management copy and errors', () => {
});
it('does not expose an extra published status pill in the market preview panel', () => {
- const previewSource = readFileSync(resolve(skillhubDir, 'SkillhubMarketPreviewPanel.tsx'), 'utf8');
+ const previewSource = readFileSync(resolve(skillhubDir, 'SkillhubMarketDetailView.tsx'), 'utf8');
expect(previewSource).not.toContain('已发布');
});
@@ -155,13 +157,13 @@ describe('market management copy and errors', () => {
expect(cardSource).not.toContain('event.preventDefault();');
});
- it('keeps the market preview panel out of the window drag region', () => {
+ it('keeps shared detail controls out of the window drag region', () => {
const listSource = readFileSync(resolve(skillhubDir, 'SkillhubMarketListView.tsx'), 'utf8');
- const previewSource = readFileSync(resolve(skillhubDir, 'SkillhubMarketPreviewPanel.tsx'), 'utf8');
+ const layoutSource = readFileSync(resolve(skillhubDir, 'components/SkillDetailLayout.tsx'), 'utf8');
- expect(previewSource).toContain('WINDOW_NO_DRAG_STYLE');
- expect(previewSource).toContain("...WINDOW_NO_DRAG_STYLE");
- expect(listSource).toContain('previewSkill ? WINDOW_NO_DRAG_STYLE : WINDOW_DRAG_STYLE');
+ expect(layoutSource).toContain('style={WINDOW_NO_DRAG_STYLE}');
+ expect(layoutSource).toContain('style={WINDOW_DRAG_STYLE}');
+ expect(listSource).toContain('...WINDOW_DRAG_STYLE');
});
it('updates the Hub copy, locale, and Platform tag slugs from the market info editor', () => {
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/detailButtons.ts b/apps/desktop/src/renderer/features/skillhub/lib/detailButtons.ts
index 4fe302bfa5..e6fb19156b 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/detailButtons.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/detailButtons.ts
@@ -1,4 +1,6 @@
import { semverCompare } from '../versionUtils';
+import type { PublishComparisonState } from '../hooks/useSkillPublishComparison';
+import { hasPublishableChanges } from './publishUpdateState';
/**
* deriveDetailState — 从 entry + server info 派生三个独立维度的 UI 状态。
@@ -126,6 +128,7 @@ export function deriveDetailActionState(
publishedStatus?: string | null,
canPublish = true,
publishTargetState: DetailState | null = detailState,
+ comparison?: PublishComparisonState,
): DetailActionState | null {
if (!detailState) return null;
@@ -141,7 +144,14 @@ export function deriveDetailActionState(
semverCompare(detailState.localVersion, publishState.latestVersion) > 0
);
const localChanged = hasLocalChanges(registryEntry, localFolderHash);
- const isMineDirty = !!(publishState.canManage === true && localChanged);
+ const isMineDirty = comparison
+ ? hasPublishableChanges(comparison)
+ : !!(publishState.canManage === true && localChanged);
+ // Preserve manual management on older servers and for administrators. Only verified
+ // creator comparisons drive automatic reminders; a matching pending release is clean.
+ const publishChanged = comparison?.status === 'same' ? false
+ : comparison?.status === 'different' && comparison.localChanges !== 'unknown'
+ ? hasPublishableChanges(comparison) : localChanged;
const showForeignDirtyBanner = !!(
detailState.origin === 'installed' &&
detailState.localVersion !== null &&
@@ -153,15 +163,18 @@ export function deriveDetailActionState(
if (publishState.canManage === true && publishedStatus === 'rejected') {
status = { kind: 'publish-new-version' };
- } else if (isPublishLocalAhead && publishState.canManage === true) {
+ } else if (isPublishLocalAhead && comparison?.status !== 'same' && publishState.canManage === true) {
status = { kind: 'publish-new-version' };
} else if (
publishState.canManage === true &&
- localChanged
+ publishChanged
) {
status = { kind: 'publish-new-version' };
+ } else if (isOutdated && comparison?.status === 'different' && !hasPublishableChanges(comparison)
+ && detailState.latestVersion !== null && detailState.origin !== 'learned' && detailState.origin !== 'imported') {
+ status = { kind: 'update', latestVersion: detailState.latestVersion };
} else if (publishState.latestVersion !== null && publishState.canManage === true) {
- status = (detailState.origin === 'learned' || detailState.origin === 'imported')
+ status = comparison?.status !== 'same' && (detailState.origin === 'learned' || detailState.origin === 'imported')
? { kind: 'publish-new-version' }
: { kind: 'published-tag', version: publishState.latestVersion };
} else if (isOutdated && detailState.latestVersion !== null && detailState.origin !== 'learned' && detailState.origin !== 'imported') {
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/detailRoutes.ts b/apps/desktop/src/renderer/features/skillhub/lib/detailRoutes.ts
new file mode 100644
index 0000000000..98599ad719
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/detailRoutes.ts
@@ -0,0 +1,36 @@
+import type { SkillhubCatalogScope } from '../../../../shared/skillhubCatalog';
+
+export function skillDetailReturnRoute(search: URLSearchParams, fallback = '/skillhub/local'): string {
+ const value = search.get('returnTo') ?? fallback;
+ return /^\/skillhub\/(local|market)(\?|$)/.test(value) ? value : '/skillhub/local';
+}
+
+export function buildMarketSkillRoute(
+ skill: { name: string; catalogScope?: SkillhubCatalogScope },
+ returnTo = '/skillhub/market',
+): string {
+ return `/skillhub/detail?${new URLSearchParams({
+ view: 'market', remote: skill.name, catalog: skill.catalogScope ?? 'native', returnTo,
+ })}`;
+}
+
+export function withSkillDetailReturn(route: string, returnTo: string): string {
+ const [pathname, query] = route.split('?');
+ const search = new URLSearchParams(query);
+ search.set('returnTo', returnTo);
+ return `${pathname}?${search}`;
+}
+
+/** Legacy links remain resolvable; new links carry the same source identity in search. */
+export function skillDetailLocalParams(search: URLSearchParams) {
+ return {
+ kind: search.get('kind') ?? undefined,
+ name: search.has('name') ? encodeURIComponent(search.get('name')!) : undefined,
+ projectHash: search.get('project') ?? undefined,
+ };
+}
+
+export function skillDetailCatalog(search: URLSearchParams): SkillhubCatalogScope | undefined {
+ const scope = search.get('catalog');
+ return scope === 'market' || scope === 'team' ? scope : undefined;
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts b/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
index 25b9957f97..3bdfbf56a7 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/localRoutes.ts
@@ -35,7 +35,8 @@ export function buildLocalSkillPathRoute(path: string, context: { scope?: string
const scope = context.scope === 'user' ? 'global' : context.scope === 'repo' ? 'project' : context.scope;
if (scope === 'global' || scope === 'project') search.set('scope', scope);
if (scope === 'project' && context.workingDir) search.set('workingDir', context.workingDir);
- return `/skillhub/local/by-path?${search.toString()}`;
+ search.set('view', 'local');
+ return `/skillhub/detail?${search.toString()}`;
}
function skillDirectoryPath(path: string): string {
@@ -45,16 +46,12 @@ function skillDirectoryPath(path: string): string {
return windows ? normalized.toLowerCase() : normalized;
}
-/** Builds a local detail URL while preserving the legacy pathname contract. */
+/** New local links use the shared detail route while retaining source identity. */
export function buildLocalSkillRoute(entry: LocalSkillRouteEntry): string {
- const name = encodeURIComponent(entry.name);
- const pathname =
- entry.scope === 'global'
- ? `/skillhub/local/${entry.kind}/global/${name}`
- : `/skillhub/local/${entry.kind}/project/${entry.projectHash}/${name}`;
- const search = new URLSearchParams({ engine: entry.engine });
+ const search = new URLSearchParams({ view: 'local', kind: entry.kind, scope: entry.scope, name: entry.name, engine: entry.engine });
+ if (entry.scope === 'project' && entry.projectHash) search.set('project', entry.projectHash);
if (entry.sourceKey) search.set('source', entry.sourceKey);
- return `${pathname}?${search.toString()}`;
+ return `/skillhub/detail?${search.toString()}`;
}
/** Resolves both source-aware links and legacy links that predate source keys. */
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/marketLocalCopies.ts b/apps/desktop/src/renderer/features/skillhub/lib/marketLocalCopies.ts
new file mode 100644
index 0000000000..7be118b3a3
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/marketLocalCopies.ts
@@ -0,0 +1,39 @@
+import { skillhubCatalogKey, type SkillhubCatalogScope } from '../../../../shared/skillhubCatalog';
+
+export interface MarketLocalIdentity {
+ name: string;
+ isMine: boolean;
+ isCreator?: boolean;
+ canManage?: boolean;
+ authorId?: string;
+ catalogScope?: SkillhubCatalogScope;
+}
+
+export function publishedLocalIdentity(local: SkillhubSkill): string | null {
+ const registry = local.registryEntry;
+ return local.kind === 'skill' && registry?.origin === 'published' && !registry.catalogScope && registry.authorId
+ ? JSON.stringify([local.registrySkillName ?? local.name, registry.authorId]) : null;
+}
+
+export function publishedMarketIdentity(market: MarketLocalIdentity): string | null {
+ // Native publishing records and their visible catalog projection share an owner.
+ // Never merge arbitrary same-slug installs or organization-owned records by name alone.
+ return market.catalogScope && market.isCreator === true && market.canManage && market.authorId
+ ? JSON.stringify([market.name, market.authorId]) : null;
+}
+
+export function marketLocalCopies(skills: readonly SkillhubSkill[], market: MarketLocalIdentity): SkillhubSkill[] {
+ const publishedIdentity = publishedMarketIdentity(market);
+ return skills.filter((local) => {
+ const name = local.registryEntry ? local.registrySkillName ?? local.name : local.name;
+ if (local.kind !== 'skill' || name !== market.name) return false;
+ if (!local.registryEntry) return market.isMine;
+ return skillhubCatalogKey(name, local.registryEntry.catalogScope) === skillhubCatalogKey(market.name, market.catalogScope)
+ || (publishedIdentity !== null && publishedLocalIdentity(local) === publishedIdentity);
+ }).sort((left, right) => {
+ const exact = (local: SkillhubSkill) => !!local.registryEntry
+ && local.registryEntry.catalogScope === market.catalogScope;
+ return Number(right.scope === 'global') - Number(left.scope === 'global')
+ || Number(exact(right)) - Number(exact(left));
+ });
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/publishUpdateState.ts b/apps/desktop/src/renderer/features/skillhub/lib/publishUpdateState.ts
new file mode 100644
index 0000000000..b196a04a8c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/skillhub/lib/publishUpdateState.ts
@@ -0,0 +1,6 @@
+import type { PublishComparisonState } from '../hooks/useSkillPublishComparison';
+
+export function hasPublishableChanges(comparison: PublishComparisonState | undefined): boolean {
+ return comparison?.status === 'different'
+ && comparison.localChanges !== 'unchanged' && comparison.localChanges !== 'unknown';
+}
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/publishedStatus.ts b/apps/desktop/src/renderer/features/skillhub/lib/publishedStatus.ts
index 2b43a40f7c..79d37d925d 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/publishedStatus.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/publishedStatus.ts
@@ -1,51 +1,7 @@
import { normalizeScanStatus } from './scanStatus';
+import { specialPublishedStatus, type SpecialPublishedStatus } from '../../../../shared/skillhubPublishedStatus';
-export type SpecialPublishedStatus = 'pending' | 'scanning' | 'quarantine' | 'rejected';
-
-export interface PublishedStatusSource {
- moderationStatus?: string | null;
- latestVersion?: string | null;
- pendingVersion?: {
- version?: string | null;
- status?: string | null;
- } | null;
-}
-
-export function normalizePublishedStatus(
- status: string | null | undefined,
-): SpecialPublishedStatus | 'published' | null {
- const value = String(status ?? '').trim().toLowerCase();
- if (!value) return null;
- if (value === 'pending' || value === 'machine_reviewing') return 'pending';
- if (value === 'scanning') return 'scanning';
- if (value === 'quarantine' || value === 'warning' || value === 'warn' || value === 'manual_reviewing') {
- return 'quarantine';
- }
- if (value === 'rejected' || value === 'failed' || value === 'fail' || value === 'blocked') {
- return 'rejected';
- }
- if (value === 'published' || value === 'passed' || value === 'pass' || value === 'approved') {
- return 'published';
- }
- return null;
-}
-
-export function specialPublishedStatus(status: string | null | undefined): SpecialPublishedStatus | null {
- const normalized = normalizePublishedStatus(status);
- return normalized === 'pending' || normalized === 'scanning' || normalized === 'quarantine' || normalized === 'rejected'
- ? normalized
- : null;
-}
-
-export function effectivePublishedStatus(source: PublishedStatusSource | null | undefined): SpecialPublishedStatus | null {
- const pendingVersion = source?.pendingVersion?.version?.trim();
- if (pendingVersion) {
- const pendingStatus = specialPublishedStatus(source?.pendingVersion?.status);
- if (pendingStatus) return pendingStatus;
- return specialPublishedStatus(source?.moderationStatus) ?? 'pending';
- }
- return specialPublishedStatus(source?.moderationStatus);
-}
+export * from '../../../../shared/skillhubPublishedStatus';
export type PublishedStatusLabelKey =
| 'skillhub.publishedStatus.waitingReview'
@@ -60,31 +16,6 @@ export function publishedStatusLabelKey(status: SpecialPublishedStatus): Publish
return 'skillhub.publishedStatus.machineReviewing';
}
-export function isActivePublishedReview(status: string | null | undefined): boolean {
- const normalized = specialPublishedStatus(status);
- return normalized === 'pending' || normalized === 'scanning' || normalized === 'quarantine';
-}
-
-export function isEffectiveActivePublishedReview(source: PublishedStatusSource | null | undefined): boolean {
- const normalized = effectivePublishedStatus(source);
- return normalized === 'pending' || normalized === 'scanning' || normalized === 'quarantine';
-}
-
-export function activePublishedReviewVersion(source: PublishedStatusSource | null | undefined): string | null {
- if (!source) return null;
- const pendingVersion = source.pendingVersion?.version?.trim() ?? '';
- if (pendingVersion && isEffectiveActivePublishedReview(source)) return pendingVersion;
- if (source.latestVersion && isActivePublishedReview(source.moderationStatus)) return source.latestVersion;
- return null;
-}
-
-export function effectivePublishedStatusVersion(source: PublishedStatusSource | null | undefined): string | null {
- if (!source) return null;
- const pendingVersion = source.pendingVersion?.version?.trim() ?? '';
- if (pendingVersion && effectivePublishedStatus(source)) return pendingVersion;
- return source.latestVersion?.trim() || null;
-}
-
function readStringField(source: unknown, field: string): string {
if (!source || typeof source !== 'object') return '';
const value = (source as Record<string, unknown>)[field];
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5af34d921b..f9abbe9f74 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11206,6 +11206,21 @@
"projectSkillNotLoaded": "This Pi task hasn't loaded this project Skill. New tasks will automatically try to load it."
},
"skillhub": {
+ "unifiedDetail": {
+ "contentSource": "Content source",
+ "local": "Local",
+ "market": "Market",
+ "marketUnavailable": "Market details are unavailable. You can still use your local copy.",
+ "retry": "Retry"
+ },
+ "publishComparison": {
+ "updateAvailable": "Update available to publish",
+ "pendingChanges": "Further local changes since submission",
+ "unavailable": "Unable to check for publication updates",
+ "diffTitle": "Changes from online v{{version}}",
+ "summaryBadge": "Summary",
+ "summaryNote": "Binary or large file, or full text unavailable. Showing file sizes."
+ },
"home": {
"title": "Skills",
"description": "Manage local skills, or discover and install more from Skill Hub.",
@@ -11433,6 +11448,8 @@
"installError": "Unknown error"
},
"marketCard": {
+ "updateAvailable": "Get update",
+ "updateFailed": "Update failed. Please try again.",
"visibilityPublic": "Public",
"visibilityDept": "Team",
"visibilityPrivate": "Personal",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3c9821c1ae..fb8259cd66 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -11190,6 +11190,21 @@
"projectSkillNotLoaded": "現在の Pi タスクでは、このプロジェクト Skill はまだ読み込まれていません。新しいタスクでは自動的に読み込みを試みます。"
},
"skillhub": {
+ "unifiedDetail": {
+ "contentSource": "表示する内容",
+ "local": "ローカル",
+ "market": "マーケット",
+ "marketUnavailable": "マーケット情報を読み込めません。ローカルのコピーは引き続き使用できます。",
+ "retry": "再試行"
+ },
+ "publishComparison": {
+ "updateAvailable": "更新を公開できます",
+ "pendingChanges": "審査への提出後にローカルの変更があります",
+ "unavailable": "公開済みの内容と比較できません",
+ "diffTitle": "オンラインの v{{version}} との差分",
+ "summaryBadge": "概要",
+ "summaryNote": "バイナリ、大きなファイル、または全文を取得できないため、ファイルサイズのみ表示します。"
+ },
"home": {
"title": "スキル",
"description": "ローカルスキルを管理し、Skill Hub から新しいスキルを見つけてインストールできます。",
@@ -11417,6 +11432,8 @@
"installError": "不明なエラー"
},
"marketCard": {
+ "updateAvailable": "更新を取得",
+ "updateFailed": "更新に失敗しました。もう一度お試しください。",
"visibilityPublic": "公開",
"visibilityDept": "チーム",
"visibilityPrivate": "個人",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 67cec27490..80c62399cc 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -11190,6 +11190,21 @@
"projectSkillNotLoaded": "현재 Pi 작업에는 이 프로젝트 Skill이 아직 로드되지 않았습니다. 새 작업에서는 자동으로 로드를 시도합니다."
},
"skillhub": {
+ "unifiedDetail": {
+ "contentSource": "콘텐츠 출처",
+ "local": "로컬",
+ "market": "마켓",
+ "marketUnavailable": "마켓 정보를 불러올 수 없습니다. 로컬 사본은 계속 사용할 수 있습니다.",
+ "retry": "다시 시도"
+ },
+ "publishComparison": {
+ "updateAvailable": "업데이트를 게시할 수 있습니다",
+ "pendingChanges": "검토 제출 후 로컬 변경 사항이 있습니다",
+ "unavailable": "게시된 내용과 비교할 수 없습니다",
+ "diffTitle": "온라인 v{{version}}과의 차이",
+ "summaryBadge": "요약",
+ "summaryNote": "바이너리, 큰 파일 또는 전체 내용을 미리 볼 수 없는 파일은 크기만 표시합니다."
+ },
"home": {
"title": "스킬",
"description": "로컬 스킬을 관리하거나 Skill Hub에서 새로운 스킬을 찾아 설치하세요.",
@@ -11417,6 +11432,8 @@
"installError": "알 수 없는 오류"
},
"marketCard": {
+ "updateAvailable": "업데이트 받기",
+ "updateFailed": "업데이트하지 못했습니다. 다시 시도해 주세요.",
"visibilityPublic": "공개",
"visibilityDept": "팀",
"visibilityPrivate": "개인",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 9e58c7a9ca..554c78b91c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -11190,6 +11190,21 @@
"projectSkillNotLoaded": "当前 Pi 任务尚未加载此项目 Skill,新任务会自动尝试加载"
},
"skillhub": {
+ "unifiedDetail": {
+ "contentSource": "内容来源",
+ "local": "本地",
+ "market": "市场",
+ "marketUnavailable": "暂时无法读取市场信息,本地副本仍可使用。",
+ "retry": "重试"
+ },
+ "publishComparison": {
+ "updateAvailable": "可发布更新",
+ "pendingChanges": "提交审核后,本地又有改动",
+ "unavailable": "暂时无法检查发布更新",
+ "diffTitle": "与线上 v{{version}} 的差异",
+ "summaryBadge": "摘要",
+ "summaryNote": "文件为二进制、过大或无法完整预览,仅显示文件大小。"
+ },
"home": {
"title": "技能",
"description": "管理本地技能,或从 Skill Hub 发现并安装更多技能。",
@@ -11417,6 +11432,8 @@
"installError": "未知错误"
},
"marketCard": {
+ "updateAvailable": "获取更新",
+ "updateFailed": "更新失败,请重试",
"visibilityPublic": "公开",
"visibilityDept": "团队",
"visibilityPrivate": "个人",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d07936276b..04979c989e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -11190,6 +11190,21 @@
"projectSkillNotLoaded": "目前的 Pi 任務尚未載入此專案 Skill,新任務會自動嘗試載入"
},
"skillhub": {
+ "unifiedDetail": {
+ "contentSource": "內容來源",
+ "local": "本機",
+ "market": "市場",
+ "marketUnavailable": "暫時無法讀取市場資訊,本機副本仍可使用。",
+ "retry": "重試"
+ },
+ "publishComparison": {
+ "updateAvailable": "可發佈更新",
+ "pendingChanges": "提交審核後,本機又有改動",
+ "unavailable": "暫時無法檢查發佈更新",
+ "diffTitle": "與線上 v{{version}} 的差異",
+ "summaryBadge": "摘要",
+ "summaryNote": "檔案為二進位、過大或無法完整預覽,僅顯示檔案大小。"
+ },
"home": {
"title": "技能",
"description": "管理本地技能,或從 Skill Hub 發現並安裝更多技能。",
@@ -11417,6 +11432,8 @@
"installError": "未知錯誤"
},
"marketCard": {
+ "updateAvailable": "取得更新",
+ "updateFailed": "更新失敗,請重試",
"visibilityPublic": "公開",
"visibilityDept": "團隊",
"visibilityPrivate": "個人",
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index 73d536e81d..5c0f6531e3 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -22,7 +22,7 @@ import { WorkdirBrowseRoute } from '@/features/cc-agent/workdir-browse/WorkdirBr
import { IssueTrackerFeatureLayout } from '@/features/issue-tracker/IssueTrackerFeatureLayout';
import { SkillhubFeatureLayout } from '@/features/skillhub/SkillhubFeatureLayout';
import { SkillhubLocalLayout } from '@/features/skillhub/SkillhubLocalLayout';
-import { SkillhubDetailView } from '@/features/skillhub/SkillhubDetailView';
+import { SkillhubDetailRoute, LegacySkillDetailRedirect } from '@/features/skillhub/SkillhubDetailRoute';
import { SkillhubMarketListView } from '@/features/skillhub/SkillhubMarketListView';
import { MakerExperimentalView } from '@/features/maker-experimental/MakerExperimentalView';
import { SchedulerPage } from '@/features/scheduler';
@@ -153,18 +153,17 @@ export const router = createHashRouter([
children: [
{ index: true, element: <Navigate to="/skillhub/local" replace /> },
{
- path: 'local',
element: <SkillhubLocalLayout />,
children: [
+ { path: 'detail', element: <SkillhubDetailRoute /> },
{
- index: true,
- element: null,
- },
- { path: 'by-path', element: <SkillhubDetailView /> },
- { path: ':kind/global/:name', element: <SkillhubDetailView /> },
- {
- path: ':kind/project/:projectHash/:name',
- element: <SkillhubDetailView />,
+ path: 'local',
+ children: [
+ { index: true, element: null },
+ { path: 'by-path', element: <LegacySkillDetailRedirect /> },
+ { path: ':kind/global/:name', element: <LegacySkillDetailRedirect /> },
+ { path: ':kind/project/:projectHash/:name', element: <LegacySkillDetailRedirect /> },
+ ],
},
],
},
@@ -172,16 +171,15 @@ export const router = createHashRouter([
path: 'market',
children: [
{ index: true, element: <SkillhubMarketListView /> },
- // 全屏详情页/旧管理整页已移除(详情与管理统一走市场列表内的浮窗),
- // 旧 URL 一律 fallback 回 market 列表
+ // Existing market bookmarks resolve to the shared detail page.
{
path: 'manage/:name',
- element: <Navigate to="/skillhub/market" replace />,
+ element: <LegacySkillDetailRedirect market />,
},
- { path: ':name', element: <Navigate to="/skillhub/market" replace /> },
+ { path: ':name', element: <LegacySkillDetailRedirect market /> },
{
path: ':kind/:name',
- element: <Navigate to="/skillhub/market" replace />,
+ element: <LegacySkillDetailRedirect market />,
},
],
},
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2e23c46ded..3ed003b649 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3463,6 +3463,8 @@ interface ElectronAPI {
error?: string;
errorCode?: string;
}>;
+ comparePublished: (params: import('../shared/skillhubPublishComparison').SkillhubPublishComparisonParams) => Promise<import('../shared/skillhubPublishComparison').SkillhubPublishComparison>;
+
getFolderHash: (absolutePath: string) => Promise<{
success: boolean;
error?: string;
@@ -7097,13 +7099,14 @@ type SkillhubSyncResult =
catalogScope?: 'market' | 'team';
exists: true;
isMine: boolean;
+ isCreator?: boolean;
canManage: boolean;
/** server 权威 authorId,用于本地 registry 回填及离线归属判定。 */
authorId?: string;
authorName?: string;
publisherName?: string;
latestVersion: string;
- folderHash: string;
+ folderHash?: string;
visibility: 'PUBLIC' | 'DEPARTMENT_SCOPED';
marketVersion?: string;
pendingVersion?: {
@@ -7125,9 +7128,10 @@ interface SkillhubInfoResult {
authorName: string;
publisherName?: string;
isMine: boolean;
+ isCreator?: boolean;
canManage: boolean;
latestVersion: string;
- folderHash: string;
+ folderHash?: string;
visibility: 'PUBLIC' | 'DEPARTMENT_SCOPED';
publishedVisibility?: 'private' | 'shared' | 'public';
ownerType?: string;
diff --git a/apps/desktop/src/shared/skillhubPublishComparison.ts b/apps/desktop/src/shared/skillhubPublishComparison.ts
new file mode 100644
index 0000000000..24482db64e
--- /dev/null
+++ b/apps/desktop/src/shared/skillhubPublishComparison.ts
@@ -0,0 +1,29 @@
+/** Local comparison state; hashes never represent permission or package authenticity. */
+export interface SkillhubContentChange {
+ path: string;
+ kind: 'added' | 'removed' | 'modified';
+ isBinary: boolean;
+ oldContent: string;
+ newContent: string;
+ oldSize: number;
+ newSize: number;
+}
+
+export interface SkillhubPublishComparisonParams {
+ absolutePath: string;
+ skillId?: string;
+ includeDiff?: boolean;
+}
+
+export type SkillhubPublishComparison =
+ | { status: 'not-owner' }
+ | { status: 'unavailable'; /** Only confirmed transport, rate-limit or server failures affect other skills. */ reason?: 'service' }
+ | {
+ status: 'same' | 'different';
+ version: string;
+ pending: boolean;
+ /** When an installed copy differs from the compared release, distinguish
+ * local edits from an unchanged older installation. Omitted by older clients. */
+ localChanges?: 'modified' | 'unchanged' | 'unknown';
+ changes?: SkillhubContentChange[];
+ };
diff --git a/apps/desktop/src/shared/skillhubPublishedStatus.ts b/apps/desktop/src/shared/skillhubPublishedStatus.ts
new file mode 100644
index 0000000000..cdbaa11293
--- /dev/null
+++ b/apps/desktop/src/shared/skillhubPublishedStatus.ts
@@ -0,0 +1,73 @@
+/** Shared publication status semantics for comparison and presentation. */
+export type SpecialPublishedStatus = 'pending' | 'scanning' | 'quarantine' | 'rejected';
+
+export interface PublishedStatusSource {
+ moderationStatus?: string | null;
+ latestVersion?: string | null;
+ pendingVersion?: {
+ version?: string | null;
+ status?: string | null;
+ } | null;
+}
+
+export function normalizePublishedStatus(
+ status: string | null | undefined,
+): SpecialPublishedStatus | 'published' | null {
+ const value = String(status ?? '').trim().toLowerCase();
+ if (!value) return null;
+ if (value === 'pending' || value === 'machine_reviewing') return 'pending';
+ if (value === 'scanning') return 'scanning';
+ if (value === 'quarantine' || value === 'warning' || value === 'warn' || value === 'manual_reviewing') {
+ return 'quarantine';
+ }
+ if (value === 'rejected' || value === 'failed' || value === 'fail' || value === 'blocked') {
+ return 'rejected';
+ }
+ if (value === 'published' || value === 'passed' || value === 'pass' || value === 'approved') {
+ return 'published';
+ }
+ return null;
+}
+
+export function specialPublishedStatus(status: string | null | undefined): SpecialPublishedStatus | null {
+ const normalized = normalizePublishedStatus(status);
+ return normalized === 'pending' || normalized === 'scanning' || normalized === 'quarantine' || normalized === 'rejected'
+ ? normalized
+ : null;
+}
+
+export function effectivePublishedStatus(source: PublishedStatusSource | null | undefined): SpecialPublishedStatus | null {
+ const pendingVersion = source?.pendingVersion?.version?.trim();
+ if (pendingVersion) {
+ const pendingStatus = specialPublishedStatus(source?.pendingVersion?.status);
+ if (pendingStatus) return pendingStatus;
+ return specialPublishedStatus(source?.moderationStatus) ?? 'pending';
+ }
+ return specialPublishedStatus(source?.moderationStatus);
+}
+
+export function isActivePublishedReview(status: string | null | undefined): boolean {
+ const normalized = specialPublishedStatus(status);
+ return normalized === 'pending' || normalized === 'scanning' || normalized === 'quarantine';
+}
+
+export function isEffectiveActivePublishedReview(source: PublishedStatusSource | null | undefined): boolean {
+ const normalized = effectivePublishedStatus(source);
+ return normalized === 'pending' || normalized === 'scanning' || normalized === 'quarantine';
+}
+
+export function activePublishedReviewVersion(source: PublishedStatusSource | null | undefined): string | null {
+ if (!source) return null;
+ const pendingVersion = source.pendingVersion?.version?.trim() ?? '';
+ if (pendingVersion && isEffectiveActivePublishedReview(source)) return pendingVersion;
+ if (source.latestVersion && isActivePublishedReview(source.moderationStatus)) return source.latestVersion;
+ return null;
+}
+
+export function effectivePublishedStatusVersion(source: PublishedStatusSource | null | undefined): string | null {
+ if (!source) return null;
+ const pendingVersion = source.pendingVersion?.version?.trim() ?? '';
+ if (pendingVersion && effectivePublishedStatus(source)) return pendingVersion;
+ return source.latestVersion?.trim() || null;
+}
+
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 6d9742d6dc..630044fc4a 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -40,8 +40,8 @@
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 47 | 0 | 79 |
| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 154 | 109 | 716 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 153 | 46 | 295 |
-| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local`(SkillhubLocalLayout 保留列表)及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name`、`/skillhub/local/by-path` | InstallTargetPicker, PluginManagementLayout, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketPreviewPanel | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx | 46 | 0 | 63 |
-| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketListView, SkillhubMarketPreviewPanel, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 53 | 0 | 62 |
+| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginManagementLayout, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx | 45 | 0 | 60 |
+| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 52 | 0 | 60 |
| `desktop.window.computer-permission-guide` | desktop | 电脑使用权限引导 | `?view=computer-permission-guide` → ComputerPermissionGuideWindow;backdrop 同文件 | ComputerPermissionBackdrop, ComputerPermissionGuideWindow | apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts, apps/desktop/src/main/computer-permission-guide/placement.ts, apps/desktop/src/main/computer-permission-guide/request.ts, apps/desktop/src/main/computer-permission-guide/switch-target.ts, apps/desktop/src/main/computer-permission-guide/window.ts, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx | 7 | 2 | 9 |
| `desktop.window.ghost-panel` | desktop | 插件面板独立窗口 | `?ghostPanelWindow=<id>` → renderer/ghost-panel-window-entry.tsx;hash `/ghost-panel-window` | GhostPanelWindowLayout | apps/desktop/src/main/ghost-panel-window/controller.ts, apps/desktop/src/main/ghost-panel-window/ipc.ts, apps/desktop/src/main/ghost-panel-window/registry.ts, apps/desktop/src/main/ghost-panel-window/settings-store.ts, apps/desktop/src/main/ghost-panel-window/window.ts, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/ghost-panel-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 63 | 38 | 14 |
| `desktop.window.remote-desktop` | desktop | 远程桌面独立窗口 | `?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx | Button, ConfirmDialog, FormField, Popover, RemoteDesktopViewerWindow, Select, Switch, Tip | apps/desktop/src/main/remote-desktop-viewer/connection.ts, apps/desktop/src/main/remote-desktop-viewer/credentials.ts, apps/desktop/src/main/remote-desktop-viewer/preferences.ts, apps/desktop/src/main/remote-desktop-viewer/registry.ts, apps/desktop/src/main/remote-desktop-viewer/safety.ts, apps/desktop/src/main/remote-desktop-viewer/windows.ts, apps/desktop/src/renderer/components/ui/button.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog.tsx, apps/desktop/src/renderer/components/ui/form-field.tsx, apps/desktop/src/renderer/components/ui/popover.tsx, apps/desktop/src/renderer/components/ui/select.tsx, apps/desktop/src/renderer/components/ui/switch.tsx, apps/desktop/src/renderer/components/ui/tooltip.tsx, apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx, apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css, apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 114 | 36 | 34 |
@@ -95,11 +95,15 @@
| `/plugins` | GhostPluginPage | `desktop.plugins.installed` |
| `/settings` | SettingsView | `desktop.settings` |
| `/sidebar-window` | SidebarWindowLayout | `desktop.window.sidebar` |
-| `/skillhub/local` | SkillhubLocalLayout | `desktop.skillhub.local` |
-| `/skillhub/local/:kind/global/:name` | SkillhubDetailView | `desktop.skillhub.local` |
-| `/skillhub/local/:kind/project/:projectHash/:name` | SkillhubDetailView | `desktop.skillhub.local` |
-| `/skillhub/local/by-path` | SkillhubDetailView | `desktop.skillhub.local` |
+| `/skillhub` | SkillhubLocalLayout | `desktop.skillhub.local` |
+| `/skillhub/detail` | SkillhubDetailRoute | `desktop.skillhub.local` |
+| `/skillhub/local/:kind/global/:name` | LegacySkillDetailRedirect | `desktop.skillhub.local` |
+| `/skillhub/local/:kind/project/:projectHash/:name` | LegacySkillDetailRedirect | `desktop.skillhub.local` |
+| `/skillhub/local/by-path` | LegacySkillDetailRedirect | `desktop.skillhub.local` |
| `/skillhub/market` | SkillhubMarketListView | `desktop.skillhub.market` |
+| `/skillhub/market/:kind/:name` | LegacySkillDetailRedirect | `desktop.skillhub.market` |
+| `/skillhub/market/:name` | LegacySkillDetailRedirect | `desktop.skillhub.market` |
+| `/skillhub/market/manage/:name` | LegacySkillDetailRedirect | `desktop.skillhub.market` |
### 排除的 redirect
@@ -111,9 +115,6 @@
| `/cc-agent/new-dialogue` | /cc-agent/new | Navigate |
| `/cc-agent/orca/new` | /cc-agent/new | Navigate |
| `/skillhub` | /skillhub/local | Navigate |
-| `/skillhub/market/:kind/:name` | /skillhub/market | Navigate |
-| `/skillhub/market/:name` | /skillhub/market | Navigate |
-| `/skillhub/market/manage/:name` | /skillhub/market | Navigate |
### Mobile 文件路由覆盖
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index f5b74097e4..87b3e7144b 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -105,6 +105,32 @@ X 快照有请求正文时,按原始 triggerMessageId 排除引用列表中的
### Skill Hub 目录与管理契约
+- 原作者发布更新比较:服务端摘要新增可选 `isCreator`,仅表示当前成员是原始上传者,
+ 独立于组织归属 `isMine` 和管理员管理权 `canManage`。Desktop 自动提示只使用
+ `isCreator === true` 的新鲜服务端结果;缺字段、离线、摘要不完整均为未知。
+ `GET /skills/:slug/files?version=...&includeHashes=1` 需认证及该 Skill 的管理权,
+ 返回每个文件原始字节的可选 `sha256`;普通 files 请求保持原预览结构。
+ `fileHash` 仍是 ZIP 校验和,绝不作为本地 `folderHash`。
+ 新包在校验时写入现有 release.fileIndex;历史包按需校验不可变 ZIP 并回填 JSON,
+ 不改数据库 schema、版本或下载计数。两仓分别保留同名 `published-content.json`
+ fixture,覆盖文本、二进制、空文件及 ZIP 元数据变化。
+- Desktop 的 `skillhub:compare-published` 只开放给受信任的本地 Renderer,
+ Main 从发送窗口的最新扫描记录解析路径、slug 和 catalog,不接受 Renderer 指定远端
+ 身份;读取前后复核账号代次、项目授权和目录身份,不扩展 device-link allowlist。
+ 比较遵循现有打包排除规则,包含 SKILL.md 的 version 字段;2,000 文件限额只计算
+ 实际打包的普通文件,不计目录和符号链接。审核中优先比较已提交版本,Main 与 Renderer
+ 共用 `skillhubPublishedStatus.ts`,统一识别机审、人工审核、隔离及历史状态别名。
+ 公开目录仅以已有列表版本判断下载更新,不逐项比较发布内容。本地列表先以批量同步确认
+ 原作者;本地列表和详情在进入、切换及回到窗口时复用同账号 30 秒内的比较结果,
+ 本地写入主动失效对应 Skill 缓存,最多并行 3 个比较,离页取消未开始的请求,无后台轮询。
+ `unavailable.reason` 可选为 `service`,仅用于 Main 确认的网络失败、408、429 或 5xx;
+ 此时同账号队列冷却 30 秒,之后在下一次进入/聚焦时重试。缺字段、本地读取、摘要或身份
+ 失败只影响该 Skill,本地修复/保存立即清除其缓存,不阻塞其它 Skill。
+ 冷却仅影响发布差异提示,不停用列表、编辑、下载或手动发布能力。
+ 差异预览锚定线上具体版本;二进制、大文件或无法完整校验的文本仅展示变更和大小,
+ 文本预览总计最多 4 MiB、单文件 1 MiB、远端预览最多 16 次。更新仍复用原发布审核流程,
+ 下载覆盖仍复用用户确认和备份。新旧两端可分别升级,旧端缺少摘要时不推断相同或不同。
+
- Desktop 本地技能管理用扫描条目 `id` 区分不同 scope / 项目中的同源记录;启停与卸载
的本地 IPC 可选携带 `skillId`,Main 同时匹配路径、当前发送窗口的扫描记录和项目授权,
缺省字段保留旧调用行为,不向 device-link 新开放管理能力。启停偏好仍按物理身份共享;
@@ -125,7 +151,10 @@ X 快照有请求正文时,按原始 triggerMessageId 排除引用列表中的
worktree 同时保留分组后的基仓与任务实际 cwd:分组路径只作目录归并,不能代替
原生技能发现路径。Renderer 项目目录和 Main 白名单使用同样的两组路径,排除远程任务。
扫描结果可选携带按物理路径关联的 `registrySkillName`,市场详情按此原始注册 slug
- 与 catalog scope 匹配;保留实际目录名用于本地展示。未注册或旧扫描缺少该字段时,
+ 与 catalog scope 匹配;批量 sync 的生产方与 registry 回填消费方同样使用此键,
+ 保留实际目录名用于本地展示。更新同一 catalog 的 published 注册记录时保留该来源身份,
+ 仅刷新下载版本和内容基线;切换 catalog 安装则记录新的 catalog + installed 来源。
+ authorId 与 Hub 摘要保持相同 owner slug,不把组织 ID 替换为当前成员 ID。未注册或旧扫描缺少该字段时,
只按精确名称匹配,不用大小写折叠推断两个目录属于同一市场技能。
源目录形状不能单独证明归属:同一分组必须有直接、非符号链接的发现入口,才可按独立
实体卸载;检查覆盖入口、发现根及引擎配置目录各级,拒绝其中的符号链接,保留发现
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index a5defe412f..6d52666cf4 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -131,6 +131,8 @@ const noopLogger: Logger = {
child: () => noopLogger,
};
+// Durable approval assertions allow 3s for the 500ms poll and asynchronous delivery.
+// The default 1s wait races the second poll on loaded CI runners; permission assertions stay exact.
// The same durable store feeds streaming foreground discovery and detached lease inspection.
function mockRunDiscovery() {
const list = vi.spyOn(piSubagentRuns, 'listPiSubagentRuns');
@@ -1274,7 +1276,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
confirmed: true,
runtimeOwnerId: ownerId(),
}),
- ));
+ ), { timeout: 3_000 });
expect(noteOpaqueWrite).toHaveBeenCalledWith({
sessionId: 's1',
provider: 'pi',
@@ -1584,7 +1586,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
confirmed,
runtimeOwnerId: ownerId(),
}),
- ));
+ ), { timeout: 3_000 });
expect(resolver).toHaveBeenCalledOnce();
expect(resolver).toHaveBeenCalledWith(expect.objectContaining({
kind: 'permission',
@@ -1617,7 +1619,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ value }),
- ));
+ ), { timeout: 3_000 });
await handle.close();
},
);
@@ -1667,7 +1669,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ value: 'auto-review-deny:This task is read-only.' }),
- ));
+ ), { timeout: 3_000 });
expect(review).toHaveBeenCalledOnce();
expect(resolver).not.toHaveBeenCalled();
await handle.close();
@@ -1688,7 +1690,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ value: 'system-deny' }),
- ));
+ ), { timeout: 3_000 });
await handle.close();
});
@@ -1849,7 +1851,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ confirmed: true }),
- ));
+ ), { timeout: 3_000 });
expect(resolver).not.toHaveBeenCalled();
await handle.close();
});
@@ -1875,7 +1877,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ confirmed: true }),
- ));
+ ), { timeout: 3_000 });
expect(review).toHaveBeenCalledWith(expect.objectContaining({
action: { kind: 'file-write', path: 'tmp/legacy-safe.txt',
resolvedPath: path.join(cwd, 'tmp', 'legacy-safe.txt'), resolvedWritableRoots: null },
@@ -1910,7 +1912,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ confirmed: false }),
- ));
+ ), { timeout: 3_000 });
expect(review).toHaveBeenCalledWith(expect.objectContaining({
action: { kind: 'file-write', path: path.join(writableDir, 'linked', 'result.txt'),
resolvedPath: path.join(outsideDir, 'result.txt'), resolvedWritableRoots: [cwd, writableDir] },
@@ -1954,7 +1956,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ confirmed: true }),
- ));
+ ), { timeout: 3_000 });
expect(resolver).not.toHaveBeenCalled();
} finally {
await handle.close();
@@ -1983,7 +1985,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ confirmed: false }),
- ));
+ ), { timeout: 3_000 });
expect(review).toHaveBeenCalledOnce();
expect(resolver).toHaveBeenCalledWith(expect.objectContaining({
toolName: 'bash',
@@ -2005,7 +2007,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
run.taskId,
'approval',
expect.objectContaining({ confirmed: false }),
- ));
+ ), { timeout: 3_000 });
await handle.close();
});
diff --git a/scripts/__tests__/design-inventory.test.mjs b/scripts/__tests__/design-inventory.test.mjs
index 2ed4a9d4e9..0024340eef 100644
--- a/scripts/__tests__/design-inventory.test.mjs
+++ b/scripts/__tests__/design-inventory.test.mjs
@@ -134,11 +134,15 @@ test('extractRouterFacts: 真实 router.tsx 的三类去向逐条钉死', () =>
'/plugins GhostPluginPage',
'/settings SettingsView',
'/sidebar-window SidebarWindowLayout',
- '/skillhub/local SkillhubLocalLayout',
- '/skillhub/local/:kind/global/:name SkillhubDetailView',
- '/skillhub/local/:kind/project/:projectHash/:name SkillhubDetailView',
- '/skillhub/local/by-path SkillhubDetailView',
+ '/skillhub SkillhubLocalLayout',
+ '/skillhub/detail SkillhubDetailRoute',
+ '/skillhub/local/:kind/global/:name LegacySkillDetailRedirect',
+ '/skillhub/local/:kind/project/:projectHash/:name LegacySkillDetailRedirect',
+ '/skillhub/local/by-path LegacySkillDetailRedirect',
'/skillhub/market SkillhubMarketListView',
+ '/skillhub/market/:kind/:name LegacySkillDetailRedirect',
+ '/skillhub/market/:name LegacySkillDetailRedirect',
+ '/skillhub/market/manage/:name LegacySkillDetailRedirect',
]);
assert.deepEqual(redirects.map((row) => `${row.path} -> ${row.to}`), [
@@ -148,9 +152,6 @@ test('extractRouterFacts: 真实 router.tsx 的三类去向逐条钉死', () =>
'/cc-agent/new-dialogue -> /cc-agent/new',
'/cc-agent/orca/new -> /cc-agent/new',
'/skillhub -> /skillhub/local',
- '/skillhub/market/:kind/:name -> /skillhub/market',
- '/skillhub/market/:name -> /skillhub/market',
- '/skillhub/market/manage/:name -> /skillhub/market',
]);
assert.deepEqual(layouts.map((row) => `${row.path} ${row.component}`), [
@@ -312,11 +313,11 @@ test('router.tsx 每条生产路由都能映射到 surface,布局壳在排除清
const mappedPaths = coverage.mapped.map((row) => row.path);
assert.ok(mappedPaths.includes('/issues'));
assert.ok(mappedPaths.includes('/login'));
- assert.ok(mappedPaths.includes('/skillhub/local'));
+ // Unlike the pure feature shell, the retained layout renders the catalog itself.
+ assert.ok(mappedPaths.includes('/skillhub'));
assert.ok(mappedPaths.includes('/skillhub/market'));
assert.equal(mappedPaths.includes('/'), false);
assert.equal(mappedPaths.includes('/cc-agent'), false);
- assert.equal(mappedPaths.includes('/skillhub'), false);
assert.equal(mappedPaths.includes('/billing'), false);
const layoutPaths = new Set(listLayoutExclusions(routerSource).map((row) => row.path));
@@ -691,7 +692,7 @@ test('市场页直接渲染的子组件纳入样式统计', () => {
const catalog = catalogSurfaces();
const market = catalog.find((surface) => surface.id === 'desktop.skillhub.market');
assert.ok(market);
- for (const component of ['MarketCard', 'InstallTargetPicker', 'SkillhubMarketPreviewPanel', 'MarketInfoEditDialog', 'VisibilityEditorDialog']) {
+ for (const component of ['MarketCard', 'InstallTargetPicker', 'SkillhubMarketDetailView', 'MarketInfoEditDialog', 'VisibilityEditorDialog']) {
assert.ok(
market.reachableComponents.includes(component),
`${component} 必须列入市场页可达组件`,
@@ -803,7 +804,7 @@ test('skillhub.local 纳入保留列表布局及直接渲染子组件的样式
const catalog = catalogSurfaces();
const local = catalog.find((surface) => surface.id === 'desktop.skillhub.local');
assert.ok(local);
- for (const component of ['SkillhubLocalLayout', 'SkillhubHomeView', 'PluginManagementLayout', 'SkillhubMarketPreviewPanel', 'InstallTargetPicker']) {
+ for (const component of ['SkillhubLocalLayout', 'SkillhubHomeView', 'PluginManagementLayout', 'SkillhubMarketDetailView', 'InstallTargetPicker']) {
assert.ok(
local.reachableComponents.includes(component),
`${component} 必须列入 skillhub.local 可达组件`,
diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjs
index c47ae6bfdd..39851e20bc 100644
--- a/scripts/shared/design-inventory.mjs
+++ b/scripts/shared/design-inventory.mjs
@@ -595,59 +595,64 @@ export function catalogSurfaces() {
platform: 'desktop',
title: 'SkillHub 本地技能',
productionEntry:
- 'hash `/skillhub/local`(SkillhubLocalLayout 保留列表)及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name`、`/skillhub/local/by-path`',
- // SkillhubLocalLayout 保留 SkillhubHomeView;首页直接渲染
- // PluginManagementLayout(features/plugin 共享布局)、
- // SkillhubMarketPreviewPanel 与 InstallTargetPicker——只扫路由入口文件
+ 'hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向)',
+ // SkillhubHomeView 直接渲染 PluginManagementLayout(features/plugin 共享布局)、
+ // 统一详情布局与 InstallTargetPicker——只扫列表组件文件
// 会漏掉这些子组件的样式事实。
reachableComponents: [
'SkillhubLocalLayout',
'SkillhubHomeView',
'SkillhubDetailView',
+ 'SkillhubDetailRoute',
+ 'SkillDetailLayout',
'SkillhubFeatureLayout',
'PluginManagementLayout',
- 'SkillhubMarketPreviewPanel',
+ 'SkillhubMarketDetailView',
'InstallTargetPicker',
],
styleRoots: [
'apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx',
'apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx',
'apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx',
+ 'apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx',
+ 'apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx',
'apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx',
- 'apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx',
+ 'apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx',
'apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx',
'apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx',
],
routerPaths: [
- '/skillhub/local',
+ // The pathless parent renders the retained catalog itself at /skillhub/local.
+ '/skillhub',
+ '/skillhub/detail',
'/skillhub/local/:kind/global/:name',
'/skillhub/local/:kind/project/:projectHash/:name',
'/skillhub/local/by-path',
],
- routeEntryComponents: { '/skillhub/local': 'SkillhubLocalLayout', '/skillhub/local/:kind/global/:name': 'SkillhubDetailView', '/skillhub/local/:kind/project/:projectHash/:name': 'SkillhubDetailView', '/skillhub/local/by-path': 'SkillhubDetailView' },
+ routeEntryComponents: { '/skillhub': 'SkillhubLocalLayout', '/skillhub/detail': 'SkillhubDetailRoute', '/skillhub/local/:kind/global/:name': 'LegacySkillDetailRedirect', '/skillhub/local/:kind/project/:projectHash/:name': 'LegacySkillDetailRedirect', '/skillhub/local/by-path': 'LegacySkillDetailRedirect' },
},
{
id: 'desktop.skillhub.market',
platform: 'desktop',
title: 'SkillHub 市场',
productionEntry: 'hash `/skillhub/market`(SkillhubMarketListView)',
- // 市场页直接渲染的子组件(MarketCard / InstallTargetPicker / 预览面板 / 两个编辑
+ // 市场页直接渲染的子组件(MarketCard / InstallTargetPicker / 详情页 / 两个编辑
// 弹窗)在 components/ 与同目录下,只扫入口文件会漏掉它们的全部样式事实。
reachableComponents: [
'SkillhubMarketListView',
'MarketCard',
'InstallTargetPicker',
- 'SkillhubMarketPreviewPanel',
+ 'SkillhubMarketDetailView',
'MarketInfoEditDialog',
'VisibilityEditorDialog',
],
styleRoots: [
'apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx',
- 'apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx',
+ 'apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx',
'apps/desktop/src/renderer/features/skillhub/components',
],
- routerPaths: ['/skillhub/market'],
- routeEntryComponents: { '/skillhub/market': 'SkillhubMarketListView' },
+ routerPaths: ['/skillhub/market', '/skillhub/market/:name', '/skillhub/market/:kind/:name', '/skillhub/market/manage/:name'],
+ routeEntryComponents: { '/skillhub/market': 'SkillhubMarketListView', '/skillhub/market/:name': 'LegacySkillDetailRedirect', '/skillhub/market/:kind/:name': 'LegacySkillDetailRedirect', '/skillhub/market/manage/:name': 'LegacySkillDetailRedirect' },
},
{
id: 'desktop.settings',