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 — 批准以 detail 后事实判断、收尾共用闸门、官方 id 隐藏本地更新入口

Chrisb63a84212477
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 3cb9d79780..f8798d5742 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -57,7 +57,12 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { Switch } from '@/components/ui/switch';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
-import type { GhostPermissionItem, GhostToolDecl, InstalledGhost } from '../../../shared/ghost';
+import {
+ isOfficialGhostId,
+ type GhostPermissionItem,
+ type GhostToolDecl,
+ type InstalledGhost,
+} from '../../../shared/ghost';
import { type GhostPluginDetail } from './lib/ghostPluginViewModel';
import { GhostPluginIcon } from './GhostPluginIcon';
import { ghostPluginSummary } from './lib/ghostPluginDetailModel';
@@ -162,6 +167,18 @@ export function GhostPluginDetailView({
const hasConfiguration =
detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;
const summary = ghostPluginSummary(detail.description, detail.id);
+ /**
+ * 「从 .cindy 文件更新」是否可用。官方保留前缀(cindy- / filo- / xd-)在**非 dev
+ * 构建**上会被 Main 的用户装入通道以 GHOST_ID_RESERVED 直接拒绝(见
+ * main/cindy-brain/index.ts 的 rejectReservedGhostId),把这个必失败的动作摆在
+ * 菜单里只会让用户选文件、等一下、然后吃一个错误。
+ *
+ * 判据用 `import.meta.env.DEV` 而不是新开一条 IPC 去问 app.isPackaged:打包产物
+ * 必然 DEV=false,覆盖 Main 拒绝的全部场景;唯一偏差是「本地 build 但未打包运行」
+ * 会多隐藏一次入口——方向保守(少一个入口 vs 给用户一个必失败按钮),可接受。
+ * 普通第三方插件不受影响。
+ */
+ const localUpdateAvailable = import.meta.env.DEV || !isOfficialGhostId(detail.id);
useLayoutEffect(() => {
setDescriptionExpanded(false);
@@ -332,13 +349,15 @@ export function GhostPluginDetailView({
sideOffset={8}
className="w-56 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-1.5 text-[var(--text-primary)] shadow-[var(--shadow-menu)]"
>
- <DropdownMenuItem
- onSelect={onUpdateFromFile}
- disabled={updateBusy}
- className="h-10 rounded-lg px-3 text-13 focus:bg-[var(--surface-hover-soft)]"
- >
- {t('settings.ghosts.detail.updateFromFile')}
- </DropdownMenuItem>
+ {localUpdateAvailable ? (
+ <DropdownMenuItem
+ onSelect={onUpdateFromFile}
+ disabled={updateBusy}
+ className="h-10 rounded-lg px-3 text-13 focus:bg-[var(--surface-hover-soft)]"
+ >
+ {t('settings.ghosts.detail.updateFromFile')}
+ </DropdownMenuItem>
+ ) : null}
{onExport ? (
<DropdownMenuItem
onSelect={onExport}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index bcdabfed33..96b51cfe67 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -289,6 +289,82 @@ describe('Ghost plugin detail sections', () => {
expect(onUpdate).not.toHaveBeenCalled();
});
+ it('hides the local .cindy update entry for reserved official ids outside dev builds', async () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ // packaged 构建上 Main 会对 cindy- / filo- / xd- 前缀直接 GHOST_ID_RESERVED,
+ // 把这个必失败动作留在菜单里等于让用户选完文件才吃错误。
+ // vitest 默认 DEV=true,这里显式模拟打包产物(DEV=false)。
+ vi.stubEnv('DEV', false);
+ render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={{ ...detail, id: 'cindy-art' }}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ fireEvent.pointerDown(
+ screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
+ { button: 0, ctrlKey: false },
+ );
+ expect(
+ screen.queryByRole('menuitem', { name: 'settings.ghosts.detail.updateFromFile' }),
+ ).toBeNull();
+ // 卸载等其余菜单项不受影响。
+ expect(screen.getByRole('menuitem', { name: 'settings.ghosts.uninstall' })).toBeTruthy();
+ vi.unstubAllEnvs();
+ });
+
+ it('keeps the local .cindy update entry for ordinary third-party plugins', async () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ // 同样是打包产物,但非保留前缀:Main 不会拒,入口必须留着。
+ vi.stubEnv('DEV', false);
+ render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={detail}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ fireEvent.pointerDown(
+ screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
+ { button: 0, ctrlKey: false },
+ );
+ expect(
+ screen.getByRole('menuitem', { name: 'settings.ghosts.detail.updateFromFile' }),
+ ).toBeTruthy();
+ vi.unstubAllEnvs();
+ });
+
it('renders an export menu item only when onExport is provided', async () => {
vi.stubGlobal(
'ResizeObserver',
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 3d44699e2a..51be9b0d6a 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
@@ -351,6 +351,91 @@ describe('updateAllController', () => {
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
});
+ it('re-reads the installed manifest after detail() instead of trusting the pre-await snapshot', async () => {
+ // 审阅基线:已装带 network,目标包在此之上多出 fs → 用户审的是 fs 这一条。
+ installedGhosts = [
+ { manifest: manifest({ version: '1.0.0', network: { hosts: ['api.example.com'] } }) },
+ ];
+ stubDetail({
+ manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),
+ sourceType: 'server',
+ });
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
+
+ // detail() 往返期间「从文件更新」把已装换成**不带 network** 的包:此刻目标包
+ // 相对当前已装多出 network + fs,而 network 用户从没审过。批准必须以
+ // detail 之后的事实判断,拿 await 前捕获的快照会直接放行。
+ detailMock.mockImplementation(async () => {
+ installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];
+ return {
+ ...marketItem({}),
+ manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),
+ readme: null,
+ } as unknown as PluginMarketDetail;
+ });
+
+ await approveUpdateExpansion('plugin-a');
+ expect(installMock).not.toHaveBeenCalled();
+ const row = getUpdateAllBatchState().rows?.[0];
+ expect(row?.status).toBe('needs-confirm');
+ // 新差异按当前事实重算,把没审过的 network 也摆出来。
+ expect(row?.permissionDiff?.added.length).toBeGreaterThan(1);
+ });
+
+ it('returns a Main-side baseline rejection to re-review instead of a terminal failure', async () => {
+ stubDetail({
+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),
+ sourceType: 'server',
+ });
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+
+ // Main 在安装锁内用当前已装 manifest 复核后否决了这次批准。
+ installMock.mockRejectedValueOnce(
+ Object.assign(new Error('[PRECONDITION_FAILED] baseline changed'), {
+ message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] baseline changed',
+ }),
+ );
+
+ await approveUpdateExpansion('plugin-a');
+ const row = getUpdateAllBatchState().rows?.[0];
+ // 「事实已变,请重新审阅」而不是「更新失败」——终态失败会让用户失去入口。
+ expect(row?.status).toBe('needs-confirm');
+ expect(row?.permissionDiff?.added.length).toBeGreaterThan(0);
+ expect(row?.errorText).toBeUndefined();
+ });
+
+ it('holds running through the post-approval refresh so no second batch can start', async () => {
+ stubDetail({
+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),
+ sourceType: 'server',
+ });
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+ expect(getUpdateAllBatchState().running).toBe(false);
+
+ let releaseRefresh: (() => void) | undefined;
+ setUpdateAllBatchHooks({
+ refreshMarket: () =>
+ new Promise<void>((resolve) => {
+ releaseRefresh = resolve;
+ }),
+ });
+
+ const approving = approveUpdateExpansion('plugin-a');
+ await vi.waitFor(() => expect(releaseRefresh).toBeDefined());
+ // 刷新还没回来:页面手里仍是旧的 update-available 快照,必须挡住第二批。
+ 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 approving;
+ expect(getUpdateAllBatchState().running).toBe(false);
+ });
+
it('never lets a superseded runner write into the batch that replaced it', async () => {
// 账号 A 的 detail() 停在半空。
let releaseDetail: ((value: PluginMarketDetail) => void) | undefined;
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
index 2c2e94e7bf..10cefd93e6 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
@@ -14,6 +14,7 @@
import { i18n } from '@/i18n';
import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
import { readInstalledGhostsSnapshot } from '@/cindy-brain/useInstalledGhosts';
import {
getDataOwnerGeneration,
@@ -250,14 +251,16 @@ export async function approveUpdateExpansion(pluginId: string): Promise<void> {
if (!row || row.status !== 'needs-confirm' || !row.releaseId) return;
// 批准作用于**当前**批次:捕获此刻的代际,await 之后一律以它为准。
const generation = batchGeneration;
- const installed = installedManifestOf(row.ghostId);
- if (installed === null) {
+ if (installedManifestOf(row.ghostId) === null) {
// 待确认期间插件被卸载:同意也不重装,按跳过收束。
patchRow(generation, pluginId, { status: 'skipped' });
maybeFinishToast();
return;
}
+ // 批准也是批次在推进:running 从这里一直撑到收尾刷新结束,期间页面拿的是
+ // 旧的 update-available 快照,不能让它启动第二批把同一 release 再装一遍。
patchRow(generation, pluginId, { status: 'installing' });
+ if (!state.running) emit({ ...state, running: true });
try {
// 一律重取详情。它同时给出三件事,缺一不可:
// 1. installState —— **目标 release 是否真的落账**的权威判据。main 侧
@@ -269,50 +272,71 @@ export async function approveUpdateExpansion(pluginId: string): Promise<void> {
const detail = await window.electronAPI.pluginMarket.detail(pluginId);
// detail 往返期间批次可能已被作废/接管:此后一律不再写状态、不再安装。
if (batchGeneration !== generation) return;
+ // **detail 之后重读已装 manifest**:这段往返里「从文件更新」等路径可能整体
+ // 换掉它,拿 await 之前的快照判断 = 拿过期事实做安全决策。
+ const installed = installedManifestOf(row.ghostId);
+ if (installed === null) {
+ patchRow(generation, pluginId, { status: 'skipped' });
+ return;
+ }
if (detail.installState === 'installed') {
// 目标 release 已由别的路径装上:直接收束,不重复下载安装。
// (return 后仍走 finally 的统一收尾——刷新市场快照 + 完成 toast。)
patchRow(generation, pluginId, { status: 'done', fromVersion: installed.version });
return;
}
+ /** 相对**当前**事实回到逐项审阅(不是终态失败:用户还能重新决定)。 */
+ const holdForReReview = (): void => {
+ patchRow(generation, pluginId, {
+ status: 'needs-confirm',
+ fromVersion: installed.version,
+ toVersion: detail.version,
+ releaseId: detail.releaseId,
+ permissionDiff: diffGhostPermissionItems(installed, detail.manifest),
+ staleReview: false,
+ reviewedBaseline: ghostPermissionBaselineKey(installed),
+ expectedManifest: detail.sourceType !== 'server' ? detail.manifest : undefined,
+ });
+ };
// 用户审阅的是「审阅当时的已装权限面 → 那一刻的目标 release」。三个前提
// 任一变了,那份 diff 与它换来的 allowPermissionExpansion 就不再对应现实:
// - staleReview:reconcile 已发现基线被换掉;
- // - 权限指纹变化:ghosts.update() 允许**同版本整体替换 manifest**(无版本
- // 单调性检查),同版本换入更宽的权限声明时版本比较完全看不出来;
+ // - 权限指纹变化(以刚重读的 installed 为准):ghosts.update() 允许**同版本
+ // 整体替换 manifest**,同版本换入更宽的声明时版本比较完全看不出来;
// - 目标 release 变化:市场在等待期间发了新版,审的不是这一版。
const reviewStillValid =
row.staleReview !== true &&
ghostPermissionBaselineKey(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,
- // 审阅基线随批准回传:Main 在安装锁内用当时的已装 manifest 复核,
- // renderer 这边的检查挡不住 IPC 往返窗口内的替换。
- ...(row.reviewedBaseline !== undefined
- ? { reviewedBaseline: row.reviewedBaseline }
- : {}),
- });
- patchRow(generation, pluginId, { status: 'done' });
- } else {
- const freshDiff = diffGhostPermissionItems(installed, detail.manifest);
- if (freshDiff.added.length > 0) {
- // 相对新事实仍是扩权:回到逐项审阅,绝不静默放行未审过的权限。
- patchRow(generation, pluginId, {
- status: 'needs-confirm',
- fromVersion: installed.version,
- toVersion: detail.version,
- releaseId: detail.releaseId,
- permissionDiff: freshDiff,
- staleReview: false,
- reviewedBaseline: ghostPermissionBaselineKey(installed),
- expectedManifest: detail.sourceType !== 'server' ? detail.manifest : undefined,
+ try {
+ await window.electronAPI.pluginMarket.install(pluginId, {
+ expectedReleaseId: row.releaseId,
+ ...(row.expectedManifest ? { expectedManifest: row.expectedManifest } : {}),
+ allowPermissionExpansion: true,
+ // 审阅基线随批准回传:Main 在安装锁内用当时的已装 manifest 复核,
+ // renderer 这边的检查挡不住 IPC 往返窗口内的替换。
+ ...(row.reviewedBaseline !== undefined
+ ? { reviewedBaseline: row.reviewedBaseline }
+ : {}),
});
- return;
+ } catch (error) {
+ if (batchGeneration !== generation) return;
+ // Main 的基线复核在安装锁内否决了这次批准(前置条件失败)——那是
+ // 「事实已变,请重新审阅」而不是「更新失败」。终态失败会让用户彻底
+ // 失去这一项的入口,所以回到 needs-confirm 并展示新的差异/release。
+ if (extractIpcError(error)?.code === 'PRECONDITION_FAILED') {
+ holdForReReview();
+ return;
+ }
+ throw error;
}
+ patchRow(generation, pluginId, { status: 'done' });
+ } else if (diffGhostPermissionItems(installed, detail.manifest).added.length > 0) {
+ // 相对新事实仍是扩权:回到逐项审阅,绝不静默放行未审过的权限。
+ holdForReReview();
+ return;
+ } else {
await window.electronAPI.pluginMarket.install(pluginId, {
expectedReleaseId: detail.releaseId,
...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
@@ -325,12 +349,10 @@ export async function approveUpdateExpansion(pluginId: string): Promise<void> {
errorText: i18n.t(pluginMarketErrorKey(error)),
});
} finally {
- // 统一收尾:已落账 / 重审 / 失败 / 正常完成四条返回路径都刷新市场快照并
- // 补完成提示;代际失效时整体跳过,不碰当前批次。
- if (batchGeneration === generation) {
- await refreshMarketIfMounted();
- if (batchGeneration === generation) maybeFinishToast();
- }
+ // 与 queue runner 共用同一套带代际校验的收尾:刷新期间 running 不落下
+ // (页面拿旧快照启动第二批会重复安装),刷新完成后才清 running + 补 toast;
+ // 代际失效时整体跳过,不碰当前批次。
+ await settleBatchTail(generation);
}
}