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): 隔离过期改名并保留已提交的本地路径

xd-bobo804f19b428ed
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 84e44231eb..7f322252a8 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -149,6 +149,7 @@ describe('registerSkillhubIpc usage handlers', () => {
installServiceMocks.listPendingUninstallCleanups.mockReturnValue([]);
handlers.clear();
vi.clearAllMocks();
+ renameLocalSkill.mockReset();
getManagedSkillRoots.mockReturnValue([]);
getCurrentDataOwnerId.mockReturnValue('local-v1');
getCurrentDbClientSnapshot.mockReset();
@@ -343,6 +344,37 @@ describe('registerSkillhubIpc usage handlers', () => {
expect(afterDestroy).toMatchObject({ success: false });
});
+ it.each(['unchanged', 'grant-wait', 'mutation-wait', 'boundary-pending'] as const)(
+ 'guards local rename at its original owner generation: %s', async (transition) => {
+ const sender = { id: 71, on: vi.fn(), once: vi.fn() };
+ scanAllSkills.mockResolvedValueOnce({ skills: [{
+ absolutePath: '/physical/demo', discoveredPath: '/repo/.pi/skills/authorized/demo',
+ scope: 'project', projectRoot: '/repo',
+ }], sources: [] });
+ await handlers.get('skillhub:scan')!({ sender }, { projects: [] });
+ const mutate = vi.fn();
+ renameLocalSkill.mockImplementationOnce(async (_params, canMutate: () => boolean) => {
+ if (transition === 'mutation-wait') ownerState.generation += 1;
+ if (transition === 'boundary-pending') ownerState.pending = true;
+ if (!canMutate()) return { success: false, error: 'Skill mutation context changed' };
+ mutate();
+ return { success: true, newAbsolutePath: '/physical/renamed' };
+ });
+ if (transition === 'grant-wait') getAllowedProjectRoots.mockImplementationOnce(async () => {
+ ownerState.generation += 1;
+ return ['/repo'];
+ });
+ const result = await handlers.get('skillhub:rename-local')!({ sender }, {
+ absolutePath: '/repo/.pi/skills/authorized/demo', newName: 'renamed',
+ });
+ expect(result).toMatchObject({ success: transition === 'unchanged' });
+ expect(mutate).toHaveBeenCalledTimes(transition === 'unchanged' ? 1 : 0);
+ if (transition === 'grant-wait') {
+ expect(renameLocalSkill).not.toHaveBeenCalled();
+ }
+ },
+ );
+
it('revokes project scan grants after the last active project session disappears', async () => {
const sender = { id: 12, on: vi.fn(), once: vi.fn() };
scanAllSkills.mockResolvedValueOnce({
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 5a584fcafe..67da9f6273 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -526,9 +526,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
ipcMain.handle(
'skillhub:rename-local',
async (event, params: { absolutePath: string; newName: string }) => {
+ const ownerScope = activeOwnerScopeKey();
+ const canMutate = () => ownerScope === activeOwnerScopeKey() && !isAppSessionBoundaryPending();
if (!await hasScannedSkillGrant(event, params.absolutePath)) return scanGrantDenied();
- const ownerId = getCurrentDataOwnerId();
- const result = await renameLocalSkill(params, () => ownerId === getCurrentDataOwnerId() && !isAppSessionBoundaryPending());
+ if (!canMutate()) return { success: false, error: 'Skill mutation context changed' };
+ const result = await renameLocalSkill(params, canMutate);
if (result.success) broadcastLocalChange();
return result;
},
diff --git a/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx b/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx
index 131a976c64..80317e0ed6 100644
--- a/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/PublishDialog.tsx
@@ -25,7 +25,7 @@ import { cn } from '@/lib/utils';
import { Spinner } from '@/components/ui/spinner';
import { toast } from '@/lib/toast';
import { useAuth } from '@/contexts/AuthContext';
-import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, isDataOwnerIdCurrent } from '@/contexts/dataOwnerGeneration';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { pickDefaultVersion } from './versionUtils';
import { triggerIncrementalSync } from './hooks/useSkillSync';
@@ -534,14 +534,11 @@ export function PublishDialog({
const renamedToRef = useRef<{ absolutePath: string; name: string } | null>(null);
const activePublishNameRef = useRef<string | null>(null);
const failedProgressNameRef = useRef<string | null>(null);
+ const mountedRef = useRef(true);
useEffect(() => {
- if (!open || isDialogOwnerCurrent) return;
- activePublishNameRef.current = null;
- failedProgressNameRef.current = null;
- renamedToRef.current = null;
- dispatch({ type: 'CLOSE' });
- onOpenChange(false);
- }, [open, isDialogOwnerCurrent, onOpenChange]);
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
/** 拿当前应使用的 (absolutePath, name) — rename 之后是新值,否则用 prop。 */
const effectiveSkill = useCallback(
(): { absolutePath: string; name: string } => ({
@@ -564,6 +561,21 @@ export function PublishDialog({
}
}, [onLocalRenamed]);
+ const reconcileCommittedRename = useCallback(() => {
+ // A committed filesystem rename remains real across auth realms sharing
+ // this local owner. Repair its mounted route without resuming publication.
+ if (mountedRef.current && isDataOwnerIdCurrent(dialogOwner)) notifyRenameAndReset();
+ else renamedToRef.current = null;
+ }, [dialogOwner, notifyRenameAndReset]);
+
+ useEffect(() => {
+ if (!open || isDialogOwnerCurrent) return;
+ activePublishNameRef.current = null;
+ failedProgressNameRef.current = null;
+ reconcileCommittedRename();
+ dispatch({ type: 'CLOSE' });
+ onOpenChange(false);
+ }, [open, isDialogOwnerCurrent, onOpenChange, reconcileCommittedRename]);
// ── Hub categories (required for first publish only) ─────────────────────
const [categoryState, setCategoryState] = useState<CategoryState>({
@@ -809,8 +821,8 @@ export function PublishDialog({
absolutePath: skill.discoveredPath ?? eff.absolutePath,
newName: submitName,
});
- if (!isDataOwnerGenerationCurrent(dialogOwner)) return;
if (!renameRes.success) {
+ if (!isDataOwnerGenerationCurrent(dialogOwner)) return;
toast.error(t('skillhub.publishDialog.renameFailed', { error: renameRes.error }));
return;
}
@@ -818,6 +830,10 @@ export function PublishDialog({
publishAbsolutePath = renameRes.newAbsolutePath;
// 旧路径的 hash 缓存清掉(它指向已不存在的目录)
invalidateHash(eff.absolutePath);
+ if (!isDataOwnerGenerationCurrent(dialogOwner)) {
+ reconcileCommittedRename();
+ return;
+ }
}
dispatch({ type: 'SUBMIT' });
@@ -840,6 +856,7 @@ export function PublishDialog({
runPublish,
skill.discoveredPath,
dialogOwner,
+ reconcileCommittedRename,
]);
// ── Cancel publish in progress (working / failure 都可调) ────────────────
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
index 0a23e1a1c6..d6c27f6667 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
@@ -34,6 +34,7 @@ import { createLogger } from '@/lib/logger';
import { buildFence, detectRenderable } from '@/lib/textPreview';
import { toast } from '@/lib/toast';
import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerIdCurrent } from '@/contexts/dataOwnerGeneration';
import { cn } from '@/lib/utils';
import { getDraft, getFastModeForModel } from '@/state/newMakerDraft';
import { useMetaColumnResize } from './hooks/useMetaColumnResize';
@@ -2553,9 +2554,11 @@ export function SkillhubDetailView() {
// + 旧 name 的 info 缓存(让新 name 重新查),然后刷新 scanner,
// 最后导航到新 URL。先 await refresh 才 navigate,确保新 URL 落地时
// skills 已包含新 entry,免得短暂闪一下"未找到"。
+ const owner = getDataOwnerGeneration();
invalidateInfo(entry.name);
invalidateHash(newAbsolutePath);
void refreshSkillhub().then((scannedSkills) => {
+ if (!isDataOwnerIdCurrent(owner)) return;
const renamed = findLocalSkillByPath(scannedSkills, newAbsolutePath);
if (!renamed) return;
setLastEntryId(renamed.id);
diff --git a/apps/desktop/src/renderer/features/skillhub/__tests__/PublishDialog.feedback.test.tsx b/apps/desktop/src/renderer/features/skillhub/__tests__/PublishDialog.feedback.test.tsx
index ba26949ac6..8e405c495e 100644
--- a/apps/desktop/src/renderer/features/skillhub/__tests__/PublishDialog.feedback.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/PublishDialog.feedback.test.tsx
@@ -5,6 +5,7 @@ import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
const mocks = vi.hoisted(() => ({
confirm: vi.fn(), refresh: vi.fn(), sync: vi.fn(), publish: vi.fn(), cancelPublish: vi.fn(),
+ renameLocal: vi.fn(), listCategories: vi.fn(),
}));
vi.mock('react-i18next', async (importOriginal) => ({
...await importOriginal<typeof import('react-i18next')>(),
@@ -34,31 +35,42 @@ beforeEach(() => {
mocks.refresh.mockReset().mockResolvedValue([]);
mocks.confirm.mockResolvedValue(true);
mocks.publish.mockResolvedValue({ success: true, result: { name: 'review-helper', version: '1.0.1' } });
+ mocks.renameLocal.mockReset().mockResolvedValue({ success: true, newAbsolutePath: '/fixture/renamed-helper' });
+ mocks.listCategories.mockResolvedValue({ success: true, categories: [] });
vi.stubGlobal('electronAPI', { skillhub: {
publish: mocks.publish,
cancelPublish: mocks.cancelPublish,
+ renameLocal: mocks.renameLocal,
+ listCategories: mocks.listCategories,
onPublishProgress: (listener: typeof progress) => { progress = listener; return () => {}; },
} });
});
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
-function mountPublication() {
+function mountPublication(overrides: Partial<PublishDialogProps> = {}) {
const onScanResult = vi.fn();
const onOpenChange = vi.fn();
+ const onLocalRenamed = vi.fn();
const props: PublishDialogProps = {
- open: true, onOpenChange, onScanResult, isFirstPublish: false, latestVersion: '1.0.0', skill: {
+ open: true, onOpenChange, onScanResult, onLocalRenamed, isFirstPublish: false, latestVersion: '1.0.0', skill: {
id: 'review-helper', urlKey: 'review-helper', engine: 'claude-code', linkedEngines: [],
kind: 'skill', scope: 'global', mdPath: '/fixture/review-helper/SKILL.md', files: [], registryEntry: null,
name: 'review-helper', absolutePath: '/fixture/review-helper', frontmatter: { version: '1.0.1' },
},
+ ...overrides,
};
const view = render(<PublishDialog {...props} />);
- fireEvent.change(screen.getByPlaceholderText('skillhub.publishDialog.changelogPlaceholder'), { target: { value: 'Improve documentation' } });
- return { onScanResult, onOpenChange, rerender: (open = true) => view.rerender(<PublishDialog {...props} open={open} />) };
+ if (props.isFirstPublish) {
+ fireEvent.change(screen.getByPlaceholderText('skillhub.publishDialog.skillNamePlaceholder'), { target: { value: 'renamed-helper' } });
+ } else {
+ fireEvent.change(screen.getByPlaceholderText('skillhub.publishDialog.changelogPlaceholder'), { target: { value: 'Improve documentation' } });
+ }
+ return { onScanResult, onOpenChange, onLocalRenamed, unmount: view.unmount,
+ rerender: (open = true) => view.rerender(<PublishDialog {...props} open={open} />) };
}
-async function startPublication() {
- const view = mountPublication();
+async function startPublication(overrides: Partial<PublishDialogProps> = {}) {
+ const view = mountPublication(overrides);
fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishDialog.startPublish' }));
await waitFor(() => expect(mocks.publish).toHaveBeenCalledOnce());
return view;
@@ -165,4 +177,38 @@ describe('PublishDialog result delivery', () => {
expect(mocks.cancelPublish).not.toHaveBeenCalled();
expect(screen.queryByRole('dialog')).toBeNull();
});
+
+ it('repairs the same-owner route for a committed rename when closing an old-realm publication', async () => {
+ mocks.publish.mockReturnValueOnce(new Promise(() => {}));
+ const view = await startPublication({ isFirstPublish: true, autoCleanName: true });
+ expect(mocks.renameLocal).toHaveBeenCalledOnce();
+ expect(view.onLocalRenamed).not.toHaveBeenCalled();
+ setDataOwnerGeneration('owner-a', 2);
+ view.rerender();
+ expect(view.onLocalRenamed).toHaveBeenCalledExactlyOnceWith('/fixture/renamed-helper', 'renamed-helper');
+ expect(view.onOpenChange).toHaveBeenCalledWith(false);
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(mocks.publish).toHaveBeenCalledOnce();
+ });
+
+ it.each(['same-owner', 'different-owner', 'unmounted', 'rename-rejected'] as const)(
+ 'reconciles a delayed rename reply only for its still-mounted local owner: %s', async (transition) => {
+ let finishRename!: (value: unknown) => void;
+ mocks.renameLocal.mockReturnValueOnce(new Promise((resolve) => { finishRename = resolve; }));
+ const view = mountPublication({ isFirstPublish: true, autoCleanName: true });
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.publishDialog.startPublish' }));
+ await waitFor(() => expect(mocks.renameLocal).toHaveBeenCalledOnce());
+ setDataOwnerGeneration(transition === 'different-owner' ? 'owner-b' : 'owner-a', 2);
+ if (transition === 'unmounted') view.unmount();
+ else view.rerender();
+ await act(async () => { finishRename(transition === 'rename-rejected'
+ ? { success: false, error: 'Skill mutation context changed' }
+ : { success: true, newAbsolutePath: '/fixture/renamed-helper' }); });
+ if (transition === 'same-owner') {
+ expect(view.onLocalRenamed).toHaveBeenCalledExactlyOnceWith('/fixture/renamed-helper', 'renamed-helper');
+ } else expect(view.onLocalRenamed).not.toHaveBeenCalled();
+ expect(mocks.publish).not.toHaveBeenCalled();
+ expect(view.onScanResult).not.toHaveBeenCalled();
+ },
+ );
});
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 89a773dae7..31e4b9ce10 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -126,6 +126,10 @@
跨区域切换不依赖按 dataOwnerId 重挂路由,普通同代次刷新仍保留当前结果。
发布弹窗同样绑定打开时的账号代次;跨代次立即隐藏并关闭,旧发布 IPC 的成功、失败、
异常返回和等待中的提交/取消确认均失效,不能让新区域的弹窗进入旧发布的扫描阶段。
+ 本地改名在 IPC 入口捕获完整账号 scope,在扫描授权等待后及持有文件锁实际变更前
+ 复核;旧代次不能写盘。已经提交的改名仍是有效本地事实:同本地 owner 跨区域时,
+ 仍挂载的详情页保留并交付新路径(包括迟到的成功回执)以修复导航,但不继续旧发布;
+ 不向不同 owner 或已经卸载的详情页交付,刷新导航期间也复核本地 owner。
旧接收端忽略新增元数据,旧的无标记事件沿用现有兼容读取;首次发布的同版本拒审例外
仅适用于 `rejected`,不能把处理失败 `failed` 或旧扫描失败 `blocked` 套进该例外。
人工拒审原因缺省时始终明确提示缺省,即使已有自动扫描失败项;扫描发现继续独立展示,