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。

fix(skillhub): retain publication owner through commit reconciliation

xd-bobo90e4ed9b3226
diff --git a/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts b/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts
index 54c892c029..5d50dc5037 100644
--- a/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts
@@ -250,7 +250,7 @@ describe('SkillPublishService', () => {
});
expect(commitCall?.[1]?.body).not.toHaveProperty('tags');
expect(commitCall?.[1]?.body).not.toHaveProperty('visibility');
- expect(scanPollSpy).toHaveBeenCalledWith('lark-task', '1.1.0');
+ expect(scanPollSpy).toHaveBeenCalledWith('lark-task', '1.1.0', 'signed-in:user-1:1');
});
it('publishes through Hub without requiring a local LLM API key file', async () => {
diff --git a/apps/desktop/src/main/skillhub/__tests__/publishServiceOwner.test.ts b/apps/desktop/src/main/skillhub/__tests__/publishServiceOwner.test.ts
new file mode 100644
index 0000000000..d7c9c53e1b
--- /dev/null
+++ b/apps/desktop/src/main/skillhub/__tests__/publishServiceOwner.test.ts
@@ -0,0 +1,129 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ ownerId: 'owner-a', generation: 1, boundaryPending: false,
+ api: vi.fn(), snapshot: vi.fn(), getInstall: vi.fn(), addInstall: vi.fn(), updateInstall: vi.fn(),
+ identity: vi.fn(), pack: vi.fn(),
+}));
+
+vi.mock('electron', () => ({ net: { fetch: vi.fn(async () => ({ ok: true, status: 200 })) } }));
+vi.mock('../../logger', () => ({ createLogger: () => ({ debug: vi.fn(), warn: vi.fn(), error: vi.fn() }) }));
+vi.mock('../../authManager', () => ({
+ getCurrentDataOwnerId: () => mocks.ownerId,
+ getCurrentUserId: () => mocks.ownerId,
+}));
+vi.mock('../../appSessionState', () => ({
+ activeOwnerScopeKey: () => `cloud:${mocks.ownerId}:${mocks.generation}`,
+ isAppSessionBoundaryPending: () => mocks.boundaryPending,
+}));
+vi.mock('../../appCapabilities.js', () => ({ getAppCapabilities: () => ({ canUseSkillHubCloud: true }) }));
+vi.mock('../identityPolicy', () => ({ currentSkillhubIdentityPolicy: mocks.identity }));
+vi.mock('../hubApi', () => ({ skillhubApiFetch: mocks.api }));
+vi.mock('../folderHash', () => ({ computeFolderHash: vi.fn(async () => 'folder-hash') }));
+vi.mock('../zipPacker', () => ({ pack: mocks.pack }));
+vi.mock('../snapshot', () => ({ writeSnapshot: mocks.snapshot }));
+vi.mock('../registry', () => ({ registryService: {
+ getInstall: mocks.getInstall, addInstall: mocks.addInstall, updateInstall: mocks.updateInstall,
+} }));
+vi.mock('../../serverApiClient', () => ({ ServerApiError: class extends Error {} }));
+
+import { SkillPublishService } from '../publishService';
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+describe('publication owner across commit reconciliation', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.useFakeTimers();
+ Object.assign(mocks, { ownerId: 'owner-a', generation: 1, boundaryPending: false });
+ mocks.identity.mockResolvedValue({ canWrite: true, allowedVisibilities: ['PUBLIC'] });
+ mocks.pack.mockResolvedValue({ buffer: Buffer.from('zip'), size: 3, sha256: 'hash', manifest: { files: [] } });
+ mocks.getInstall.mockResolvedValue(null);
+ mocks.snapshot.mockResolvedValue(undefined);
+ mocks.api.mockImplementation(async (apiPath: string) => {
+ if (apiPath.endsWith('/publish/init')) {
+ return { nextVersion: '1.0.0', ossKey: 'object', uploadUrl: 'https://upload.invalid/object' };
+ }
+ if (apiPath.endsWith('/publish/commit')) return {};
+ if (apiPath.includes('/scan?')) return { status: 'pending', gates: [] };
+ throw new Error(`Unexpected request: ${apiPath}`);
+ });
+ });
+ afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
+
+ it.each((['commit', 'snapshot', 'registry'] as const).flatMap(stage =>
+ (['unchanged', 'different-owner', 'new-generation', 'boundary-pending'] as const).map(transition => ({ stage, transition })),
+ ))('preserves committed success during $stage / $transition', async ({ stage, transition }) => {
+ const entered = deferred(); const resume = deferred();
+ const pause = async () => { entered.resolve(); await resume.promise; };
+ if (stage === 'commit') {
+ const api = mocks.api.getMockImplementation()!;
+ mocks.api.mockImplementation(async (...args) => {
+ if (String(args[0]).endsWith('/publish/commit')) await pause();
+ return api(...args);
+ });
+ } else if (stage === 'snapshot') mocks.snapshot.mockImplementationOnce(pause);
+ else mocks.getInstall.mockImplementationOnce(async () => { await pause(); return null; });
+
+ const globalProgress = vi.fn(); const localProgress = vi.fn();
+ const service = new SkillPublishService({ onProgress: globalProgress, scanPollIntervalMs: 10 });
+ const publishing = service.publish({ absolutePath: 'virtual-skill', name: 'review-helper', isFirstPublish: false }, localProgress);
+ await entered.promise;
+ localProgress.mockClear(); globalProgress.mockClear();
+ if (transition === 'different-owner') mocks.ownerId = 'owner-b';
+ if (transition === 'new-generation') mocks.generation++;
+ if (transition === 'boundary-pending') mocks.boundaryPending = true;
+ resume.resolve();
+
+ await expect(publishing).resolves.toEqual({ success: true, result: { name: 'review-helper', version: '1.0.0' } });
+ expect(mocks.addInstall).toHaveBeenCalledWith('review-helper', 'virtual-skill', expect.objectContaining({ authorId: 'owner-a', version: '1.0.0' }));
+ if (transition === 'unchanged') {
+ expect(localProgress).toHaveBeenCalledWith({ phase: 'done', name: 'review-helper', version: '1.0.0' });
+ await vi.advanceTimersByTimeAsync(20);
+ expect(globalProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'scan-result' }));
+ } else {
+ await vi.advanceTimersByTimeAsync(20);
+ expect(localProgress).not.toHaveBeenCalled();
+ expect(globalProgress).not.toHaveBeenCalled();
+ expect(mocks.api.mock.calls.some(([apiPath]) => String(apiPath).includes('/scan?'))).toBe(false);
+ }
+ service.stopScanPoll();
+ });
+
+ it('keeps a newer owner poll when completion callbacks switch the active owner', async () => {
+ const onProgress = vi.fn();
+ const service = new SkillPublishService({ onProgress, scanPollIntervalMs: 10 });
+ const result = await service.publish({ absolutePath: 'virtual-skill', name: 'review-helper', isFirstPublish: false }, event => {
+ if (event.phase !== 'done') return;
+ mocks.ownerId = 'owner-b';
+ service.startScanPoll('review-helper', '2.0.0');
+ onProgress.mockClear();
+ });
+ expect(result.success).toBe(true);
+ expect(onProgress).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(20);
+ const scanPaths = mocks.api.mock.calls.map(([apiPath]) => String(apiPath)).filter(apiPath => apiPath.includes('/scan?'));
+ expect(scanPaths).toEqual(['/api/skills-hub/skills/review-helper/scan?version=2.0.0']);
+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: 'scan-result', version: '2.0.0' }));
+ });
+
+ it('does not rebind a publication when identity lookup crosses an owner boundary', async () => {
+ const policy = deferred();
+ mocks.identity.mockImplementationOnce(async () => {
+ await policy.promise;
+ return { canWrite: true, allowedVisibilities: ['PUBLIC'] };
+ });
+ const onProgress = vi.fn();
+ const service = new SkillPublishService({ onProgress });
+ const publishing = service.publish({ absolutePath: 'virtual-skill', name: 'review-helper', isFirstPublish: false });
+ mocks.ownerId = 'owner-b'; policy.resolve();
+ await expect(publishing).resolves.toMatchObject({ success: false, errorCode: 'CANCELLED' });
+ expect(mocks.pack).not.toHaveBeenCalled();
+ expect(mocks.api).not.toHaveBeenCalled();
+ expect(onProgress).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/skillhub/publishService.ts b/apps/desktop/src/main/skillhub/publishService.ts
index bafc0e4c11..d35f72a70f 100644
--- a/apps/desktop/src/main/skillhub/publishService.ts
+++ b/apps/desktop/src/main/skillhub/publishService.ts
@@ -180,24 +180,24 @@ async function syncPublishedRegistry(
absolutePath: string,
version: string,
folderHash: string,
+ authorId: string,
catalogScope?: SkillhubCatalogScope | null,
): Promise<void> {
const nowSec = Math.floor(Date.now() / 1000);
- const myUserId = getCurrentUserId() ?? '';
const existing = await registryService.getInstall(slug, absolutePath);
if (existing) {
await registryService.updateInstall(slug, absolutePath, {
version,
folderHash,
updatedAt: nowSec,
- authorId: myUserId,
+ authorId,
origin: 'published',
...(catalogScope !== undefined ? { catalogScope: catalogScope ?? undefined } : {}),
});
} else {
await registryService.addInstall(slug, absolutePath, {
version,
- authorId: myUserId,
+ authorId,
folderHash,
installedAt: nowSec,
updatedAt: nowSec,
@@ -241,28 +241,34 @@ export class SkillPublishService {
errorCode?: string;
error?: string;
}> {
+ // Capture before identity hydration: every await belongs to this publication's owner.
+ const publishOwnerScope = activeOwnerScopeKey();
+ const publishOwnerId = getCurrentDataOwnerId();
+ const publishAuthorId = getCurrentUserId() ?? '';
+ const isPublishOwnerCurrent = () => !isAppSessionBoundaryPending()
+ && activeOwnerScopeKey() === publishOwnerScope;
+ const emitProgress = (event: PublishProgressEvent) => this.emitProgress(event, onProgress, publishOwnerScope);
if (!getAppCapabilities().canUseSkillHubCloud) {
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: 'CANCELLED',
message: 'SkillHub publish is unavailable in local mode',
},
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
const identityPolicy = await currentSkillhubIdentityPolicy();
+ if (!isPublishOwnerCurrent()) return { success: false, errorCode: 'CANCELLED' };
if (!identityPolicy.canWrite) {
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: 'CANCELLED',
message: 'SkillHub publish requires sign-in',
},
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -271,7 +277,7 @@ export class SkillPublishService {
&& params.visibility
&& !identityPolicy.allowedVisibilities.includes(params.visibility)
) {
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
@@ -280,33 +286,29 @@ export class SkillPublishService {
? 'Organization skills only support public or organization visibility'
: 'Personal skills only support public or private visibility',
},
- onProgress,
);
return { success: false, errorCode: 'INVALID_VISIBILITY' };
}
- const publishOwnerId = getCurrentDataOwnerId();
if (!publishOwnerId) {
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: 'CANCELLED',
message: 'SkillHub publish requires an active data owner',
},
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
const tags = params.isFirstPublish ? normalizePublishTags(params.tags) : undefined;
if (this.current) {
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: 'INTERNAL',
message: '已有发布任务进行中',
},
- onProgress,
);
return { success: false, errorCode: 'INTERNAL' };
}
@@ -319,7 +321,7 @@ export class SkillPublishService {
const isCancelled = (): boolean =>
signal.aborted ||
!getAppCapabilities().canUseSkillHubCloud ||
- getCurrentDataOwnerId() !== publishOwnerId;
+ !isPublishOwnerCurrent();
let originalSkillMd: string | null = null;
let publishSucceeded = false;
@@ -340,11 +342,10 @@ export class SkillPublishService {
// ── 步骤 2: 打包 ─────────────────────────────────────────────────────
if (!state.packCache) {
- this.emitProgress({ phase: 'packing' }, onProgress);
+ emitProgress({ phase: 'packing' });
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -357,23 +358,21 @@ export class SkillPublishService {
if (isCancelled()) throw err;
const message = err instanceof Error ? err.message : String(err);
log.error(`[publish:pack] failed | name=${params.name}:`, err);
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: 'PACK_FAILED',
message,
},
- onProgress,
);
return { success: false, errorCode: 'PACK_FAILED', error: message };
}
}
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -383,11 +382,10 @@ export class SkillPublishService {
for (;;) {
if (!state.initCache) {
- this.emitProgress({ phase: 'init' }, onProgress);
+ emitProgress({ phase: 'init' });
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -421,32 +419,29 @@ export class SkillPublishService {
} catch (err) {
log.error(`[publish:init] failed | name=${params.name} err=`, err);
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
const code = serverErrorToCode(err);
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: code,
message: err instanceof Error ? err.message : String(err),
},
- onProgress,
);
return { success: false, errorCode: code };
}
}
// ── 步骤 5: OSS PUT ──────────────────────────────────────────────
- this.emitProgress({ phase: 'uploading' }, onProgress);
+ emitProgress({ phase: 'uploading' });
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -512,9 +507,8 @@ export class SkillPublishService {
}
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -522,37 +516,34 @@ export class SkillPublishService {
if (ossExpired) {
state.initCache = undefined;
state.packCache = undefined;
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: 'OSS_PUT_EXPIRED',
message: '上传链接已过期,请重新发布',
},
- onProgress,
);
return { success: false, errorCode: 'OSS_PUT_EXPIRED' };
}
if (!ossOk) {
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: 'OSS_PUT_FAILED',
message: ossFailDetail || '上传失败,请重试',
},
- onProgress,
);
return { success: false, errorCode: 'OSS_PUT_FAILED' };
}
// ── 步骤 6: publish/commit ───────────────────────────────────────
- this.emitProgress({ phase: 'commit' }, onProgress);
+ emitProgress({ phase: 'commit' });
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -604,6 +595,7 @@ export class SkillPublishService {
params.absolutePath,
publishedVersion,
folderHash,
+ publishAuthorId,
params.isFirstPublish
? params.visibility === 'DEPARTMENT_SCOPED'
? 'team'
@@ -611,19 +603,17 @@ export class SkillPublishService {
: undefined,
).catch((err) => log.warn('[publish] registry sync failed (non-fatal):', err));
- this.emitProgress(
+ emitProgress(
{ phase: 'done', name: params.name, version: publishedVersion },
- onProgress,
);
// 公开发布完成机审后会进入 pending,等待 Platform 人工审核。收到 pending 后
// 结束本轮轮询;用户主动刷新列表或详情时再读取最新审核状态。
- this.startScanPoll(params.name, publishedVersion);
+ this.startScanPoll(params.name, publishedVersion, publishOwnerScope);
return { success: true, result: { name: params.name, version: publishedVersion } };
} catch (err) {
if (isCancelled()) {
- this.emitProgress(
+ emitProgress(
{ phase: 'failed', name: params.name, errorCode: 'CANCELLED', message: '已取消' },
- onProgress,
);
return { success: false, errorCode: 'CANCELLED' };
}
@@ -635,14 +625,13 @@ export class SkillPublishService {
}
}
const code = serverErrorToCode(err);
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: code,
message: err instanceof Error ? err.message : String(err),
},
- onProgress,
);
return { success: false, errorCode: code };
}
@@ -655,14 +644,13 @@ export class SkillPublishService {
} else {
log.error(`[publish] unexpected failure | name=${params.name} code=${code}:`, err);
}
- this.emitProgress(
+ emitProgress(
{
phase: 'failed',
name: params.name,
errorCode: code,
message,
},
- onProgress,
);
return { success: false, errorCode: code, error: message };
} finally {
@@ -687,10 +675,10 @@ export class SkillPublishService {
}
}
- startScanPoll(slug: string, version: string): void {
+ startScanPoll(slug: string, version: string, ownerScope = activeOwnerScopeKey()): void {
+ // A late committed publication must neither bind to the next owner nor stop their newer poll.
+ if (!getCurrentDataOwnerId() || isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) return;
this.stopScanPoll();
- if (!getCurrentDataOwnerId() || isAppSessionBoundaryPending()) return;
- const ownerScope = activeOwnerScopeKey();
const generation = this.scanPollGeneration;
const isCurrentPoll = () => {
if (
@@ -753,8 +741,11 @@ export class SkillPublishService {
);
}
- private emitProgress(event: PublishProgressEvent, localProgress?: ProgressCb): void {
+ private emitProgress(event: PublishProgressEvent, localProgress?: ProgressCb, ownerScope = activeOwnerScopeKey()): void {
+ const isCurrent = () => !isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScope;
+ if (!isCurrent()) return;
localProgress?.(event);
- this.onProgress?.(event);
+ // Callback delivery is synchronous with the IPC stamp; never stamp old progress as the new owner.
+ if (isCurrent()) this.onProgress?.(event);
}
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 75b342f19d..19b55ae757 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -116,6 +116,9 @@
不向辅助窗口或已导航到外部内容的窗口发送私有反馈。
推送附带可选 `ownerStamp`(复用 `DataOwnerPushStamp`);接收端同时校验 Skill 和账号代次,
丢弃已在 IPC 队列中的旧账号事件。弹窗在异步刷新后及交付结果前再次校验账号代次。
+ 整次发布在首次异步身份读取前捕获发起账号代次;提交成功后的本地对账保留成功语义和
+ 原发布者身份,但过期发布不再派发进度或启动轮询,也不能停止新账号已启动的轮询。
+ 进度回调与 IPC 标记之间同步复核发起代次,不能给旧发布重新标上当前账号。
旧接收端忽略新增元数据,旧的无标记事件沿用现有兼容读取;首次发布的同版本拒审例外
仅适用于 `rejected`,不能把处理失败 `failed` 或旧扫描失败 `blocked` 套进该例外。
人工拒审原因缺省时始终明确提示缺省,即使已有自动扫描失败项;扫描发现继续独立展示,