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: address review — 批次收尾竞态/release 落账判据/忽略轮次按账号隔离

Chris258bcc3126a8
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 094cda54bb..570cc0a553 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -81,7 +81,7 @@ import {
sortGhostPluginItemsByRecentUse,
type GhostPluginListItem,
} from './lib/ghostPluginViewModel';
-import { isBatchFinished, updateRoundKey } from './lib/updateAllModel';
+import { ignoredRoundStorageKey, isBatchFinished, updateRoundKey } from './lib/updateAllModel';
import {
approveUpdateExpansion,
getUpdateAllBatchState,
@@ -132,12 +132,10 @@ const RECOMMENDED_FILTERS: readonly PluginPresentationFilter[] = [
'custom',
];
-/** 「忽略本轮更新」的持久键(值 = updateRoundKey,版本集合变化后横幅自动回归)。 */
-const IGNORED_UPDATE_ROUND_KEY = 'cindy.pluginUpdates.ignoredRound';
-
-function readIgnoredRound(): string {
+/** 读「忽略本轮更新」的持久值(键按数据归属分桶,见 ignoredRoundStorageKey)。 */
+function readIgnoredRound(storageKey: string): string {
try {
- return window.localStorage.getItem(IGNORED_UPDATE_ROUND_KEY) ?? '';
+ return window.localStorage.getItem(storageKey) ?? '';
} catch {
return '';
}
@@ -171,7 +169,12 @@ export function GhostPluginPage() {
const [query, setQuery] = useState('');
const [marketSnapshot, setMarketSnapshot] = useState<PluginMarketSnapshot | null>(null);
const [openPanelId, setOpenPanelId] = useState<string | null>(null);
- const [ignoredRound, setIgnoredRound] = useState(readIgnoredRound);
+ const ignoredRoundKey = ignoredRoundStorageKey(mode, dataOwnerId);
+ const [ignoredRound, setIgnoredRound] = useState(() => readIgnoredRound(ignoredRoundKey));
+ // 账号 / 本地云模式切换:换桶重读,不把上一个身份的「忽略本轮」带进来。
+ useEffect(() => {
+ setIgnoredRound(readIgnoredRound(ignoredRoundKey));
+ }, [ignoredRoundKey]);
const [originFilter, setOriginFilter] = useState<PluginPresentationFilter>('all');
const [marketDetail, setMarketDetail] = useState<PluginMarketDetail | null>(null);
const [marketBusyId, setMarketBusyId] = useState<string | null>(null);
@@ -345,7 +348,8 @@ export function GhostPluginPage() {
next.delete('panel');
setSearchParams(next, { replace: true });
}, [searchParams, setSearchParams]);
- const marketItems = marketSnapshot?.items ?? [];
+ // 引用稳定:批次对账 effect 以它为依赖,裸 `?? []` 每次渲染都是新数组会空转。
+ const marketItems = useMemo(() => marketSnapshot?.items ?? [], [marketSnapshot]);
const customSourceNames = useMemo(
() => marketSnapshot?.customSourceNames ?? [],
[marketSnapshot?.customSourceNames],
@@ -511,12 +515,12 @@ export function GhostPluginPage() {
const currentRoundKey = useMemo(() => updateRoundKey(marketItems), [marketItems]);
const handleIgnoreRound = useCallback(() => {
try {
- window.localStorage.setItem(IGNORED_UPDATE_ROUND_KEY, currentRoundKey);
+ window.localStorage.setItem(ignoredRoundKey, currentRoundKey);
} catch {
// localStorage 不可用时仅本次会话内生效。
}
setIgnoredRound(currentRoundKey);
- }, [currentRoundKey]);
+ }, [currentRoundKey, ignoredRoundKey]);
// 批次状态住在模块级控制器里(生命周期长于本页:关弹窗离开 /plugins
// 后批次继续跑,回来仍保留待确认项的批准/跳过入口),页面只订阅快照。
@@ -524,11 +528,12 @@ export function GhostPluginPage() {
const updateRows = updateBatch.rows;
const batchRunning = updateBatch.running;
const [updateDialogOpen, setUpdateDialogOpen] = useState(false);
- // 与外部事实对账:已装清单变化(单项更新/文件更新/卸载)收束对应批量行,
- // 账号或模式切换作废整批——旧账号发起的批次绝不落到新账号数据上。
+ // 与外部事实对账:已装清单或市场快照变化(单项更新/文件更新/卸载)收束
+ // 对应批量行——完成判据取市场快照的 installState(目标 release 是否落账),
+ // 不用版本号;账号或模式切换作废整批,旧账号的批次绝不落到新账号数据上。
useEffect(() => {
- reconcileUpdateAllBatch();
- }, [ghosts, mode, dataOwnerId]);
+ reconcileUpdateAllBatch(marketItems);
+ }, [ghosts, marketItems, mode, dataOwnerId]);
// 有未完结批次(含待确认项)时横幅必须在场:它是重开批量弹窗的唯一入口,
// 「忽略本轮」不得顺带藏掉待确认项的批准/跳过路径。
const hasUnfinishedBatch = updateRows !== null && !isBatchFinished(updateRows);
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
index ea8e45ac13..dd05c80ba2 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
@@ -27,6 +27,7 @@ import {
approveUpdateExpansion,
getUpdateAllBatchState,
reconcileUpdateAllBatch,
+ setUpdateAllBatchHooks,
startUpdateAllBatch,
} from '../lib/updateAllController';
@@ -308,9 +309,9 @@ describe('updateAllController', () => {
await waitForSettledBatch();
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
- // 单项/文件更新把插件装到了目标版本 → 待确认行收束为完成,不再重复安装。
+ // 目标 release 已落账(市场快照报 installed)→ 待确认行收束为完成。
installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];
- reconcileUpdateAllBatch();
+ reconcileUpdateAllBatch([marketItem({ installState: 'installed' })]);
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
expect(installMock).not.toHaveBeenCalled();
@@ -321,6 +322,72 @@ describe('updateAllController', () => {
expect(getUpdateAllBatchState().rows).toBeNull();
});
+ it('does not settle as done when a same-version foreign release was installed', async () => {
+ stubDetail({
+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),
+ sourceType: 'server',
+ });
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+
+ // 「从文件更新」装了同版本但**不是目标 release** 的包:版本号看着到位,
+ // 但 main 侧 record.releaseId 对不上,市场仍报 update-available。
+ installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];
+ reconcileUpdateAllBatch([marketItem({ installState: 'update-available' })]);
+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
+
+ await approveUpdateExpansion('plugin-a');
+ // 目标 release 仍未落账 → 必须真正安装,不得凭版本号收成完成。
+ expect(installMock).toHaveBeenCalledWith('plugin-a', {
+ expectedReleaseId: 'release-2',
+ allowPermissionExpansion: true,
+ });
+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
+ });
+
+ it('settles without reinstalling once the target release is actually on record', async () => {
+ stubDetail({
+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),
+ sourceType: 'server',
+ });
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+
+ // 目标 release 已落账:detail 报 installed,批准直接收束不重复下载。
+ installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];
+ detailMock.mockResolvedValue({
+ ...marketItem({ installState: 'installed' }),
+ manifest: manifest({ version: '1.1.0', network: { hosts: ['api.example.com'] } }),
+ readme: null,
+ } as unknown as PluginMarketDetail);
+
+ await approveUpdateExpansion('plugin-a');
+ expect(installMock).not.toHaveBeenCalled();
+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
+ });
+
+ it('holds running until the post-batch refresh settles so no second batch overlaps', async () => {
+ let releaseRefresh: (() => void) | undefined;
+ setUpdateAllBatchHooks({
+ refreshMarket: () =>
+ new Promise<void>((resolve) => {
+ releaseRefresh = resolve;
+ }),
+ });
+ stubDetail({ manifest: manifest({}), sourceType: 'server' });
+
+ startUpdateAllBatch([marketItem({})]);
+ await vi.waitFor(() => expect(releaseRefresh).toBeDefined());
+
+ // 刷新还没回来:running 必须仍为 true,旧 runner 的收尾不能让第二批插进来。
+ expect(getUpdateAllBatchState().running).toBe(true);
+ startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);
+ expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);
+
+ releaseRefresh?.();
+ await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));
+ });
+
it('keeps pending confirmations readable after the page unsubscribes (unmount)', async () => {
stubDetail({
manifest: manifest({ network: { hosts: ['api.example.com'] } }),
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
index 295dd584fd..a213dea302 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
@@ -10,6 +10,7 @@ import type { PluginMarketItem } from '../../../../shared/pluginMarket';
import {
batchSummary,
buildUpdateAllRows,
+ ignoredRoundStorageKey,
isBatchFinished,
isBatchSettled,
updateRoundKey,
@@ -108,3 +109,17 @@ describe('updateRoundKey', () => {
).toBe(updateRoundKey(a));
});
});
+
+describe('ignoredRoundStorageKey', () => {
+ it('isolates the ignore state per data owner and mode', () => {
+ const cloudA = ignoredRoundStorageKey('cloud', 'owner-a');
+ const cloudB = ignoredRoundStorageKey('cloud', 'owner-b');
+ const local = ignoredRoundStorageKey('local', null);
+
+ // 账号 A 忽略本轮,不得静默压掉账号 B 或本地模式的更新横幅。
+ expect(new Set([cloudA, cloudB, local]).size).toBe(3);
+ expect(ignoredRoundStorageKey('cloud', 'owner-a')).toBe(cloudA);
+ // 未登录/本地无 owner 时也有稳定桶,不回落到共享键。
+ expect(local).toContain('anonymous');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
index 2e96ae1873..0d69bfab3a 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
@@ -184,8 +184,12 @@ async function runQueue(): Promise<void> {
}
}
} finally {
- emit({ ...state, running: false });
+ // running 必须**撑到刷新结束**才落下:刷新期间市场快照还是旧的,若此时
+ // 放开 running,页面拿旧快照就能启动第二批,而本 runner 的收尾还会
+ // patch/emit 到新批次上(旧收尾改写新批次)。先刷新、后放行,
+ // startUpdateAllBatch 的 running 闸门才真正拦得住。
await refreshMarketIfMounted();
+ emit({ ...state, running: false });
maybeFinishToast();
}
}
@@ -205,27 +209,42 @@ export async function approveUpdateExpansion(pluginId: string): Promise<void> {
maybeFinishToast();
return;
}
- if (installed.version === row.toVersion) {
- // 等待确认期间已通过单项/文件更新装到目标版本:不再重复下载安装。
- patchRow(pluginId, { status: 'done' });
- maybeFinishToast();
- return;
- }
patchRow(pluginId, { status: 'installing' });
try {
- // 用户审阅的是「当前已装权限面 → 目标版本」的差异。等待期间若被
- // 「从文件更新」等外部路径换掉了已装 manifest,那份 diff 与它换来的
- // allowPermissionExpansion 就不再对应现实——重新取详情、以当前已装
- // manifest 重算,权限没扩张就按普通更新装,扩张面变了则退回待确认重审。
- //
- // 判据是权限指纹而非版本号:ghosts.update() 允许**同版本整体替换
- // manifest**(无版本单调性检查),同版本换入更宽的权限声明时版本比较
- // 完全看不出来,旧的 allowPermissionExpansion 会把未审阅的新权限一并
- // 放行。staleReview 并联进来覆盖 reconcile 已打标的情形。
- if (row.staleReview === true || permissionBaselineKey(installed) !== row.reviewedBaseline) {
- const detail = await window.electronAPI.pluginMarket.detail(pluginId);
+ // 一律重取详情。它同时给出三件事,缺一不可:
+ // 1. installState —— **目标 release 是否真的落账**的权威判据。main 侧
+ // 只有 record.releaseId === 目标 release 且所有权归本插件时才报
+ // 'installed'(plugin-market/service.ts),所以「从文件装了同版本
+ // 但不同 release」不会被误判成完成;版本号比对做不到这点。
+ // 2. 最新 releaseId / manifest —— 并发防护与非 server 源的 reviewed manifest。
+ // 3. 当前 manifest —— 与已装 manifest 重算权限差异。
+ const detail = await window.electronAPI.pluginMarket.detail(pluginId);
+ if (detail.installState === 'installed') {
+ // 目标 release 已由别的路径装上:直接收束,不重复下载安装。
+ patchRow(pluginId, { status: 'done', fromVersion: installed.version });
+ return;
+ }
+ // 用户审阅的是「审阅当时的已装权限面 → 那一刻的目标 release」。三个前提
+ // 任一变了,那份 diff 与它换来的 allowPermissionExpansion 就不再对应现实:
+ // - staleReview:reconcile 已发现基线被换掉;
+ // - 权限指纹变化:ghosts.update() 允许**同版本整体替换 manifest**(无版本
+ // 单调性检查),同版本换入更宽的权限声明时版本比较完全看不出来;
+ // - 目标 release 变化:市场在等待期间发了新版,审的不是这一版。
+ const reviewStillValid =
+ row.staleReview !== true &&
+ permissionBaselineKey(installed) === row.reviewedBaseline &&
+ detail.releaseId === row.releaseId;
+ if (reviewStillValid) {
+ await window.electronAPI.pluginMarket.install(pluginId, {
+ expectedReleaseId: row.releaseId,
+ ...(row.expectedManifest ? { expectedManifest: row.expectedManifest } : {}),
+ allowPermissionExpansion: true,
+ });
+ patchRow(pluginId, { status: 'done' });
+ } else {
const freshDiff = diffGhostPermissionItems(installed, detail.manifest);
if (freshDiff.added.length > 0) {
+ // 相对新事实仍是扩权:回到逐项审阅,绝不静默放行未审过的权限。
patchRow(pluginId, {
status: 'needs-confirm',
fromVersion: installed.version,
@@ -243,13 +262,6 @@ export async function approveUpdateExpansion(pluginId: string): Promise<void> {
...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
});
patchRow(pluginId, { status: 'done', fromVersion: installed.version });
- } else {
- await window.electronAPI.pluginMarket.install(pluginId, {
- expectedReleaseId: row.releaseId,
- ...(row.expectedManifest ? { expectedManifest: row.expectedManifest } : {}),
- allowPermissionExpansion: true,
- });
- patchRow(pluginId, { status: 'done' });
}
} catch (error) {
patchRow(pluginId, { status: 'failed', errorText: i18n.t(pluginMarketErrorKey(error)) });
@@ -272,17 +284,23 @@ export function skipUpdateExpansion(pluginId: string): void {
/**
* 与外部事实对账:账号切换 → 整批作废;待确认行的插件被卸载 → 跳过、
- * 已被单项/文件更新装到目标版本 → 记为完成(不再提供重复安装入口)、
+ * **目标 release 已落账**(市场快照报 'installed')→ 记为完成、
* 权限基线被换掉(含同版本替换 manifest)→ 旧 permissionDiff 已不对应
* 现实,清掉并标记待重审(真正的重算在 approve 时做,那里能取详情)。
- * 页面在已装清单或身份变化时调用。
+ *
+ * 完成判据只认市场快照的 installState,不认版本号:同版本不同 release
+ * (从文件装入)在版本比对下无法区分,会把没装上目标 release 的行误收成完成。
+ * 页面在已装清单、市场快照或身份变化时调用,并把当前市场快照传进来。
*/
-export function reconcileUpdateAllBatch(): void {
+export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[] = []): void {
if (state.rows === null) return;
if (!batchOwnerCurrent()) {
voidStaleBatch();
return;
}
+ const installStateByPluginId = new Map(
+ marketItems.map((item) => [item.pluginId, item.installState]),
+ );
let rows = state.rows;
let changed = false;
for (const row of state.rows) {
@@ -291,7 +309,8 @@ export function reconcileUpdateAllBatch(): void {
if (installed === null) {
rows = updateRow(rows, row.pluginId, { status: 'skipped' });
changed = true;
- } else if (installed.version === row.toVersion) {
+ } else if (installStateByPluginId.get(row.pluginId) === 'installed') {
+ // 目标 release 已落账(main 侧 record.releaseId 对上):无需再装。
rows = updateRow(rows, row.pluginId, { status: 'done' });
changed = true;
} else if (permissionBaselineKey(installed) !== row.reviewedBaseline) {
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
index 39ffb66653..208711bbf5 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
@@ -126,6 +126,18 @@ export function batchSummary(rows: readonly UpdateAllRow[]): {
return { done, skipped, failed };
}
+/**
+ * 「忽略本轮更新」的 localStorage 键:按数据归属分桶(云账号各自一桶、
+ * 本地模式一桶)。插件清单与可更新集合本就随账号/模式不同,共用一个键会让
+ * 账号 A 的「忽略本轮」静默压掉账号 B 的更新横幅。
+ */
+export function ignoredRoundStorageKey(
+ mode: 'signed-out' | 'local' | 'cloud',
+ dataOwnerId: string | null,
+): string {
+ return `cindy.pluginUpdates.ignoredRound.${mode}.${dataOwnerId ?? 'anonymous'}`;
+}
+
/**
* 「忽略本轮」的身份键:同一批可更新集合(id@目标版本)只被忽略一次,
* 任何插件出现更新的版本变化都会产生新键,横幅随之重新出现。