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(plugin): 插件未读角标通道(notify.badge) (#1421)

Chris Zhang4cbbbdee6cc1
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/badgeSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/badgeSlot.test.ts
new file mode 100644
index 0000000000..f11ecaec60
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/badgeSlot.test.ts
@@ -0,0 +1,177 @@
+/**
+ * badgeSlot.test.ts — 未读角标槽单测(纯 DI,无 Electron)。
+ * 覆盖:happy path(落盘 + 广播)、两道资格审(notify 槽 / notify.badge 声明)、
+ * 沉睡拒、载荷校验(unread 形状、summary 形状/超长)、净化(控制字符剥除、换行
+ * 坍缩、净化后为空不拒点)、限速只挡点亮方向、熄灭幂等免广播。
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+
+import { GhostBadgeSlot, type BadgeSlotDeps } from '../badgeSlot';
+import {
+ GHOST_BADGE_MIN_INTERVAL_MS,
+ GHOST_BADGE_SUMMARY_MAX_CHARS,
+ type InstalledGhost,
+} from '../../../shared/ghost';
+
+function fakeGhost(
+ overrides: { enabled?: boolean; slots?: string[]; badge?: boolean } = {},
+): InstalledGhost {
+ const badge = overrides.badge ?? true;
+ const slots = overrides.slots ?? ['panel', 'notify'];
+ return {
+ manifest: {
+ schemaVersion: 2,
+ id: 'inbox',
+ name: '收件箱',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: badge ? [...slots, 'badge'] : slots,
+ },
+ dir: '/fake/brain/inbox',
+ enabled: overrides.enabled ?? true,
+ } as InstalledGhost;
+}
+
+function makeSlot(ghost: InstalledGhost | null, overrides: Partial<BadgeSlotDeps> = {}) {
+ const mark = vi.fn(() => true);
+ const clear = vi.fn(() => true);
+ const broadcast = vi.fn();
+ const slot = new GhostBadgeSlot({
+ getGhost: () => ghost,
+ mark,
+ clear,
+ broadcast,
+ ...overrides,
+ });
+ return { slot, mark, clear, broadcast };
+}
+
+describe('GhostBadgeSlot', () => {
+ it('happy path:落盘 + 广播(摘要净化后原样带上,时刻由主机铸)', () => {
+ const { slot, mark, broadcast } = makeSlot(fakeGhost(), { now: () => 1_700_000_000_000 });
+ const r = slot.handleBadge('inbox', { type: 'badge', unread: true, summary: '3 条新工单' });
+ expect(r).toEqual({ ok: true });
+ expect(mark).toHaveBeenCalledWith('inbox', '3 条新工单', 1_700_000_000_000);
+ expect(broadcast).toHaveBeenCalledWith({
+ ghostId: 'inbox',
+ unread: true,
+ summary: '3 条新工单',
+ at: 1_700_000_000_000,
+ });
+ });
+
+ it('资格只看 badge 卡槽:没声明就拒(存量只有 notify 槽的老包不白捡这档能力)', () => {
+ const noDecl = makeSlot(fakeGhost({ badge: false }));
+ const r = noDecl.slot.handleBadge('inbox', { unread: true });
+ expect(r).toMatchObject({ ok: false });
+ if (!r.ok) expect(r.message).toContain('badge');
+ expect(noDecl.mark).not.toHaveBeenCalled();
+ });
+
+ it('不要求 notify 槽:只声明 panel + badge 的意识照样能点亮(两档权限并列)', () => {
+ const { slot, mark } = makeSlot(fakeGhost({ slots: ['panel'] }), { now: () => 1 });
+ expect(slot.handleBadge('inbox', { unread: true, summary: '新内容' })).toEqual({ ok: true });
+ expect(mark).toHaveBeenCalledWith('inbox', '新内容', 1);
+ });
+
+ it('沉睡 / 不在装:拒,不落盘不广播', () => {
+ const asleep = makeSlot(fakeGhost({ enabled: false }));
+ expect(asleep.slot.handleBadge('inbox', { unread: true })).toMatchObject({ ok: false });
+ expect(asleep.broadcast).not.toHaveBeenCalled();
+
+ const gone = makeSlot(null);
+ expect(gone.slot.handleBadge('inbox', { unread: true })).toMatchObject({ ok: false });
+ expect(gone.broadcast).not.toHaveBeenCalled();
+ });
+
+ it('载荷校验:unread 必须是布尔;summary 必须是字符串且不超限', () => {
+ const { slot, mark } = makeSlot(fakeGhost());
+ expect(slot.handleBadge('inbox', { unread: 'yes' })).toMatchObject({ ok: false });
+ expect(slot.handleBadge('inbox', {})).toMatchObject({ ok: false });
+ expect(slot.handleBadge('inbox', { unread: true, summary: 42 })).toMatchObject({ ok: false });
+ // 超长直接拒,不静默截断——作者需要知道自己超了。
+ expect(
+ slot.handleBadge('inbox', {
+ unread: true,
+ summary: 'x'.repeat(GHOST_BADGE_SUMMARY_MAX_CHARS + 1),
+ }),
+ ).toMatchObject({ ok: false });
+ expect(mark).not.toHaveBeenCalled();
+ });
+
+ it('净化:控制字符剥除、换行坍缩成空格;净化后为空按"没给摘要"处理而不是拒点', () => {
+ const { slot, mark, broadcast } = makeSlot(fakeGhost(), { now: () => 1 });
+ expect(
+ slot.handleBadge('inbox', { unread: true, summary: '第一行\n\n第二行\u0007' }),
+ ).toEqual({ ok: true });
+ expect(mark).toHaveBeenCalledWith('inbox', '第一行 第二行', 1);
+
+ const blank = makeSlot(fakeGhost(), { now: () => 1 });
+ expect(blank.slot.handleBadge('inbox', { unread: true, summary: ' \u0000 ' })).toEqual({
+ ok: true,
+ });
+ expect(blank.mark).toHaveBeenCalledWith('inbox', undefined, 1);
+ expect(blank.broadcast).toHaveBeenCalledWith({ ghostId: 'inbox', unread: true, at: 1 });
+ expect(broadcast).toHaveBeenCalled();
+ });
+
+ it('净化后的长度才是判超限的依据(不许拿控制字符注水绕过上限)', () => {
+ const { slot } = makeSlot(fakeGhost(), { now: () => 1 });
+ const padded = 'x'.repeat(GHOST_BADGE_SUMMARY_MAX_CHARS) + '\u0000'.repeat(50);
+ expect(slot.handleBadge('inbox', { unread: true, summary: padded })).toEqual({ ok: true });
+ });
+
+ it('限速只挡点亮方向:连点被拒,熄灭永远放行', () => {
+ let now = 1_000;
+ const { slot, mark, clear } = makeSlot(fakeGhost(), { now: () => now });
+ expect(slot.handleBadge('inbox', { unread: true })).toEqual({ ok: true });
+ now += GHOST_BADGE_MIN_INTERVAL_MS - 1;
+ expect(slot.handleBadge('inbox', { unread: true })).toMatchObject({ ok: false });
+ expect(mark).toHaveBeenCalledTimes(1);
+ // 关键:熄灭是降级动作,被限速会留下一颗清不掉的死点。
+ expect(slot.handleBadge('inbox', { unread: false })).toEqual({ ok: true });
+ expect(clear).toHaveBeenCalledTimes(1);
+ // 过了窗口再点亮放行。
+ now += 1;
+ expect(slot.handleBadge('inbox', { unread: true })).toEqual({ ok: true });
+ expect(mark).toHaveBeenCalledTimes(2);
+ });
+
+ it('熄灭:本来就没亮时幂等成功且不广播(免掉每次开面板刷一轮全窗口推送)', () => {
+ const { slot, broadcast } = makeSlot(fakeGhost(), { clear: () => false });
+ expect(slot.handleBadge('inbox', { unread: false })).toEqual({ ok: true });
+ expect(broadcast).not.toHaveBeenCalled();
+ });
+
+ it('落盘失败:不广播、不记限速账,如实回失败 —— 免得留下一颗清不掉的点', () => {
+ const { slot, broadcast } = makeSlot(fakeGhost(), { mark: () => false, now: () => 1_000 });
+ const r = slot.handleBadge('inbox', { unread: true, summary: '新内容' });
+ expect(r).toMatchObject({ ok: false });
+ // 广播了就会在 renderer 留下账本里根本不存在的点,而熄灭路径查不到记录
+ // → 不广播 → 那颗点再也清不掉。
+ expect(broadcast).not.toHaveBeenCalled();
+ });
+
+ it('落盘失败不占限速额度:作者重试不该被自己上一条挡住', () => {
+ let now = 1_000;
+ let ok = false;
+ const { slot, broadcast } = makeSlot(fakeGhost(), { mark: () => ok, now: () => now });
+ expect(slot.handleBadge('inbox', { unread: true })).toMatchObject({ ok: false });
+ ok = true;
+ now += 1; // 远小于最小间隔
+ expect(slot.handleBadge('inbox', { unread: true })).toEqual({ ok: true });
+ expect(broadcast).toHaveBeenCalledTimes(1);
+ });
+
+ it('forget 抹掉限速记账:重装后第一条不被上一世的时刻挡住', () => {
+ let now = 1_000;
+ const { slot, mark } = makeSlot(fakeGhost(), { now: () => now });
+ expect(slot.handleBadge('inbox', { unread: true })).toEqual({ ok: true });
+ slot.forget('inbox');
+ now += 1; // 远小于最小间隔
+ expect(slot.handleBadge('inbox', { unread: true })).toEqual({ ok: true });
+ expect(mark).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts
new file mode 100644
index 0000000000..6f8a584049
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts
@@ -0,0 +1,83 @@
+/**
+ * ghostUnreadProjection.test.ts — 未读"该不该显示 / 该不该清"的判据。
+ * 覆盖:资格审(notify 槽 + badge 声明)、停用只停投影不删记录、能力撤销要清、
+ * 以及空清单不误清(启动早期 / 账号切换窗口的 manager 空表)。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ ghostDeclaresBadge,
+ isGhostUnreadProjectable,
+ selectRevokedGhostUnreadIds,
+} from '../ghostUnreadProjection';
+import type { InstalledGhost } from '../../../shared/ghost';
+
+function ghost(
+ id: string,
+ opts: { enabled?: boolean; slots?: string[]; badge?: boolean } = {},
+): InstalledGhost {
+ const badge = opts.badge ?? true;
+ return {
+ manifest: {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: badge ? [...(opts.slots ?? ['panel', 'notify']), 'badge'] : (opts.slots ?? ['panel', 'notify']),
+
+ },
+ dir: `/fake/${id}`,
+ enabled: opts.enabled ?? true,
+ } as InstalledGhost;
+}
+
+describe('ghostUnreadProjection', () => {
+ it('资格只看 badge 卡槽:与 notify 槽无关,也与启用与否无关', () => {
+ expect(ghostDeclaresBadge(ghost('a'))).toBe(true);
+ expect(ghostDeclaresBadge(ghost('a', { enabled: false }))).toBe(true);
+ expect(ghostDeclaresBadge(ghost('a', { badge: false }))).toBe(false);
+ // 没有 notify 槽照样算数——绿点与 toast 是并列的两档权限。
+ expect(ghostDeclaresBadge(ghost('a', { slots: ['panel'] }))).toBe(true);
+ expect(ghostDeclaresBadge(null)).toBe(false);
+ });
+
+ it('投影 = 资格 + 已启用 —— 沉睡的意识不显示点(但记录另说)', () => {
+ expect(isGhostUnreadProjectable(ghost('a'))).toBe(true);
+ expect(isGhostUnreadProjectable(ghost('a', { enabled: false }))).toBe(false);
+ expect(isGhostUnreadProjectable(ghost('a', { badge: false }))).toBe(false);
+ expect(isGhostUnreadProjectable(undefined)).toBe(false);
+ });
+
+ it('停用**不**进撤销名单:记录保留,唤醒后那颗点要回来', () => {
+ const entries = [{ ghostId: 'a' }];
+ expect(selectRevokedGhostUnreadIds(entries, [ghost('a', { enabled: false })])).toEqual([]);
+ });
+
+ it('能力撤销进撤销名单:更新后不再声明 badge / 包已卸载', () => {
+ const entries = [{ ghostId: 'revoked' }, { ghostId: 'noslot' }, { ghostId: 'gone' }, { ghostId: 'ok' }];
+ const ids = selectRevokedGhostUnreadIds(entries, [
+ ghost('revoked', { badge: false }),
+ // 只丢了 notify 槽但 badge 还在 → **不算**撤销(两档权限彼此独立)。
+ ghost('noslot', { slots: ['panel'] }),
+ ghost('ok'),
+ ]);
+ expect(ids.sort()).toEqual(['gone', 'revoked']);
+ });
+
+ it('**非权威**空清单不当成"全都撤销了" —— 启动早期 / 账号切换窗口的空表不许误清', () => {
+ expect(selectRevokedGhostUnreadIds([{ ghostId: 'a' }], [])).toEqual([]);
+ expect(selectRevokedGhostUnreadIds([], [ghost('a')])).toEqual([]);
+ });
+
+ it('**权威**空清单必须清孤儿 —— 否则同 id 重装时旧角标会凭空复活', () => {
+ // 卸掉最后一个插件后 manager.list() 就是空表,而且是刚扫完的事实。
+ // 不清的话账本里那条永远留着,用户重装同 id 插件时那颗旧点直接亮回来。
+ expect(selectRevokedGhostUnreadIds([{ ghostId: 'a' }], [], true)).toEqual(['a']);
+ // 权威但非空:照旧只清不再声明能力的那些。
+ expect(selectRevokedGhostUnreadIds([{ ghostId: 'a' }, { ghostId: 'b' }], [ghost('b')], true))
+ .toEqual(['a']);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadStore.test.ts
new file mode 100644
index 0000000000..cda947f47f
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadStore.test.ts
@@ -0,0 +1,93 @@
+/**
+ * ghostUnreadStore.test.ts — 未读账本的落盘形状归一(纯函数,不碰 electron-store)。
+ * 覆盖:非法 id / 非法时刻整条丢弃、坏 summary 只丢文案不丢点、最新在前、上限截断。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyGhostUnreadMark,
+ isStaleGhostUnreadClear,
+ normalizeGhostUnreadEntries,
+} from '../ghostUnreadStore';
+import { GHOST_BADGE_SUMMARY_MAX_CHARS } from '../../../shared/ghost';
+
+describe('ghostUnreadStore · normalizeGhostUnreadEntries', () => {
+ it('丢掉非法 id 与非法时刻,保留合法条目并按最新在前排序', () => {
+ expect(
+ normalizeGhostUnreadEntries({
+ 'cindy-github': { summary: '2 条新 PR', at: 200 },
+ 'bad id': { summary: 'x', at: 300 },
+ 'xd-mivo': { at: 100 },
+ 'no-time': { summary: 'x' },
+ 'bad-time': { at: -1 },
+ 'nan-time': { at: Number.NaN },
+ }),
+ ).toEqual([
+ { ghostId: 'cindy-github', summary: '2 条新 PR', at: 200 },
+ { ghostId: 'xd-mivo', at: 100 },
+ ]);
+ });
+
+ it('坏 summary 只丢文案不丢点 —— 角标是"有新内容"这条事实,不该被一段坏文案连坐', () => {
+ expect(
+ normalizeGhostUnreadEntries({
+ 'a-plugin': { summary: 42, at: 10 },
+ 'b-plugin': { summary: 'x'.repeat(GHOST_BADGE_SUMMARY_MAX_CHARS + 1), at: 9 },
+ 'c-plugin': { summary: '', at: 8 },
+ }),
+ ).toEqual([
+ { ghostId: 'a-plugin', at: 10 },
+ { ghostId: 'b-plugin', at: 9 },
+ { ghostId: 'c-plugin', at: 8 },
+ ]);
+ });
+
+ it('非对象输入(损坏配置 / 老格式)一律降级成空,不阻断插件页首屏', () => {
+ expect(normalizeGhostUnreadEntries(null)).toEqual([]);
+ expect(normalizeGhostUnreadEntries(['a'])).toEqual([]);
+ expect(normalizeGhostUnreadEntries('nope')).toEqual([]);
+ expect(normalizeGhostUnreadEntries({ 'a-plugin': 'nope' })).toEqual([]);
+ });
+
+ it('applyGhostUnreadMark:同 id 覆盖不堆叠,最新在前', () => {
+ const r = applyGhostUnreadMark(
+ [
+ { ghostId: 'a', summary: '旧', at: 10 },
+ { ghostId: 'b', at: 20 },
+ ],
+ { ghostId: 'a', summary: '新', at: 30 },
+ );
+ expect(r.entries).toEqual([
+ { ghostId: 'a', summary: '新', at: 30 },
+ { ghostId: 'b', at: 20 },
+ ]);
+ expect(r.evicted).toEqual([]);
+ });
+
+ it('applyGhostUnreadMark:触到上限时**如实报出被挤掉的 id** —— 不报的话 renderer 会留着一颗账本里已经没有的点', () => {
+ const current = Array.from({ length: 3 }, (_, i) => ({ ghostId: `p-${i}`, at: i + 1 }));
+ const r = applyGhostUnreadMark(current, { ghostId: 'newcomer', at: 99 }, 3);
+ expect(r.entries.map((e) => e.ghostId)).toEqual(['newcomer', 'p-2', 'p-1']);
+ // 最老的那条被挤出账本,调用方必须据此补一条 unread:false 广播。
+ expect(r.evicted).toEqual(['p-0']);
+ });
+
+ it('条件删除的判据:账本比"看到的那条"新时不得删', () => {
+ // clearGhostUnread 的落盘那层要 electron-store,这里直接验判据本身:
+ // renderer 清除请求与插件新点亮走两条独立 IPC,「新点亮先到、旧清除后到」
+ // 时,无条件删会把用户还没看到的新摘要抹掉(codex review)。
+ expect(isStaleGhostUnreadClear(20, 10)).toBe(true); // 账本更新 → 跳过
+ expect(isStaleGhostUnreadClear(10, 10)).toBe(false); // 就是看到的那条 → 删
+ expect(isStaleGhostUnreadClear(5, 10)).toBe(false); // 账本更旧 → 删
+ expect(isStaleGhostUnreadClear(20, undefined)).toBe(false); // 主机侧无条件熄灭
+ });
+
+ it('截断到上限(未读是"当前还亮着的",不是历史流水)', () => {
+ const raw: Record<string, { at: number }> = {};
+ for (let i = 0; i < 260; i += 1) raw[`plugin-${i}`] = { at: i + 1 };
+ const entries = normalizeGhostUnreadEntries(raw);
+ expect(entries).toHaveLength(200);
+ expect(entries[0]).toEqual({ ghostId: 'plugin-259', at: 260 });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/badgeSlot.ts b/apps/desktop/src/main/cindy-brain/badgeSlot.ts
new file mode 100644
index 0000000000..1ae228d474
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/badgeSlot.ts
@@ -0,0 +1,135 @@
+/**
+ * badgeSlot.ts — 未读角标槽(badge 槽,2026-08-03)。
+ * ---------------------------------------------------------------------------
+ * 意识经管子上行 `{type:'badge', unread, summary?}`,请主机点亮/熄灭它在插件
+ * 入口与插件卡上的**未读绿点**。设计边界(与 notify 同一信任模型):
+ *
+ * - 资格审只看 `badge` 卡槽——它与 `notify` 卡槽**并列**,不要求也不捆绑
+ * notify(绿点比 toast 克制,只想点绿点的意识不该被迫连"能弹全屏顶部提示"
+ * 一起申请)。装入时 validateGhostManifest 已强制 badge 必须同时声明 panel,
+ * 这里不重复判;`slots` 是硬白名单,老包不可能带这个槽,天然拒绝;
+ * - 意识只供**纯文本** summary:与 notify 共用 sanitizeGhostNoticeText 剥控制
+ * 字符,换行坍缩成空格(摘要占卡片一行,换行没有正当用途),超限拒收——
+ * 不静默截断,作者需要知道自己超了;
+ * - 点的颜色/位置/身份头全由主机画,意识改不了别人的角标(ghostId 由沙箱
+ * 绑定,不看载荷自报);
+ * - 限速只挡**点亮**方向:GHOST_BADGE_MIN_INTERVAL_MS。熄灭是降级动作,
+ * 被限速会留下一颗清不掉的死点,反而更糟。
+ *
+ * 处理结果永不 reject——一切失败折叠成 { ok:false, message }(同 notify 纪律)。
+ * 依赖注入(规则 14):取意识/落盘/广播/时钟全部经 deps,单测直测。
+ */
+
+import {
+ GHOST_BADGE_MIN_INTERVAL_MS,
+ GHOST_BADGE_SUMMARY_MAX_CHARS,
+ type GhostPipeBadgeResult,
+ type InstalledGhost,
+} from '../../shared/ghost.js';
+import { sanitizeGhostNoticeText } from './notifySlot.js';
+
+/** 推给 renderer 的角标载荷(身份由主机按已装清单认,不信意识自报)。 */
+export interface GhostBadgePush {
+ ghostId: string;
+ unread: boolean;
+ /** 未读摘要(已净化限长;unread:false 或意识没给时缺省)。 */
+ summary?: string;
+ /** 点亮时刻(epoch ms;unread:false 时缺省)。 */
+ at?: number;
+}
+
+export interface BadgeSlotDeps {
+ getGhost(id: string): InstalledGhost | null;
+ /**
+ * 落盘点亮(账本按 owner 隔离,见 ghostUnreadStore)。
+ * 返回 false = **没写进去**(只读磁盘 / 磁盘满 / 配置损坏)。此时不得广播
+ * 点亮:renderer 会留下一颗账本里根本不存在的点,而后续的熄灭路径查不到
+ * 记录 → 不广播 → 那颗点再也清不掉(codex review)。
+ */
+ mark(ghostId: string, summary: string | undefined, at: number): boolean;
+ /** 落盘熄灭;返回 false = 本来就没亮(调用方据此免掉一次无意义广播)。 */
+ clear(ghostId: string): boolean;
+ /** 把角标变化推给全部宿主窗口。 */
+ broadcast(payload: GhostBadgePush): void;
+ now?(): number;
+ log?: {
+ info: (msg: string, meta?: Record<string, unknown>) => void;
+ warn: (msg: string, meta?: Record<string, unknown>) => void;
+ };
+}
+
+export class GhostBadgeSlot {
+ /** 每意识最近一次成功**点亮**的时刻(限速账本;熄灭不记账、不受限)。 */
+ private readonly lastMarkedAt = new Map<string, number>();
+
+ constructor(private readonly deps: BadgeSlotDeps) {}
+
+ /** 处理一条 badge(ghost-pipe:send 的 invoke 返回值即本结果)。 */
+ handleBadge(ghostId: string, payload: unknown): GhostPipeBadgeResult {
+ const p = payload as { unread?: unknown; summary?: unknown };
+
+ const ghost = this.deps.getGhost(ghostId);
+ if (!ghost || !ghost.enabled) {
+ return { ok: false, message: '意识不在可用状态' };
+ }
+ if (!ghost.manifest.slots?.includes('badge')) {
+ return {
+ ok: false,
+ message: '本意识未声明 badge 卡槽,无权点亮未读角标(需在 ghost.json 的 slots 里加 "badge" 并重新装入)',
+ };
+ }
+
+ if (typeof p?.unread !== 'boolean') {
+ return { ok: false, message: 'unread 必须是布尔值' };
+ }
+
+ // 熄灭:不限速、不校验 summary(按协议忽略),没亮着就静默幂等成功。
+ if (!p.unread) {
+ const changed = this.deps.clear(ghostId);
+ if (changed) {
+ this.deps.broadcast({ ghostId, unread: false });
+ this.deps.log?.info('ghost badge cleared by plugin', { ghostId });
+ }
+ return { ok: true };
+ }
+
+ let summary: string | undefined;
+ if (p.summary !== undefined) {
+ if (typeof p.summary !== 'string') {
+ return { ok: false, message: 'summary 必须是字符串' };
+ }
+ // 先净化再验超限(防用控制字符注水绕过上限);换行坍缩成空格。
+ const cleaned = sanitizeGhostNoticeText(p.summary).replace(/\n+/g, ' ').trim();
+ if (cleaned.length > GHOST_BADGE_SUMMARY_MAX_CHARS) {
+ return { ok: false, message: `summary 过长(上限 ${GHOST_BADGE_SUMMARY_MAX_CHARS} 字符)` };
+ }
+ // 净化后为空 = 作者给的全是空白/控制字符,按"没给摘要"处理,不因此拒点。
+ if (cleaned.length > 0) summary = cleaned;
+ }
+
+ const now = this.deps.now?.() ?? Date.now();
+ const last = this.lastMarkedAt.get(ghostId);
+ if (last !== undefined && now - last < GHOST_BADGE_MIN_INTERVAL_MS) {
+ return {
+ ok: false,
+ message: `角标上报过于频繁(同一意识最小间隔 ${GHOST_BADGE_MIN_INTERVAL_MS} 毫秒),本条已丢弃`,
+ };
+ }
+ if (!this.deps.mark(ghostId, summary, now)) {
+ // 落盘失败:不广播、不记限速账(否则作者重试还会被自己上一条挡住),
+ // 如实回结构化失败让意识知道这条没生效。
+ this.deps.log?.warn('ghost badge dropped: ledger write failed', { ghostId });
+ return { ok: false, message: '未读角标写入失败(主机侧存储不可用),本条未生效' };
+ }
+ this.lastMarkedAt.set(ghostId, now);
+
+ this.deps.broadcast({ ghostId, unread: true, ...(summary ? { summary } : {}), at: now });
+ this.deps.log?.info('ghost badge marked', { ghostId, hasSummary: summary !== undefined });
+ return { ok: true };
+ }
+
+ /** 卸载/停用时抹掉限速记账(重装后第一条不该被上一世的时刻挡住)。 */
+ forget(ghostId: string): void {
+ this.lastMarkedAt.delete(ghostId);
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index e90dab713a..f0d484f14b 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -559,7 +559,10 @@ async function buildGhostPackage(
*/
expectedRealDir?: string,
): Promise<
- | { ok: true; buf: Buffer; manifest: GhostManifest }
+ // manifestRaw = 校验前的原始清单对象。作者期严格校验(见 firstGhostAuthoringIssue)
+ // 需要它来看见「作者写了但被校验器按未登记字段忽略掉」的内容——校验后的
+ // manifest 里那些字段已经不见了,只看它无从判断。
+ | { ok: true; buf: Buffer; manifest: GhostManifest; manifestRaw: Record<string, unknown> }
| Exclude<ForgePackResult, { ok: true }>
> {
try {
@@ -781,7 +784,12 @@ async function buildGhostPackage(
message: `压缩包体积超上限(${maxCindyBytes} 字节)`,
};
}
- return { ok: true, buf, manifest };
+ return {
+ ok: true,
+ buf,
+ manifest,
+ manifestRaw: (manifestRaw ?? {}) as Record<string, unknown>,
+ };
} catch (err) {
return {
ok: false,
@@ -799,6 +807,10 @@ async function buildGhostPackage(
export async function packGhostDir(dir: string): Promise<ForgePackResult> {
const built = await buildGhostPackage(dir);
if (!built.ok) return built;
+ const authoringIssue = firstGhostAuthoringIssue(built.manifestRaw);
+ if (authoringIssue) {
+ return { ok: false, errorCode: 'MANIFEST_INVALID', message: authoringIssue };
+ }
// 产物跟源码住一起(2026-07 Lizi 定案:拿取直观);文件收集在写盘之前完成
// + shouldSkip 跳过 *.cindy,自身产物不会进包;同名覆盖。
const cindyPath = path.join(dir, `${built.manifest.id}-${built.manifest.version}.cindy`);
@@ -814,6 +826,32 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {
return { ok: true, cindyPath, manifest: built.manifest };
}
+/**
+ * **作者期严格校验**(只在 packGhostDir 这条打包出口上跑,不进任何安装路径)。
+ *
+ * 未读角标现在由 `badge` **卡槽**声明。槽名走硬白名单,写错直接被
+ * validateGhostManifest 拒掉,所以本身不需要额外把关。真正会静默失败的是另一种:
+ * 作者(或 agent)照着**早期示例**写成顶层 `notify: { badge: ... }` —— 那个字段
+ * 从来没被登记过,校验器一律忽略,于是包打出来了、装进去了、运行期每次发 badge
+ * 都被拒,作者却以为自己声明过(codex review)。
+ *
+ * 这里在打包期把它变成一条可行动的报错。放在 packGhostDir 而不是共用校验器或
+ * packGhostDirToFile:后两者会作用到**已在用户机器上**的清单与自定义市场安装管道,
+ * 给它们加新拒绝面就会踩存量红线;而作者正在打包的这一份没有存量问题。
+ */
+function firstGhostAuthoringIssue(raw: Record<string, unknown>): string | null {
+ const notifyRaw = raw.notify;
+ if (
+ notifyRaw !== null &&
+ typeof notifyRaw === 'object' &&
+ !Array.isArray(notifyRaw) &&
+ 'badge' in (notifyRaw as Record<string, unknown>)
+ ) {
+ return '未读角标已改为独立卡槽:请把 notify.badge 删掉,改成在 slots 里声明 "badge"(并同时声明 "panel")';
+ }
+ return null;
+}
+
/**
* 打包到调用方指定的绝对路径。自定义市场安装管道用:市场克隆缓存是只读事实,
* 产物落到临时目录,装完即删。校验与打包规则与 packGhostDir 完全一致。
@@ -877,7 +915,8 @@ ghost_forge_pack 打包 → 用户在弹窗上确认装入。**
显式点名(推荐,§2)。
- **启动模式**:on-demand 按需拉起(缺省,推荐)/ resident 常驻(仅订阅型、要秒响应
的场景,§2)。
-- **后台能力**:要不要旁听事件(subscribe 槽,§4.6)、发系统提示(notify 槽,§4.9)、
+- **后台能力**:要不要旁听事件(subscribe 槽,§4.6)、发系统提示(notify 槽,§4.9)、留一条持久
+ 未读绿点(badge 槽,§4.9.1)、
动手前弹确认框征求同意(confirm 槽,§4.18)。
- **联网与凭证**:要不要 network 槽白名单联网(§4.7);要用户填 key 就需要 setup
就绪声明与 settingsHtml 设置区(§4.7、§4.8)。
@@ -1028,7 +1067,8 @@ node secretBindings key、setup kv key——都不能使用 \`__proto__\`、\`co
当前 Agent 开始一个普通用户回合,或派活取回结果,见 §4.11 / §4.11.1)、\`panel\`(常驻
面板)、\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话
事件 + 拦截用户消息,见 §4.6)、\`network\`(访问自带服务的域名白名单 HTTP,主机代发,
-见 §4.7)、\`notify\`(弹系统轻提示,主机画壳带你的身份头,见 §4.9)、\`confirm\`(弹主机
+见 §4.7)、\`notify\`(弹系统轻提示,主机画壳带你的身份头,见 §4.9)、\`badge\`
+(在插件入口留一颗持久的未读绿点,与 notify 并列、互不为前置,见 §4.9.1)、\`confirm\`(弹主机
同款确认框征求用户同意并拿回真实点击,见 §4.18)、\`fs\`(请主机
代写文件:私有数据目录/会话工作目录/过户目录三档,见 §4.10)、\`node\`(运行随包
Node 工作进程或 stdio MCP,见 §4.12)、\`session-context\`(派活时主机把当前会话的
@@ -2266,6 +2306,43 @@ const r = await cindy.send({ type: 'notify', text: '视频已生成,点面板查
给你,用 §4.18 的 confirm 槽(主机同款确认框);要在聊天流里放按钮用交互卡
(§4.5 的 data-ghost-action)。
+### 4.9.1 未读角标(badge 槽 —— 与 notify 槽并列的独立一档)
+
+toast 是"说一句就走",错过就没了。要留下一条**持久**的"我这儿有新内容"——
+用户没去看就一直亮着——在身份卡里加一档:
+
+\`\`\`json
+{ "slots": ["panel", "badge"] }
+\`\`\`
+
+\`badge\` 与 \`notify\` 是**并列的两档权限**,谁也不是谁的前置。只想安静点个绿点就
+别申请 \`notify\` 槽——多要一档"能弹全屏顶部提示"的权限,用户装的时候只会更犹豫。
+两个都要就两个都声明。
+
+\`\`\`js
+// 有新内容:点亮侧栏插件入口与自己卡片上的绿点,并把摘要显示在卡片简介位
+await cindy.send({ type: 'badge', unread: true, summary: '3 条新工单待处理' });
+// 自己清零(比如插件内已读)
+await cindy.send({ type: 'badge', unread: false });
+\`\`\`
+
+规则(都由主机强制):
+
+- **必须同时声明 \`panel\`**,装入时校验,漏了整个包装不进去。这是本档唯一的门槛:
+ 未读点承诺"点开能看到内容",没有面板的意识点亮了也无处可点,给了就是骗点击;
+- 装入确认框里**单列一项**权限,已装插件加这一档会触发扩权重新确认——常驻的
+ 注意力入口值这一次打断;
+- \`summary\`(可选):**纯文本**,≤80 字符,换行会被坍缩成空格,超长直接拒
+ (\`ok:false\`,不静默截断);净化后为空按"没给摘要"处理,点照亮;
+- **限速**只挡点亮方向:同一意识两次点亮最小间隔 500 毫秒;\`unread:false\` 的
+ 清零不限速(降级动作被拦会留下一颗清不掉的死点);
+- **用户打开你的面板 = 已读**,主机自动清零(三种面板宿主都算:插件页页签、
+ 停靠态、独立窗口);
+- **沉睡只停显示、不算已读**:用户唤醒你之后那颗点会回来。卸载、或更新后身份卡
+ 不再声明 badge,既有未读则被清除(权限撤了就不再兑现);
+- 角标**不出声、不震动、不进系统通知中心**——它只是屏幕内的一颗点;
+- 状态跨重启存活,按账号隔离(账号 A 的未读不会在账号 B 的界面上亮)。
+
## 4.10 写文件(fs 槽)
声明 \`"slots": [..., "fs"]\` 后,电子脑可以请主机代写文件(创建/覆盖)。沙箱本身
diff --git a/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts b/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts
new file mode 100644
index 0000000000..85e359b198
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts
@@ -0,0 +1,52 @@
+/**
+ * ghostUnreadProjection.ts — 未读角标"该不该显示"的判据(纯函数,可直测)。
+ * ---------------------------------------------------------------------------
+ * 账本(ghostUnreadStore)记的是**事实**:哪个意识点亮过、摘要是什么。
+ * 能不能投影到界面上是另一回事,判据集中在这里,免得散落在 index.ts 的
+ * 各条广播路径上各写一遍(那正是"同一规则只实现在其中一处"的老毛病)。
+ *
+ * 两条规则:
+ * - **停用只停投影、不删记录** —— 沉睡是"先别烦我",不是"这条我读过了";
+ * 唤醒后那颗点要回来。
+ * - **能力撤了就清记录** —— 更新后身份卡不再声明 `badge` 卡槽,既有未读必须
+ * 清除;权限收回了还留一颗点 = 继续兑现已撤销的能力。
+ */
+
+import type { InstalledGhost } from '../../shared/ghost.js';
+
+/**
+ * 该意识当前是否还持有未读角标能力(资格,与启用与否无关)。
+ * 只看 `badge` 卡槽:它与 `notify` 卡槽是并列的两档权限,不互为前置。
+ */
+export function ghostDeclaresBadge(ghost: InstalledGhost | null | undefined): boolean {
+ return ghost?.manifest.slots?.includes('badge') === true;
+}
+
+/** 该意识的未读现在该不该出现在界面上(资格 + 已启用)。 */
+export function isGhostUnreadProjectable(ghost: InstalledGhost | null | undefined): boolean {
+ return ghostDeclaresBadge(ghost) && ghost?.enabled === true;
+}
+
+/**
+ * 从已装清单里挑出**能力已撤销**的未读条目(应当整条清除的那些)。
+ * 停用中的意识不在结果里——它只是不投影,记录要留着。
+ *
+ * `rosterAuthoritative` 区分两种「空清单」,它们语义完全相反:
+ * - **false(缺省)= 还不知道**:启动早期、账号切换窗口里 manager 可能返回空表
+ * 或旧表,按"全都撤销了"理解会把用户的未读整批误清。这时空表一律不动。
+ * - **true = 权威地确认过**:调用方刚做完一次完整扫描(装入 / 更新 / 卸载 /
+ * 内置对账),空表就是事实。此时必须清掉孤儿记录——否则用户卸掉最后一个插件
+ * 后账本里那条永远留着,同 id 重装时旧角标会凭空复活(codex review)。
+ */
+export function selectRevokedGhostUnreadIds(
+ entries: readonly { ghostId: string }[],
+ ghosts: readonly InstalledGhost[],
+ rosterAuthoritative = false,
+): string[] {
+ if (entries.length === 0) return [];
+ if (ghosts.length === 0 && !rosterAuthoritative) return [];
+ const stillDeclared = new Set(
+ ghosts.filter(ghostDeclaresBadge).map((ghost) => ghost.manifest.id),
+ );
+ return entries.map((entry) => entry.ghostId).filter((id) => !stillDeclared.has(id));
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostUnreadStore.ts b/apps/desktop/src/main/cindy-brain/ghostUnreadStore.ts
new file mode 100644
index 0000000000..e03ce211d8
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostUnreadStore.ts
@@ -0,0 +1,163 @@
+/**
+ * ghostUnreadStore.ts — 意识未读角标的落盘账本(badge 槽,2026-08-03)。
+ * ---------------------------------------------------------------------------
+ * 未读点必须**跨重启存活**:意识在后台点亮了角标,用户关掉 app 再打开,那条
+ * 「有新内容」不该凭空消失(否则未读机制退化成一次性 toast,与 notify 无异)。
+ *
+ * 归属:与 ghostRecentUsageStore 同款,落在 `ownerScopedUserDataPath()` 下,
+ * 天然按账号隔离——账号 A 的未读不会在账号 B 的界面上点亮。
+ *
+ * 存的是**主机自己判定过的事实**:summary 在写入前已由 badgeSlot 净化限长,
+ * 这里只做形状归一(损坏配置不阻断插件页首屏,读失败一律降级成"无未读")。
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ */
+
+import Store from 'electron-store';
+
+import { GHOST_BADGE_SUMMARY_MAX_CHARS, isValidGhostId } from '../../shared/ghost.js';
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+
+/** 一条未读记录(ghostId → 最近一次点亮的摘要与时刻)。 */
+export interface GhostUnreadEntry {
+ ghostId: string;
+ /** 意识给的一句话摘要(已净化限长;缺省 = 只点亮不带文案)。 */
+ summary?: string;
+ /** 点亮时刻(epoch ms;插件卡按它排"最新一条")。 */
+ at: number;
+}
+
+interface GhostUnreadShape {
+ entries: Record<string, { summary?: string; at: number }>;
+}
+
+/** 账本条目上限:未读是"当前还亮着的",不是历史流水,不该无限长。 */
+const MAX_UNREAD_ENTRIES = 200;
+
+let storeInstance: Store<GhostUnreadShape> | null = null;
+let storePath: string | null = null;
+
+function getStore(): Store<GhostUnreadShape> {
+ const currentPath = ownerScopedUserDataPath();
+ if (!storeInstance || storePath !== currentPath) {
+ storeInstance = new Store<GhostUnreadShape>({
+ name: 'ghost-unread',
+ cwd: currentPath,
+ defaults: { entries: {} },
+ schema: { entries: { type: 'object' } },
+ clearInvalidConfig: true,
+ });
+ storePath = currentPath;
+ }
+ return storeInstance;
+}
+
+/**
+ * 落盘形状归一:非法 id / 非法时刻整条丢弃,summary 非字符串或超限时**只丢
+ * summary 不丢点**——角标本身是"有新内容"这条事实,不该被一段坏文案连坐。
+ * 按 at 倒序截断到上限。
+ */
+export function normalizeGhostUnreadEntries(value: unknown): GhostUnreadEntry[] {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return [];
+ const entries: GhostUnreadEntry[] = [];
+ for (const [ghostId, raw] of Object.entries(value as Record<string, unknown>)) {
+ if (!isValidGhostId(ghostId)) continue;
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) continue;
+ const at = (raw as { at?: unknown }).at;
+ if (typeof at !== 'number' || !Number.isFinite(at) || at <= 0) continue;
+ const summary = (raw as { summary?: unknown }).summary;
+ const keepSummary =
+ typeof summary === 'string' &&
+ summary.length > 0 &&
+ summary.length <= GHOST_BADGE_SUMMARY_MAX_CHARS;
+ entries.push({ ghostId, ...(keepSummary ? { summary: summary as string } : {}), at });
+ }
+ entries.sort((a, b) => b.at - a.at);
+ return entries.slice(0, MAX_UNREAD_ENTRIES);
+}
+
+function persist(entries: GhostUnreadEntry[]): void {
+ const shape: GhostUnreadShape['entries'] = {};
+ for (const entry of entries) {
+ shape[entry.ghostId] = { ...(entry.summary ? { summary: entry.summary } : {}), at: entry.at };
+ }
+ getStore().set('entries', shape);
+}
+
+/**
+ * 这次清除是否**陈旧**(账本里的记录比请求方看到的那条新)。抽成导出的纯函数
+ * 是为了能直测:clearGhostUnread 本身要 electron-store,单测碰不到。
+ */
+export function isStaleGhostUnreadClear(entryAt: number, seenAt?: number): boolean {
+ return seenAt !== undefined && entryAt > seenAt;
+}
+
+/** 当前还亮着的全部未读(最新在前)。 */
+export function loadGhostUnread(): GhostUnreadEntry[] {
+ return normalizeGhostUnreadEntries(getStore().get('entries', {}));
+}
+
+/** 某意识当前的未读记录(没有则 null)。停用后重新启用时靠它把点找回来。 */
+export function readGhostUnread(ghostId: string): GhostUnreadEntry | null {
+ return loadGhostUnread().find((entry) => entry.ghostId === ghostId) ?? null;
+}
+
+/**
+ * 点亮一条未读(同一意识重复点亮 = 覆盖摘要并刷新时刻,不堆叠——角标是
+ * 幂等的"有/无",不是消息队列)。
+ *
+ * 返回 `evicted` = 因触到上限而被挤掉的 ghostId。调用方**必须**为它们补一条
+ * `unread:false` 广播:只推新点亮那一条的话,renderer 的表里会留着已被账本
+ * 删掉的条目,那颗点和聚合入口点会一直亮到重启或下一次全量快照(codex review)。
+ */
+export function markGhostUnread(
+ ghostId: string,
+ summary: string | undefined,
+ at: number,
+): { entries: GhostUnreadEntry[]; evicted: string[] } {
+ const result = applyGhostUnreadMark(loadGhostUnread(), {
+ ghostId,
+ ...(summary ? { summary } : {}),
+ at,
+ });
+ persist(result.entries);
+ return result;
+}
+
+/**
+ * markGhostUnread 的纯函数内核(抽出来只为可测:落盘那层要 electron-store)。
+ * 同 id 覆盖而不堆叠,按时刻倒序,超出上限的挤出去并如实报给调用方。
+ */
+export function applyGhostUnreadMark(
+ current: GhostUnreadEntry[],
+ entry: GhostUnreadEntry,
+ max = MAX_UNREAD_ENTRIES,
+): { entries: GhostUnreadEntry[]; evicted: string[] } {
+ const sorted = [entry, ...current.filter((candidate) => candidate.ghostId !== entry.ghostId)].sort(
+ (a, b) => b.at - a.at,
+ );
+ return {
+ entries: sorted.slice(0, max),
+ evicted: sorted.slice(max).map((candidate) => candidate.ghostId),
+ };
+}
+
+/**
+ * 熄灭一条未读。返回 null = 没有发生变化(调用方据此免掉一次无意义广播,
+ * 别让"打开面板"每次都刷一轮全窗口推送)。
+ *
+ * `seenAt` = **请求方当时实际看到的那条**的点亮时刻。给了就做条件删除:账本里
+ * 的记录比它新时不动。用户已读是针对他看见的那条内容,而 renderer 的清除请求
+ * 与插件的新点亮走的是两条独立 IPC——"新点亮先到、旧清除后到"的顺序完全可能
+ * 发生,无条件按 ghostId 删会把用户还没看到的新摘要一并抹掉(codex review)。
+ * 不给 seenAt 则是主机侧的无条件熄灭(停用 / 卸载 / 能力撤销),那些场景没有
+ * "看见了哪一条"可言。
+ */
+export function clearGhostUnread(ghostId: string, seenAt?: number): GhostUnreadEntry[] | null {
+ const current = loadGhostUnread();
+ const entry = current.find((candidate) => candidate.ghostId === ghostId);
+ if (!entry) return null;
+ if (isStaleGhostUnreadClear(entry.at, seenAt)) return null;
+ const next = current.filter((candidate) => candidate.ghostId !== ghostId);
+ persist(next);
+ return next;
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index d156df7405..cc2b6760bc 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -13,6 +13,7 @@ import {
GHOST_CARD_HEIGHT_MIN,
GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,
GHOST_NOTIFY_MIN_INTERVAL_MS,
+ diffGhostPermissionItems,
ghostWebviewEntryPaths,
isCindyAccountGhostId,
isOfficialGhostId,
@@ -96,7 +97,11 @@ import { reclaimLoopbackPort } from './portReclaim.js';
import { GhostConnectionManager } from './ghostConnections.js';
import { getResolvedMainLocale, t } from '../i18n.js';
import { reconcileGhostSkillLinks } from './skillSlot.js';
-import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import {
+ assertTrustedAppRendererEvent,
+ isTrustedAppRendererEvent,
+ isTrustedAppRendererWindow,
+} from '../security/trustedAppRenderer.js';
import {
FILO_GOOGLE_GHOST_ID,
FILO_GOOGLE_SECRET_KEY,
@@ -153,6 +158,18 @@ import { GhostPreviewSlot } from './previewSlot.js';
import { GhostWorkspaceSlot, type WorkspaceSessionService } from './workspaceSlot.js';
import type { GhostTrustRegistry } from './ghostSignature.js';
import { GhostNotifySlot, sanitizeGhostNoticeText } from './notifySlot.js';
+import { GhostBadgeSlot } from './badgeSlot.js';
+import {
+ clearGhostUnread,
+ loadGhostUnread,
+ markGhostUnread,
+ readGhostUnread,
+ type GhostUnreadEntry,
+} from './ghostUnreadStore.js';
+import {
+ isGhostUnreadProjectable,
+ selectRevokedGhostUnreadIds,
+} from './ghostUnreadProjection.js';
import { GhostConfirmSlot } from './confirmSlot.js';
import {
getGhostConfirmDialogBridge,
@@ -804,7 +821,8 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {
});
// 播种绕过 manager 写盘,广播由这里补上(renderer 首帧 sendSync 早于对账
// 完成时,靠 ghosts:changed 热更新兜底,多窗口同一套通道)。
- broadcastGhostsChanged(manager.list());
+ // 对账跑完 = 一次完整扫描,清单权威(见 broadcastGhostsChanged 的说明)。
+ broadcastGhostsChanged(manager.list(), true);
// 首装的意识停进布局树(与 installAndDock 同一套停靠逻辑;覆盖更新 id 未变,
// 布局位置天然保留,不动树;回收不动树 —— 与 uninstall 口径一致,位置记录
// 由布局引擎保留)。
@@ -1696,6 +1714,189 @@ export function getGhostNotifySlot(): GhostNotifySlot {
return notifySlotSingleton;
}
+let badgeSlotSingleton: GhostBadgeSlot | null = null;
+
+/** 意识未读角标通道(main → 全窗口 renderer;插件入口与插件卡上的绿点)。 */
+export const GHOST_BADGE_CHANNEL = 'ghosts:badge';
+
+/**
+ * 未读全量快照通道(main → 全窗口 renderer)。逐条的 GHOST_BADGE_CHANNEL 只表达
+ * 增量,**换账号**必须整表替换:未读账本按 owner 分文件(ownerScopedUserDataPath),
+ * 切到账号 B 后 renderer 手上还攥着账号 A 的点和摘要,不推一次快照就是跨账号残留。
+ */
+export const GHOST_UNREAD_SNAPSHOT_CHANNEL = 'ghosts:unread-snapshot';
+
+/**
+ * 未读推送的收口:**只发给可信的 Cindy 自有顶层页面**。
+ *
+ * 载荷里的 summary 是插件正文(工单标题、邮件主题、任务名)。无条件
+ * `getAllWindows().send()` 会把它发给所有窗口,包括已经导航到别处的那些——
+ * 出站推送与入站 IPC 是同一道授权边界,不能只守一边(codex review)。
+ * 判据复用 `isTrustedAppRendererWindow`,与 `ghosts:unread` 同步读那道闸同源。
+ */
+function sendToTrustedAppWindows(channel: string, payload: unknown): void {
+ BrowserWindow.getAllWindows().forEach((window) => {
+ if (window.isDestroyed()) return;
+ if (!isTrustedAppRendererWindow(window)) return;
+ window.webContents.send(channel, payload);
+ });
+}
+
+function broadcastGhostBadge(payload: { ghostId: string; unread: boolean; summary?: string; at?: number }): void {
+ sendToTrustedAppWindows(GHOST_BADGE_CHANNEL, payload);
+}
+
+/**
+ * 推一份当前 owner 的未读全量快照(登录 / 登出 / 换账号后由 onAuthStateChange 调)。
+ * 由 main 主动推而不是让 renderer 自己重读:owner 是否已经切完只有 main 说了算,
+ * renderer 猜时机就可能读到旧账号的账本。读失败按空表推——宁可少一颗点,不可
+ * 把账号 A 的未读留在账号 B 的界面上。
+ */
+function broadcastGhostUnreadSnapshot(): void {
+ const entries = visibleGhostUnread();
+ sendToTrustedAppWindows(GHOST_UNREAD_SNAPSHOT_CHANNEL, { entries });
+}
+
+/**
+ * 可投影的未读 = 账本里还亮着 **且** 意识当前可用且已启用。
+ *
+ * 停用**保留记录、只停投影**(不是删记录):用户把插件按沉睡是"先别烦我",
+ * 不是"这条我读过了";重新启用时那颗点应该回来。已卸载的残留条目也在这里
+ * 被滤掉——包都没了的点用户既点不开也清不掉。
+ * 读失败按空表:宁可少一颗点,不可让损坏的账本挡住插件页首屏。
+ */
+function visibleGhostUnread(): GhostUnreadEntry[] {
+ try {
+ const entries = loadGhostUnread();
+ if (entries.length === 0) return [];
+ // **一次快照建索引**,不要逐条 findAvailableGhost():那个函数每次都调
+ // GhostManager.list(),而 list() 会同步重扫插件目录、重读每份 manifest /
+ // locale / 图标 / 信任文件。账本允许 200 条,逐条查就是 O(未读 × 已装) 次
+ // 磁盘扫描,而本函数服务的是**同步** ghosts:unread(首屏渲染路径),
+ // 足以卡住启动(codex review)。
+ const available = new Map(availableGhosts().map((ghost) => [ghost.manifest.id, ghost]));
+ return entries.filter((entry) => isGhostUnreadProjectable(available.get(entry.ghostId) ?? null));
+ } catch (error) {
+ log.warn('ghost unread 读取失败', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return [];
+ }
+}
+
+/**
+ * 未读角标槽单例(badge 槽):资格审/净化/限速在 GhostBadgeSlot,这里只装配
+ * 取意识、落盘与广播。落盘失败**不吞成静默**——账本写不进去时角标只在本次
+ * 运行期有效,如实记日志,但仍然推给 renderer(用户当下看得见比事后可靠更重要)。
+ */
+export function getGhostBadgeSlot(): GhostBadgeSlot {
+ if (!badgeSlotSingleton) {
+ badgeSlotSingleton = new GhostBadgeSlot({
+ getGhost: findAvailableGhost,
+ mark: (ghostId, summary, at) => {
+ try {
+ // 触到上限被挤掉的条目要补一条熄灭广播,否则 renderer 表里留着账本
+ // 已经删掉的点(卡片与聚合入口一直亮到重启)。
+ for (const evictedId of markGhostUnread(ghostId, summary, at).evicted) {
+ broadcastGhostBadge({ ghostId: evictedId, unread: false });
+ }
+ return true;
+ } catch (error) {
+ // 写不进去就**如实回 false**,由槽决定不广播。此前这里吞掉异常后
+ // 照常广播,renderer 会留下一颗账本里根本不存在的点;而后续熄灭
+ // 路径查不到记录 → 不广播 → 那颗点再也清不掉(codex review)。
+ log.warn('ghost unread 落盘失败', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
+ }
+ },
+ clear: (ghostId) => {
+ try {
+ return clearGhostUnread(ghostId) !== null;
+ } catch (error) {
+ log.warn('ghost unread 清除失败', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ // 落盘清不掉时仍回 true:让广播照发,界面上的点先灭掉,
+ // 否则用户点开了面板却看到点还亮着,属于更可见的错。
+ return true;
+ }
+ },
+ broadcast: broadcastGhostBadge,
+ log,
+ });
+ }
+ return badgeSlotSingleton;
+}
+
+/**
+ * 主机侧熄灭未读(用户打开面板 / 停用 / 卸载)。与意识自发的 badge 熄灭同
+ * 通道同落盘,但不经意识代码、不占限速——判定者是主机。
+ */
+function extinguishGhostUnread(ghostId: string, seenAt?: number): void {
+ try {
+ // null = 没发生变化(本来就没亮,或账本比 seenAt 新)——免掉一轮广播,
+ // 也别把仍然亮着的那条误报成已熄灭。
+ if (clearGhostUnread(ghostId, seenAt) === null) return;
+ } catch (error) {
+ log.warn('ghost unread 清除失败', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ broadcastGhostBadge({ ghostId, unread: false });
+}
+
+/**
+ * 停用:只停投影,**不删记录**——沉睡是"先别烦我",不是"这条我读过了"。
+ * 限速记账一并抹掉,重新唤醒后的第一条不该被上一世的时刻挡住。
+ */
+function suspendGhostUnreadProjection(ghostId: string): void {
+ badgeSlotSingleton?.forget(ghostId);
+ broadcastGhostBadge({ ghostId, unread: false });
+}
+
+/**
+ * 撤销扫尾:插件更新后身份卡不再声明 badge 卡槽时,
+ * 既有未读**立即清除**——权限撤了还留一颗点,等于把已收回的能力继续兑现。
+ * 挂在 broadcastGhostsChanged 上:装入 / 更新 / 卸载 / 对账都从这一处过,
+ * 不用在每条清单变更路径上各补一遍。
+ */
+function sweepRevokedGhostUnread(ghosts: InstalledGhost[], rosterAuthoritative: boolean): void {
+ let entries: GhostUnreadEntry[];
+ try {
+ entries = loadGhostUnread();
+ } catch {
+ return; // 账本读不出来时不做任何猜测,交给下一次变更
+ }
+ for (const id of selectRevokedGhostUnreadIds(entries, ghosts, rosterAuthoritative)) {
+ extinguishGhostUnread(id);
+ }
+}
+
+/** 重新启用:账本里还留着的那颗点要回来(与 suspend 成对)。 */
+function resumeGhostUnreadProjection(ghostId: string): void {
+ let entry: GhostUnreadEntry | null = null;
+ try {
+ entry = readGhostUnread(ghostId);
+ } catch (error) {
+ log.warn('ghost unread 读取失败', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ if (!entry) return;
+ broadcastGhostBadge({
+ ghostId,
+ unread: true,
+ ...(entry.summary ? { summary: entry.summary } : {}),
+ at: entry.at,
+ });
+}
+
let confirmSlotSingleton: GhostConfirmSlot | null = null;
/** 意识确认弹窗通道(main → **单个**窗口;renderer 用主机同款 ConfirmDialog 渲染)。 */
@@ -2958,6 +3159,12 @@ export async function installOrUpdateMarketGhostPackage(
expected: {
ghostId: string;
version: string;
+ /**
+ * 装入确认框实际展示给用户的那份 manifest(来源方给的)。给了就逐项比对:
+ * 包里多出来的权限一律拒装(见 Locked 版里的说明)。两条市场路径都必须给;
+ * 本地 `.cindy` 装入不经此出口,确认框读的就是包本身,没有这层漂移。
+ */
+ reviewedManifest?: GhostManifest;
},
): Promise<InstalledGhost> {
// 卡点:按 ghostId 上锁,覆盖 inspect → 落位整段。服务端与自定义两条市场路径
@@ -2973,6 +3180,7 @@ async function installOrUpdateMarketGhostPackageLocked(
expected: {
ghostId: string;
version: string;
+ reviewedManifest?: GhostManifest;
},
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
@@ -2991,6 +3199,36 @@ async function installOrUpdateMarketGhostPackageLocked(
);
}
requireGhostAvailableForActiveSession(expected.ghostId);
+ /**
+ * 「审阅过的」与「真要装的」权限必须一致(2026-08-03,codex review P1)。
+ *
+ * 装入确认框渲染的是**来源方给的 manifest**(服务端市场 = release manifest,
+ * 自定义市场 = 抓到的 ghost.json),而真正落地的是 `.cindy` 包里的 ghost.json。
+ * 两者本该同一份,但来源方的投影层可能与客户端的清单契约漂移——`cindy-protocol`
+ * 那份平行校验器就已经缺了 `confirm` 槽;新登记的槽(如 `badge`)在它眼里是
+ * 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着
+ * 它装进来,用户**从没审过就多出一个常驻能力面**。
+ *
+ * 这里按权限项逐项比对,包里多出来的一律拒装——不是只挡 badge,是把这一整类
+ * 「来源投影漏字段」的洞一次封死。落在 inspect 之后、任何落地动作之前,所以
+ * 拒绝时磁盘上什么都没动,不需要回滚。
+ */
+ if (expected.reviewedManifest) {
+ const unreviewed = diffGhostPermissionItems(
+ expected.reviewedManifest,
+ inspected.manifest,
+ ).added;
+ if (unreviewed.length > 0) {
+ log.warn('market package declares unreviewed permissions', {
+ ghostId: expected.ghostId,
+ keys: unreviewed.map((item) => item.key),
+ });
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ '下载包申请的权限多于安装确认框展示的内容,已阻止安装(请向插件来源反馈)',
+ );
+ }
+ }
rejectUnauthorizedTokenBroker(inspected.manifest);
const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
@@ -3154,7 +3392,13 @@ async function uninstallGhostAndCleanupLocked(
error: error instanceof Error ? error.message : String(error),
});
}
- broadcastGhostsChanged(manager.list());
+ // 未读随意识一起走:包都没了还留一颗点,用户既点不开也清不掉。
+ // 限速记账一并抹掉,重装后的第一条不该被上一世的时刻挡住。
+ extinguishGhostUnread(id);
+ badgeSlotSingleton?.forget(id);
+ // 卸载刚落地,manager.list() 就是当下的全部事实(哪怕是空表)——标权威,
+ // 好让「卸掉最后一个插件」也能把账本里的孤儿记录一并清掉。
+ broadcastGhostsChanged(manager.list(), true);
if (recentIds) broadcastGhostRecentUsageChanged(recentIds);
try {
await completeLedger?.();
@@ -3631,6 +3875,9 @@ export function registerGhostIpc(): void {
// Even when provisioning itself is a no-op, the renderer and agent
// roster must immediately reflect the new session capability set.
broadcastGhostsChanged(manager.list());
+ // 未读账本按 owner 分文件,换账号后必须整表替换,否则账号 A 的绿点与摘要
+ // 会留在账号 B 的插件入口与卡片上(跨账号残留)。
+ broadcastGhostUnreadSnapshot();
void scheduleBuiltinReconcile('auth-change');
builtinReconcileChain = builtinReconcileChain.then(
activateGhostsAndMigrateLegacyAccounts,
@@ -3743,6 +3990,11 @@ export function registerGhostIpc(): void {
if (type === 'notify') {
return getGhostNotifySlot().handleNotify(id, payload);
}
+ // badge = 未读角标(badge 槽):资格审看 badge 卡槽、
+ // 净化/限速/落盘在 badgeSlot。与 notify 的分工是"持久状态"对"一次性 toast"。
+ if (type === 'badge') {
+ return getGhostBadgeSlot().handleBadge(id, payload);
+ }
// confirm-request = 确认弹窗(confirm 槽):资格审/净化/限速/单飞在
// confirmSlot,往返与超时兜底在 ghostConfirmDialogBridge。invoke 返回值即
// 结构化结果:ok:true 只代表问到了,答案看 confirmed。
@@ -3874,6 +4126,36 @@ export function registerGhostIpc(): void {
}
});
+ // 未读角标快照(badge 槽)。同步读的理由与 recent-usage 同款:插件入口
+ // 与插件卡的绿点必须**首帧就对**,先渲染成"全无未读"再跳出一颗点是可见跳变。
+ // 账本损坏 / 权限异常一律降级成空,不阻断首屏。
+ // 来源闸:未读 summary 是**插件正文**(工单标题、邮件主题、任务名),
+ // 泄给导航到别处的 renderer / WebView / 插件页就是内容泄漏。
+ // 这里用非抛出的判据而不是 assert:sendSync 里抛错会在 renderer 侧变成同步
+ // 异常炸掉调用点,而未读只是提醒——不可信来源降级成空表即可(codex review)。
+ ipcMain.on('ghosts:unread', (event) => {
+ event.returnValue = { entries: isTrustedAppRendererEvent(event) ? visibleGhostUnread() : [] };
+ });
+
+ // 用户侧熄灭未读(打开面板 = 明确已读)。不要求意识仍在装:卸载残留的
+ // 陈旧条目也该能被清掉,否则界面上会留一颗永远点不掉的点。
+ // 来源闸同上:它会改写 owner 作用域的账本,不能让非可信 frame 拿任意合法
+ // 插件 id 把别人的未读清掉(codex review)。
+ ipcMain.handle('ghosts:clear-unread', (event, id: unknown, seenAt: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof id !== 'string' || !isValidGhostId(id)) {
+ throwIpcError('INVALID_PARAMS', 'id must be a valid Ghost id');
+ }
+ if (seenAt !== undefined && (typeof seenAt !== 'number' || !Number.isFinite(seenAt))) {
+ throwIpcError('INVALID_PARAMS', 'seenAt must be a finite number when provided');
+ }
+ // seenAt = renderer 当时**实际看到的那条**的点亮时刻。清除请求与插件的新点亮
+ // 走两条独立 IPC,「新点亮先到、旧清除后到」完全可能发生;按它做条件删除,
+ // 陈旧清除不会把用户还没看到的新摘要一并抹掉(codex review)。
+ extinguishGhostUnread(id, seenAt as number | undefined);
+ return { ok: true };
+ });
+
// ── 配置就绪检查(使用前置门,判定与 handler 主体在 ghostSetupStatus.ts)──
// 插件页点「使用」时现查:清单推导需求(有 setup 声明按声明,无则启发式),
// 逐项核对保险库 / OAuth 账号 / 连接 / kv。全同步毫秒级、不缓存、不唤沙箱;
@@ -4316,6 +4598,16 @@ export function registerGhostIpc(): void {
runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起
const ghost = findAvailableGhost(id);
if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动
+ resumeGhostUnreadProjection(id); // 沉睡期间保留的那颗点回来
+ } else {
+ // 未读停止投影(记录保留):沉睡的意识没法把面板里的内容给你看,留一颗点
+ // 只是噪声;但用户是"先别烦我"不是"这条我读过了",唤醒要能找回来。
+ //
+ // **必须在 setEnabled 成功之后**:写 `.disabled` 可能失败(目录只读 / IO
+ // 错误),那时插件仍是启用态,可提前熄灭的话未读点就被错误清掉、且不会自愈
+ // (要等插件再次上报或重启)。熄灯类操作(runtime/node/订阅)放在前面是既有
+ // 行为且幂等,唯独这条会留下用户可见的错状态(copilot + codex review)。
+ suspendGhostUnreadProjection(id);
}
return { ok: true };
});
@@ -4497,8 +4789,18 @@ function broadcastGhostProvisioning(active: boolean): void {
});
}
-function broadcastGhostsChanged(ghosts: InstalledGhost[]): void {
+/**
+ * `rosterAuthoritative` = 传进来的这份清单是否来自**刚做完的完整扫描**。
+ * 只影响未读孤儿扫尾:权威的空表意味着"插件真的一个都没有了",要清账本;
+ * 非权威的空表(账号切换窗口里 manager 尚未重扫)必须当作"还不知道",
+ * 否则会把用户的未读整批误清。缺省 false = 保守。
+ */
+function broadcastGhostsChanged(
+ ghosts: InstalledGhost[],
+ rosterAuthoritative = false,
+): void {
getGhostSetupManifestTracker().note(ghosts);
+ sweepRevokedGhostUnread(ghosts, rosterAuthoritative);
const visible = ghosts.filter((ghost) => isGhostAvailableForActiveSession(ghost.manifest.id));
BrowserWindow.getAllWindows().forEach((window) => {
if (window.isDestroyed()) return;
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 3641e18b07..36a1db7780 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -388,6 +388,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: 'cindy-test',
version: '1.0.0',
+ reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
},
);
expect(snapshot.items[0]).toMatchObject({
@@ -418,12 +419,37 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: 'cindy-test',
version: '1.0.0',
+ reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
},
);
// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。
expect(ghost.enabled).toBe(true);
});
+ // 装入确认框渲染的是**服务端给的** manifest,真正落地的是 .cindy 包里的
+ // ghost.json。服务端投影层与客户端清单契约漂移时(cindy-protocol 那份平行
+ // 校验器已经缺了 confirm 槽,新字段按「忽略未知字段」被静默丢掉),包会带着
+ // 用户没审过的权限装进来。出口处需要这份 reviewedManifest 才能逐项比对拦下。
+ it('passes the reviewed server manifest to the install entry so unreviewed package permissions can be blocked', async () => {
+ const item = summary();
+ runtime.install.mockResolvedValue({
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const h = harness([item]);
+
+ await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+
+ const passed = runtime.install.mock.calls[0]?.[1] as { reviewedManifest?: unknown };
+ expect(passed.reviewedManifest).toBeDefined();
+ // 必须是服务端那一份原文(确认框渲染的就是它),不是包里的或已装的。
+ expect(passed.reviewedManifest).toMatchObject({
+ id: item.ghostId,
+ version: item.currentRelease.version,
+ });
+ });
+
it('installs and enables a public defaultInstall package in local mode', async () => {
runtime.session = {
mode: 'local',
@@ -449,6 +475,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: item.ghostId,
version: item.currentRelease.version,
+ reviewedManifest: expect.objectContaining({ id: item.ghostId }),
},
);
expect(snapshot.items[0]).toMatchObject({
diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.ts
index dbcf11f877..99122d8353 100644
--- a/apps/desktop/src/main/plugin-market/install.ts
+++ b/apps/desktop/src/main/plugin-market/install.ts
@@ -163,6 +163,9 @@ export async function installCustomMarketPlugin(input: {
// 复核与落位必须在同一把锁内完成,否则复核结论会在落位前过期。
const commit = async (): Promise<InstalledGhost> => {
await input.beforeCommit?.();
+ // 这里不传 reviewedManifest:上面那道逐字节比对(packed.manifest ===
+ // input.expected)比出口处的逐项权限比对**更强**,自定义来源不存在服务端
+ // 那种「投影层丢字段」的漂移面。传了是死代码,不传不是漏改。
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: validated.manifest.id,
version: validated.manifest.version,
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index c763a1ae63..56ec2d4f84 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -1188,6 +1188,10 @@ export class PluginMarketService {
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: plugin.ghostId,
version: plugin.currentRelease.version,
+ // 确认框渲染的就是这份服务端 manifest;包里若多出权限项,出口处拒装
+ // ——服务端投影层与客户端清单契约漂移时,用户会在没审过的情况下多拿
+ // 一个能力面(codex review P1)。
+ reviewedManifest: compatible.manifest,
});
// Once the package directory is committed, finish provenance against
// the owner captured at operation start even if the active session
diff --git a/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts b/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts
index 9c52d9451b..a552f5ad5a 100644
--- a/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts
+++ b/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts
@@ -17,6 +17,7 @@ import { markAppContentWindow } from '../../windowFocusClassifier';
import {
isTrustedAppRendererEventForLocation,
isTrustedAppRendererUrl,
+ isTrustedAppRendererWindowForLocation,
} from '../trustedAppRenderer';
const packagedRendererFile = path.resolve('/Applications/Cindy/resources/app/renderer/index.html');
@@ -85,3 +86,40 @@ describe('trustedAppRenderer · sender frame', () => {
).toBe(false);
});
});
+
+/**
+ * 出站推送(webContents.send)与入站 IPC 是同一道授权边界。载荷带用户私密内容时
+ * (如插件未读摘要:工单标题、邮件主题),拿 getAllWindows() 无条件广播就是把它
+ * 发给所有窗口,包括已经导航到别处的那些。
+ */
+describe('trustedAppRenderer · 窗口级判据(出站推送用)', () => {
+ const fakeWindow = (url: string) =>
+ ({ isDestroyed: () => false, webContents: { mainFrame: { url } } }) as never;
+
+ it('登记过且停在 renderer 页的窗口才可收推送', () => {
+ const win = fakeWindow(pathToFileURL(packagedRendererFile).toString());
+ markAppContentWindow(win);
+ expect(isTrustedAppRendererWindowForLocation(win, packagedOptions)).toBe(true);
+ });
+
+ it('已导航到别处的窗口不可收 —— 这正是内容泄漏面', () => {
+ const win = fakeWindow('https://attacker.example/index.html');
+ markAppContentWindow(win);
+ expect(isTrustedAppRendererWindowForLocation(win, packagedOptions)).toBe(false);
+ });
+
+ it('未登记的窗口、已销毁的窗口、null 一律不可收', () => {
+ const unregistered = fakeWindow(pathToFileURL(packagedRendererFile).toString());
+ expect(isTrustedAppRendererWindowForLocation(unregistered, packagedOptions)).toBe(false);
+
+ const destroyed = {
+ isDestroyed: () => true,
+ webContents: { mainFrame: { url: pathToFileURL(packagedRendererFile).toString() } },
+ } as never;
+ markAppContentWindow(destroyed);
+ expect(isTrustedAppRendererWindowForLocation(destroyed, packagedOptions)).toBe(false);
+
+ expect(isTrustedAppRendererWindowForLocation(null, packagedOptions)).toBe(false);
+ expect(isTrustedAppRendererWindowForLocation(undefined, packagedOptions)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/security/trustedAppRenderer.ts b/apps/desktop/src/main/security/trustedAppRenderer.ts
index 06e314e059..8613f48398 100644
--- a/apps/desktop/src/main/security/trustedAppRenderer.ts
+++ b/apps/desktop/src/main/security/trustedAppRenderer.ts
@@ -67,6 +67,29 @@ export function isTrustedAppRendererEventForLocation(
return isTrustedAppRendererUrl(frame.url, options);
}
+/**
+ * 窗口级判据:这个窗口此刻是否是 Cindy 自有顶层页面。
+ *
+ * 事件级判据只管**入站** IPC;**出站**推送(webContents.send)同样是授权边界——
+ * 拿 BrowserWindow.getAllWindows() 无条件广播,等于把载荷发给所有窗口,包括已经
+ * 导航到别处的那些。载荷带用户私密内容(如插件未读摘要:工单标题、邮件主题)时
+ * 就是内容泄漏。判据与入站那条同源同口径,免得两边各写一套慢慢漂开。
+ */
+export function isTrustedAppRendererWindow(win: BrowserWindow | null | undefined): boolean {
+ return isTrustedAppRendererWindowForLocation(win, currentRendererUrlOptions());
+}
+
+/** 与生产判定相同,但允许测试显式传入 renderer 地址。 */
+export function isTrustedAppRendererWindowForLocation(
+ win: BrowserWindow | null | undefined,
+ options: TrustedRendererUrlOptions,
+): boolean {
+ if (!isAppContentWindow(win)) return false;
+ const frame = win.webContents.mainFrame;
+ if (!frame) return false;
+ return isTrustedAppRendererUrl(frame.url, options);
+}
+
/** 高权限 IPC 的统一断言;失败时不泄露真实允许地址。 */
export function assertTrustedAppRendererEvent(event: MainIpcEvent): void {
if (!isTrustedAppRendererEvent(event)) {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 049ff77fe6..fa201d6a90 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -449,6 +449,10 @@ const fanOutGhostAssistantPending = createIpcFanOut('ghosts:assistant-message-pe
const fanOutGhostHookFused = createIpcFanOut('ghosts:hook-fused');
// 意识系统提示(notify 槽:宿主 Toast 渲染,带意识身份头)。
const fanOutGhostNotify = createIpcFanOut('ghosts:notify');
+// 意识未读角标(badge 槽:插件入口与插件卡上的绿点,持久状态非一次性 toast)。
+const fanOutGhostBadge = createIpcFanOut('ghosts:badge');
+// 未读全量快照(换账号后整表替换;逐条 badge 只表达增量)。
+const fanOutGhostUnreadSnapshot = createIpcFanOut('ghosts:unread-snapshot');
// 意识确认弹窗(confirm 槽:renderer 用主机同款 ConfirmDialog 弹,答案回 main)。
// main 只投单个窗口(不广播),所以这里落地的窗口就是该弹框的唯一归属。
const fanOutGhostConfirmRequest = createIpcFanOut('ghosts:confirm-request');
@@ -872,6 +876,35 @@ contextBridge.exposeInMainWorld('electronAPI', {
},
markUsed: (id: string): Promise<{ ids: string[] }> =>
ipcRenderer.invoke('ghosts:mark-used', id),
+ /**
+ * 未读角标快照(badge 槽)。同步读:绿点要与插件入口同帧出现,
+ * 先渲染成"无未读"再补一颗点是可见跳变。main 不可用 / 旧版无 channel
+ * 时按"全无未读"降级(未读是提醒不是内容,缺了不影响可用)。
+ */
+ unreadSync: (): { entries: { ghostId: string; summary?: string; at: number }[] } => {
+ try {
+ const result = ipcRenderer.sendSync('ghosts:unread') as { entries?: unknown } | null;
+ if (!Array.isArray(result?.entries)) return { entries: [] };
+ const entries: { ghostId: string; summary?: string; at: number }[] = [];
+ for (const raw of result.entries) {
+ if (typeof raw !== 'object' || raw === null) continue;
+ const { ghostId, summary, at } = raw as Record<string, unknown>;
+ if (typeof ghostId !== 'string' || typeof at !== 'number') continue;
+ entries.push({ ghostId, ...(typeof summary === 'string' ? { summary } : {}), at });
+ }
+ return { entries };
+ } catch {
+ return { entries: [] };
+ }
+ },
+ /**
+ * 用户侧熄灭未读(打开面板 = 明确已读)。
+ * `seenAt` = renderer **当时实际看到的那条**的点亮时刻,必须原样转发:
+ * main 靠它做条件删除,不转发的话 handler 收到 undefined 就退化成无条件
+ * 删除,插件的新点亮先到时会把用户还没看到的新摘要一并抹掉(codex review)。
+ */
+ clearUnread: (id: string, seenAt?: number): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('ghosts:clear-unread', id, seenAt),
/** 配置就绪检查(插件页「使用」前置门;main 现查凭证/账号/连接/kv)。 */
setupStatus: (id: string): Promise<unknown> =>
ipcRenderer.invoke('ghosts:setup-status', id),
@@ -970,6 +1003,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
onAssistantMessagePending: fanOutGhostAssistantPending,
onHookFused: fanOutGhostHookFused,
onNotify: fanOutGhostNotify,
+ onBadge: fanOutGhostBadge,
+ onUnreadSnapshot: fanOutGhostUnreadSnapshot,
onConfirmRequest: fanOutGhostConfirmRequest,
// 确认弹窗回包(confirm 槽):renderer 把用户的点击送回 main 结算那条挂起的
// 管子请求。requestId 是 main 铸的,陌生/重复 id 由桥忽略。
diff --git a/apps/desktop/src/renderer/__tests__/ghostUnreadStore.test.tsx b/apps/desktop/src/renderer/__tests__/ghostUnreadStore.test.tsx
new file mode 100644
index 0000000000..40645617ef
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/ghostUnreadStore.test.tsx
@@ -0,0 +1,333 @@
+// @vitest-environment jsdom
+/**
+ * ghostUnreadStore.test.tsx — 未读角标 renderer store 的订阅语义。
+ * ---------------------------------------------------------------------------
+ * 覆盖:首帧 unreadSync 快照(绿点不许晚一帧跳出来)、推送增删、per-ghostId 的
+ * primitive 订阅(挂载 N 行不退回整表)、聚合 hook、以及"本地先熄灭再报主机"。
+ */
+
+import { act, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const listeners: Array<(p: { ghostId: string; unread: boolean; summary?: string; at?: number }) => void> = [];
+const snapshotListeners: Array<
+ (p: { entries: Array<{ ghostId: string; summary?: string; at: number }> }) => void
+> = [];
+const clearUnread = vi.fn(() => Promise.resolve({ ok: true }));
+const unreadSync = vi.fn(() => ({
+ entries: [{ ghostId: 'inbox', summary: '3 条新工单', at: 100 }],
+}));
+
+beforeEach(() => {
+ listeners.length = 0;
+ snapshotListeners.length = 0;
+ clearUnread.mockClear();
+ unreadSync.mockClear();
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ ghosts: {
+ unreadSync,
+ clearUnread,
+ onBadge: (cb: (typeof listeners)[number]) => {
+ listeners.push(cb);
+ return () => {
+ const i = listeners.indexOf(cb);
+ if (i >= 0) listeners.splice(i, 1);
+ };
+ },
+ onUnreadSnapshot: (cb: (typeof snapshotListeners)[number]) => {
+ snapshotListeners.push(cb);
+ return () => {
+ const i = snapshotListeners.indexOf(cb);
+ if (i >= 0) snapshotListeners.splice(i, 1);
+ };
+ },
+ },
+ };
+ vi.resetModules();
+});
+
+afterEach(() => {
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+});
+
+async function loadStore() {
+ const mod = await import('../cindy-brain/ghostUnreadStore');
+ mod.__resetGhostUnreadForTest();
+ return mod;
+}
+
+function push(payload: { ghostId: string; unread: boolean; summary?: string; at?: number }): void {
+ act(() => {
+ for (const cb of [...listeners]) cb(payload);
+ });
+}
+
+describe('ghostUnreadStore', () => {
+ it('首帧就带上 unreadSync 的快照(绿点与插件入口同帧,不晚一帧跳出来)', async () => {
+ const { useGhostUnread, useGhostUnreadSummary } = await loadStore();
+ function Probe() {
+ return (
+ <span data-testid="row">
+ {useGhostUnread('inbox') ? 'on' : 'off'}:{useGhostUnreadSummary('inbox') ?? '-'}
+ </span>
+ );
+ }
+ render(<Probe />);
+ expect(screen.getByTestId('row').textContent).toBe('on:3 条新工单');
+ expect(unreadSync).toHaveBeenCalledTimes(1);
+ });
+
+ it('首帧就正确:快照必须在**第一次 getSnapshot** 之前就绪,不许晚一帧', async () => {
+ const { useGhostUnread, useGhostUnreadSummary, useAnyGhostUnread } = await loadStore();
+ // 逐次 render 记录快照值:只要出现过一次 false→true 的翻转,就说明绿点是
+ // 晚一帧跳出来的(useSyncExternalStore 订阅后复查才纠正),而不是首帧就对。
+ const frames: string[] = [];
+ function Probe() {
+ frames.push(
+ `${useGhostUnread('inbox')}|${useGhostUnreadSummary('inbox') ?? '-'}|${useAnyGhostUnread()}`,
+ );
+ return null;
+ }
+ render(<Probe />);
+ expect(frames.length).toBeGreaterThan(0);
+ // 第一帧就必须带上 unreadSync 的内容。
+ expect(frames[0]).toBe('true|3 条新工单|true');
+ // 之后每一帧都一样(没有纠正性的第二次 render)。
+ expect(new Set(frames).size).toBe(1);
+ });
+
+ it('先绑监听再取快照 —— 同步读期间到达的推送不会丢', async () => {
+ // 用 unreadSync 的执行时刻模拟那个窗口:它被调用时,监听如果已经绑好,
+ // 这条推送就能被接住;如果顺序反了(先读后绑),它无人接收,而就绪标记已置位
+ // 不会再读,那颗点会一直缺到重启。
+ unreadSync.mockImplementationOnce(() => {
+ for (const cb of [...listeners]) cb({ ghostId: 'mail', unread: true, at: 9 });
+ return { entries: [] };
+ });
+ const { useGhostUnread } = await loadStore();
+ function Probe() {
+ return <span data-testid="row">{useGhostUnread('mail') ? 'on' : 'off'}</span>;
+ }
+ render(<Probe />);
+ expect(listeners.length).toBeGreaterThan(0); // 读之前监听确实已绑上
+ expect(screen.getByTestId('row').textContent).toBe('on');
+ });
+
+ it('推送点亮 / 熄灭都反映到订阅者;摘要跟着最新一次点亮走', async () => {
+ const { useGhostUnread, useGhostUnreadSummary } = await loadStore();
+ function Probe() {
+ return (
+ <span data-testid="row">
+ {useGhostUnread('mail') ? 'on' : 'off'}:{useGhostUnreadSummary('mail') ?? '-'}
+ </span>
+ );
+ }
+ render(<Probe />);
+ expect(screen.getByTestId('row').textContent).toBe('off:-');
+ push({ ghostId: 'mail', unread: true, summary: '1 封新邮件', at: 1 });
+ expect(screen.getByTestId('row').textContent).toBe('on:1 封新邮件');
+ push({ ghostId: 'mail', unread: true, summary: '2 封新邮件', at: 2 });
+ expect(screen.getByTestId('row').textContent).toBe('on:2 封新邮件');
+ push({ ghostId: 'mail', unread: false });
+ expect(screen.getByTestId('row').textContent).toBe('off:-');
+ });
+
+ it('按 ghostId 精准订阅:别的意识点亮不重渲染本行(性能不变量)', async () => {
+ const { useGhostUnread } = await loadStore();
+ const renders = { count: 0 };
+ function Row() {
+ renders.count += 1;
+ return <span>{useGhostUnread('mail') ? 'on' : 'off'}</span>;
+ }
+ render(<Row />);
+ const before = renders.count;
+ push({ ghostId: 'other', unread: true, at: 1 });
+ // useSyncExternalStore 的快照没变 → React 不该重跑本组件。
+ expect(renders.count).toBe(before);
+ push({ ghostId: 'mail', unread: true, at: 2 });
+ expect(renders.count).toBeGreaterThan(before);
+ });
+
+ it('聚合 hook:任一意识有未读即为真(侧栏插件入口的静态点)', async () => {
+ const { useAnyGhostUnread, __resetGhostUnreadForTest } = await loadStore();
+ // 起点清空,免得 unreadSync 的快照把这条测试变成恒真。
+ unreadSync.mockReturnValueOnce({ entries: [] });
+ __resetGhostUnreadForTest();
+ function Probe() {
+ return <span data-testid="any">{useAnyGhostUnread() ? 'yes' : 'no'}</span>;
+ }
+ render(<Probe />);
+ expect(screen.getByTestId('any').textContent).toBe('no');
+ push({ ghostId: 'a', unread: true, at: 1 });
+ push({ ghostId: 'b', unread: true, at: 2 });
+ expect(screen.getByTestId('any').textContent).toBe('yes');
+ push({ ghostId: 'a', unread: false });
+ expect(screen.getByTestId('any').textContent).toBe('yes'); // b 还亮着
+ push({ ghostId: 'b', unread: false });
+ expect(screen.getByTestId('any').textContent).toBe('no');
+ });
+
+ it('用户已读:本地先熄灭再报主机(面板已在眼前,点还亮着半秒是可见的错)', async () => {
+ const { useGhostUnread, clearGhostUnread } = await loadStore();
+ function Probe() {
+ return <span data-testid="row">{useGhostUnread('inbox') ? 'on' : 'off'}</span>;
+ }
+ render(<Probe />);
+ expect(screen.getByTestId('row').textContent).toBe('on');
+ act(() => clearGhostUnread('inbox'));
+ expect(screen.getByTestId('row').textContent).toBe('off');
+ // 必须带上"当时看到的那条"的点亮时刻,main 据此条件删除。
+ expect(clearUnread).toHaveBeenCalledWith('inbox', 100);
+ });
+
+ it('换账号快照整表替换 —— 账号 A 的点与摘要不许留在账号 B 的界面上', async () => {
+ const { useGhostUnread, useGhostUnreadSummary } = await loadStore();
+ function Probe({ id }: { id: string }) {
+ return (
+ <span data-testid={id}>
+ {useGhostUnread(id) ? 'on' : 'off'}:{useGhostUnreadSummary(id) ?? '-'}
+ </span>
+ );
+ }
+ render(
+ <>
+ <Probe id="inbox" />
+ <Probe id="mail" />
+ </>,
+ );
+ // 起点是账号 A:unreadSync 的快照点亮了 inbox。
+ expect(screen.getByTestId('inbox').textContent).toBe('on:3 条新工单');
+
+ // 切到账号 B:main 推来 B 自己的账本(inbox 不在其中)。
+ act(() => {
+ for (const cb of [...snapshotListeners]) {
+ cb({ entries: [{ ghostId: 'mail', summary: 'B 的邮件', at: 5 }] });
+ }
+ });
+ expect(screen.getByTestId('inbox').textContent).toBe('off:-');
+ expect(screen.getByTestId('mail').textContent).toBe('on:B 的邮件');
+
+ // 登出:空快照把界面清干净。
+ act(() => {
+ for (const cb of [...snapshotListeners]) cb({ entries: [] });
+ });
+ expect(screen.getByTestId('mail').textContent).toBe('off:-');
+ });
+
+ it('前台判据:窗口最小化 / 失焦时为假 —— 常开面板不许把用户没看见的未读吞掉', async () => {
+ const { useHostWindowForeground } = await loadStore();
+ let visibility: DocumentVisibilityState = 'visible';
+ let focused = true;
+ vi.spyOn(document, 'visibilityState', 'get').mockImplementation(() => visibility);
+ vi.spyOn(document, 'hasFocus').mockImplementation(() => focused);
+
+ function Probe() {
+ return <span data-testid="fg">{useHostWindowForeground() ? 'fg' : 'bg'}</span>;
+ }
+ render(<Probe />);
+ expect(screen.getByTestId('fg').textContent).toBe('fg');
+
+ // 最小化 / 切到后台 → visibilityState 变 hidden。
+ visibility = 'hidden';
+ act(() => document.dispatchEvent(new Event('visibilitychange')));
+ expect(screen.getByTestId('fg').textContent).toBe('bg');
+
+ // 恢复可见但没聚焦(被别的窗口盖住 / 用户在别的 app)→ 仍然不算看见。
+ visibility = 'visible';
+ focused = false;
+ act(() => window.dispatchEvent(new Event('blur')));
+ expect(screen.getByTestId('fg').textContent).toBe('bg');
+
+ // 用户切回来 → 这一刻才算看见。
+ focused = true;
+ act(() => window.dispatchEvent(new Event('focus')));
+ expect(screen.getByTestId('fg').textContent).toBe('fg');
+
+ vi.restoreAllMocks();
+ });
+
+ it('元素可见判据:已挂载但被压成零宽/隐藏时为假,切回可见才转真', async () => {
+ // 同一前台窗口里另一个停靠面板被最大化 → 本面板仍挂载但零宽。只看窗口
+ // foreground 会把这段时间到来的未读当成已读吞掉(codex review)。
+ type IoCb = (entries: Array<{ isIntersecting: boolean; intersectionRatio: number }>) => void;
+ let fire: IoCb | null = null;
+ const disconnect = vi.fn();
+ const observed: Element[] = [];
+ class FakeIO {
+ constructor(cb: IoCb) {
+ fire = cb;
+ }
+ observe(el: Element) {
+ observed.push(el);
+ }
+ disconnect = disconnect;
+ }
+ vi.stubGlobal('IntersectionObserver', FakeIO);
+
+ const { useElementVisible } = await loadStore();
+ function Probe({ show = true }: { show?: boolean }) {
+ const { ref, visible } = useElementVisible();
+ return show ? (
+ <div ref={ref} data-testid="vis">
+ {visible ? 'vis' : 'hidden'}
+ </div>
+ ) : (
+ <span data-testid="vis">gone</span>
+ );
+ }
+ const { unmount, rerender } = render(<Probe />);
+ // **首帧必须是"尚未观测到可见"**:IntersectionObserver 的首次结果下一拍才到,
+ // 这期间面板可能正躺在被邻居最大化压成零宽的容器里。初值若为可见,清零 effect
+ // 会在首帧就把未读消费掉(greptile review P1)。
+ expect(screen.getByTestId('vis').textContent).toBe('hidden');
+ // 被最大化的邻居压成零宽:不相交、比例 0。
+ act(() => fire?.([{ isIntersecting: false, intersectionRatio: 0 }]));
+ expect(screen.getByTestId('vis').textContent).toBe('hidden');
+ // 用户切回本面板 → 重新占面积,这一刻才算看见。
+ act(() => fire?.([{ isIntersecting: true, intersectionRatio: 1 }]));
+ expect(screen.getByTestId('vis').textContent).toBe('vis');
+
+ // 崩溃走 fallback:host 节点脱离 DOM → 观察器解绑,判据回落到"还不知道"。
+ const before = observed.length;
+ rerender(<Probe show={false} />);
+ expect(disconnect).toHaveBeenCalled();
+ // 用户点「重载」生成**新的** host:必须重新观察新节点,否则那颗点永远清不掉。
+ rerender(<Probe show />);
+ expect(observed.length).toBeGreaterThan(before);
+ act(() => fire?.([{ isIntersecting: true, intersectionRatio: 1 }]));
+ expect(screen.getByTestId('vis').textContent).toBe('vis');
+ unmount();
+ expect(disconnect).toHaveBeenCalled();
+ vi.unstubAllGlobals();
+ });
+
+ it('环境不支持 IntersectionObserver 时 fail-open —— 不因判据缺失而永远清不掉', async () => {
+ vi.stubGlobal('IntersectionObserver', undefined);
+ const { useElementVisible } = await loadStore();
+ function Probe() {
+ const { ref, visible } = useElementVisible();
+ return (
+ <span ref={ref} data-testid="vis">
+ {visible ? 'vis' : 'hidden'}
+ </span>
+ );
+ }
+ render(<Probe />);
+ expect(screen.getByTestId('vis').textContent).toBe('vis');
+ vi.unstubAllGlobals();
+ });
+
+ it('unreadSync 抛错时按"全无未读"起步,后续推送照常生效(未读是提醒不是内容)', async () => {
+ unreadSync.mockImplementationOnce(() => {
+ throw new Error('store broken');
+ });
+ const { useGhostUnread } = await loadStore();
+ function Probe() {
+ return <span data-testid="row">{useGhostUnread('inbox') ? 'on' : 'off'}</span>;
+ }
+ render(<Probe />);
+ expect(screen.getByTestId('row').textContent).toBe('off');
+ push({ ghostId: 'inbox', unread: true, at: 1 });
+ expect(screen.getByTestId('row').textContent).toBe('on');
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
index 260496cd6d..e8ba4fc94f 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
@@ -9,6 +9,7 @@
import {
AppWindow,
Bell,
+ BellDot,
BadgeCheck,
Bot,
ChevronDown,
@@ -65,6 +66,10 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {
function itemIcon(item: GhostPermissionItem): LucideIcon {
if (item.labelKey === 'panelLeft') return PanelLeft;
+ // 未读角标与一次性提示同属 notify kind,但一个是常驻注意力入口、一个是弹完就走
+ // (两者是并列的两档权限,可以只申请其中一项),同时出现时同图标读起来像重复项,
+ // 给角标换一枚带点的铃铛以示区分。
+ if (item.labelKey === 'badge') return BellDot;
// network 槽的凭证条目换钥匙图标(与域名条目区分:一个是"去哪",一个是"带什么")。
if (
item.labelKey === 'networkSecret' ||
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
index 34a27944f5..5109e9271a 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState, type ReactNode } from 'react';
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleAlert, Copy, FolderOpen } from 'lucide-react';
import type { ContextMenuEvent, WebviewTag } from 'electron';
@@ -13,6 +13,12 @@ import { toast } from '@/lib/toast';
import { GHOST_SCHEME, ghostPartition, type GhostManifest } from '../../shared/ghost';
import { createGhostThemeInjector, observeHostTheme } from './ghostPanelTheme';
+import {
+ clearGhostUnread,
+ useElementVisible,
+ useGhostUnread,
+ useHostWindowForeground,
+} from './ghostUnreadStore';
/**
* 意识面板体(webview 供片)—— 顶层停靠 pane(ghostPanels)与插件页内面板
@@ -177,6 +183,42 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
const [mediaMenu, setMediaMenu] = useState<GhostPanelMediaMenuState | null>(null);
const hostRef = useRef<HTMLDivElement | null>(null);
+ /**
+ * 面板体挂载 = 未读已读(badge 槽的 explicit 清零)。
+ *
+ * 清零收在这里而不是各宿主的"打开"动作里:面板体有三个宿主(插件页页签
+ * GhostPagePanelHost、布局停靠 ghostPanels、独立窗口 GhostPanelWindowLayout),
+ * 挂载到本组件才是"内容确实在用户眼前"的唯一判据,三处天然对称。
+ * unread 进依赖:面板**已经开着**时插件又点亮一次(后台拿到新内容),用户
+ * 正看着它,不该留一颗清不掉的点。
+ *
+ * 清零的必要条件是**两层可见性同时成立**,缺一层都会把用户没看见的未读吞掉:
+ * 1. `foreground` —— 宿主窗口可见且聚焦。停靠面板与独立面板窗口长期挂着,
+ * 只看挂载的话,窗口最小化 / 失焦期间到来的未读会被一律清掉,常开面板的
+ * 用户从此收不到这个插件的提醒(codex review P1)。
+ * 2. `visible` —— 本面板**自己**占着可见面积。光有第 1 层还不够:同一个前台
+ * 窗口里,另一个停靠面板被最大化时本面板仍然挂载,却被压成零宽/隐藏,
+ * 用户根本没看到内容(codex review)。
+ * 两层都满足的那一刻 effect 重跑并清零,语义正是「他看的时候才算看过」。
+ */
+ const unread = useGhostUnread(manifest.id);
+ const foreground = useHostWindowForeground();
+ const { ref: observeHost, visible } = useElementVisible();
+ // 同一个 div 既要给 webview 挂载用(命令式 hostRef),又要被可见性观察器盯住。
+ // 合成一个 callback ref:崩溃走 fallback 时它带 null 触发(观察器解绑),
+ // 用户「重载」生成新 div 时又带新节点触发(观察器重挂)——正是 ref 对象做不到的。
+ const setHostNode = useCallback(
+ (el: HTMLDivElement | null) => {
+ hostRef.current = el;
+ observeHost(el);
+ },
+ [observeHost],
+ );
+ useEffect(() => {
+ if (!unread || !foreground || !visible) return;
+ clearGhostUnread(manifest.id);
+ }, [manifest.id, unread, foreground, visible]);
+
const panelHtml = manifest.panel?.html;
useEffect(() => {
if (crashed || !panelHtml) return;
@@ -273,7 +315,7 @@ export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): R
// (globals.css 与内置浏览器 pool 同款规则)。
return (
<>
- <div ref={hostRef} data-ghost-webview className="flex min-h-0 flex-1" />
+ <div ref={setHostNode} data-ghost-webview className="flex min-h-0 flex-1" />
{mediaMenu ? (
<GhostPanelMediaMenu menu={mediaMenu} onClose={() => setMediaMenu(null)} />
) : null}
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostUnreadStore.ts b/apps/desktop/src/renderer/cindy-brain/ghostUnreadStore.ts
new file mode 100644
index 0000000000..0dba251389
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/ghostUnreadStore.ts
@@ -0,0 +1,284 @@
+/**
+ * ghostUnreadStore.ts — 意识未读角标(badge 槽)的 renderer 侧状态源。
+ * ---------------------------------------------------------------------------
+ * 主机在意识上行 badge 时点亮、用户打开面板 / 停用 / 卸载时熄灭,变化经
+ * 'ghosts:badge' 推送到达;首帧用 unreadSync() 同步取快照(绿点要与插件入口
+ * 同帧出现,晚一帧跳出来是可见跳变)。
+ *
+ * 订阅纪律与 ghostSessionActivityStore / sessionAttentionStore 同款(性能不变量):
+ * 组件按 ghostId 订阅 **primitive**(boolean / string | undefined),逐行挂载不
+ * 退回整表订阅。摘要与"有没有未读"因此拆成两个 hook——返回对象会让
+ * useSyncExternalStore 每次拿到新引用而无限重渲染。
+ */
+
+import { useEffect, useState, useSyncExternalStore } from 'react';
+
+interface UnreadEntry {
+ summary?: string;
+ at: number;
+}
+
+const unread = new Map<string, UnreadEntry>();
+const listeners = new Set<() => void>();
+let ready = false;
+
+interface UnreadSnapshotEntry {
+ ghostId: string;
+ summary?: string;
+ at: number;
+}
+
+interface GhostUnreadApi {
+ onBadge?: (
+ cb: (p: { ghostId: string; unread: boolean; summary?: string; at?: number }) => void,
+ ) => () => void;
+ onUnreadSnapshot?: (cb: (p: { entries: UnreadSnapshotEntry[] }) => void) => () => void;
+ unreadSync?: () => { entries: UnreadSnapshotEntry[] };
+ clearUnread?: (id: string, seenAt?: number) => Promise<{ ok: boolean }>;
+}
+
+function api(): GhostUnreadApi | undefined {
+ return (window as unknown as { electronAPI?: { ghosts?: GhostUnreadApi } }).electronAPI?.ghosts;
+}
+
+function emit(): void {
+ for (const cb of [...listeners]) cb();
+}
+
+function toEntry(entry: UnreadSnapshotEntry): UnreadEntry | null {
+ if (typeof entry?.ghostId !== 'string' || typeof entry.at !== 'number') return null;
+ return { ...(entry.summary ? { summary: entry.summary } : {}), at: entry.at };
+}
+
+/** 整表替换。**换账号**专用:新 owner 的账本就是全部事实,旧的必须整体作废。 */
+function applySnapshot(entries: UnreadSnapshotEntry[] | undefined): void {
+ unread.clear();
+ for (const entry of entries ?? []) {
+ const value = toEntry(entry);
+ if (value) unread.set(entry.ghostId, value);
+ }
+}
+
+/**
+ * 首次落位:**补齐缺的,不动已有的**。
+ *
+ * 不能复用整表替换:监听是在同步读之前绑好的(见 ensureReady),读取返回之前到达
+ * 的推送已经写进表里,整表替换会把它抹掉——等于换个姿势重新丢掉那条推送。
+ * 活推送比落盘快照新,冲突时以推送为准。
+ */
+function seedSnapshot(entries: UnreadSnapshotEntry[] | undefined): void {
+ for (const entry of entries ?? []) {
+ const value = toEntry(entry);
+ if (value && !unread.has(entry.ghostId)) unread.set(entry.ghostId, value);
+ }
+}
+
+/**
+ * 惰性就绪:**绑增量监听 → 取同步快照**,顺序不可颠倒,且必须在第一次
+ * getSnapshot 之前完成——所以每个 getSnapshot 都先过这里,不是只挂在 subscribe 上。
+ *
+ * 两条约束各自解决一个真问题:
+ *
+ * 1. **必须早于第一次 getSnapshot**。useSyncExternalStore 的顺序是 render 期先调
+ * getSnapshot、mount 后才调 subscribe。把同步读放在 subscribe 里的话,首帧一定
+ * 读到空表,要等 React 订阅后复查快照才纠正——绿点与摘要**晚一帧跳出来**,
+ * 恰好抵消了当初做 `unreadSync` 同步读的全部意义。
+ * 2. **必须先绑监听再读快照**。反过来的话,两步之间插件恰好点亮角标,那条推送
+ * 无人接收,而就绪标记已置位不会再读——那颗点会一直缺到重启或换账号快照。
+ * 主机是「先落盘再广播」,所以绑定之后的这次读一定含得上窗口期内的变化。
+ *
+ * 幂等且只读一次;拿不到就按"全无未读"起步,后续推送照常生效(未读是提醒不是内容)。
+ * 模块导入零副作用;测试环境无 electronAPI 时整段是空转,同样安全。
+ */
+function ensureReady(): void {
+ if (ready) return;
+ ready = true;
+ const ghosts = api();
+ // 换账号:main 在 auth 状态变化后推一份新 owner 的全量快照,这里整表替换。
+ // 只订阅增量的话,账号 A 的绿点与摘要会留在账号 B 的界面上(跨账号残留)。
+ ghosts?.onUnreadSnapshot?.((payload) => {
+ applySnapshot(payload?.entries);
+ emit();
+ });
+ ghosts?.onBadge?.((payload) => {
+ if (!payload || typeof payload.ghostId !== 'string') return;
+ if (payload.unread) {
+ unread.set(payload.ghostId, {
+ ...(payload.summary ? { summary: payload.summary } : {}),
+ at: typeof payload.at === 'number' ? payload.at : 0,
+ });
+ } else if (!unread.delete(payload.ghostId)) {
+ return; // 本来就没亮,不惊动订阅者
+ }
+ emit();
+ });
+ try {
+ seedSnapshot(ghosts?.unreadSync?.().entries);
+ } catch {
+ /* 读不到就空表起步 */
+ }
+}
+
+function subscribe(cb: () => void): () => void {
+ ensureReady();
+ listeners.add(cb);
+ return () => listeners.delete(cb);
+}
+
+/** 某意识当前是否有未读(primitive 快照,per-row 精准订阅)。 */
+export function useGhostUnread(ghostId: string): boolean {
+ return useSyncExternalStore(
+ subscribe,
+ () => {
+ ensureReady();
+ return unread.has(ghostId);
+ },
+ () => false,
+ );
+}
+
+/** 某意识最新一条未读的摘要(没有未读或意识没给摘要时 undefined)。 */
+export function useGhostUnreadSummary(ghostId: string): string | undefined {
+ return useSyncExternalStore(
+ subscribe,
+ () => {
+ ensureReady();
+ return unread.get(ghostId)?.summary;
+ },
+ () => undefined,
+ );
+}
+
+/**
+ * 是否**任一**意识有未读(侧栏插件入口的聚合静态点)。
+ * 返回 boolean 而非计数:入口点不显示数量,订阅 boolean 能少掉一大半重渲染。
+ */
+export function useAnyGhostUnread(): boolean {
+ return useSyncExternalStore(
+ subscribe,
+ () => {
+ ensureReady();
+ return unread.size > 0;
+ },
+ () => false,
+ );
+}
+
+/**
+ * 宿主窗口此刻是否真的在用户眼前(可见 **且** 聚焦)。
+ *
+ * 「面板挂载」不等于「用户看见了」:停靠面板与独立面板窗口会一直挂着,窗口最小化、
+ * 被别的窗口盖住、或者用户切到别的 app 时,插件新点亮的未读会被立刻当成已读清掉
+ * ——常开面板的用户从此**再也收不到这个插件的提醒**(codex review P1)。
+ *
+ * 判据取两条的交集:`visibilityState` 可靠覆盖最小化 / 后台;`hasFocus` 覆盖失焦,
+ * 并顺带兜住「被别的窗口盖住」——遮挡在 Chromium 里不可靠上报,拿聚焦当代理是
+ * 目前唯一站得住的近似。代价是用户切回窗口那一刻才清零,这恰恰是对的语义:
+ * **他看的时候才算看过**。
+ */
+export function useHostWindowForeground(): boolean {
+ return useSyncExternalStore(
+ (cb) => {
+ const events = ['visibilitychange', 'focus', 'blur'] as const;
+ for (const name of events) {
+ (name === 'visibilitychange' ? document : window).addEventListener(name, cb);
+ }
+ return () => {
+ for (const name of events) {
+ (name === 'visibilitychange' ? document : window).removeEventListener(name, cb);
+ }
+ };
+ },
+ () => document.visibilityState === 'visible' && document.hasFocus(),
+ () => false,
+ );
+}
+
+/**
+ * 这个元素此刻是否真的占着可见面积。
+ *
+ * 「宿主窗口在前台」还不够:同一个前台窗口里,另一个停靠面板被最大化时,本面板
+ * **仍然挂载**但被压成零宽/隐藏——用户根本没看到内容,却会被当成已读清零,
+ * 切回来时那颗点已经没了(codex review)。
+ *
+ * 判据用 IntersectionObserver(能同时覆盖零尺寸与滚出可视区);环境不支持时
+ * fail-open,退回「窗口前台」那一层,不会比改动前更差。
+ *
+ * **入参是 callback ref 而不是 ref 对象**:ref 对象的身份永不变化,effect 依赖它
+ * 就永远不会重跑——面板崩溃走 fallback、用户点「重载」生成一个**新的** host 元素
+ * 之后,观察器还盯着已经脱离 DOM 的旧节点,从此再也不会报告可见,那颗点永远
+ * 清不掉(codex review)。改成把元素本身放进 state,换了节点就自然重挂观察器。
+ */
+export function useElementVisible(): {
+ ref: (el: Element | null) => void;
+ visible: boolean;
+} {
+ const [el, setEl] = useState<Element | null>(null);
+ /**
+ * 初值必须是 **false = 尚未观测到可见**,不能图省事写 true。
+ *
+ * `IntersectionObserver` 的首次结果要下一拍才到。若初值为 true,面板一挂载
+ * (或恢复挂载)时清零 effect 就已经跑完了——而它此刻很可能正躺在被邻居
+ * 最大化压成零宽的容器里,用户没看到内容却已经丢了角标(greptile review P1)。
+ *
+ * 清零是**消费型**动作:宁可晚一拍,不可误清。观测结果到达后 effect 自会重跑。
+ */
+ const [visible, setVisible] = useState(false);
+ useEffect(() => {
+ if (!el) {
+ setVisible(false); // 还没挂上元素 = 还不知道,不许当成"看见了"
+ return;
+ }
+ if (typeof IntersectionObserver === 'undefined') {
+ setVisible(true); // 观测不了就 fail-open,退回「宿主窗口前台」那一层判据
+ return;
+ }
+ const observer = new IntersectionObserver((entries) => {
+ const entry = entries[entries.length - 1];
+ if (entry) setVisible(entry.isIntersecting && entry.intersectionRatio > 0);
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [el]);
+ return { ref: setEl, visible };
+}
+
+/**
+ * 用户明确已读(打开面板)。本地先熄灭再报主机:面板已经在眼前展开了,
+ * 点还亮着半秒是可见的错;主机那边失败也只是下次重启又亮起来,不丢内容。
+ */
+export function clearGhostUnread(ghostId: string): void {
+ ensureReady();
+ // 带上**当前这条**的点亮时刻:清除请求与插件的新点亮走两条独立 IPC,
+ // "新点亮先到、旧清除后到"完全可能发生。main 按它条件删除,陈旧清除不会
+ // 抹掉用户还没看到的新摘要(codex review)。
+ const seenAt = unread.get(ghostId)?.at;
+ if (unread.delete(ghostId)) emit();
+ void api()?.clearUnread?.(ghostId, seenAt)?.catch(() => undefined);
+}
+
+/** 测试专用:直灌一条角标变化(绕过 IPC)。 */
+export function __ingestGhostBadgeForTest(
+ ghostId: string,
+ payload: { unread: boolean; summary?: string; at?: number },
+): void {
+ // 先把就绪落定(无 electronAPI 时是空转),否则灌进来的条目会被随后首个
+ // 消费者触发的 ensureReady → applySnapshot 整表清掉。
+ ensureReady();
+ if (payload.unread) {
+ unread.set(ghostId, {
+ ...(payload.summary ? { summary: payload.summary } : {}),
+ at: payload.at ?? 0,
+ });
+ } else {
+ unread.delete(ghostId);
+ }
+ emit();
+}
+
+/** 测试专用:清空全部状态。 */
+export function __resetGhostUnreadForTest(): void {
+ unread.clear();
+ listeners.clear();
+ ready = false;
+}
diff --git a/apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx b/apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx
index 5926fe9d83..0b67690510 100644
--- a/apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx
@@ -18,6 +18,9 @@
* • 呼吸(breathing=true):单条会话"有需要你关注的未读结果"的提醒点——卡片
* 任务完成未读、rail 瓷砖未读。复用 `.session-card-dot` 的 session-card-pulse
* 关键帧(prefers-reduced-motion 下自动停),用呼吸吸引注意。
+ * 该关键帧是**常驻循环动画**,按 DESIGN.md §14.4 只动 ::after 光环的
+ * transform / opacity(compositor-only)——多张未读卡长期同屏时不会持续重绘。
+ * 改这段动画前先读那条红线,别退回 box-shadow / width 之类会触发绘制的属性。
* • 静态(breathing=false,默认):聚合入口/常驻类未读徽标——如自动化入口(🕐)
* 的未读小点。不动,低打扰。
*
diff --git a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
index 9e6e78b82c..68e6459fb0 100644
--- a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
@@ -24,6 +24,8 @@ import { useNavigate, useMatch } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
+import { AttentionDot } from '@/components/sidebar/AttentionDot';
+import { useAnyGhostUnread } from '@/cindy-brain/ghostUnreadStore';
import { useActiveMainView } from '@/hooks/useActiveMainView';
import { MachineSwitcherMenu } from '@/features/cc-agent/sidebar/MachineSwitcherMenu';
import { SidebarInlineSearch } from '@/features/cc-agent/sidebar/SidebarInlineSearch';
@@ -45,6 +47,9 @@ export function SidebarTopNav(): React.ReactElement {
const { activeKey, navigateToView } = useActiveMainView();
const onScheduleMatch = useMatch('/cc-agent/scheduled');
const { search, allKnownProjects, openSignal } = useConversationSearchContext();
+ // 任一插件有未读 → 入口行尾一颗**静态**绿点(聚合入口按 AttentionDot 规范不呼吸,
+ // 呼吸留给单条卡片;见 AttentionDot 头部的形态规范)。
+ const hasGhostUnread = useAnyGhostUnread();
// 通用「新建」入口:只 navigate 到草稿页,不清空 newMakerDraft。
// 之前这里会把 workingDir / remoteHostId / extraDirs 清成默认,导致用户在草稿页
@@ -110,6 +115,7 @@ export function SidebarTopNav(): React.ReactElement {
)}
/>
<span className="leading-none">{t('sidebar.tabs.plugins')}</span>
+ {hasGhostUnread && <AttentionDot size={6} className="ml-auto mr-0.5" />}
</button>
{/* 4. 搜索 —— 静息态与上面三行同款;hover / 聚焦就地展开成搜索框 */}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 88e6fef026..e0be2fdc8f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -84,6 +84,7 @@ import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';
import { useBackgroundActivitySessionIds } from '@/lib/sessionBackgroundActivityStore';
import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
import { useActiveMainView } from '@/hooks/useActiveMainView';
+import { useAnyGhostUnread } from '@/cindy-brain/ghostUnreadStore';
import { getNotificationsEnabled } from '@/hooks/useNotificationSettings';
import { getFeishuNotificationsEnabled } from '@/hooks/useFeishuNotificationSettings';
import { getAgentIslandEnabled, isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';
@@ -3062,6 +3063,8 @@ function CollapsedView({
// 主视图切换(Plugin / Skill 管理)——与展开态 SidebarTopNav 的管理入口同源:
// 命中 Plugin 或 Skill 视图时高亮。折叠 rail 之前漏了这颗按钮,现保持两态一致。
const { activeKey, navigateToView } = useActiveMainView();
+ // 插件未读聚合(badge 槽)——与展开态同源同语义。
+ const hasGhostUnread = useAnyGhostUnread();
// 接管中的会话(/ctr)——面板行沿用 SessionStatusIcon 的 RadioTower 表达。
const attachedSessionIds = useAttachedSessionIds();
@@ -3113,12 +3116,15 @@ function CollapsedView({
onClick={handleNavScheduled}
onContextMenu={onAutomationsContextMenu}
/>
+ {/* 插件 rail 入口 —— 未读绿点与展开态 SidebarTopNav 对称(同一聚合语义:
+ 任一插件有未读就点亮,静态不呼吸)。 */}
<SidebarIconButton
icon={Plug}
label={t('sidebar.tabs.plugins')}
variant="rail"
active={activeKey === 'plugins'}
aria-current={activeKey === 'plugins' ? 'page' : undefined}
+ showDot={hasGhostUnread}
onClick={() => navigateToView('plugins')}
/>
<ConversationSearchBox
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index e4bf8d5a23..2624b49bf5 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -56,6 +56,8 @@ import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';
import { confirmAndInstallGhost, pickAndUpdateGhost } from '@/cindy-brain/installFlow';
import { GhostPermissionList, GhostUpdateReview } from '@/cindy-brain/GhostPermissionList';
import { cn } from '@/lib/utils';
+import { AttentionDot } from '@/components/sidebar/AttentionDot';
+import { useGhostUnread, useGhostUnreadSummary } from '@/cindy-brain/ghostUnreadStore';
import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';
import { findSplitChildByPanelKind } from '../../../shared/layoutTree';
import { resolveSystemLocale } from '../../../shared/locale';
@@ -586,6 +588,10 @@ export function GhostPluginPage() {
useEffect(() => {
if (openPanelId && !openPanelGhost) setOpenPanelId(null);
}, [openPanelGhost, openPanelId]);
+ // 「打开面板 = 已读」不在这里清:三个 setOpenPanelId 调用点(卡片主动作 /
+ // 详情页「使用」/ ?panel= 深链)只是"想开",而面板还有停靠态与独立窗口两种
+ // 宿主。清零统一收在面板体 GhostChipPanelBody 挂载处——那才是"内容确实在
+ // 用户眼前"的唯一判据,三个宿主自然对称。
/**
* 账号 / 本地云模式切换必须关掉在开的面板。
*
@@ -1759,6 +1765,10 @@ export function GhostPluginCard({
}) {
const { t } = useTranslation();
const enabled = effectiveEnabled ?? item.enabled;
+ // 未读(badge 槽):单条卡片走**呼吸**点(AttentionDot 形态规范——聚合入口
+ // 静态、单条呼吸)。有摘要时顶替静态描述:用户扫一眼就知道新内容是什么。
+ const unread = useGhostUnread(item.id);
+ const unreadSummary = useGhostUnreadSummary(item.id);
const primary = ghostPrimaryAction(item);
const cardAction = enabled && primary !== 'manage' ? onPrimary : onManage;
const handleCardKeyDown = (event: KeyboardEvent<HTMLElement>) => {
@@ -1821,8 +1831,13 @@ export function GhostPluginCard({
onIconLoadError={onIconLoadError}
/>
<span className="flex min-w-0 flex-1 flex-col self-stretch pt-0.5">
- <span className="truncate text-15 font-medium text-[var(--text-primary)]">
- {item.name}
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate text-15 font-medium text-[var(--text-primary)]">
+ {item.name}
+ </span>
+ {unread ? (
+ <AttentionDot breathing size={6} className="mt-px" />
+ ) : null}
</span>
<span className="mt-1 block min-w-0 truncate text-11 text-[var(--text-tertiary)]">
{sourceLabel ? `${sourceLabel} · ` : ''}v{item.version}
@@ -1835,8 +1850,16 @@ export function GhostPluginCard({
) : null}
{!enabled ? ` · ${t('settings.ghosts.disabledTag')}` : ''}
</span>
- <span className="mt-1.5 line-clamp-2 text-13 leading-5 text-[var(--text-secondary)]">
- {item.description || item.id}
+ {/* 未读摘要顶替静态描述:静态描述用户早读过了,"新内容是什么"才是这一刻
+ 的信息。摘要文字提到 primary 档以区别于常态描述(不另加色,颜色语义
+ 留给那颗点)。 */}
+ <span
+ className={cn(
+ 'mt-1.5 line-clamp-2 text-13 leading-5',
+ unreadSummary ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]',
+ )}
+ >
+ {unreadSummary || item.description || item.id}
</span>
</span>
{/* 右列控制区:自行消费点击,不冒泡到整卡主动作(纯冒泡拦截层,无独立语义)。 */}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index c2638d3e02..0ec7d3d754 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -7,7 +7,7 @@
*/
import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
@@ -24,6 +24,10 @@ import {
MarketPluginCard,
LegacyGhostRecoveryNotice,
} from '../GhostPluginPage';
+import {
+ __ingestGhostBadgeForTest,
+ __resetGhostUnreadForTest,
+} from '@/cindy-brain/ghostUnreadStore';
import type { GhostPluginListItem } from '../lib/ghostPluginViewModel';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
@@ -71,6 +75,9 @@ const marketPlugin: PluginMarketItem = {
};
describe('GhostPluginCard', () => {
+ // 未读是模块级 store,用例间必须互不串味。
+ afterEach(() => __resetGhostUnreadForTest());
+
it('fires the primary action from the whole card for a command plugin', () => {
const onPrimary = vi.fn();
const onManage = vi.fn();
@@ -220,6 +227,47 @@ describe('GhostPluginCard', () => {
expect(fallbackIcon).toBeTruthy();
expect(fallbackIcon?.parentElement?.className).toContain('var(--surface-elevated)');
});
+
+ // ── 未读角标(badge 槽)────────────────────────────────────────────
+ it('无未读时不画点,描述位仍是静态描述', () => {
+ const { container } = render(
+ <GhostPluginCard item={commandPlugin} onPrimary={vi.fn()} onManage={vi.fn()} />,
+ );
+ expect(container.querySelector('.session-card-dot')).toBeNull();
+ expect(screen.getByText('Google services')).toBeTruthy();
+ });
+
+ it('有未读时:呼吸绿点 + 摘要顶替静态描述', () => {
+ __ingestGhostBadgeForTest('filo-google', { unread: true, summary: '2 封新邮件', at: 1 });
+ const { container } = render(
+ <GhostPluginCard item={commandPlugin} onPrimary={vi.fn()} onManage={vi.fn()} />,
+ );
+ // 单条卡片走呼吸形态(session-card-dot 带呼吸关键帧),绿色走 done token。
+ const dot = container.querySelector('.session-card-dot');
+ expect(dot).toBeTruthy();
+ expect(dot?.className).toContain('var(--card-status-done)');
+ // 摘要顶替静态描述:静态描述用户早读过了,"新内容是什么"才是这一刻的信息。
+ expect(screen.getByText('2 封新邮件')).toBeTruthy();
+ expect(screen.queryByText('Google services')).toBeNull();
+ });
+
+ it('有未读但插件没给摘要:只点亮,静态描述保留(不留空白)', () => {
+ __ingestGhostBadgeForTest('filo-google', { unread: true, at: 1 });
+ const { container } = render(
+ <GhostPluginCard item={commandPlugin} onPrimary={vi.fn()} onManage={vi.fn()} />,
+ );
+ expect(container.querySelector('.session-card-dot')).toBeTruthy();
+ expect(screen.getByText('Google services')).toBeTruthy();
+ });
+
+ it('未读只认本插件的 id:别的插件亮着不影响本卡', () => {
+ __ingestGhostBadgeForTest('signoff-board', { unread: true, summary: '别人的', at: 1 });
+ const { container } = render(
+ <GhostPluginCard item={commandPlugin} onPrimary={vi.fn()} onManage={vi.fn()} />,
+ );
+ expect(container.querySelector('.session-card-dot')).toBeNull();
+ expect(screen.getByText('Google services')).toBeTruthy();
+ });
});
describe('MarketPluginCard', () => {
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts
new file mode 100644
index 0000000000..0359c13e89
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts
@@ -0,0 +1,47 @@
+/**
+ * unreadDotMotion.test.ts — 未读呼吸点的常驻动画约束(DESIGN.md §14.4 红线)。
+ * ---------------------------------------------------------------------------
+ * 未读卡与会话卡不同:插件的未读可能**长期存在、多张同屏**(一页插件卡各亮一颗)。
+ * 常驻循环动画因此只允许动 transform / opacity(compositor-only);退回 box-shadow /
+ * width 这类会触发每帧重绘的属性,会持续吃 CPU 与电量(codex review)。
+ *
+ * 这条把「呼吸挂在哪个属性上」钉在样式表里,而不是靠 code review 记住。
+ * node 环境(不加 jsdom docblock):要用 import.meta.url 直接读源文件。
+ *
+ * **读进来先归一化行尾**:仓库只对 .sh / .mjs / hooks / .sql 钉了 LF,.css 没钉,
+ * Windows 检出成 CRLF。任何按 `\n` 定位的匹配在那边都会落空——本仓已经因为同一类
+ * 问题红过(#1448 的 VoiceInputSection 源码正则)。这类「读源文件做断言」的用例
+ * 一律不得对检出行尾敏感。
+ */
+
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+const CSS = readFileSync(
+ fileURLToPath(new URL('../../../styles/globals.css', import.meta.url)),
+ 'utf8',
+).replace(/\r\n/g, '\n');
+
+describe('未读呼吸点 · 常驻动画红线', () => {
+ it('关键帧只动 transform / opacity,不含任何触发绘制或布局的属性', () => {
+ // 用正则整块捕获,不靠 indexOf 数括号:嵌套的 `{}` 与行尾差异都不会把它切歪。
+ const block = /@keyframes session-card-pulse\s*\{([\s\S]*?)\n\}/.exec(CSS)?.[1];
+ expect(block, '找不到 session-card-pulse 关键帧').toBeTruthy();
+ expect(block).toMatch(/transform:/);
+ expect(block).toMatch(/opacity:/);
+ expect(block).not.toMatch(/box-shadow|width|height|top:|left:|background|filter/);
+ });
+
+ it('动画挂在 ::after 光环上(点本体不参与动画)', () => {
+ expect(CSS).toMatch(/\.session-card-dot::after\s*\{[^}]*animation:\s*session-card-pulse/);
+ });
+
+ it('两处闸门都跟着挂动画的那个元素走 —— 减动偏好停掉、页面隐藏时冻结', () => {
+ // 清单按「真正挂动画的那个元素」收敛(见 globals.css 里那段说明),
+ // 动画从点本体挪到 ::after 之后,两处选择器也必须跟着挪,否则闸门失效。
+ expect(CSS).toMatch(/\.session-card-dot::after,/); // prefers-reduced-motion 清单
+ expect(CSS).toMatch(/\[data-app-hidden='true'\] \.session-card-dot::after,/);
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 043543a481..8363a61090 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3376,6 +3376,8 @@
"cardExternalLinkDetail": "Clicking a card link shows a confirmation dialog; the URL opens in your system browser only after you approve. Only http/https addresses are allowed.",
"notify": "Can show system tips (light banner at the top of the screen)",
"notifyDetail": "Tip text is provided by this plugin and labeled with its name; tips fade automatically and never block your work.",
+ "badge": "Can light an unread mark on the Plugins entry",
+ "badgeDetail": "When it has something new, it can show a green dot on the sidebar Plugins entry and on its own card, with a one-line summary. Opening its panel clears the dot. The dot makes no sound, does not vibrate, never reaches your system notification center, and is a permission separate from system tips.",
"confirm": "Can ask for your confirmation in a dialog",
"confirmDetail": "Before acting it can open a dialog that looks like Cindy's own to ask you. The question comes from the plugin and the dialog is labeled with its name; only you can click confirm or cancel — the plugin cannot. At most one dialog at a time, and asking too often is blocked.",
"fsWrite": "Can write files (create / modify)",
@@ -3513,6 +3515,7 @@
"slotCard": "Message cards",
"slotNetwork": "Network access",
"slotNotify": "System tips",
+ "slotBadge": "Unread badge",
"slotFs": "File writing",
"slotSkill": "Agent skills",
"slotWorkspace": "Workspace sessions"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a5f09a03ad..3a51e2360f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3375,6 +3375,8 @@
"cardExternalLinkDetail": "カード内のリンクをクリックすると確認ダイアログが表示され、承認後にシステムブラウザで開きます。http/https アドレスのみ許可されます。",
"notify": "システム通知を表示可能(画面上部のライトな通知)",
"notifyDetail": "通知の内容はこのプラグインが提供し、通知にはその名前が表示されます。自動的に消え、操作を妨げることはありません。",
+ "badge": "プラグイン入口に未読マークを点灯できます",
+ "badgeDetail": "新しい内容があるとき、サイドバーのプラグイン入口と自身のカードに緑の点を点灯し、一行の要約を添えられます。パネルを開くと消えます。音は鳴らず、振動もせず、システムの通知センターにも入らず、システム通知とは別個の権限です。",
"confirm": "確認ダイアログで同意を求められます",
"confirmDetail": "実行前に Cindy 自身と同じ確認ダイアログを開いて尋ねることができます。文面はプラグインが提供し、ダイアログにはその名前が表示されます。確認するかキャンセルするかはあなたがクリックして決め、プラグイン自身はクリックできません。同時に開けるのは 1 つまでで、頻繁な要求はブロックされます。",
"fsWrite": "ファイルを書き込めます(作成/変更)",
@@ -3512,6 +3514,7 @@
"slotCard": "メッセージカード",
"slotNetwork": "ネットワークアクセス",
"slotNotify": "システム通知",
+ "slotBadge": "未読バッジ",
"slotFs": "ファイル書き込み",
"slotSkill": "エージェントスキル",
"slotWorkspace": "ワークスペースセッション"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 34280485c0..7e44510942 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3375,6 +3375,8 @@
"cardExternalLinkDetail": "카드의 링크를 클릭하면 확인 대화 상자가 표시되며, 승인 후에만 시스템 브라우저에서 열립니다. http/https 주소만 허용됩니다.",
"notify": "시스템 알림 표시 가능(화면 상단의 가벼운 알림)",
"notifyDetail": "알림 내용은 이 플러그인이 제공하며 알림에는 이름이 표시됩니다. 자동으로 사라지며 작업을 방해하지 않습니다.",
+ "badge": "플러그인 입구에 읽지 않음 표시를 켤 수 있음",
+ "badgeDetail": "새 내용이 있으면 사이드바 플러그인 입구와 자체 카드에 초록 점을 켜고 한 줄 요약을 함께 표시할 수 있습니다. 패널을 열면 사라집니다. 소리를 내지 않고 진동하지도 않으며 시스템 알림 센터에도 들어가지 않고, 시스템 알림과는 별개의 권한입니다.",
"confirm": "확인 대화상자로 동의를 요청할 수 있음",
"confirmDetail": "작업 전에 Cindy 자체와 동일한 확인 대화상자를 열어 물어볼 수 있습니다. 질문 내용은 플러그인이 제공하며 대화상자에는 그 이름이 표시됩니다. 확인이든 취소든 직접 클릭해야 하고 플러그인은 스스로 누를 수 없습니다. 동시에 하나만 열 수 있으며 너무 자주 요청하면 차단됩니다.",
"fsWrite": "파일을 쓸 수 있음(생성/수정)",
@@ -3512,6 +3514,7 @@
"slotCard": "메시지 카드",
"slotNetwork": "네트워크 접근",
"slotNotify": "시스템 알림",
+ "slotBadge": "읽지 않음 배지",
"slotFs": "파일 쓰기",
"slotSkill": "에이전트 스킬",
"slotWorkspace": "워크스페이스 세션"
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 c33b1bc9b0..5bb028f0c9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3375,6 +3375,8 @@
"cardExternalLinkDetail": "卡片中的链接点击后会弹出确认框,你同意后才会在系统浏览器中打开;仅限 http/https 地址。",
"notify": "可弹出系统提示(屏幕顶部的轻提示)",
"notifyDetail": "提示内容由这个插件提供,提示上会标注它的名字;自动消失,不会打断你的操作。",
+ "badge": "可在插件入口点亮未读提醒",
+ "badgeDetail": "有新内容时,它可以在侧栏插件入口和自己的卡片上点亮一个绿点,并附一句话摘要;你打开它的面板即清零。绿点不出声、不震动,也不会进入系统通知中心,和上面的系统提示是两项独立权限。",
"confirm": "可弹出确认框征求你同意",
"confirmDetail": "它动手前可以弹一个和 Cindy 同款的确认框来问你,问句由它提供、框上会标注它的名字;同意还是取消都由你亲手点,它自己点不了。同时最多一个确认框,弹得太频会被拦下。",
"fsWrite": "可写入文件(创建/修改)",
@@ -3512,6 +3514,7 @@
"slotCard": "消息卡片",
"slotNetwork": "网络访问",
"slotNotify": "系统提示",
+ "slotBadge": "未读角标",
"slotFs": "写文件",
"slotSkill": "Agent 技能",
"slotWorkspace": "工作区任务"
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index b5404a83c7..ab677326b8 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -872,18 +872,40 @@ body.resizing-pane [data-ghost-webview] {
}
/* 需关注圆点——深色 + box-shadow 扩散脉冲(对照 redesign 稿 xdtsb-pulse) */
+/* 呼吸点(AttentionDot 的 breathing 形态)。
+ 常驻循环动画按 DESIGN.md §14.4 只允许动 transform / opacity(compositor-only);
+ 原实现动的是 box-shadow,每帧都要重绘,多张未读卡长期同屏时持续吃 CPU 与电量
+ (codex review)。改成一个 ::after 光环做 scale + opacity,视觉节奏不变:
+ 6px 的点外扩到约 4px 光环(6→14px ≈ scale 2.33),同时淡出。
+ 起始帧 opacity 为 0,所以 scale(1) 那一刻光环不可见,不会给点本身蒙一层底色。 */
.session-card-dot {
+ position: relative;
+}
+.session-card-dot::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ border-radius: 9999px;
+ background: hsl(var(--foreground));
animation: session-card-pulse 2.1s infinite;
+ will-change: transform, opacity;
+ pointer-events: none;
}
@keyframes session-card-pulse {
0% {
- box-shadow: 0 0 0 0 hsl(var(--foreground) / 0.32);
+ transform: scale(1);
+ opacity: 0;
+ }
+ 30% {
+ opacity: 0.32;
}
70% {
- box-shadow: 0 0 0 4px hsl(var(--foreground) / 0);
+ transform: scale(2.33);
+ opacity: 0;
}
100% {
- box-shadow: 0 0 0 0 hsl(var(--foreground) / 0);
+ transform: scale(2.33);
+ opacity: 0;
}
}
@@ -907,7 +929,7 @@ body.resizing-pane [data-ghost-webview] {
.session-status-breathing,
.session-card-bar::before,
.session-card--settle,
- .session-card-dot,
+ .session-card-dot::after,
.session-running-dot,
.thinking-dot,
.card-col-fade {
@@ -946,7 +968,7 @@ body.resizing-pane [data-ghost-webview] {
[data-app-hidden='true'] .status-bar-shimmer,
[data-app-hidden='true'] .session-status-breathing,
[data-app-hidden='true'] .session-card-bar::before,
-[data-app-hidden='true'] .session-card-dot,
+[data-app-hidden='true'] .session-card-dot::after,
[data-app-hidden='true'] .session-running-dot,
[data-app-hidden='true'] .thinking-dot,
[data-app-hidden='true'] .ghost-card-sweep,
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 37002293d2..883b1aacbf 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1320,6 +1320,28 @@ interface ElectronAPI {
tone: 'info' | 'success' | 'warning' | 'error';
}) => void,
) => () => void;
+ /** badge 槽:意识未读角标变化(插件入口与插件卡上的绿点)。
+ * 与 onNotify 的分工是持久状态对一次性 toast——用户没去看就一直亮着。
+ * summary/at 只在 unread:true 时给。 */
+ onBadge: (
+ callback: (payload: {
+ ghostId: string;
+ unread: boolean;
+ summary?: string;
+ at?: number;
+ }) => void,
+ ) => () => void;
+ /** badge 槽:未读全量快照(换账号后整表替换;逐条 onBadge 只表达增量)。 */
+ onUnreadSnapshot: (
+ callback: (payload: {
+ entries: Array<{ ghostId: string; summary?: string; at: number }>;
+ }) => void,
+ ) => () => void;
+ /** badge 槽:未读角标首帧快照(同步读,避免绿点晚一帧跳出来)。 */
+ unreadSync: () => { entries: Array<{ ghostId: string; summary?: string; at: number }> };
+ /** badge 槽:用户侧熄灭未读(打开面板 = 明确已读)。seenAt = 当时看到的那条
+ * 的点亮时刻,main 据此条件删除,避免陈旧清除抹掉更新的未读。 */
+ clearUnread: (id: string, seenAt?: number) => Promise<{ ok: boolean }>;
/** confirm 槽:插件请求弹主机同款确认框(main 已资格审+净化+限速+单飞)。
* main 只投单个窗口,所以收到即本窗口负责弹;答案用 resolveConfirm 回包。
* confirmText/cancelText 为 null 时用 renderer 自己的缺省文案(跟语言走)。 */
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 9d83b92a81..6b7f97d71b 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -2225,6 +2225,87 @@ describe('ghost · network 详单校验', () => {
expect(ghostContentKeys(r.manifest)).toContain('slotNotify');
const item = ghostPermissionItems(r.manifest).find((i) => i.key === 'notify');
expect(item).toMatchObject({ kind: 'notify', labelKey: 'notify', detailKey: 'notifyDetail' });
+ // 没声明 notify.badge 的老包不该凭空多出未读角标权限。
+ expect(ghostPermissionItems(r.manifest).map((i) => i.key)).not.toContain('badge');
+ });
+
+ it('badge 槽出**独立**权限条目 —— 老包加这一档必须触发扩权重新确认', () => {
+ const before = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'notify'] });
+ const after = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'notify', 'badge'] });
+ expect(before.ok && after.ok).toBe(true);
+ if (!before.ok || !after.ok) return;
+ expect(ghostPermissionItems(after.manifest).find((i) => i.key === 'badge')).toMatchObject({
+ kind: 'notify',
+ labelKey: 'badge',
+ detailKey: 'badgeDetail',
+ });
+ // 关键回归:并进既有 notify key 会让 added 为空,扩权确认框永远不弹
+ // (与 subscribe 的 activity topic 同一先例)。
+ const diff = diffGhostPermissionItems(before.manifest, after.manifest);
+ expect(diff.added.map((i) => i.key)).toEqual(['badge']);
+ expect(diff.removed).toHaveLength(0);
+ });
+
+ it('badge 与 notify 槽并列:不要 toast 也能要绿点(最小必要权限)', () => {
+ const r = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'badge'] });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ const keys = ghostPermissionItems(r.manifest).map((i) => i.key);
+ expect(keys).toContain('badge');
+ expect(keys).not.toContain('notify');
+ });
+
+ it('存量兼容(红线):老包里任何形态的 notify 顶层字段都照旧被忽略,不影响装入', () => {
+ // `notify` 顶层字段从头到尾就没被登记过,校验器「宽进严出」直接忽略。
+ // 现在角标改由 `badge` **卡槽**声明,这个字段更是彻底不参与解释——
+ // 老包里写成什么形态都装得进来,也不会因此白拿角标能力。
+ for (const shape of [true, 'badge', ['badge'], { badge: true }, { sound: true }, {}]) {
+ const r = validateGhostManifest({ ...goodManifest(), slots: ['panel'], notify: shape });
+ expect(r.ok, `notify: ${JSON.stringify(shape)} 不该被判 invalid`).toBe(true);
+ // **关键**:哪怕老包恰好写成 { badge: true } 且有 panel,也不得凭空获得能力
+ // ——它没有经过任何安装/更新确认(codex review P1)。
+ if (r.ok) expect(ghostPermissionItems(r.manifest).map((i) => i.key)).not.toContain('badge');
+ }
+ });
+
+ it('badge 槽是**可证明**的新声明:老包不可能带它(未知槽名一律拒装)', () => {
+ // slots 是硬白名单,当年装老包的客户端遇到未登记的 'badge' 会直接拒绝整份清单。
+ // 所以「清单里有 badge 槽」⇒「这份清单是本能力上线之后写的」,严格校验才安全。
+ const r = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'not-a-real-slot'] });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.reason).toContain('未知卡槽');
+ });
+
+ it('来源投影丢掉 badge 槽时,包里的 badge 必须被识别成「未审权限」', () => {
+ // 场景:服务端市场那份平行校验器不认识 `badge` 槽(它连 `confirm` 都还没有),
+ // 投影出的 manifest 少了这一档 → 确认框漏列;而下载的 .cindy 包里 ghost.json
+ // 原样带着。装入出口就是拿这个 diff 拦下的(codex review P1)。
+ const reviewed = validateGhostManifest({ ...goodManifest(), slots: ['panel'] });
+ const packed = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'badge'] });
+ expect(reviewed.ok && packed.ok).toBe(true);
+ if (!reviewed.ok || !packed.ok) return;
+ const unreviewed = diffGhostPermissionItems(reviewed.manifest, packed.manifest).added;
+ expect(unreviewed.map((i) => i.key)).toEqual(['badge']);
+ // 反向:两份一致时不得误报,否则正常安装会被闸门全拦死。
+ expect(diffGhostPermissionItems(packed.manifest, packed.manifest).added).toHaveLength(0);
+ });
+
+ it('badge 槽与 panel 严格成对:声明了槽却没有面板一律拒装', () => {
+ // 这里可以放心用严格拒绝:带 badge 槽的清单必然是本能力上线之后写的,
+ // 不存在"拒了会让存量插件消失"的问题(见上一条的可证明性)。
+ const noPanel = validateGhostManifest({
+ ...goodManifest(),
+ slots: ['tool', 'badge'],
+ panel: undefined,
+ tools: [{ name: 'ping', description: 'ping' }],
+ });
+ expect(noPanel.ok).toBe(false);
+ if (!noPanel.ok) expect(noPanel.reason).toContain('panel');
+
+ // 有面板就通过,并落成权限项。
+ const ok = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'badge'] });
+ expect(ok.ok).toBe(true);
+ if (ok.ok) expect(ghostPermissionItems(ok.manifest).map((i) => i.key)).toContain('badge');
});
});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 8996d0b109..6fd9def267 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -115,6 +115,7 @@ export const GHOST_SLOTS = [
'node',
'network',
'notify',
+ 'badge',
'confirm',
'fs',
'session-context',
@@ -1349,6 +1350,7 @@ export function ghostContentKeys(manifest: GhostManifest): string[] {
else if (slot === 'card') keys.push('slotCard');
else if (slot === 'network') keys.push('slotNetwork');
else if (slot === 'notify') keys.push('slotNotify');
+ else if (slot === 'badge') keys.push('slotBadge');
else if (slot === 'confirm') keys.push('slotConfirm');
else if (slot === 'fs') keys.push('slotFs');
// skill 是信任面最高的内容(给主 Agent 灌指令),详情页必须如实露出。
@@ -1771,6 +1773,15 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
items.push({ key: 'notify', kind: 'notify', labelKey: 'notify', detailKey: 'notifyDetail' });
}
}
+ // 未读角标:与 notify 槽**并列**的独立一档(不是它的子项)——绿点比 toast 克制,
+ // 只想安静点个绿点的意识不该被迫连"能弹全屏顶部提示"一起申请。
+ // key 独立还有一层必要性(同 subscribe 的 activity topic 判例):
+ // diffGhostPermissionItems 按 key + detail 比对,若并进某个固定 key,已装插件
+ // 新增这一档时 added 为空,plugin-market 的扩权确认就不会拦——用户会在毫不
+ // 知情的情况下多给出一个常驻的注意力入口。
+ if (manifest.slots.includes('badge')) {
+ items.push({ key: 'badge', kind: 'notify', labelKey: 'badge', detailKey: 'badgeDetail' });
+ }
// confirm 槽:能请主机弹一个二选一确认框(会打断操作)。装入时如实告知"它会来问",
// 决定权仍在用户的点击上——detailKey 的固定说明把这层讲清。
if (manifest.slots.includes('confirm')) {
@@ -2746,6 +2757,28 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
}
+ /**
+ * 未读角标槽(badge)与 `panel` 严格成对:未读点承诺「点开能看到内容」,
+ * 纯工具型 / 对话型意识没有可打开的界面,点亮了也无处可点,给了就是骗点击。
+ *
+ * **为什么用一个新 slot 而不是 `notify` 下的子字段**(2026-08-03,codex review P1):
+ * `slots` 是硬白名单——未登记的槽名一律拒装。所以任何**已经装在用户机器上**的
+ * 老包都不可能带 `badge` 槽:当初装它的客户端会直接拒绝那份清单。这让「新声明」
+ * 与「老包的同名自定义字段」成为**可证明**可分,而不是靠概率赌。
+ *
+ * 早前的方案把它放在顶层 `notify` 对象里。那个字段在本改动前完全未登记、会被
+ * 校验器静默忽略,于是两头堵:严格校验会让写过同名字段的老包升级后消失(§5 红线),
+ * 放松成"识别到就给"又会让恰好写成 `badge:true` 且有面板的老包在**没有任何安装
+ * 或更新确认**的情况下白拿一个常驻注意力面。换成 slot 后两个问题同时消失,
+ * `notify` 顶层字段也不再被解释——存量清单里有什么形态都照旧忽略。
+ */
+ if (slots.includes('badge') && panel === undefined) {
+ return {
+ ok: false,
+ reason: 'slots 声明了 "badge" 但缺少 panel——未读点承诺「点开能看到内容」,没有面板的意识点亮了也无处可点',
+ };
+ }
+
// 工具声明(卡槽②):与 slots 含 'tool' 严格成对,规则同 panel。
let tools: GhostToolDecl[] | undefined;
if (raw.tools !== undefined) {
@@ -4826,6 +4859,49 @@ export interface GhostPipeNotify {
/** notify 的 invoke 返回(失败带人话原因,供意识作者调试;不涉他人信息)。 */
export type GhostPipeNotifyResult = { ok: true } | { ok: false; message: string };
+/**
+ * 上行:未读角标(badge 槽,2026-08-03)。意识告诉主机"我这儿有新内容了",
+ * 主机在插件入口与插件卡上点一颗**绿点**,并把 summary 显示在卡片简介位。
+ *
+ * 与 notify 的分工:notify 是"弹一条即走"的一次性 toast(错过就没了);本消息
+ * 是**持久状态**——用户没去看就一直亮着,打开面板即清零。两者是**并列的两档
+ * 权限**,不是加档关系:要 toast 声明 `notify` 槽,要绿点声明 `badge` 槽,
+ * 谁也不是谁的前置(绿点比 toast 克制,不该被 toast 权限捆绑)。
+ *
+ * 门槛(validateGhostManifest 强制):只有声明了 `panel` 的意识能申请。理由是
+ * 未读点承诺"点开能看到内容",纯工具型/对话型意识没有可打开的界面,给了就是
+ * 骗点击。
+ *
+ * 信任边界与 notify 同款:意识只供纯文本 summary(净化 + 限长),点的颜色、
+ * 位置、身份头全由主机画;意识改不了别人的角标(id 由沙箱绑定,不看载荷自报)。
+ */
+export interface GhostPipeBadge {
+ type: 'badge';
+ /** true = 有未读(点亮);false = 自己清零(如意识内已读)。 */
+ unread: boolean;
+ /**
+ * 最新一条的摘要(纯文本,≤ GHOST_BADGE_SUMMARY_MAX_CHARS)。
+ * 显示在插件卡的简介位,替代静态描述——用户扫一眼就知道新内容是什么。
+ * unread:false 时忽略。
+ */
+ summary?: string;
+}
+
+/** badge 的 invoke 返回(与 notify 同款结构化拒绝,不抛异常穿透沙箱)。 */
+export type GhostPipeBadgeResult = { ok: true } | { ok: false; message: string };
+
+/**
+ * 未读摘要长度上限。比 notify 正文更短:它要挤进卡片一行、单行省略,
+ * 太长的部分用户根本看不到,不如让作者自己裁。
+ */
+export const GHOST_BADGE_SUMMARY_MAX_CHARS = 80;
+
+/**
+ * 同一意识两次角标上报的最小间隔 ms。比 notify 宽松得多——角标是幂等的
+ * 状态写入(不像 toast 每条都打扰用户),但仍要挡住死循环刷写。
+ */
+export const GHOST_BADGE_MIN_INTERVAL_MS = 500;
+
/** 提示正文长度上限(与订阅槽 block reason ≤200 同量级:一眼能读完的量)。 */
export const GHOST_NOTIFY_MAX_CHARS = 200;
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 5b36c36b66..bcc6c6875b 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -30,7 +30,7 @@
| 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) |
| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |
| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |
-| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) |
+| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) |
| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |
| 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` |
| 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |