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。

feat(desktop): 装入确认框区分 Agent 发起与用户手动

fmfsaisai2f350c448d77
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts
new file mode 100644
index 0000000000..a244e39581
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts
@@ -0,0 +1,93 @@
+/**
+ * openFileInstall.test.ts —— 待装转交缓冲的不变量。
+ *
+ * 钉住的核心不变量:**装入来源(origin)与待装路径同存同取。**
+ *
+ * 为什么值得一条专门的测试:来源决定确认框是否展示「这次是 Agent 发起的」红色
+ * 横幅并加重确认,是一条安全事实。第一版实现把它只挂在 `ghosts:install-requested`
+ * 广播 payload 上,而广播是易失通道——macOS 关窗后应用不退出,scheduler 拉起的
+ * agent 仍能调 `ghost_forge_pack`,此刻 `getAllWindows()` 为空、广播无人接收,
+ * 但路径仍留在缓冲里等 renderer 挂载后自取。那一取就把 origin 丢了,
+ * Agent 发起的装入被显示成手动。**丢失方向恰好是最危险的那个**,所以这里用
+ * 「零窗口」这个具体场景把两者的绑定钉死。
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const windows: { isDestroyed: () => boolean; webContents: { send: (ch: string) => void } }[] = [];
+const sent: string[] = [];
+
+vi.mock('electron', () => ({
+ BrowserWindow: { getAllWindows: () => windows },
+}));
+vi.mock('../logger.js', () => ({
+ createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
+}));
+
+const { handleIncomingCindyFile, takePendingCindyInstall } = await import('../openFileInstall');
+const { MANUAL_GHOST_INSTALL_ORIGIN } = await import('../../../shared/ghostInstallOrigin');
+
+const AGENT_ORIGIN = {
+ kind: 'agent-forge' as const,
+ sessionTitle: '处理外部文档',
+ sourceRelPath: 'plugins/evil',
+};
+
+/** 用本文件自身当"存在且可读的普通文件",避免造临时目录。 */
+const REAL_FILE = new URL(import.meta.url).pathname;
+
+beforeEach(() => {
+ windows.length = 0;
+ sent.length = 0;
+ takePendingCindyInstall(); // 清干净上一条用例可能留下的缓冲
+});
+
+function addWindow(): void {
+ windows.push({
+ isDestroyed: () => false,
+ webContents: { send: (ch: string) => sent.push(ch) },
+ });
+}
+
+describe('openFileInstall · origin 与路径同存同取', () => {
+ it('零窗口(macOS 关窗后 agent 转交):广播没人收,但 origin 仍能被取到', async () => {
+ await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);
+ expect(sent).toEqual([]); // 没有窗口 → 广播确实丢了
+
+ const pending = takePendingCindyInstall();
+ expect(pending?.filePath).toBe(REAL_FILE);
+ expect(pending?.origin).toEqual(AGENT_ORIGIN); // ← 丢广播不等于丢来源
+ });
+
+ it('有窗口:广播只是通知,不携带任何事实', async () => {
+ addWindow();
+ await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);
+ // send 只带 channel,没有第二个参数——事实的唯一来源是缓冲。
+ expect(sent).toEqual(['ghosts:install-requested']);
+ expect(takePendingCindyInstall()?.origin).toEqual(AGENT_ORIGIN);
+ });
+
+ it('手动入口(双击 / open-file)不传 origin 时缺省 manual', async () => {
+ await handleIncomingCindyFile(REAL_FILE, 'open-file');
+ expect(takePendingCindyInstall()?.origin).toEqual(MANUAL_GHOST_INSTALL_ORIGIN);
+ });
+
+ it('取即清空:同一条待装项不会被消费两次', async () => {
+ await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);
+ expect(takePendingCindyInstall()).not.toBeNull();
+ expect(takePendingCindyInstall()).toBeNull();
+ });
+
+ it('只保留最新一条,且换条时来源随之更新(不会残留上一条的 agent 来源)', async () => {
+ await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);
+ await handleIncomingCindyFile(REAL_FILE, 'open-file');
+ expect(takePendingCindyInstall()?.origin).toEqual(MANUAL_GHOST_INSTALL_ORIGIN);
+ });
+
+ it('路径不存在:不写缓冲、不广播(容错口径与 open-folder 一致)', async () => {
+ addWindow();
+ await handleIncomingCindyFile('/definitely/not/here.cindy', 'open-file');
+ expect(sent).toEqual([]);
+ expect(takePendingCindyInstall()).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 603e371377..408be208d7 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -116,6 +116,7 @@ import {
type GhostRepoRootCacheEntry,
} from './repoRoot.js';
import { takePendingCindyInstall } from './openFileInstall.js';
+import { MANUAL_GHOST_INSTALL_ORIGIN } from '../../shared/ghostInstallOrigin.js';
import { GhostRuntime } from './runtime/GhostRuntime.js';
import {
electronSandboxAdapter,
@@ -7059,7 +7060,13 @@ export function registerGhostIpc(): void {
// 取走(取即清空),随后走与按钮/拖入完全相同的确认装入编排。
ipcMain.handle('ghosts:take-pending-install', (event) => {
assertTrustedAppRendererEvent(event);
- return { filePath: takePendingCindyInstall() };
+ // 路径与来源一起返回:来源是确认框加重展示的依据,不能走比路径更易失的
+ // 通道(理由见 openFileInstall.ts 头注释)。
+ const pending = takePendingCindyInstall();
+ return {
+ filePath: pending?.filePath ?? null,
+ origin: pending?.origin ?? MANUAL_GHOST_INSTALL_ORIGIN,
+ };
});
// 本地包第三条恢复路径第一步:从**已装目录**读出确认卡事实,零副作用。
diff --git a/apps/desktop/src/main/cindy-brain/openFileInstall.ts b/apps/desktop/src/main/cindy-brain/openFileInstall.ts
index 2cbe4c61fb..fd3a96e554 100644
--- a/apps/desktop/src/main/cindy-brain/openFileInstall.ts
+++ b/apps/desktop/src/main/cindy-brain/openFileInstall.ts
@@ -3,6 +3,10 @@ import fs from 'node:fs';
import { BrowserWindow } from 'electron';
import { createLogger } from '../logger.js';
+import {
+ MANUAL_GHOST_INSTALL_ORIGIN,
+ type GhostInstallOrigin,
+} from '../../shared/ghostInstallOrigin.js';
/**
* 双击 .cindy 文件的转交通道。
@@ -13,38 +17,69 @@ import { createLogger } from '../logger.js';
* 一个。
*
* 转交模型(对齐 deepLink 的 pending buffer 成熟套路):
- * - 收到路径 → 存入 pending(仅保留最新一条;双击语义上就是"装这一个")
- * → 广播信号 ghosts:install-requested;
+ * - 收到路径与来源 → 一起存入 pending(仅保留最新一条;双击语义上就是"装这一个")
+ * → 广播信号 ghosts:install-requested(**纯通知,不带事实**);
* - renderer(GlobalDropImportListener)在信号或自身挂载时调
* ghosts:take-pending-install 原子取走并消费 —— 冷启动双击时
* renderer 尚未挂载,pending 缓冲天然覆盖,不丢意图、不重复消费。
*
+ * **来源标记(origin)**:装入确认框要区分"用户亲手发起"和"Agent 单方面发起"
+ * (`ghost_forge_pack` 转交)。来源是主机侧结论,绝不能走 agent 可控通道 ——
+ * 它由本模块填写,agent 只能触发转交、碰不到这个值。
+ *
+ * **origin 必须与路径同存同取,不能只挂在广播 payload 上。** 广播是易失通道:
+ * macOS 关窗后应用不退出,scheduler 拉起的 agent 照样能调 `ghost_forge_pack`,
+ * 此时没有任何窗口接收广播,而路径仍在缓冲里等着 renderer 挂载后自取 ——
+ * 若 origin 只在 payload 里,这一取就把它丢了,Agent 发起的装入会被显示成手动,
+ * 来源横幅与手输 id 全部失效。**丢失方向恰好是最危险的那个**,所以两者绑在一起。
+ *
* 入口(与 deepLink / open-folder 的结构对齐):
* - Windows 冷启动:文件路径在 process.argv(bootstrap 扫描);
* - Windows 已运行:单例锁转 second-instance,路径在其 argv;
- * - macOS:Finder 经 CFBundleDocumentTypes 关联走 open-file 事件。
+ * - macOS:Finder 经 CFBundleDocumentTypes 关联走 open-file 事件;
+ * - Agent:`ghost_forge_pack` 打包成功后经本通道转交(source='ghost-forge',
+ * 带 agent-forge origin)。
*/
const log = createLogger('ghosts:open-file');
-let pendingCindyInstall: string | null = null;
+let pendingCindyInstall: { filePath: string; origin: GhostInstallOrigin } | null = null;
-/** renderer 原子取走待装路径(取即清空;无则 null)。IPC handler 消费。 */
-export function takePendingCindyInstall(): string | null {
- const path = pendingCindyInstall;
+/**
+ * renderer 原子取走待装路径与来源(取即清空;无则 null)。IPC handler 消费。
+ *
+ * 来源与路径**必须一起存、一起取**:两者存在不同强度的通道里就会丢。
+ * 反例(已修):把 origin 只挂在 `ghosts:install-requested` 广播 payload 上时,
+ * macOS 关窗后应用不退出,scheduler 拉起的 agent 照样能调 `ghost_forge_pack`——
+ * 此刻 `getAllWindows()` 为空,广播无人接收,路径仍留在缓冲里;用户之后开窗,
+ * renderer 挂载自取,origin 已经丢了 → Agent 发起的装入被显示成手动,
+ * 红色来源横幅与手输 id 全部失效。**恰好是最危险的丢失方向。**
+ */
+export function takePendingCindyInstall(): { filePath: string; origin: GhostInstallOrigin } | null {
+ const pending = pendingCindyInstall;
pendingCindyInstall = null;
- return path;
+ return pending;
}
-export async function handleIncomingCindyFile(filePath: string, source: string): Promise<void> {
- log.info('incoming .cindy file', { filePath, source });
+export async function handleIncomingCindyFile(
+ filePath: string,
+ source: string,
+ /**
+ * 主机侧填写的来源标记;缺省 = 手动入口(双击 / open-file)。只有 forge 转交
+ * 路径会传 agent-forge origin。绝不接受来自 agent 或 renderer 的值。
+ */
+ origin: GhostInstallOrigin = MANUAL_GHOST_INSTALL_ORIGIN,
+): Promise<void> {
+ log.info('incoming .cindy file', { filePath, source, originKind: origin.kind });
try {
if (!(await fs.promises.stat(filePath)).isFile()) return;
} catch {
return; // 路径不存在 / 不可读 → 静默忽略(与 open-folder 的容错口径一致)
}
- pendingCindyInstall = filePath;
- // 已运行的窗口立即收到信号;冷启动时没有窗口,renderer 挂载后主动来取。
+ pendingCindyInstall = { filePath, origin };
+ // 广播只是"来取货"的通知,不携带任何事实:唯一真相是上面那个缓冲,
+ // renderer 一律经 ghosts:take-pending-install 取路径与来源。没有窗口时
+ // (冷启动 / macOS 关窗后应用仍在跑)广播丢掉也不影响正确性。
BrowserWindow.getAllWindows().forEach((window) => {
if (window.isDestroyed()) return;
window.webContents.send('ghosts:install-requested');
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index bdb294e0f3..43be0247ac 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -698,6 +698,30 @@ export async function getSessionFsSnapshot(id: string): Promise<{
}
}
+/**
+ * 按 session id 查任务标题(装入确认框的 Agent 来源横幅用:告诉用户"这次装入是
+ * 哪个任务里的 Agent 发起的")。纯展示用途,失败 swallow 返 null —— 拿不到标题
+ * 只是横幅少一行,不阻断装入编排。
+ */
+export async function getSessionTitle(id: string): Promise<string | null> {
+ try {
+ const db = getDbClient().drizzle;
+ const [row] = await db
+ .select({ title: sessions.title })
+ .from(sessions)
+ .where(eq(sessions.id, id))
+ .limit(1);
+ const title = row?.title?.trim();
+ return title ? title : null;
+ } catch (err) {
+ log.warn('getSessionTitle failed', {
+ sessionId: id,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
+}
+
/**
* 内部 API:标记用户显式发送时间。
*
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index fb89b1ce6a..0cc4acb448 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -54,7 +54,7 @@ import {
} from '../cindy-brain/ghostGrantConfirmBridge.js';
import { classifyLocalAttachmentPath } from '../cindy-brain/ghostLocalPathGrant.js';
import { toolNotFoundMessage } from '../cindy-brain/pipeDispatcher.js';
-import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
+import { getSessionFsSnapshot, getSessionTitle } from '../localDb/ipc/sessions.js';
import {
deriveGhostSessionContext,
type GhostSessionContextInjected,
@@ -86,6 +86,7 @@ import {
} from '../plugin-publisher/host.js';
import { workdirWriteVerdict } from '../cindy-brain/fsSlot.js';
import { handleIncomingCindyFile } from '../cindy-brain/openFileInstall.js';
+import type { GhostInstallOrigin } from '../../shared/ghostInstallOrigin.js';
import * as blobStore from '../cindy-media/blobStore.js';
import { commitMessageMediaRefs } from '../cindy-media/chatAttachments.js';
import { callCindyMedia } from '../cindy-media/invocationService.js';
@@ -1756,9 +1757,29 @@ export function getCindyGhostsMcpDeps(
}
}
if (!packed.ok) return packed;
+ // Agent 来源标记:这次装入是 Agent 调 ghost_forge_pack 发起的,不是用户
+ // 亲手点的。标题与源码相对路径都由主机侧算(agent 改不了),供确认框如实
+ // 展示"哪个任务里的 Agent 发起 + 打包了工作目录里的哪个源码目录"。
+ // 相对路径:forge 已强制源码在会话工作目录内,故 path.relative 可靠;
+ // 若源码目录恰是工作目录本身(relative='')回落目录名,不给空串。
+ const forgeSessionId = resolveSessionContext()?.sessionId;
+ const sessionTitle = forgeSessionId
+ ? (await getSessionTitle(forgeSessionId)) ?? undefined
+ : undefined;
+ const relFromWorkdir = path.relative(gate.workingDir, dir);
+ const sourceRelPath =
+ relFromWorkdir && !relFromWorkdir.startsWith('..')
+ ? relFromWorkdir
+ : path.basename(dir);
+ const origin: GhostInstallOrigin = {
+ kind: 'agent-forge',
+ ...(sessionTitle ? { sessionTitle } : {}),
+ ...(sourceRelPath ? { sourceRelPath } : {}),
+ };
// 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则
- // 自动转"更新 vX → vY"),用户点头才真装。lease 持到转交完成。
- await handleIncomingCindyFile(packed.cindyPath, 'ghost-forge');
+ // 自动转"更新 vX → vY"),用户点头才真装。lease 持到转交完成。带上 agent
+ // 来源,确认框据此展示来源横幅 + 分级加重(高危需手输 id 确认)。
+ await handleIncomingCindyFile(packed.cindyPath, 'ghost-forge', origin);
log.info('ghost forge packed', { dir, cindyPath: packed.cindyPath, id: packed.manifest.id });
return {
ok: true,
@@ -1766,7 +1787,10 @@ export function getCindyGhostsMcpDeps(
id: packed.manifest.id,
name: packed.manifest.name,
version: packed.manifest.version,
- note: `${iconNote}已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。`,
+ // 不在这里说明确认框的加重形式(如"需手输 id"):本 note 会回到 agent,
+ // 被注入的 agent 读到就能照着编引导话术,帮用户"过掉"那一步。
+ // 告知"必须在应用内确认才会安装"已足够让作者知道下一步做什么。
+ note: `${iconNote}已打包并弹出装入/更新确认框,请提示用户:只有在应用内确认后插件才会真正安装。`,
};
});
},
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index afa37ee8f6..a05381dd12 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -14,6 +14,7 @@ import {
SIDEBAR_PROJECT_ORDER_CHANGED_CHANNEL,
type SyncedProjectOrderSnapshot,
} from '../shared/projectOrderSettings';
+import type { GhostInstallOrigin } from '../shared/ghostInstallOrigin';
import type { SessionDragPreviewPalette } from '../shared/sessionDragPreview';
import {
AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL,
@@ -1226,8 +1227,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
disabled: boolean,
): Promise<{ disabled: string[] }> =>
ipcRenderer.invoke('ghosts:workdir-prefs:set', workdir, id, disabled),
- takePendingInstall: (): Promise<{ filePath: string | null }> =>
- ipcRenderer.invoke('ghosts:take-pending-install'),
+ takePendingInstall: (): Promise<{
+ filePath: string | null;
+ origin: GhostInstallOrigin;
+ }> => ipcRenderer.invoke('ghosts:take-pending-install'),
onChanged: fanOutGhostsChanged,
onSetupNavigate: (
callback: (
@@ -1326,9 +1329,17 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('ghosts:library-overview', id),
libraryPickLocation: (
id: string,
- ): Promise<{ ok: boolean; cancelled?: boolean; candidate?: string; warnings?: string[]; message?: string }> =>
- ipcRenderer.invoke('ghosts:library-pick-location', id),
- libraryBind: (id: string, candidate: string): Promise<{ ok: boolean; message?: string; warnings?: string[] }> =>
+ ): Promise<{
+ ok: boolean;
+ cancelled?: boolean;
+ candidate?: string;
+ warnings?: string[];
+ message?: string;
+ }> => ipcRenderer.invoke('ghosts:library-pick-location', id),
+ libraryBind: (
+ id: string,
+ candidate: string,
+ ): Promise<{ ok: boolean; message?: string; warnings?: string[] }> =>
ipcRenderer.invoke('ghosts:library-bind', id, candidate),
libraryRelocate: (id: string, candidate: string): Promise<{ ok: boolean; message?: string }> =>
ipcRenderer.invoke('ghosts:library-relocate', id, candidate),
@@ -3489,9 +3500,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
// connect 只对 providers 页有意义;主进程已做 id 白名单,这里按纵深防御
// 原样复用同一规则。字段存在但不合法时丢弃整个 payload,不降级成半执行。
if (
- p.connect !== undefined
- && (p.tab !== 'providers' || !isDeepLinkProviderConnectId(p.connect))
- ) return;
+ p.connect !== undefined &&
+ (p.tab !== 'providers' || !isDeepLinkProviderConnectId(p.connect))
+ )
+ return;
callback({
type: 'settings',
tab: p.tab,
@@ -4762,11 +4774,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp;
projectOrder: 'activity' | 'custom';
}): Promise<SyncedProjectOrderSnapshot> =>
- parseProjectOrderSnapshot(await ipcRenderer.invoke(SIDEBAR_APPLY_PROJECT_ORDER_CHANNEL, {
- ...request.ownerStamp,
- manualProjectOrder: request.manualProjectOrder,
- projectOrder: request.projectOrder,
- })),
+ parseProjectOrderSnapshot(
+ await ipcRenderer.invoke(SIDEBAR_APPLY_PROJECT_ORDER_CHANNEL, {
+ ...request.ownerStamp,
+ manualProjectOrder: request.manualProjectOrder,
+ projectOrder: request.projectOrder,
+ }),
+ ),
onProjectOrderChanged: (
cb: (
snapshot: SyncedProjectOrderSnapshot,
@@ -4775,7 +4789,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
): (() => void) =>
fanOutSidebarProjectOrderChanged((payload, ownerStamp) => {
if (!isDataOwnerPushStamp(ownerStamp)) return;
- cb(parseProjectOrderSnapshot({ ...parseProjectOrderSnapshot(payload), ownerStamp }), ownerStamp);
+ cb(
+ parseProjectOrderSnapshot({ ...parseProjectOrderSnapshot(payload), ownerStamp }),
+ ownerStamp,
+ );
}),
},
@@ -5335,15 +5352,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:local-model:abort', reason, name),
localModelEnsure: (): Promise<{ ok: true; created: boolean }> =>
ipcRenderer.invoke('maker:local-model:ensure'),
- localModelSetInPicker: (name: string, enabled: boolean): Promise<{ ok: true; created: boolean }> =>
+ localModelSetInPicker: (
+ name: string,
+ enabled: boolean,
+ ): Promise<{ ok: true; created: boolean }> =>
ipcRenderer.invoke('maker:local-model:set-in-picker', name, enabled),
localModelDelete: (name: string): Promise<{ ok: true; created: boolean }> =>
ipcRenderer.invoke('maker:local-model:delete', name),
localModelDiscardPaused: (name: string): Promise<{ ok: true }> =>
ipcRenderer.invoke('maker:local-model:discard-paused', name),
- localModelInstall: (
- input: { consent: true },
- ): Promise<{
+ localModelInstall: (input: {
+ consent: true;
+ }): Promise<{
ok: true;
status?: import('../shared/localModelRuntime').LocalRuntimeStatus;
created?: boolean;
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
index dbbfdb94d3..6cd6ba6c9a 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
@@ -83,7 +83,13 @@ function itemIcon(item: GhostPermissionItem): LucideIcon {
return KIND_ICON[item.kind];
}
-function PermRow({ item, badge }: { item: GhostPermissionItem; badge?: 'added' | 'removed' | 'updated' }) {
+function PermRow({
+ item,
+ badge,
+}: {
+ item: GhostPermissionItem;
+ badge?: 'added' | 'removed' | 'updated';
+}) {
const { t } = useTranslation();
const Icon = itemIcon(item);
// 主机固定说明(detailKey)与作者自由文本(detail)可以并存(oauth 凭证:
@@ -289,6 +295,87 @@ export function GhostOauthClientChangedAlert({ className }: { className?: string
);
}
+/**
+ * Agent 发起装入时展示的来源信息(2026-08)。
+ *
+ * 目的:让用户在"刚让 Agent 干了一堆事、没有'我没让它装插件'清晰记忆"的状态下,
+ * 仍能一眼判断"这次不是我点的"。因此第一句直接点破发起者,再给出任务标题与源码
+ * 相对路径这两个**主机可核实**的事实作为判断依据(不是"可能有风险"的空话)。
+ *
+ * 用 warning 族语义 token(非 destructive 红):平常的手动安装框保持中性、不显示
+ * 本横幅,危险的那次才多出这一块——对比度本身就是信号,不靠"更醒目的红"训练
+ * 用户无脑点(那正是 https 证书警告的失败模式)。
+ *
+ * 高危档才追加 hazard 点破行;中危档只展示来源事实。是否 firstInstall / 展示哪些
+ * hazard 由调用方(installFlow)按风险分档决定,本组件只如实渲染。
+ */
+export interface GhostAgentOriginInfo {
+ sessionTitle?: string;
+ sourceRelPath?: string;
+ /** 该 id 此前从未安装过(仅新装分支为 true;更新分支恒 false)。 */
+ firstInstall: boolean;
+ /** 高危点破(仅高危档传入 true;中危/低危全 false → 不出 callout)。 */
+ hazards: { skill: boolean; node: boolean; credential: boolean };
+ /** 凭证外发对象域名(credential 点破用;credential 为 true 时非空)。 */
+ credentialHosts: string[];
+}
+
+export function GhostAgentOriginBanner({ info }: { info: GhostAgentOriginInfo }) {
+ const { t } = useTranslation();
+ const title = info.sessionTitle?.trim();
+ const path = info.sourceRelPath?.trim();
+ const contextKey =
+ title && path ? 'context' : title ? 'contextNoPath' : path ? 'contextNoTitle' : 'contextBare';
+ return (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-xl bg-[var(--warning-bg-soft)] px-3 py-2.5"
+ >
+ <ShieldAlert
+ size={16}
+ className="mt-0.5 shrink-0 text-[var(--warning-fg)]"
+ aria-hidden="true"
+ />
+ <div className="min-w-0 flex-1 space-y-1">
+ <p className="text-13 font-medium leading-[1.5] text-[var(--confirm-desc)]">
+ {t('settings.ghosts.installConfirm.agentBanner.title')}
+ </p>
+ <p className="break-words text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {t(`settings.ghosts.installConfirm.agentBanner.${contextKey}`, {
+ title: title ?? '',
+ path: path ?? '',
+ })}
+ </p>
+ <p className="text-12 leading-[1.5] text-[var(--text-secondary)]">
+ {t('settings.ghosts.installConfirm.agentBanner.advice')}
+ </p>
+ {info.firstInstall && (
+ <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.ghosts.installConfirm.agentBanner.firstInstall')}
+ </p>
+ )}
+ {info.hazards.skill && (
+ <p className="text-12 font-medium leading-[1.5] text-[var(--warning-fg)]">
+ {t('settings.ghosts.installConfirm.agentBanner.hazardSkill')}
+ </p>
+ )}
+ {info.hazards.node && (
+ <p className="text-12 font-medium leading-[1.5] text-[var(--warning-fg)]">
+ {t('settings.ghosts.installConfirm.agentBanner.hazardNode')}
+ </p>
+ )}
+ {info.hazards.credential && (
+ <p className="break-words text-12 font-medium leading-[1.5] text-[var(--warning-fg)]">
+ {t('settings.ghosts.installConfirm.agentBanner.hazardCredential', {
+ hosts: info.credentialHosts.join('、'),
+ })}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
export function GhostManualSummary({ count }: { count: number }) {
const { t } = useTranslation();
if (count <= 0) return null;
@@ -316,6 +403,8 @@ export function GhostInstallReview({
items,
manualCount = 0,
extra,
+ agentOrigin,
+ enableNotice,
}: {
description?: string;
meta: string;
@@ -324,6 +413,13 @@ export function GhostInstallReview({
manualCount?: number;
/** 追加内容(如 library 槽的存储位置行),渲染在权限清单下方。 */
extra?: ReactNode;
+ /** Agent 发起装入时的来源信息;手动入口不传 → 不展示来源横幅。 */
+ agentOrigin?: GhostAgentOriginInfo;
+ /**
+ * 启用结果说明(重新确认权限路径用):替代已删除的"立即开启"勾选框,如实
+ * 陈述确认后是保持沉睡还是保持启用,不再让用户在没有判断依据的勾选框上选。
+ */
+ enableNotice?: string;
}) {
const { t } = useTranslation();
const [descriptionExpanded, setDescriptionExpanded] = useState(false);
@@ -333,6 +429,11 @@ export function GhostInstallReview({
return (
<div>
+ {agentOrigin && (
+ <div className="mb-3">
+ <GhostAgentOriginBanner info={agentOrigin} />
+ </div>
+ )}
{description && (
<div>
<p
@@ -368,6 +469,9 @@ export function GhostInstallReview({
<GhostPermissionList items={items} />
</div>
{extra ? <div className="mt-3">{extra}</div> : null}
+ {enableNotice && (
+ <p className="mt-3 text-12 leading-[1.5] text-[var(--text-tertiary)]">{enableNotice}</p>
+ )}
</div>
);
}
@@ -455,23 +559,27 @@ export function GhostUpdateReview({
trust,
diff,
manualCount = 0,
+ agentOrigin,
}: {
trust?: GhostTrustInfo;
diff: GhostPermissionDiff;
manualCount?: number;
+ /** Agent 发起的更新时的来源信息;手动更新不传 → 不展示来源横幅。 */
+ agentOrigin?: GhostAgentOriginInfo;
}) {
return (
<div>
+ {agentOrigin && (
+ <div className="mb-3">
+ <GhostAgentOriginBanner info={agentOrigin} />
+ </div>
+ )}
{trust && <GhostTrustSummary trust={trust} />}
{diff.builtinOauthClientChanged ? (
<GhostOauthClientChangedAlert className={trust ? 'mt-3' : undefined} />
) : null}
<GhostManualSummary count={manualCount} />
- <div
- className={cn(
- (trust || diff.builtinOauthClientChanged || manualCount > 0) && 'mt-3',
- )}
- >
+ <div className={cn((trust || diff.builtinOauthClientChanged || manualCount > 0) && 'mt-3')}>
<GhostPermissionDiffView diff={diff} />
</div>
</div>
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostInstallRisk.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostInstallRisk.test.ts
new file mode 100644
index 0000000000..03d3a1f08c
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostInstallRisk.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import { assessGhostInstallRisk } from '../ghostInstallRisk';
+import type { GhostPermissionItem } from '../../../shared/ghost';
+
+/** 只给分档器关心的 key/labelArgs;其余字段占位,分档不看它们。 */
+function item(key: string, labelArgs?: Record<string, string>): GhostPermissionItem {
+ return { key, kind: 'tool', labelKey: 'tool', ...(labelArgs ? { labelArgs } : {}) };
+}
+
+describe('assessGhostInstallRisk · 分档', () => {
+ it('skill / node / 凭证 / agent 后台 / agent 派活 都是高危', () => {
+ for (const key of [
+ 'skill:my-skill',
+ 'node:execute',
+ 'node:secret:k:main.js:call',
+ 'network:secret:token',
+ 'agent:background',
+ 'agent:errand',
+ ]) {
+ expect(assessGhostInstallRisk([item(key)]).tier).toBe('high');
+ }
+ });
+
+ it('oauth 凭证(network:secret: 前缀)判高危', () => {
+ // ghostPermissionItems 里 oauth 凭证 key = `network:secret:<key>`。
+ expect(assessGhostInstallRisk([item('network:secret:jira')]).tier).toBe('high');
+ });
+
+ it('fs / 出网域名 / 自动化 是中危', () => {
+ for (const key of ['fs', 'network:host:api.example.com', 'agent:schedule']) {
+ expect(assessGhostInstallRisk([item(key)]).tier).toBe('mid');
+ }
+ });
+
+ it('纯沙箱工具 / 卡片 / 面板 / 聊天指令是低危', () => {
+ const low = [item('tool:hello'), item('card'), item('panel'), item('command:foo')];
+ expect(assessGhostInstallRisk(low).tier).toBe('low');
+ });
+
+ it('高危优先于中危:同时有 fs 与 node 时整体判高危', () => {
+ expect(assessGhostInstallRisk([item('fs'), item('node:execute')]).tier).toBe('high');
+ });
+
+ it('中危优先于低危:同时有 tool 与 fs 时整体判中危', () => {
+ expect(assessGhostInstallRisk([item('tool:x'), item('fs')]).tier).toBe('mid');
+ });
+
+ it('命中标记与出网域名如实汇总', () => {
+ const assessment = assessGhostInstallRisk([
+ item('skill:s'),
+ item('network:secret:tok'),
+ item('network:host:a.example.com', { host: 'a.example.com' }),
+ item('network:host:b.example.com', { host: 'b.example.com' }),
+ ]);
+ expect(assessment.tier).toBe('high');
+ expect(assessment.hazards.skill).toBe(true);
+ expect(assessment.hazards.secret).toBe(true);
+ expect(assessment.hazards.node).toBe(false);
+ expect(assessment.networkHosts).toEqual(['a.example.com', 'b.example.com']);
+ });
+
+ it('空清单为低危,无命中,无域名', () => {
+ const assessment = assessGhostInstallRisk([]);
+ expect(assessment.tier).toBe('low');
+ expect(assessment.networkHosts).toEqual([]);
+ expect(Object.values(assessment.hazards).every((v) => v === false)).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
index 74320e5eb5..21f6d5aa4a 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
@@ -60,10 +60,16 @@ function deps(confirm: (options: unknown) => Promise<boolean>) {
return {
t: ((key: string) => key) as never,
confirm,
- confirmWithCheckbox: vi.fn(async () => ({ ok: true, checked: false })),
};
}
+/** agent-forge 来源:触发来源横幅与高危加重。 */
+const AGENT_ORIGIN = {
+ kind: 'agent-forge' as const,
+ sessionTitle: '处理外部文档',
+ sourceRelPath: 'plugins/evil',
+};
+
afterEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks();
@@ -82,42 +88,92 @@ describe('installFlow · 装入确认', () => {
},
};
setupWindow(manifest);
- const d = deps(vi.fn(async () => true));
- await confirmAndInstallGhost('/tmp/manual.cindy', d);
- const options = (d.confirmWithCheckbox as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] as {
+ const confirm = vi.fn(async (_options: unknown) => true);
+ await confirmAndInstallGhost('/tmp/manual.cindy', deps(confirm));
+ const options = confirm.mock.calls[0]?.[0] as {
content?: { props?: { manualCount?: number } };
};
expect(options.content?.props?.manualCount).toBe(2);
});
- it('Renderer 权限清单确认后把 Node 插件安装交给 Main,并提示装入完成', async () => {
+ it('新装一律直接生效(勾选框已删):install 带 enable:true', async () => {
const { install } = setupWindow(baseManifest);
- const confirm = vi.fn(async () => true);
+ const confirm = vi.fn(async (_options: unknown) => true);
await confirmAndInstallGhost('/tmp/node.cindy', deps(confirm));
- // confirmWithCheckbox 是唯一确认层(权限清单含 Node 高风险行);
- // 普通 confirm 不再伪装成安全边界。
- expect(confirm).not.toHaveBeenCalled();
+ // confirm 是唯一确认层(权限清单含 Node 高风险行);无勾选框、装入即生效。
+ expect(confirm).toHaveBeenCalledTimes(1);
expect(install).toHaveBeenCalledWith('/tmp/node.cindy', {
- enable: false,
+ enable: true,
expectedPackageSha256: 'a'.repeat(64),
});
expect(toast.success).toHaveBeenCalledTimes(1);
});
- it('普通浏览器沙箱插件同样只走现有权限清单', async () => {
- const manifest = { ...baseManifest, slots: ['card'], node: undefined };
- const { install } = setupWindow(manifest);
- const confirm = vi.fn(async () => true);
+ it('手动来源不加来源横幅、不加手输 id 闸', async () => {
+ const { install } = setupWindow(baseManifest);
+ const confirm = vi.fn(async (_options: unknown) => true);
+ // 不传 origin = 手动入口(拖入/双击/设置页选文件)。
await confirmAndInstallGhost('/tmp/plain.cindy', deps(confirm));
- expect(confirm).not.toHaveBeenCalled();
+ const options = confirm.mock.calls[0]?.[0] as {
+ content?: { props?: { agentOrigin?: unknown } };
+ requireTypedConfirmation?: unknown;
+ };
+ expect(options.content?.props?.agentOrigin).toBeUndefined();
+ expect(options.requireTypedConfirmation).toBeUndefined();
expect(install).toHaveBeenCalledTimes(1);
});
});
+describe('installFlow · Agent 发起分级加重', () => {
+ it('高危(node)+ Agent 发起 → 手输插件 id 才能确认,横幅点破 node', async () => {
+ setupWindow(baseManifest);
+ const confirm = vi.fn(async (_options: unknown) => true);
+
+ await confirmAndInstallGhost('/tmp/node.cindy', deps(confirm), AGENT_ORIGIN);
+
+ const options = confirm.mock.calls[0]?.[0] as {
+ content?: { props?: { agentOrigin?: { firstInstall: boolean; hazards: { node: boolean } } } };
+ requireTypedConfirmation?: { expected: string };
+ };
+ // 手输 id 闸:目标串 = 插件 id。
+ expect(options.requireTypedConfirmation?.expected).toBe('node-ghost');
+ // 来源横幅:首次安装 + node 高危点破。
+ expect(options.content?.props?.agentOrigin?.firstInstall).toBe(true);
+ expect(options.content?.props?.agentOrigin?.hazards.node).toBe(true);
+ });
+
+ it('低危(card)+ Agent 发起 → 只加来源横幅,不加手输 id 闸', async () => {
+ const manifest = { ...baseManifest, slots: ['card'], node: undefined };
+ setupWindow(manifest);
+ const confirm = vi.fn(async (_options: unknown) => true);
+
+ await confirmAndInstallGhost('/tmp/card.cindy', deps(confirm), AGENT_ORIGIN);
+
+ const options = confirm.mock.calls[0]?.[0] as {
+ content?: { props?: { agentOrigin?: { hazards: { node: boolean; skill: boolean } } } };
+ requireTypedConfirmation?: unknown;
+ };
+ expect(options.requireTypedConfirmation).toBeUndefined();
+ // 横幅仍在(来源事实),但无高危点破。
+ expect(options.content?.props?.agentOrigin).toBeDefined();
+ expect(options.content?.props?.agentOrigin?.hazards.node).toBe(false);
+ expect(options.content?.props?.agentOrigin?.hazards.skill).toBe(false);
+ });
+
+ it('用户取消手输 id(confirm 返回 false)→ 不落盘', async () => {
+ const { install } = setupWindow(baseManifest);
+ const confirm = vi.fn(async (_options: unknown) => false);
+
+ await confirmAndInstallGhost('/tmp/node.cindy', deps(confirm), AGENT_ORIGIN);
+
+ expect(install).not.toHaveBeenCalled();
+ });
+});
+
describe('installFlow · approved update binding', () => {
function installed(
approval: InstalledGhost['approval'],
@@ -173,7 +229,7 @@ describe('installFlow · approved update binding', () => {
});
});
-describe('installFlow · tab 型插件「立即开启并打开面板」', () => {
+describe('installFlow · tab 型插件装入即开面板', () => {
const tabManifest = {
schemaVersion: 2 as const,
id: 'tab-demo-a',
@@ -185,39 +241,20 @@ describe('installFlow · tab 型插件「立即开启并打开面板」', () =>
panel: { html: 'panel.html', position: 'tab' as const },
};
- function tabDeps(overrides: {
- checked?: boolean;
- openPluginPanel?: (ghostId: string) => void;
- }) {
- const confirmWithCheckbox = vi.fn(async () => ({
- ok: true,
- checked: overrides.checked ?? true,
- }));
+ function tabDeps(openPluginPanel?: (ghostId: string) => void) {
return {
- deps: {
- t: ((key: string) => key) as never,
- confirm: vi.fn(async () => true),
- confirmWithCheckbox,
- ...(overrides.openPluginPanel ? { openPluginPanel: overrides.openPluginPanel } : {}),
- },
- confirmWithCheckbox,
+ t: ((key: string) => key) as never,
+ confirm: vi.fn(async (_options: unknown) => true),
+ ...(openPluginPanel ? { openPluginPanel } : {}),
};
}
- it('tab 清单 + 勾选 → enable 装入并打开插件页面板,勾选文案换 openPanel 版', async () => {
+ it('tab 清单 → enable 装入(勾选框已删)并原地打开插件页面板', async () => {
const { install } = setupWindow(tabManifest);
const openPluginPanel = vi.fn();
- const { deps: d, confirmWithCheckbox } = tabDeps({ openPluginPanel });
- await confirmAndInstallGhost('/tmp/tab.cindy', d);
+ await confirmAndInstallGhost('/tmp/tab.cindy', tabDeps(openPluginPanel));
- expect(confirmWithCheckbox).toHaveBeenCalledWith(
- expect.objectContaining({
- checkboxLabel: 'settings.ghosts.installConfirm.enableNowOpenPanel',
- // 2026-07-25 起"立即开启"默认勾选:装入即带电,取消勾选才沉睡。
- checkboxDefaultChecked: true,
- }),
- );
expect(install).toHaveBeenCalledWith('/tmp/tab.cindy', {
enable: true,
expectedPackageSha256: 'a'.repeat(64),
@@ -226,43 +263,26 @@ describe('installFlow · tab 型插件「立即开启并打开面板」', () =>
expect(toast.success).toHaveBeenCalledTimes(1);
});
- it('不勾选 → 沉睡装入,不打开面板', async () => {
- setupWindow(tabManifest);
- const openPluginPanel = vi.fn();
- const { deps: d } = tabDeps({ checked: false, openPluginPanel });
-
- await confirmAndInstallGhost('/tmp/tab.cindy', d);
-
- expect(openPluginPanel).not.toHaveBeenCalled();
- });
-
- it('入口未提供 openPluginPanel → 勾选文案保持旧版,不许诺打开', async () => {
- setupWindow(tabManifest);
- const { deps: d, confirmWithCheckbox } = tabDeps({});
+ it('入口未提供 openPluginPanel → 装入即生效但不许诺打开', async () => {
+ const { install } = setupWindow(tabManifest);
- await confirmAndInstallGhost('/tmp/tab.cindy', d);
+ await confirmAndInstallGhost('/tmp/tab.cindy', tabDeps());
- expect(confirmWithCheckbox).toHaveBeenCalledWith(
- expect.objectContaining({ checkboxLabel: 'settings.ghosts.installConfirm.enableNow' }),
- );
+ expect(install).toHaveBeenCalledWith('/tmp/tab.cindy', {
+ enable: true,
+ expectedPackageSha256: 'a'.repeat(64),
+ });
});
- it('停靠形态(position: left)勾选只带电,不打开面板', async () => {
+ it('停靠形态(position: left)只带电,不打开面板', async () => {
setupWindow({
...tabManifest,
panel: { html: 'panel.html', position: 'left' as const },
});
const openPluginPanel = vi.fn();
- const { deps: d, confirmWithCheckbox } = tabDeps({ openPluginPanel });
- await confirmAndInstallGhost('/tmp/dock.cindy', d);
+ await confirmAndInstallGhost('/tmp/dock.cindy', tabDeps(openPluginPanel));
- expect(confirmWithCheckbox).toHaveBeenCalledWith(
- expect.objectContaining({
- checkboxLabel: 'settings.ghosts.installConfirm.enableNow',
- checkboxDefaultChecked: true,
- }),
- );
expect(openPluginPanel).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostInstallRisk.ts b/apps/desktop/src/renderer/cindy-brain/ghostInstallRisk.ts
new file mode 100644
index 0000000000..88cc20ae2c
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/ghostInstallRisk.ts
@@ -0,0 +1,88 @@
+/**
+ * 装入确认框的风险分档(纯函数,无 React、无 i18n)。
+ *
+ * 只在 **Agent 单方面发起** 装入时改变确认框行为——手动入口不受影响。分档决定
+ * 是否加重(高危:手输插件 id 才能确认;中危:只加来源横幅)。判据一律按
+ * `ghostPermissionItems` 产出的权限项 **key** 归类,与用户在确认框里实际看到的
+ * 逐项清单同源——不另立一套"作者声明"口径,避免"分档看到的"与"清单展示的"分叉。
+ *
+ * 分档(2026-08 产品拍板):
+ * - 高危:skill(技能指令以用户全部权限执行、跨项目)/ node(本机执行,浏览器
+ * 沙箱管不住)/ network.secrets 任意来源(含 oauth,能把用户凭证发往声明域名)/
+ * agent.background(后台自动触发)/ agent.errand(替它干活并取走结果)。
+ * - 中危:fs(写文件——最危险那档写会话工作目录已受会话 permission 模式约束,
+ * 免批模式下 Agent 本就能直写,插件多这能力不改变攻击面)/ network.hosts(出网
+ * 域名)/ agent.schedule(能反复弹自动化面板、烧模型额度,但须用户在面板上
+ * 亲手保存才生效)。
+ * - 低危:纯沙箱 tool / card / panel 及其它未列入的能力。
+ */
+import type { GhostPermissionItem } from '../../shared/ghost';
+
+export type GhostRiskTier = 'high' | 'mid' | 'low';
+
+export interface GhostRiskAssessment {
+ tier: GhostRiskTier;
+ /** 高危能力命中标记(来源横幅据此点破最该被看见的那一两条)。 */
+ hazards: {
+ skill: boolean;
+ node: boolean;
+ /** 声明了需要凭证(network.secrets 任意来源,含 oauth / 组织身份)。 */
+ secret: boolean;
+ agentBackground: boolean;
+ agentErrand: boolean;
+ };
+ /** 声明的出网域名(凭证外发对象;凭证点破文案用)。 */
+ networkHosts: string[];
+}
+
+/** 单条权限项的风险档(按 key 归类,与清单展示同源)。 */
+function itemRiskTier(item: GhostPermissionItem): GhostRiskTier {
+ const key = item.key;
+ if (
+ key.startsWith('skill:') ||
+ key.startsWith('node:') ||
+ key.startsWith('network:secret:') ||
+ key === 'agent:background' ||
+ key === 'agent:errand'
+ ) {
+ return 'high';
+ }
+ if (key === 'fs' || key.startsWith('network:host:') || key === 'agent:schedule') {
+ return 'mid';
+ }
+ return 'low';
+}
+
+/**
+ * 汇总一份权限清单的整体风险档 + 高危命中标记 + 出网域名。
+ * 传全量清单 = 新装分档;传更新 diff 的新增项 = 更新扩权分档(tier !== 'low'
+ * 即"新增了高危或中危能力")。
+ */
+export function assessGhostInstallRisk(items: GhostPermissionItem[]): GhostRiskAssessment {
+ const hazards = {
+ skill: false,
+ node: false,
+ secret: false,
+ agentBackground: false,
+ agentErrand: false,
+ };
+ const networkHosts: string[] = [];
+ let hasHigh = false;
+ let hasMid = false;
+ for (const item of items) {
+ const tier = itemRiskTier(item);
+ if (tier === 'high') hasHigh = true;
+ else if (tier === 'mid') hasMid = true;
+ if (item.key.startsWith('skill:')) hazards.skill = true;
+ else if (item.key.startsWith('node:')) hazards.node = true;
+ else if (item.key.startsWith('network:secret:')) hazards.secret = true;
+ else if (item.key === 'agent:background') hazards.agentBackground = true;
+ else if (item.key === 'agent:errand') hazards.agentErrand = true;
+ if (item.key.startsWith('network:host:')) {
+ const host = item.labelArgs?.host;
+ if (host) networkHosts.push(host);
+ }
+ }
+ const tier: GhostRiskTier = hasHigh ? 'high' : hasMid ? 'mid' : 'low';
+ return { tier, hazards, networkHosts };
+}
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index c30bf595e4..2bcb19c9ae 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -13,8 +13,14 @@ import {
type GhostTrustInfo,
type InstalledGhost,
} from '../../shared/ghost';
-import { GhostInstallReview, GhostUpdateReview } from './GhostPermissionList';
+import {
+ GhostInstallReview,
+ GhostUpdateReview,
+ type GhostAgentOriginInfo,
+} from './GhostPermissionList';
+import { assessGhostInstallRisk, type GhostRiskAssessment } from './ghostInstallRisk';
import { ghostInstallErrorKey } from './installErrorKey';
+import { isAgentForgeOrigin, type GhostInstallOrigin } from '../../shared/ghostInstallOrigin';
/**
* 装入/更新意识的统一编排:inspect(验明正身)→ Renderer 权限清单 →
@@ -33,13 +39,25 @@ import { ghostInstallErrorKey } from './installErrorKey';
* 同 id 已装 → 自动转「更新」分支:确认框展示版本变化(vX → vY)+ 权限 diff
* (只高亮新增/移除,不变项折叠计数),无"立即开启"勾选(更新延续当前唤醒
* 状态,不偷偷点亮也不偷偷熄灯)。
+ *
+ * 「安装后立即生效」勾选框已删除(2026-08 产品拍板):它是弱信号——把决定权推给
+ * 用户却不给判断依据。新装一律直接生效,高危插件改由**手输插件 id** 这道强确认
+ * 把关;低危插件本就该直接可用。
+ *
+ * **来源分级加重**:装入由 Agent 单方面发起(`ghost_forge_pack` 转交,origin =
+ * agent-forge)时,确认框展示来源横幅;高危档(skill/node/凭证/agent 后台/派活)
+ * 额外要求用户手输插件 id 才能确认。手动入口(拖入/双击/设置页选文件)不加横幅、
+ * 不加重——亲手选文件本身就是意图表达。判据见 ghostInstallRisk.assessGhostInstallRisk。
*/
const installFlowLog = createLogger('ghost-install-flow');
interface InstallFlowDeps {
t: TFunction;
- /** ui/confirm-dialog-provider 的 confirm(更新确认,无勾选)。 */
+ /**
+ * ui/confirm-dialog-provider 的 confirm(装入 / 更新 / 重新确认统一走它,无勾选)。
+ * requireTypedConfirmation:高危 Agent 发起时要求手输插件 id 才解锁主按钮。
+ */
confirm: (options: {
title: string;
description?: string;
@@ -47,26 +65,56 @@ interface InstallFlowDeps {
maxWidth?: number;
confirmText?: string;
cancelText?: string;
+ requireTypedConfirmation?: { expected: string; label: string; placeholder?: string };
}) => Promise<boolean>;
- /** ui/confirm-dialog-provider 的 confirmWithCheckbox(装入确认 + "立即开启"勾选)。 */
- confirmWithCheckbox: (options: {
- title: string;
- description?: string;
- content?: ReactNode;
- maxWidth?: number;
- confirmText?: string;
- cancelText?: string;
- checkboxLabel: string;
- checkboxDefaultChecked?: boolean;
- }) => Promise<{ ok: boolean; checked: boolean }>;
/**
- * 打开插件页内的页签面板(面板收束后 tab 型插件的唯一宿主)。只在
- * 「tab 型插件 + 勾选立即开启」时消费:插件页原地开面板,其它入口
- * 导航到 /plugins?panel=<id>。不传 = 该入口不许诺"打开"。
+ * 打开插件页内的页签面板(面板收束后 tab 型插件的唯一宿主)。tab 型插件装入
+ * 即生效后消费:插件页原地开面板,其它入口导航到 /plugins?panel=<id>。
+ * 不传 = 该入口不许诺"打开"。
*/
openPluginPanel?: (ghostId: string) => void;
}
+/**
+ * Agent 发起时构造来源横幅信息(手动入口返回 undefined → 不展示横幅)。
+ * hazards 只含高危标记(skill/node/凭证);中危/低危不会点亮任何 callout。
+ * hazardsFrom 决定"点破哪些":新装看全量清单,更新只看本次新增项。
+ * allHosts = 插件(更新后)能出网的全部域名,凭证 callout 据此列出外发对象。
+ */
+function agentOriginInfoFrom(
+ origin: GhostInstallOrigin | undefined,
+ firstInstall: boolean,
+ hazardsFrom: GhostRiskAssessment,
+ allHosts: string[],
+): GhostAgentOriginInfo | undefined {
+ if (!isAgentForgeOrigin(origin)) return undefined;
+ return {
+ ...(origin.sessionTitle ? { sessionTitle: origin.sessionTitle } : {}),
+ ...(origin.sourceRelPath ? { sourceRelPath: origin.sourceRelPath } : {}),
+ firstInstall,
+ hazards: {
+ skill: hazardsFrom.hazards.skill,
+ node: hazardsFrom.hazards.node,
+ credential: hazardsFrom.hazards.secret && allHosts.length > 0,
+ },
+ credentialHosts: allHosts,
+ };
+}
+
+/** 高危 Agent 发起时的「手输插件 id」闸参数(否则 undefined = 不加重)。 */
+function typedIdConfirmation(
+ t: TFunction,
+ ghostId: string,
+ required: boolean,
+): { expected: string; label: string; placeholder?: string } | undefined {
+ if (!required) return undefined;
+ return {
+ expected: ghostId,
+ label: t('settings.ghosts.installConfirm.typedIdLabel', { id: ghostId }),
+ placeholder: ghostId,
+ };
+}
+
/** 意识装入/更新确认框统一宽度:权限清单是富内容,默认 400px 折行到累。 */
const GHOST_CONFIRM_MAX_WIDTH = 520;
@@ -88,10 +136,18 @@ async function confirmAndRunUpdate(
packageSha256: string,
installed: InstalledGhost,
deps: InstallFlowDeps,
+ origin?: GhostInstallOrigin,
): Promise<void> {
const { t, confirm } = deps;
// 权限 diff:只把新增/移除的权限亮给用户,不变项折叠计数。
const diff = diffInstalledGhostPermissionItems(installed, manifest);
+ // Agent 发起的更新:新增项含高危/中危能力(tier !== 'low')即要求手输 id ——
+ // 堵"注入者篡改作者正在开发的同 id 插件、借版本升级夹带权限"。横幅点破的
+ // hazard 只看本次新增项(hazardsFrom = 新增),但凭证外发域名列出更新后的全量。
+ const addedRisk = assessGhostInstallRisk(diff.added);
+ const allHosts = assessGhostInstallRisk(ghostPermissionItems(manifest)).networkHosts;
+ const agentOrigin = agentOriginInfoFrom(origin, false, addedRisk, allHosts);
+ const escalate = isAgentForgeOrigin(origin) && addedRisk.tier !== 'low';
const ok = await confirm({
title: t('settings.ghosts.updateConfirm.title', { name: manifest.name }),
description: t('settings.ghosts.updateConfirm.body', {
@@ -103,11 +159,13 @@ async function confirmAndRunUpdate(
trust={trust}
diff={diff}
manualCount={manifest.manual?.items.length ?? 0}
+ agentOrigin={agentOrigin}
/>
),
maxWidth: GHOST_CONFIRM_MAX_WIDTH,
confirmText: t('settings.ghosts.updateConfirm.confirm'),
cancelText: t('settings.ghosts.updateConfirm.cancel'),
+ requireTypedConfirmation: typedIdConfirmation(t, manifest.id, escalate),
});
if (!ok) return;
try {
@@ -129,8 +187,13 @@ async function confirmAndRunUpdate(
export async function confirmAndInstallGhost(
lizFilePath: string,
deps: InstallFlowDeps,
+ /**
+ * 主机侧填写的来源;缺省 = 手动(拖入/双击/设置页选文件),不加横幅、不加重。
+ * agent-forge = Agent 单方面发起,展示来源横幅;高危档追加手输 id 闸。
+ */
+ origin?: GhostInstallOrigin,
): Promise<void> {
- const { t, confirmWithCheckbox } = deps;
+ const { t, confirm } = deps;
// 1) 只验不装,拿身份卡;坏文件在这一步就被拒,不会弹确认。
let manifest: GhostManifest;
@@ -147,10 +210,10 @@ export async function confirmAndInstallGhost(
}
// 1.5) 同 id 已装 → 转更新分支(拖入/双击/装入按钮选到新版包时不再报
- // "已经注入",直接给换版确认)。
+ // "已经注入",直接给换版确认)。origin 透传:Agent 发起的更新也要能加重。
const installed = findInstalled(manifest.id);
if (installed) {
- await confirmAndRunUpdate(lizFilePath, manifest, trust, packageSha256, installed, deps);
+ await confirmAndRunUpdate(lizFilePath, manifest, trust, packageSha256, installed, deps, origin);
return;
}
@@ -164,41 +227,46 @@ export async function confirmAndInstallGhost(
version: manifest.version,
})
: t('settings.ghosts.installConfirm.meta', { version: manifest.version });
- // "立即开启"勾选(2026-07-25 Lizi 定案,改自 2026-07-09 的默认不勾):
- // 默认勾选 = 装入即带电;用户显式取消勾选才装成沉睡。确认弹窗本身
- // 仍是授权边界 —— 权限清单如实展示,点"装入"即同意运行。
- // tab 型插件(panel.position:'tab')在入口能打开插件页面板时,勾选语义
- // 升级为「立即开启并打开面板」——面板收束后页签面板只住在插件页,
- // 不再创建右侧栏 ghost 页签;入口给不出面板宿主就不许诺"打开"。
+ // 新装一律直接生效(2026-08 拍板删「立即开启」勾选):高危靠手输 id 把关,低危
+ // 本该直接可用。tab 型插件(panel.position:'tab')在入口能开面板时,生效后原地
+ // 打开插件页面板;入口给不出面板宿主就不许诺"打开"。
const willOpenPanel = manifest.panel?.position === 'tab' && deps.openPluginPanel !== undefined;
// library 槽(持久作品库):装入确认里提供「存储位置」行——默认预选系统
// 管理位置(不点更改 = 零额外步骤),点「更改…」由宿主弹原生选择器并做
// 候选校验;装入成功后才落 binding(取消装入不留孤儿 binding)。
- const libraryChoice: { candidate: string | null; warnings: string[] } = { candidate: null, warnings: [] };
+ const libraryChoice: { candidate: string | null; warnings: string[] } = {
+ candidate: null,
+ warnings: [],
+ };
const librarySlots = manifest.slots.includes('library');
- const { ok, checked: enable } = await confirmWithCheckbox({
+ const items = ghostPermissionItems(manifest);
+ const risk = assessGhostInstallRisk(items);
+ // 新装是该 id 首次安装(installed 已在上面判空);Agent 发起才构造横幅。
+ const agentOrigin = agentOriginInfoFrom(origin, true, risk, risk.networkHosts);
+ // 高危 + Agent 发起 → 手输插件 id 才能确认(每个新插件 id 一生只打一次:
+ // 第二次起走更新分支,权限没变只显示小框)。
+ const requireTypedId = isAgentForgeOrigin(origin) && risk.tier === 'high';
+ const ok = await confirm({
title: t('settings.ghosts.installConfirm.title', { name: manifest.name }),
content: (
<GhostInstallReview
description={manifest.description}
meta={factsLine}
trust={trust}
- items={ghostPermissionItems(manifest)}
+ items={items}
manualCount={manifest.manual?.items.length ?? 0}
- extra={librarySlots ? (
- <LibraryInstallLocationRow ghostId={manifest.id} choice={libraryChoice} />
- ) : undefined}
+ extra={
+ librarySlots ? (
+ <LibraryInstallLocationRow ghostId={manifest.id} choice={libraryChoice} />
+ ) : undefined
+ }
+ agentOrigin={agentOrigin}
/>
),
maxWidth: GHOST_CONFIRM_MAX_WIDTH,
confirmText: t('settings.ghosts.installConfirm.confirm'),
cancelText: t('settings.ghosts.installConfirm.cancel'),
- checkboxLabel: t(
- willOpenPanel
- ? 'settings.ghosts.installConfirm.enableNowOpenPanel'
- : 'settings.ghosts.installConfirm.enableNow',
- ),
- checkboxDefaultChecked: true,
+ requireTypedConfirmation: typedIdConfirmation(t, manifest.id, requireTypedId),
});
if (!ok) return;
@@ -216,19 +284,15 @@ export async function confirmAndInstallGhost(
}
// 3) 真装(main 侧同一主体:来源校验 + 落盘 + 停靠)。Node 高风险提示
- // 已在上面的权限清单里如实展示,不再有 Main 原生二次确认。
+ // 已在上面的权限清单里如实展示,不再有 Main 原生二次确认。装入即生效。
try {
const { ghost } = await window.electronAPI.ghosts.install(lizFilePath, {
- enable,
+ enable: true,
expectedPackageSha256: packageSha256,
});
- toast.success(
- enable
- ? t('settings.ghosts.toast.installed', { name: ghost.manifest.name })
- : t('settings.ghosts.toast.installedAsleep', { name: ghost.manifest.name }),
- );
- if (enable && willOpenPanel) {
- // 兑现勾选文案:进入插件页并打开该插件的页签面板。
+ toast.success(t('settings.ghosts.toast.installed', { name: ghost.manifest.name }));
+ if (willOpenPanel) {
+ // 进入插件页并打开该插件的页签面板。
deps.openPluginPanel?.(ghost.manifest.id);
}
} catch (err) {
@@ -247,8 +311,11 @@ export async function confirmAndInstallGhost(
* 安装目录读不出/清单不合法时回退到「重新选包」路线 —— 目录坏了才需要用户找文件,
* 目录完好时一次点击即恢复。
*/
-export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlowDeps): Promise<void> {
- const { t, confirmWithCheckbox } = deps;
+export async function reapproveInstalledGhost(
+ ghostId: string,
+ deps: InstallFlowDeps,
+): Promise<void> {
+ const { t, confirm } = deps;
const installed = findInstalled(ghostId);
if (!installed) {
toast.error(t('settings.ghosts.errors.generic'));
@@ -283,7 +350,11 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
version: manifest.version,
})
: t('settings.ghosts.installConfirm.meta', { version: manifest.version });
- const { ok, checked: enable } = await confirmWithCheckbox({
+ // 「保持之前启用状态」不再做成勾选框(勾选框是弱信号)——它本质是"保持现状"
+ // 而非"让用户选":之前主动停用的插件,恢复权限后不该被顺手点亮。改成一句如实
+ // 说明(保持启用 / 保持沉睡),启用值直接取升级前偏好。
+ const enable = previouslyEnabled;
+ const ok = await confirm({
title: t('settings.ghosts.reapproveConfirm.title', { name: manifest.name }),
description: t('settings.ghosts.reapproveConfirm.body'),
content: (
@@ -292,15 +363,16 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
meta={factsLine}
trust={trust}
items={ghostPermissionItems(manifest)}
+ enableNotice={t(
+ previouslyEnabled
+ ? 'settings.ghosts.reapproveConfirm.enableNoticeEnabled'
+ : 'settings.ghosts.reapproveConfirm.enableNoticeAsleep',
+ )}
/>
),
maxWidth: GHOST_CONFIRM_MAX_WIDTH,
confirmText: t('settings.ghosts.reapproveConfirm.confirm'),
cancelText: t('settings.ghosts.installConfirm.cancel'),
- checkboxLabel: t('settings.ghosts.installConfirm.enableNow'),
- // 默认值取用户升级前的启停偏好(.disabled 镜像):恢复权限 ≠ 替用户把停用的
- // 插件重新点亮。
- checkboxDefaultChecked: previouslyEnabled,
});
if (!ok) return;
try {
@@ -350,14 +422,7 @@ export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDe
toast.error(t('settings.ghosts.errors.generic'));
return;
}
- await confirmAndRunUpdate(
- picked.filePath,
- manifest,
- trust,
- packageSha256,
- installed,
- deps,
- );
+ await confirmAndRunUpdate(picked.filePath, manifest, trust, packageSha256, installed, deps);
}
/**
diff --git a/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx b/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx
index 1c88899b31..f22eb9c4df 100644
--- a/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx
+++ b/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx
@@ -61,7 +61,7 @@ export function GlobalDropImportListener({
const interceptRef = useRef(false);
const navigate = useNavigate();
const { t } = useTranslation();
- const { confirm, confirmWithCheckbox } = useConfirmDialog();
+ const { confirm } = useConfirmDialog();
// 装入 tab 型插件勾选「立即开启并打开面板」的兑现:面板收束后页签面板
// 只住在插件页,从任意视图导航过去并经 ?panel= 深链打开。
const openPluginPanel = useCallback(
@@ -69,25 +69,26 @@ export function GlobalDropImportListener({
[navigate],
);
- // 双击 .cindy 的转交消费:挂载时取一次(冷启动双击,main 已缓存)+ 订阅
- // 信号(已运行时双击)。取到路径即走与按钮/拖入完全相同的确认装入编排。
+ // 双击 .cindy / forge 转交的消费:挂载时取一次(冷启动双击 / 关窗期间转交的,
+ // main 已缓存)+ 订阅通知(已运行时双击 / forge 转交)。取到路径即走与按钮/拖入
+ // 完全相同的确认装入编排。
+ //
+ // 来源与路径**一起从 takePendingInstall 取**,不从通知 payload 拿:通知是易失的
+ // (没有窗口时直接丢),而 forge 转交在 macOS 关窗后仍可能发生,来源丢了就会把
+ // Agent 发起的装入显示成手动 —— 恰好是最危险的方向。理由全文见 main 侧
+ // openFileInstall.ts 的头注释。
useEffect(() => {
const consumePending = async () => {
- const { filePath } = await window.electronAPI.ghosts.takePendingInstall();
+ const { filePath, origin } = await window.electronAPI.ghosts.takePendingInstall();
if (filePath) {
- await confirmAndInstallGhost(filePath, {
- t,
- confirm,
- confirmWithCheckbox,
- openPluginPanel,
- });
+ await confirmAndInstallGhost(filePath, { t, confirm, openPluginPanel }, origin);
}
};
void consumePending().catch((err) => log.warn('consume pending cindy install failed', err));
return window.electronAPI.ghosts.onInstallRequested(() => {
void consumePending().catch((err) => log.warn('consume pending cindy install failed', err));
});
- }, [confirm, confirmWithCheckbox, openPluginPanel, t]);
+ }, [confirm, openPluginPanel, t]);
useEffect(() => {
// 悬停识别:单文件且 MIME 命中才给遮罩。
@@ -147,12 +148,8 @@ export function GlobalDropImportListener({
markGlobalDropIntercepted(e);
if (kind === 'cindy') {
// 验明正身 → 确认弹窗 → 装入的编排在 installFlow(与设置页装入按钮同契约)。
- void confirmAndInstallGhost(path, {
- t,
- confirm,
- confirmWithCheckbox,
- openPluginPanel,
- });
+ // 拖入是用户亲手操作 → 手动来源(不传 origin),不加横幅、不加重。
+ void confirmAndInstallGhost(path, { t, confirm, openPluginPanel });
return;
}
void window.electronAPI.localDb.sessionShare
@@ -210,7 +207,7 @@ export function GlobalDropImportListener({
window.removeEventListener('dragover', onDragOver);
window.removeEventListener('drop', onDrop);
};
- }, [confirm, confirmWithCheckbox, navigate, onOpenShareImport, openPluginPanel, t]);
+ }, [confirm, navigate, onOpenShareImport, openPluginPanel, t]);
return (
<>
diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
index f4321b2fd6..8299a7c049 100644
--- a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
@@ -35,6 +35,15 @@ export interface ConfirmOptions {
* 破坏性确认(删除/重置等)请保持默认。
*/
autoFocusConfirm?: boolean;
+ /**
+ * 高危确认的「手输一致才放行」闸(见 ConfirmDialogProps.requireTypedConfirmation)。
+ * 设了就要求用户逐字打出 expected 才解锁主按钮;有它时焦点自动落到输入框。
+ */
+ requireTypedConfirmation?: {
+ expected: string;
+ label: string;
+ placeholder?: string;
+ };
}
const DONT_SHOW_AGAIN_PREFIX = 'confirm-dialog.skip:';
@@ -282,6 +291,7 @@ export function ConfirmDialogProvider({ children }: { children: ReactNode }) {
showCancel={currentItem.options.showCancel}
tertiaryText={currentItem.options.tertiaryText}
autoFocusConfirm={currentItem.options.autoFocusConfirm}
+ requireTypedConfirmation={currentItem.options.requireTypedConfirmation}
dontShowAgainLabel={
currentItem.options.dontShowAgainKey
? currentItem.options.dontShowAgainLabel ?? '下次不再提示'
diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx
index 60a572cf14..01668b46e0 100644
--- a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx
+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx
@@ -50,6 +50,20 @@ export interface ConfirmDialogProps {
autoFocusConfirm?: boolean;
/** Disable the primary action until caller-owned validation has passed. */
confirmDisabled?: boolean;
+ /**
+ * 高危确认的「手输一致才放行」闸(如 Agent 发起装入高危插件时手打插件 id)。
+ * 设了就在按钮上方渲染一个输入框,用户必须逐字打出 `expected` 才解锁主按钮 ——
+ * 这是比勾选框更强的确认:它逼用户对着确认框里的那个 id 亲手核对一遍,而不是
+ * 无脑点。输入状态由本组件持有(每次打开复位),不外泄给调用方。
+ */
+ requireTypedConfirmation?: {
+ /** 必须逐字打出的目标串(如插件 id)。 */
+ expected: string;
+ /** 输入框上方的说明,通常含 expected 的插值。 */
+ label: string;
+ /** 输入框 placeholder(缺省用 expected)。 */
+ placeholder?: string;
+ };
/** 嵌套在其它 Dialog 内时提升层级;普通确认继续使用默认层级。 */
zIndex?: number;
/** Destructive actions use the semantic destructive theme tokens. */
@@ -96,6 +110,7 @@ export function ConfirmDialog({
checkboxDefaultChecked = false,
autoFocusConfirm,
confirmDisabled = false,
+ requireTypedConfirmation,
confirmVariant = 'default',
confirmIcon,
describeContent = false,
@@ -115,7 +130,16 @@ export function ConfirmDialog({
useEffect(() => {
if (open) setDontShowAgain(checkboxDefaultChecked);
}, [open, checkboxDefaultChecked]);
+ // 手输确认串:每次打开复位为空,逐字打出 expected 前主按钮保持禁用。
+ const [typedConfirmation, setTypedConfirmation] = useState('');
+ useEffect(() => {
+ if (open) setTypedConfirmation('');
+ }, [open]);
+ const typedConfirmationSatisfied =
+ !requireTypedConfirmation || typedConfirmation.trim() === requireTypedConfirmation.expected;
+ const confirmBlocked = loading || confirmDisabled || !typedConfirmationSatisfied;
const confirmBtnRef = useRef<HTMLButtonElement>(null);
+ const typedConfirmationRef = useRef<HTMLInputElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
// 滚动条 thumb 默认透明(globals.css),不滚不 hover 就看不见"下面还有内容"。
// 授权确认场景里这不是观感问题:权限清单被折在视口下面而用户不知道,等于
@@ -185,14 +209,21 @@ export function ConfirmDialog({
if (loading) e.preventDefault();
}}
onOpenAutoFocus={
- autoFocusConfirm
+ requireTypedConfirmation
? (e) => {
- // Radix 默认聚焦第一个可聚焦元素 / Cancel —— 这里覆盖,
- // 把焦点交给主按钮,避免"取消"天然带 focus ring。
+ // 有手输闸时把焦点交给输入框:用户一开就在核对/输入 id,
+ // 而不是停在一个当前还被禁用的主按钮上。
e.preventDefault();
- confirmBtnRef.current?.focus();
+ typedConfirmationRef.current?.focus();
}
- : undefined
+ : autoFocusConfirm
+ ? (e) => {
+ // Radix 默认聚焦第一个可聚焦元素 / Cancel —— 这里覆盖,
+ // 把焦点交给主按钮,避免"取消"天然带 focus ring。
+ e.preventDefault();
+ confirmBtnRef.current?.focus();
+ }
+ : undefined
}
>
<AlertDialog.Title
@@ -246,11 +277,50 @@ export function ConfirmDialog({
{dontShowAgainLabel}
</label>
)}
+ {requireTypedConfirmation && (
+ <div className="mt-4 shrink-0">
+ <label
+ htmlFor={`${bodyId}-typed`}
+ className="block text-13 leading-[1.5] text-[var(--confirm-desc)]"
+ >
+ {requireTypedConfirmation.label}
+ </label>
+ <input
+ ref={typedConfirmationRef}
+ id={`${bodyId}-typed`}
+ type="text"
+ autoComplete="off"
+ autoCorrect="off"
+ autoCapitalize="off"
+ spellCheck={false}
+ value={typedConfirmation}
+ disabled={loading}
+ onChange={(e) => setTypedConfirmation(e.target.value)}
+ onKeyDown={(e) => {
+ // Enter 在闸满足时等同点主按钮;未满足则吞掉,不误触。
+ if (e.key === 'Enter' && typedConfirmationSatisfied && !loading) {
+ e.preventDefault();
+ onConfirm?.({ dontShowAgain });
+ }
+ }}
+ placeholder={
+ requireTypedConfirmation.placeholder ?? requireTypedConfirmation.expected
+ }
+ className={cn(
+ 'mt-1.5 h-9 w-full rounded-lg border px-3 text-13',
+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',
+ 'text-[var(--settings-input-text)] placeholder:text-[var(--text-placeholder)]',
+ 'outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]',
+ 'disabled:cursor-not-allowed disabled:opacity-60',
+ )}
+ />
+ </div>
+ )}
<div className="mt-6 flex shrink-0 justify-end gap-2.5">
<AlertDialog.Action asChild>
<button
ref={confirmBtnRef}
- disabled={loading || confirmDisabled}
+ disabled={confirmBlocked}
aria-busy={loading || undefined}
aria-label={resolvedConfirmText}
onClick={() => onConfirm?.({ dontShowAgain })}
@@ -267,7 +337,9 @@ export function ConfirmDialog({
loading &&
confirmVariant === 'destructive' &&
'cursor-default opacity-80 active:scale-100 hover:opacity-80',
- confirmDisabled && 'cursor-not-allowed opacity-50 active:scale-100',
+ !loading &&
+ (confirmDisabled || !typedConfirmationSatisfied) &&
+ 'cursor-not-allowed opacity-50 active:scale-100',
)}
>
{loading ? (
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 7a3c7c0b4d..0fd9935179 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -327,7 +327,7 @@ export function GhostPluginPage({
const marketLocale = resolveSystemLocale(i18n.resolvedLanguage ?? i18n.language);
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
- const { confirm, confirmWithCheckbox } = useConfirmDialog();
+ const { confirm } = useConfirmDialog();
const { user, mode, dataOwnerId } = useAuth();
const showEnterprise = user?.membershipKind === 'org';
const ghosts = useInstalledGhosts();
@@ -949,8 +949,8 @@ export function GhostPluginPage({
await handleMarketUpdate(selectedDetail.id);
return;
}
- await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });
- }, [confirm, confirmWithCheckbox, handleMarketUpdate, selectedDetail, selectedMarketUpdate, t]);
+ await pickAndUpdateGhost(selectedDetail.id, { t, confirm });
+ }, [confirm, handleMarketUpdate, selectedDetail, selectedMarketUpdate, t]);
/**
* 缺少批准状态时的恢复入口。市场自有的包重走市场安装确认(重新下载 + 逐项
@@ -967,15 +967,15 @@ export function GhostPluginPage({
}
// 本地包路线:从已装目录读全量权限清单确认后开 receipt,不用用户翻出原始
// .cindy 文件;目录读不出时该流程内部自动回退到"重新选包"。
- await reapproveInstalledGhost(ghostId, { t, confirm, confirmWithCheckbox });
+ await reapproveInstalledGhost(ghostId, { t, confirm });
},
- [confirm, confirmWithCheckbox, ghosts, handleMarketUpdate, marketByGhostId, t],
+ [confirm, ghosts, handleMarketUpdate, marketByGhostId, t],
);
const handleUpdateFromFile = useCallback(async () => {
if (!selectedDetail) return;
- await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });
- }, [confirm, confirmWithCheckbox, selectedDetail, t]);
+ await pickAndUpdateGhost(selectedDetail.id, { t, confirm });
+ }, [confirm, selectedDetail, t]);
// 控制器在挂载期借用本页的市场刷新;卸载后批次继续跑,重新进页全量刷新。
useEffect(
@@ -1016,17 +1016,17 @@ export function GhostPluginPage({
const handleInstall = useCallback(async () => {
const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);
if (!picked || 'canceled' in picked) return;
+ // 设置页选文件是用户亲手操作 → 手动来源(不传 origin),不加横幅、不加重。
await confirmAndInstallGhost(picked.filePath, {
t,
confirm,
- confirmWithCheckbox,
- // 已在插件页:tab 型插件勾选「立即开启并打开面板」后原地开面板。
+ // 已在插件页:tab 型插件装入即生效后原地开面板。
openPluginPanel: (ghostId) => {
setSelectedId(null);
setOpenPanelId(ghostId);
},
});
- }, [confirm, confirmWithCheckbox, t]);
+ }, [confirm, t]);
const handleRetryLegacyRecovery = useCallback(async () => {
legacyRecoveryStatusRequestRef.current += 1;
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts
index 7761ee1486..fd5d173b92 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginStateCopy.test.ts
@@ -19,7 +19,6 @@ const zhCommon = JSON.parse(
ghosts: {
disabledTag: string;
enableAria: string;
- toast: { installedAsleep: string };
detail: { customSlotAsleep: string; disabledLabel: string };
};
};
@@ -31,7 +30,8 @@ describe('Ghost Plugin lifecycle wording', () => {
expect(zhCommon.settings.ghosts.disabledTag).toBe('已停用');
expect(zhCommon.settings.ghosts.detail.disabledLabel).toBe('已停用');
expect(zhCommon.settings.ghosts.enableAria).toContain('启用');
- expect(zhCommon.settings.ghosts.toast.installedAsleep).toContain('可随时在此启用');
+ // 原先还钉 toast.installedAsleep(「已装入但沉睡」)。新装的「立即开启」勾选框
+ // 去掉后一律装入即生效,那条 toast 与其文案 key 一起删了,故不再断言。
expect(zhCommon.settings.ghosts.detail.customSlotAsleep).toContain('启用后');
});
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6ea892c724..97ea993046 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4278,7 +4278,6 @@
"toast": {
"installed": "Installed \"{{name}}\"",
"uninstalled": "Uninstalled \"{{name}}\"",
- "installedAsleep": "Installed \"{{name}}\" (disabled — enable it here anytime)",
"updated": "\"{{name}}\" updated to v{{version}}",
"reapproved": "\"{{name}}\" restored",
"exported": "Exported the .cindy file for \"{{name}}\"",
@@ -4298,11 +4297,22 @@
"cancel": "Cancel",
"meta": "Version {{version}}. Installs locally and can be uninstalled anytime.",
"metaWithAuthor": "By {{author}} · Version {{version}}. Installs locally and can be uninstalled anytime.",
- "enableNow": "Enable right after install",
- "enableNowOpenPanel": "Enable and open its panel right after install",
"manualCount": "Bundled manuals: {{count}}",
"expandDescription": "Show Full Description",
- "collapseDescription": "Hide Full Description"
+ "collapseDescription": "Hide Full Description",
+ "typedIdLabel": "Type the plugin id \"{{id}}\" to confirm installation",
+ "agentBanner": {
+ "title": "An Agent started this install — you didn't click it.",
+ "context": "It packaged the plugin source under {{path}} while working on the task \"{{title}}\".",
+ "contextNoPath": "It packaged a plugin source directory while working on the task \"{{title}}\".",
+ "contextNoTitle": "It packaged the plugin source under {{path}}.",
+ "contextBare": "It packaged a plugin source directory.",
+ "advice": "If you didn't ask it to make a plugin in this task, cancel — and look back at what external content this task just read.",
+ "firstInstall": "This plugin id has never been installed before.",
+ "hazardSkill": "It ships skill instructions the AI runs with all your permissions, outside the plugin sandbox, across all your projects.",
+ "hazardNode": "It can run programs on your computer, outside the browser sandbox.",
+ "hazardCredential": "It will send the credentials you enter on its settings page to {{hosts}}."
+ }
},
"trust": {
"official": "Official Cindy plugin",
@@ -4592,7 +4602,9 @@
"reapproveConfirm": {
"title": "Re-approve permissions for \"{{name}}\"?",
"body": "Review the permissions below to re-approve this installed plugin — no install file needed.",
- "confirm": "Approve & Restore"
+ "confirm": "Approve & Restore",
+ "enableNoticeEnabled": "Keeps its current enabled state after you confirm.",
+ "enableNoticeAsleep": "Stays asleep after you confirm (not enabled automatically); you can enable it here later."
},
"pick": {
"dialogTitle": "Choose a folder",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index ccc58c136a..9a684fa8db 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4277,7 +4277,6 @@
"toast": {
"installed": "「{{name}}」をインストールしました",
"uninstalled": "「{{name}}」をアンインストールしました",
- "installedAsleep": "「{{name}}」をインストールしました(無効状態。ここでいつでも有効化できます)",
"updated": "「{{name}}」を v{{version}} に更新しました",
"reapproved": "「{{name}}」を復元しました",
"exported": "「{{name}}」の .cindy ファイルを書き出しました",
@@ -4297,11 +4296,22 @@
"cancel": "キャンセル",
"meta": "バージョン {{version}}。ローカルにインストールされ、いつでもアンインストールできます。",
"metaWithAuthor": "作者 {{author}} · バージョン {{version}}。ローカルにインストールされ、いつでもアンインストールできます。",
- "enableNow": "インストール後すぐに有効化",
- "enableNowOpenPanel": "インストール後すぐに有効化してパネルを開く",
"manualCount": "同梱マニュアル {{count}} 件",
"expandDescription": "紹介全文を表示",
- "collapseDescription": "紹介を折りたたむ"
+ "collapseDescription": "紹介を折りたたむ",
+ "typedIdLabel": "プラグイン id「{{id}}」を入力してインストールを確認",
+ "agentBanner": {
+ "title": "このインストールは Agent が開始しました。あなたが押したものではありません。",
+ "context": "タスク「{{title}}」の作業中に、{{path}} 配下のプラグインソースをパッケージしました。",
+ "contextNoPath": "タスク「{{title}}」の作業中に、プラグインのソースディレクトリをパッケージしました。",
+ "contextNoTitle": "{{path}} 配下のプラグインソースをパッケージしました。",
+ "contextBare": "プラグインのソースディレクトリをパッケージしました。",
+ "advice": "このタスクでプラグイン作成を頼んでいないなら、キャンセルしてください —— そのうえで、このタスクが直前に読み込んだ外部コンテンツを見直してください。",
+ "firstInstall": "このプラグイン id はこれまで一度もインストールされていません。",
+ "hazardSkill": "スキル指示を含みます。AI はそれをあなたの全権限で実行し、プラグインのサンドボックス外で、すべてのプロジェクトに対して有効になります。",
+ "hazardNode": "ブラウザのサンドボックス外で、あなたのコンピュータ上でプログラムを実行できます。",
+ "hazardCredential": "設定ページで入力した認証情報を {{hosts}} に送信します。"
+ }
},
"trust": {
"official": "Cindy 公式プラグイン",
@@ -4591,7 +4601,9 @@
"reapproveConfirm": {
"title": "「{{name}}」の権限を再確認しますか?",
"body": "以下の権限を確認して、このインストール済みプラグインをあらためて許可します。インストールファイルは不要です。",
- "confirm": "確認して復元"
+ "confirm": "確認して復元",
+ "enableNoticeEnabled": "確認後も現在の有効状態を維持します。",
+ "enableNoticeAsleep": "確認後もスリープ状態のままにします(自動では有効化しません)。あとでここから手動で有効化できます。"
},
"pick": {
"dialogTitle": "フォルダを選択",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 2486c27103..5b86fdb72a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4277,7 +4277,6 @@
"toast": {
"installed": "\"{{name}}\" 설치됨",
"uninstalled": "\"{{name}}\" 제거됨",
- "installedAsleep": "\"{{name}}\" 설치 완료 (비활성 상태이며 여기에서 언제든 활성화할 수 있습니다)",
"updated": "\"{{name}}\"이(가) v{{version}}(으)로 업데이트되었습니다",
"reapproved": "\"{{name}}\"이(가) 복원되었습니다",
"exported": "\"{{name}}\"의 .cindy 파일을 내보냈습니다",
@@ -4297,11 +4296,22 @@
"cancel": "취소",
"meta": "버전 {{version}}. 로컬에 설치되며 언제든 제거할 수 있습니다.",
"metaWithAuthor": "제작자 {{author}} · 버전 {{version}}. 로컬에 설치되며 언제든 제거할 수 있습니다.",
- "enableNow": "설치 후 바로 활성화",
- "enableNowOpenPanel": "설치 후 바로 활성화하고 패널 열기",
"manualCount": "번들 매뉴얼 {{count}}개",
"expandDescription": "전체 소개 보기",
- "collapseDescription": "소개 접기"
+ "collapseDescription": "소개 접기",
+ "typedIdLabel": "플러그인 id \"{{id}}\"을(를) 입력하여 설치를 확인하세요",
+ "agentBanner": {
+ "title": "이 설치는 Agent가 시작한 것입니다 — 당신이 누른 것이 아닙니다.",
+ "context": "작업 \"{{title}}\"을(를) 진행하던 중 {{path}} 아래의 플러그인 소스를 패키징했습니다.",
+ "contextNoPath": "작업 \"{{title}}\"을(를) 진행하던 중 플러그인 소스 디렉터리를 패키징했습니다.",
+ "contextNoTitle": "{{path}} 아래의 플러그인 소스를 패키징했습니다.",
+ "contextBare": "플러그인 소스 디렉터리를 패키징했습니다.",
+ "advice": "이 작업에서 플러그인 제작을 요청하지 않았다면 취소하세요 —— 그리고 이 작업이 방금 읽은 외부 콘텐츠를 다시 살펴보세요.",
+ "firstInstall": "이 플러그인 id는 이전에 설치된 적이 없습니다.",
+ "hazardSkill": "스킬 지시가 포함되어 있습니다. AI는 이를 당신의 모든 권한으로, 플러그인 샌드박스 밖에서, 모든 프로젝트에 대해 실행합니다.",
+ "hazardNode": "브라우저 샌드박스 밖에서 당신의 컴퓨터에서 프로그램을 실행할 수 있습니다.",
+ "hazardCredential": "설정 페이지에 입력한 자격 증명을 {{hosts}}(으)로 보냅니다."
+ }
},
"trust": {
"official": "Cindy 공식 플러그인",
@@ -4591,7 +4601,9 @@
"reapproveConfirm": {
"title": "\"{{name}}\" 권한을 다시 확인할까요?",
"body": "아래 권한을 확인하면 설치된 플러그인이 다시 승인됩니다. 설치 파일은 필요하지 않습니다.",
- "confirm": "확인 후 복원"
+ "confirm": "확인 후 복원",
+ "enableNoticeEnabled": "확인 후 현재 활성화 상태를 유지합니다.",
+ "enableNoticeAsleep": "확인 후 휴면 상태를 유지합니다(자동으로 활성화되지 않음). 나중에 여기에서 수동으로 활성화할 수 있습니다."
},
"pick": {
"dialogTitle": "폴더 선택",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 4c6870769f..428c4ef6a8 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4277,7 +4277,6 @@
"toast": {
"installed": "已安装「{{name}}」",
"uninstalled": "已卸载「{{name}}」",
- "installedAsleep": "已安装「{{name}}」(已停用,可随时在此启用)",
"updated": "「{{name}}」已更新到 v{{version}}",
"reapproved": "已恢复「{{name}}」",
"exported": "已导出「{{name}}」的 .cindy 文件",
@@ -4297,11 +4296,22 @@
"cancel": "取消",
"meta": "版本 {{version}}。将安装到本机,可随时卸载。",
"metaWithAuthor": "作者 {{author}} · 版本 {{version}}。将安装到本机,可随时卸载。",
- "enableNow": "安装后立即生效",
- "enableNowOpenPanel": "安装后立即生效并打开面板",
"manualCount": "随包手册 {{count}} 篇",
"expandDescription": "展开完整介绍",
- "collapseDescription": "收起介绍"
+ "collapseDescription": "收起介绍",
+ "typedIdLabel": "输入插件 id「{{id}}」以确认安装",
+ "agentBanner": {
+ "title": "这次安装是 Agent 发起的,不是你点的。",
+ "context": "它在任务「{{title}}」里打包了 {{path}} 下的插件源码。",
+ "contextNoPath": "它在任务「{{title}}」里打包了一个插件源码目录。",
+ "contextNoTitle": "它打包了 {{path}} 下的插件源码。",
+ "contextBare": "它打包了一个插件源码目录。",
+ "advice": "如果你没在这个任务里要求做插件,请取消 —— 并回头看看这个任务刚才读过哪些外部内容。",
+ "firstInstall": "这个插件 id 此前从未安装过。",
+ "hazardSkill": "它带了技能指令,AI 会以你的全部权限执行,不受插件沙箱限制,而且对你所有项目生效。",
+ "hazardNode": "它可以在你的电脑上运行程序,不受浏览器沙箱限制。",
+ "hazardCredential": "它会把你在它设置页填的凭证发给 {{hosts}}。"
+ }
},
"trust": {
"official": "Cindy 官方插件",
@@ -4591,7 +4601,9 @@
"reapproveConfirm": {
"title": "重新确认「{{name}}」的权限?",
"body": "按下方清单重新授权这个已安装的插件,无需重新提供安装包文件。",
- "confirm": "确认并恢复"
+ "confirm": "确认并恢复",
+ "enableNoticeEnabled": "确认后保持当前启用状态。",
+ "enableNoticeAsleep": "确认后保持沉睡(不自动启用);你可以稍后在这里手动启用。"
},
"pick": {
"dialogTitle": "选择文件夹",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 82914434b9..c6f3613424 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4278,7 +4278,6 @@
"reapproved": "已恢復「{{name}}」",
"installed": "已安裝「{{name}}」",
"uninstalled": "已解除安裝「{{name}}」",
- "installedAsleep": "已安裝「{{name}}」(未生效,可在此開啟)",
"updated": "「{{name}}」已更新到 v{{version}}",
"exported": "已匯出「{{name}}」的 .cindy 檔案",
"exportFailed": "匯出「{{name}}」失敗,請重試",
@@ -4297,11 +4296,22 @@
"cancel": "取消",
"meta": "版本 {{version}}。將安裝到本機,可隨時解除安裝。",
"metaWithAuthor": "作者 {{author}} · 版本 {{version}}。將安裝到本機,可隨時解除安裝。",
- "enableNow": "安裝後立即生效",
- "enableNowOpenPanel": "安裝後立即生效並打開面板",
"manualCount": "隨包手冊 {{count}} 篇",
"expandDescription": "展開完整介紹",
- "collapseDescription": "收起介紹"
+ "collapseDescription": "收起介紹",
+ "typedIdLabel": "輸入插件 id「{{id}}」以確認安裝",
+ "agentBanner": {
+ "title": "這次安裝是 Agent 發起的,不是你點的。",
+ "context": "它在任務「{{title}}」裡打包了 {{path}} 下的插件原始碼。",
+ "contextNoPath": "它在任務「{{title}}」裡打包了一個插件原始碼目錄。",
+ "contextNoTitle": "它打包了 {{path}} 下的插件原始碼。",
+ "contextBare": "它打包了一個插件原始碼目錄。",
+ "advice": "如果你沒在這個任務裡要求做插件,請取消 —— 並回頭看看這個任務剛才讀過哪些外部內容。",
+ "firstInstall": "這個插件 id 此前從未安裝過。",
+ "hazardSkill": "它帶了技能指令,AI 會以你的全部權限執行,不受插件沙箱限制,而且對你所有專案生效。",
+ "hazardNode": "它可以在你的電腦上執行程式,不受瀏覽器沙箱限制。",
+ "hazardCredential": "它會把你在它設定頁填的憑證發給 {{hosts}}。"
+ }
},
"trust": {
"official": "Cindy 官方插件",
@@ -4584,7 +4594,9 @@
"reapproveConfirm": {
"title": "重新確認「{{name}}」的權限?",
"body": "按下方清單重新授權這個已安裝的插件,不需要重新提供安裝包檔案。",
- "confirm": "確認並恢復"
+ "confirm": "確認並恢復",
+ "enableNoticeEnabled": "確認後保持目前啟用狀態。",
+ "enableNoticeAsleep": "確認後保持沉睡(不自動啟用);你可以稍後在這裡手動啟用。"
},
"updateConfirm": {
"title": "更新插件「{{name}}」?",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index ababa4b748..f85c79aa43 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1355,8 +1355,14 @@ interface ElectronAPI {
id: string,
disabled: boolean,
) => Promise<{ disabled: string[] }>;
- /** 双击 .cindy 的待装路径,原子取走(取即清空;无则 null)。 */
- takePendingInstall: () => Promise<{ filePath: string | null }>;
+ /**
+ * 双击 .cindy / forge 转交的待装路径与来源,原子取走(取即清空;无则 null)。
+ * 来源由主机填写、与路径同存同取,agent 不可伪造;没有待装项时返回 manual。
+ */
+ takePendingInstall: () => Promise<{
+ filePath: string | null;
+ origin: import('../shared/ghostInstallOrigin').GhostInstallOrigin;
+ }>;
onChanged: (
callback: (payload: { ghosts: import('../shared/ghost').InstalledGhost[] }) => void,
) => () => void;
@@ -1368,7 +1374,11 @@ interface ElectronAPI {
| { sessionId: string; target: 'client_settings' },
) => void,
) => () => void;
- /** 双击 .cindy 转交信号:收到后调 takePendingInstall 取路径走确认装入流程。 */
+ /**
+ * 双击 .cindy / forge 转交的"来取货"通知,**不携带任何事实**:收到后调
+ * takePendingInstall 取路径与来源。事实只放在 main 的 pending 缓冲里,
+ * 没有窗口时(冷启动 / macOS 关窗后应用仍在跑)本通知丢掉也不影响正确性。
+ */
onInstallRequested: (callback: () => void) => () => void;
/** 运行时状态广播:crashed / fused 时面板原地显示错误接管态。 */
onRuntimeChanged: (
diff --git a/apps/desktop/src/shared/ghostInstallOrigin.ts b/apps/desktop/src/shared/ghostInstallOrigin.ts
new file mode 100644
index 0000000000..4839c606e7
--- /dev/null
+++ b/apps/desktop/src/shared/ghostInstallOrigin.ts
@@ -0,0 +1,38 @@
+/**
+ * 装入确认框的「发起来源」——主机侧填写、agent 不可伪造。
+ *
+ * 为什么需要它:插件装入有四个入口(设置页选文件 / 窗口拖入 / 双击 .cindy /
+ * `ghost_forge_pack` 打包转交),前三个都是用户亲手操作、意图明确;唯独 forge
+ * 转交是 **Agent 单方面调工具发起的**——注入攻击可以让 Agent 在处理外部内容时
+ * 偷偷打包并弹装入框,而用户此刻刚让 Agent 干了一堆事,没有"我没让它装插件"的
+ * 清晰记忆。确认框必须能如实告诉用户"这次是 Agent 发起的,不是你点的",用户才有
+ * 判断依据。
+ *
+ * 该结论只能由主机产生:forge 转交路径在 main 侧记下来源,经既有的
+ * `ghosts:install-requested` 广播 payload 送到 renderer(不经 agent 可控通道)。
+ * 手动入口一律 `manual`,不加任何提示——亲手选文件本身就是意图表达。
+ */
+export type GhostInstallOrigin =
+ | { kind: 'manual' }
+ | {
+ /**
+ * Agent 经 `ghost_forge_pack` 打包并转交装入。字段都由主机填:sessionTitle
+ * 取自会话行(agent 改不了),sourceRelPath 是源码目录相对会话工作目录的
+ * 路径(forge 打包已强制源码必须在工作目录内,故该路径可靠)。
+ */
+ kind: 'agent-forge';
+ /** 发起该次打包的任务标题(查不到时缺省,不编造)。 */
+ sessionTitle?: string;
+ /** 被打包的插件源码目录,相对当前会话工作目录。 */
+ sourceRelPath?: string;
+ };
+
+/** 手动入口的缺省来源(拖入 / 双击 / 设置页选文件共用)。 */
+export const MANUAL_GHOST_INSTALL_ORIGIN: GhostInstallOrigin = { kind: 'manual' };
+
+/** 是否为 Agent 单方面发起(确认框据此决定是否展示来源横幅)。 */
+export function isAgentForgeOrigin(
+ origin: GhostInstallOrigin | null | undefined,
+): origin is Extract<GhostInstallOrigin, { kind: 'agent-forge' }> {
+ return origin?.kind === 'agent-forge';
+}