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): invalidate review feedback across auth realms

xd-boboec9bf7780331
diff --git a/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts b/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts
index 99cf7b1830..3aaea4b3e7 100644
--- a/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts
+++ b/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts
@@ -28,6 +28,8 @@ import {
commitActiveAppSession,
commitVolatileAppSession,
getActiveAppSession,
+ activeOwnerScopeKey,
+ getActiveDataOwnerPushStamp,
isAppSessionBoundaryPending,
setAppSessionCommitBoundaryHook,
} from '../appSessionState.js';
@@ -36,6 +38,7 @@ import {
clearAllSessionRuntimeControlStates,
sessionRuntimeControlOwnerEpochMatches,
} from '../maker-ipc/sessionRuntimeControl.js';
+import { isDataOwnerPushCurrent, setDataOwnerGeneration } from '../../renderer/contexts/dataOwnerGeneration';
describe('application session boundary isolation', () => {
it('does not treat a different durable Ghost projection owner as an App transition', () => {
@@ -89,6 +92,35 @@ describe('application session boundary isolation', () => {
}
});
+ it.each([['primary', commitActiveAppSession], ['passive', commitVolatileAppSession]] as const)(
+ 'invalidates request scopes and queued push stamps on a same-id realm move in %s instances', (_name, commit) => {
+ commit('cloud', 'shared-membership-id');
+ const oldScope = activeOwnerScopeKey();
+ const oldStamp = getActiveDataOwnerPushStamp();
+ const hook = vi.fn();
+ setAppSessionCommitBoundaryHook(hook);
+ try {
+ // Auth commits force this bump only when the issuing realm changes.
+ commit('cloud', 'shared-membership-id', true);
+ expect(activeOwnerScopeKey()).not.toBe(oldScope);
+ expect(getActiveDataOwnerPushStamp()).toEqual({
+ dataOwnerId: oldStamp.dataOwnerId, ownerGeneration: oldStamp.ownerGeneration + 1,
+ });
+ const movedScope = activeOwnerScopeKey();
+ const movedStamp = getActiveDataOwnerPushStamp();
+ setDataOwnerGeneration(movedStamp.dataOwnerId, movedStamp.ownerGeneration);
+ expect(isDataOwnerPushCurrent(oldStamp)).toBe(false);
+ expect(isDataOwnerPushCurrent(movedStamp)).toBe(true);
+ commit('cloud', 'shared-membership-id');
+ expect(activeOwnerScopeKey()).toBe(movedScope);
+ expect(getActiveDataOwnerPushStamp()).toEqual(movedStamp);
+ expect(hook).not.toHaveBeenCalled();
+ } finally {
+ setAppSessionCommitBoundaryHook(null);
+ }
+ },
+ );
+
it('does not create a boundary for a repeated volatile commit to the same owner', () => {
const current = getActiveAppSession();
const targetMode = current.mode === 'signed-out' ? 'local' : 'signed-out';
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index 2e2917a8b9..3030ad3946 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -904,6 +904,27 @@ describe('auth login-flow reset', () => {
expect(helperBody).toContain('writePersistedAuthSessionOrThrow(pair.refreshToken, realm);');
});
+ it('advances the existing owner generation when login or restoration commits another realm', () => {
+ for (const [entry, realm] of [
+ ['async function runColdStartRefreshFlow(', 'storedRealm'],
+ ['async function completeLogin(', 'committedRealm'],
+ ]) {
+ const start = source.indexOf(entry);
+ expect(start).toBeGreaterThan(-1);
+ const body = source.slice(start, source.indexOf('\n}\n', start));
+ const capture = body.indexOf(`const authRealmChanged = ${realm} !== activeAuthRealm;`);
+ const activate = body.indexOf(`activeAuthRealm = ${realm};`);
+ const commit = body.indexOf('commitCloudAppSession(currentUser.id, authRealmChanged);');
+ expect(capture).toBeGreaterThan(-1);
+ expect(activate).toBeGreaterThan(capture);
+ expect(commit).toBeGreaterThan(activate);
+ }
+ const start = source.indexOf('function commitCloudAppSession(');
+ const helper = source.slice(start, source.indexOf('\n}\n', start));
+ expect(helper).toContain("commitActiveAppSession('cloud', ownerId, authRealmChanged);");
+ expect(helper).toContain("commitVolatileAppSession('cloud', ownerId, authRealmChanged);");
+ });
+
it('reconnects realm-bound main clients after a runtime realm change commits its new token', () => {
const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');
const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);
@@ -912,6 +933,7 @@ describe('auth login-flow reset', () => {
expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');
expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');
expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');
+ expect(refreshBody.match(/commitCloudAppSession\(currentUser.id, authRealmChanged\);/g)).toHaveLength(2);
expect(refreshBody).toContain(
'const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;',
);
@@ -1094,7 +1116,7 @@ describe('auth login-flow reset', () => {
const completeStart = source.indexOf('async function completeLogin(');
const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);
const completeBody = source.slice(completeStart, completeEnd);
- const ownerCommit = completeBody.indexOf('commitCloudAppSession(currentUser.id);');
+ const ownerCommit = completeBody.indexOf('commitCloudAppSession(currentUser.id, authRealmChanged);');
const clearPreviousFlag = completeBody.indexOf('canaryFlagStore.clear();', ownerCommit);
expect(ownerCommit).toBeGreaterThan(-1);
expect(clearPreviousFlag).toBeGreaterThan(ownerCommit);
diff --git a/apps/desktop/src/main/appSessionState.ts b/apps/desktop/src/main/appSessionState.ts
index 5fc66ac715..6e70c5557b 100644
--- a/apps/desktop/src/main/appSessionState.ts
+++ b/apps/desktop/src/main/appSessionState.ts
@@ -203,6 +203,7 @@ export function commitActiveAppSession(
export function commitVolatileAppSession(
mode: AppSessionMode,
cloudOwnerId?: string | null,
+ forceBumpGeneration = false,
): ActiveAppSession {
const previous = ensureLoaded();
let dataOwnerId: string | null = null;
@@ -213,10 +214,11 @@ export function commitVolatileAppSession(
if (!normalized) throw new Error('cloud app session requires a verified data owner');
dataOwnerId = normalized;
}
- if (previous.mode === mode && previous.dataOwnerId === dataOwnerId) {
+ const ownerChanged = previous.mode !== mode || previous.dataOwnerId !== dataOwnerId;
+ if (!ownerChanged && !forceBumpGeneration) {
return { ...previous };
}
- appSessionCommitBoundaryHook?.();
+ if (ownerChanged) appSessionCommitBoundaryHook?.();
active = {
mode,
dataOwnerId,
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 862ed5bf47..1026586af3 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -2713,11 +2713,12 @@ async function repairStableCloudOwnerDataReservations(ownerId: string): Promise<
}
}
-function commitCloudAppSession(ownerId: string): void {
+function commitCloudAppSession(ownerId: string, authRealmChanged = false): void {
+ // Saved identities are [realm, membershipId]. Same-id realm moves must fence old API work too.
if (isPassiveSharedUserDataInstance()) {
- commitVolatileAppSession('cloud', ownerId);
+ commitVolatileAppSession('cloud', ownerId, authRealmChanged);
} else {
- commitActiveAppSession('cloud', ownerId);
+ commitActiveAppSession('cloud', ownerId, authRealmChanged);
}
}
@@ -4787,13 +4788,14 @@ async function runColdStartRefreshFlow(
}
},
commit: () => {
- if (storedRealm !== activeAuthRealm) {
+ const authRealmChanged = storedRealm !== activeAuthRealm;
+ if (authRealmChanged) {
activateClientEndpointRealm(storedRealm);
activeAuthRealm = storedRealm;
}
accessToken = refreshData.accessToken;
currentUser = mapMembershipToAuthUser(refreshData.membership);
- commitCloudAppSession(currentUser.id);
+ commitCloudAppSession(currentUser.id, authRealmChanged);
persistedRefreshTokenNeedsIdentityCheck = false;
clearReplacementIntegrationReloadTimers();
},
@@ -5015,6 +5017,7 @@ async function completeLogin(
accessToken = outcome.accessToken;
persistedRefreshTokenNeedsIdentityCheck = false;
clearReplacementIntegrationReloadTimers();
+ const authRealmChanged = committedRealm !== activeAuthRealm;
activateClientEndpointRealm(committedRealm);
activeAuthRealm = committedRealm;
if (!isPassiveSharedUserDataInstance()) {
@@ -5029,7 +5032,7 @@ async function completeLogin(
passiveLocalSignOut = false;
foreignDeviceLocalSignOut = false;
currentUser = nextUser;
- commitCloudAppSession(currentUser.id);
+ commitCloudAppSession(currentUser.id, authRealmChanged);
if (!isPassiveSharedUserDataInstance()) {
canaryFlagStore.clear();
}
@@ -5688,7 +5691,7 @@ export async function refresh(): Promise<boolean> {
}
accessToken = data.accessToken;
currentUser = nextUser;
- commitCloudAppSession(currentUser.id);
+ commitCloudAppSession(currentUser.id, authRealmChanged);
},
});
await migrateLocalProviderBindingsAfterCloudCommit(nextUser.id);
@@ -5746,7 +5749,7 @@ export async function refresh(): Promise<boolean> {
}
accessToken = data.accessToken;
currentUser = nextUser;
- commitCloudAppSession(currentUser.id);
+ commitCloudAppSession(currentUser.id, authRealmChanged);
},
});
await migrateLocalProviderBindingsAfterCloudCommit(nextUser.id);
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
index 9ff79f038b..0a23e1a1c6 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx
@@ -72,10 +72,10 @@ import {
} from './lib/skillUsageState';
import { buildRecentTrendRows, formatLocalDayKey } from './lib/skillUsageTrend';
import { type SkillUsageVersionComparison, selectSkillUsageVersionComparison } from './lib/skillUsageViewModel';
-import { PublishDialog, type ScanResultPayload } from './PublishDialog';
+import { PublishDialog } from './PublishDialog';
import { ScanResultDialog } from './ScanResultDialog';
import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
-import { useRejectionFeedback } from './hooks/useRejectionFeedback';
+import { usePublicationFeedback, useRejectionFeedback } from './hooks/useRejectionFeedback';
import { shouldHandlePublishProgressEvent } from './lib/publishProgressFilter';
import { SkillhubDiffPanel } from './SkillhubDiffPanel';
@@ -971,7 +971,7 @@ function FileTreeRow({ entry, parentDir, depth, currentPath, onSelectFile }: Fil
export function SkillhubDetailView() {
const { t } = useTranslation();
- const { user, dataOwnerId } = useAuth();
+ const { user } = useAuth();
const identityPolicy = useSkillhubIdentityPolicy(user);
const params = useParams();
const [searchParams] = useSearchParams();
@@ -1071,6 +1071,7 @@ export function SkillhubDetailView() {
// 改成同步从 SWR 缓存取上次结果,缓存命中(常见的重访场景)时直接渲染最终态,
// 完全不闪;缓存 miss(首访)时才退回到 null + loading=true。
const entryInfoKey = entry?.name ? `${entryCatalogScope ?? 'default'}:${entry.name}` : null;
+ const { result: scanResult, setResult: setScanResult } = usePublicationFeedback(entryInfoKey);
const [trackedEntryInfoKey, setTrackedEntryInfoKey] = useState<string | null>(entryInfoKey);
if (entryInfoKey !== trackedEntryInfoKey) {
setTrackedEntryInfoKey(entryInfoKey);
@@ -1243,7 +1244,7 @@ export function SkillhubDetailView() {
}
});
return unsubscribe;
- }, [publishProgressTarget]);
+ }, [publishProgressTarget, setScanResult]);
// dialog 关闭后重新查一次当前 skill 远端状态。进入人工审核后不再自动轮询,
// 用户主动刷新时由常规 info 请求读取最新状态。
@@ -1313,10 +1314,6 @@ export function SkillhubDetailView() {
const isMineDirty = detailActionState?.isMineDirty ?? false;
const showForeignDirtyBanner = detailActionState?.showForeignDirtyBanner ?? false;
- const [scanResult, setScanResult] = useState<ScanResultPayload | null>(null);
- useEffect(() => {
- setScanResult(null);
- }, [entryInfoKey, dataOwnerId]);
const rejectionFeedback = useRejectionFeedback({
entryKey: entryInfoKey,
name: entry?.name ?? null,
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useRejectionFeedback.test.ts b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useRejectionFeedback.test.ts
index 0703cda3bb..2bf4567207 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useRejectionFeedback.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useRejectionFeedback.test.ts
@@ -2,7 +2,7 @@
import { act, cleanup, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
-import { useRejectionFeedback } from '../useRejectionFeedback';
+import { usePublicationFeedback, useRejectionFeedback } from '../useRejectionFeedback';
const target = { entryKey: 'local:helper', name: 'helper', version: '1.1.0', canManage: true };
const response = { success: true, status: 'rejected', gates: [], rejectionReason: 'Remove private notes' };
@@ -15,6 +15,46 @@ beforeEach(() => {
});
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+describe('automatic publication feedback', () => {
+ it('keeps visible results through ordinary same-owner refreshes and supports dismissing them', () => {
+ const { result, rerender } = renderHook(() => usePublicationFeedback(target.entryKey));
+ act(() => result.current.setResult(response));
+ rerender();
+ expect(result.current.result?.rejectionReason).toBe(response.rejectionReason);
+ act(() => result.current.setResult(null));
+ expect(result.current.result).toBeNull();
+ });
+
+ it('hides stored reasons during the first render after a same-id realm generation change', () => {
+ const renderedReasons: Array<string | undefined> = [];
+ const { result, rerender } = renderHook(() => {
+ const feedback = usePublicationFeedback(target.entryKey);
+ renderedReasons.push(feedback.result?.rejectionReason);
+ return feedback;
+ });
+ act(() => result.current.setResult(response));
+ const oldDelivery = result.current.setResult;
+ setDataOwnerGeneration('owner-a', 2);
+ renderedReasons.length = 0;
+ rerender();
+ expect(renderedReasons).toEqual([undefined]);
+ act(() => oldDelivery(response));
+ expect(result.current.result).toBeNull();
+ act(() => result.current.setResult({ ...response, rejectionReason: 'Current realm feedback' }));
+ expect(result.current.result?.rejectionReason).toBe('Current realm feedback');
+ });
+
+ it('does not reuse stored feedback or an old callback for another entry', () => {
+ const { result, rerender } = renderHook(key => usePublicationFeedback(key), { initialProps: target.entryKey });
+ act(() => result.current.setResult(response));
+ const oldDelivery = result.current.setResult;
+ rerender('local:another');
+ expect(result.current.result).toBeNull();
+ act(() => oldDelivery(response));
+ expect(result.current.result).toBeNull();
+ });
+});
+
describe('useRejectionFeedback', () => {
it.each(['local', 'team'])('requests the native rejected version for a %s entry and shows manual feedback', async (catalog) => {
const { result } = renderHook(() => useRejectionFeedback({ ...target, entryKey: `${catalog}:helper` }));
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useRejectionFeedback.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useRejectionFeedback.ts
index 327e2c0362..7dec9d4677 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useRejectionFeedback.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useRejectionFeedback.ts
@@ -9,6 +9,20 @@ interface RejectionFeedbackTarget {
canManage: boolean;
}
+/** Keep already displayed automatic results inside the same owner generation and entry. */
+export function usePublicationFeedback(entryKey: string | null) {
+ const owner = getDataOwnerGeneration();
+ const scope = useMemo(() => ({ entryKey, owner }), [entryKey, owner]);
+ const [feedback, setFeedback] = useState<{ scope: typeof scope; result: ScanResultPayload } | null>(null);
+ const setResult = useCallback((result: ScanResultPayload | null) => {
+ if (!isDataOwnerGenerationCurrent(scope.owner)) return;
+ setFeedback(result ? { scope, result } : null);
+ }, [scope]);
+ const result = feedback?.scope === scope && isDataOwnerGenerationCurrent(scope.owner)
+ ? feedback.result : null;
+ return { result, setResult };
+}
+
/** User-requested feedback is scoped separately from automatic publication results. */
export function useRejectionFeedback({ entryKey, name, version, canManage }: RejectionFeedbackTarget) {
const owner = getDataOwnerGeneration();
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 19b55ae757..77d2d94ab4 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -119,6 +119,11 @@
整次发布在首次异步身份读取前捕获发起账号代次;提交成功后的本地对账保留成功语义和
原发布者身份,但过期发布不再派发进度或启动轮询,也不能停止新账号已启动的轮询。
进度回调与 IPC 标记之间同步复核发起代次,不能给旧发布重新标上当前账号。
+ 认证区域变化也是代次边界,即使 membership ID 相同:显式登录、恢复和运行期刷新
+ 均推进 owner generation,主实例与共享 userData 的被动实例一致;同区域普通刷新不推进。
+ 因此现有请求 scope 与推送 stamp 即可拒绝旧区域反馈,无需修改 wire 字段或持久账号键。
+ 已打开的自动结果也保存 owner snapshot,在新代次的首次渲染中隐藏旧反馈;同 ID
+ 跨区域切换不依赖按 dataOwnerId 重挂路由,普通同代次刷新仍保留当前结果。
旧接收端忽略新增元数据,旧的无标记事件沿用现有兼容读取;首次发布的同版本拒审例外
仅适用于 `rejected`,不能把处理失败 `failed` 或旧扫描失败 `blocked` 套进该例外。
人工拒审原因缺省时始终明确提示缺省,即使已有自动扫描失败项;扫描发现继续独立展示,