Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 插件页全面改版——已安装/推荐分区、卡片主动作三分、一键全部更新、面板收束

Chris811287eba1ce
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelWebviewPool.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelWebviewPool.test.ts
deleted file mode 100644
index 8be1c9432c..0000000000
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelWebviewPool.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-// @vitest-environment jsdom
-/**
- * ghostPanelWebviewPool —— 常驻池生命周期单测。
- * jsdom 下 <webview> 是普通 HTMLElement,只断言 DOM 归属 / 指纹重建 / 释放 /
- * 崩溃广播,不测真 webContents(browserWebviewPool.test.ts 同口径)。
- * 主题注入依赖 webview.executeJavaScript 等真 Electron 面,整体 mock 掉。
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-vi.mock('../ghostPanelTheme', () => ({
- createGhostThemeInjector: vi.fn(() => ({
- inject: vi.fn(),
- onDomReady: vi.fn(),
- dispose: vi.fn(),
- })),
- observeHostTheme: vi.fn(() => () => undefined),
-}));
-
-import type { GhostManifest } from '../../../shared/ghost';
-import {
- GHOST_PANEL_POOL_CONTAINER_ID,
- ghostPanelFingerprint,
- ghostPanelWebviewPool,
-} from '../ghostPanelWebviewPool';
-
-function makeManifest(overrides: Partial<GhostManifest> = {}): GhostManifest {
- return {
- id: 'cindy-art',
- name: 'Cindy Art',
- version: '1.0.0',
- panel: { html: 'panel.html', position: 'tab' },
- ...overrides,
- } as GhostManifest;
-}
-
-describe('ghostPanelWebviewPool', () => {
- beforeEach(() => {
- ghostPanelWebviewPool.releaseAll();
- });
- afterEach(() => {
- ghostPanelWebviewPool.releaseAll();
- });
-
- it('acquire 创建 wrapper + webview(partition / src 与停靠形态同源)并停进停车区', () => {
- const entry = ghostPanelWebviewPool.acquire(makeManifest());
- expect(entry).not.toBeNull();
- expect(entry!.webview.getAttribute('partition')).toBe('cindy-ghost-cindy-art');
- expect(entry!.webview.getAttribute('src')).toBe('cindy-ghost://cindy-art/panel.html');
- const parking = document.getElementById(GHOST_PANEL_POOL_CONTAINER_ID);
- expect(parking).not.toBeNull();
- expect(entry!.wrapper.parentElement).toBe(parking);
- });
-
- it('同指纹 acquire 返回同一 entry(webview 不重建)', () => {
- const manifest = makeManifest();
- const a = ghostPanelWebviewPool.acquire(manifest);
- const b = ghostPanelWebviewPool.acquire(makeManifest());
- expect(b).toBe(a);
- });
-
- it('指纹变化(原位升级)→ 释放旧 entry 重建', () => {
- const a = ghostPanelWebviewPool.acquire(makeManifest());
- const b = ghostPanelWebviewPool.acquire(makeManifest({ version: '2.0.0' }));
- expect(b).not.toBe(a);
- expect(a!.wrapper.isConnected).toBe(false);
- expect(b!.wrapper.isConnected).toBe(true);
- });
-
- it('无 panel.html 的清单返回 null', () => {
- expect(ghostPanelWebviewPool.acquire(makeManifest({ panel: undefined }))).toBeNull();
- });
-
- it('release:wrapper 移出 DOM,peek 变 null', () => {
- ghostPanelWebviewPool.acquire(makeManifest());
- const entry = ghostPanelWebviewPool.peek('cindy-art');
- ghostPanelWebviewPool.release('cindy-art');
- expect(ghostPanelWebviewPool.peek('cindy-art')).toBeNull();
- expect(entry!.wrapper.isConnected).toBe(false);
- });
-
- it('sync:不在存活清单或指纹已变的 entry 释放,匹配的保留', () => {
- const keep = makeManifest();
- const stale = makeManifest({ id: 'cindy-mermaid' });
- const gone = makeManifest({ id: 'cindy-web-search' });
- ghostPanelWebviewPool.acquire(keep);
- ghostPanelWebviewPool.acquire(stale);
- ghostPanelWebviewPool.acquire(gone);
- ghostPanelWebviewPool.sync([
- { ghostId: 'cindy-art', fingerprint: ghostPanelFingerprint(keep) },
- {
- ghostId: 'cindy-mermaid',
- fingerprint: ghostPanelFingerprint(makeManifest({ id: 'cindy-mermaid', version: '9.9.9' })),
- },
- ]);
- expect(ghostPanelWebviewPool.inspectGhostIds()).toEqual(['cindy-art']);
- });
-
- it('render-process-gone → entry.crashed + onCrash 广播;释放后不再广播', () => {
- const crashes: string[] = [];
- const off = ghostPanelWebviewPool.onCrash((id) => crashes.push(id));
- const entry = ghostPanelWebviewPool.acquire(makeManifest());
- entry!.webview.dispatchEvent(new Event('render-process-gone'));
- expect(entry!.crashed).toBe(true);
- expect(crashes).toEqual(['cindy-art']);
- // 重复事件不重复广播
- entry!.webview.dispatchEvent(new Event('render-process-gone'));
- expect(crashes).toEqual(['cindy-art']);
- // release 之后事件不再进入池
- ghostPanelWebviewPool.release('cindy-art');
- entry!.webview.dispatchEvent(new Event('render-process-gone'));
- expect(crashes).toEqual(['cindy-art']);
- off();
- });
-
- it('releaseAll 清空全部 entry', () => {
- ghostPanelWebviewPool.acquire(makeManifest());
- ghostPanelWebviewPool.acquire(makeManifest({ id: 'cindy-mermaid' }));
- ghostPanelWebviewPool.releaseAll();
- expect(ghostPanelWebviewPool.inspectGhostIds()).toEqual([]);
- });
-});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
index 76570075a6..368f93198b 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
@@ -101,6 +101,7 @@ describe('ghostPluginViewModel', () => {
version: '1',
enabled: true,
canUse: true,
+ tabPanel: false,
},
{
id: 'lizi-mivo',
@@ -109,6 +110,7 @@ describe('ghostPluginViewModel', () => {
version: '1',
enabled: true,
canUse: true,
+ tabPanel: false,
},
{
id: 'slack',
@@ -117,6 +119,7 @@ describe('ghostPluginViewModel', () => {
version: '1',
enabled: true,
canUse: true,
+ tabPanel: false,
},
] satisfies GhostPluginListItem[];
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
deleted file mode 100644
index 99fd1a5f85..0000000000
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, describe, expect, it } from 'vitest';
-
-import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';
-import {
- _resetTabKindRegistry,
- getTabKind,
- listGhostTabMenuMetas,
-} from '../../features/right-sidebar/registry';
-import { __resetPanelRegistryForTest, hasPanelKind } from '../../panels/registry';
-import { __resetGhostPanelsForTest, syncGhostPanelRegistrations } from '../ghostPanels';
-import {
- __resetGhostTabPluginsForTest,
- buildGhostTabPlugin,
- syncGhostTabRegistrations,
-} from '../ghostTabPlugins';
-
-/** 造一个已装意识(panel 可覆写;enabled 默认 true)。 */
-function ghost(id: string, panel?: GhostManifest['panel'], enabled = true): InstalledGhost {
- const manifest: GhostManifest = {
- schemaVersion: 2,
- id,
- name: `${id} 意识`,
- version: '1.0.0',
- kind: 'chip',
- entry: 'main.js',
- slots: ['panel'],
- panel: panel ?? { html: 'panel.html', position: 'tab' },
- };
- return { manifest, dir: `/fake/${id}`, enabled };
-}
-
-afterEach(() => {
- __resetGhostTabPluginsForTest();
- _resetTabKindRegistry();
- __resetPanelRegistryForTest();
- __resetGhostPanelsForTest();
-});
-
-describe('buildGhostTabPlugin · 契约形状', () => {
- it('kind 复用 ghost:<id>;menu 单例、labelText 取 panel.title 缺省意识名', () => {
- const withTitle = buildGhostTabPlugin(ghost('art', { html: 'p.html', position: 'tab', title: '画廊' }).manifest);
- expect(withTitle.kind).toBe('ghost:art');
- expect(withTitle.menu).toMatchObject({
- kind: 'ghost:art',
- labelText: '画廊',
- labelKey: 'rightSidebar.tabs.kinds.ghostPanel',
- singleton: true,
- enabled: true,
- });
- expect(withTitle.defaultState()).toBeNull();
-
- const noTitle = buildGhostTabPlugin(ghost('plain').manifest);
- expect(noTitle.menu.labelText).toBe('plain 意识');
- });
-});
-
-describe('syncGhostTabRegistrations · Tab 注册表与已装清单对齐', () => {
- it("position:'tab' 且启用的注册;停用/消失的注销", () => {
- syncGhostTabRegistrations([ghost('a'), ghost('b')]);
- expect(getTabKind('ghost:a')).not.toBeNull();
- expect(getTabKind('ghost:b')).not.toBeNull();
-
- // b 停用、a 保留
- syncGhostTabRegistrations([ghost('a'), ghost('b', undefined, false)]);
- expect(getTabKind('ghost:a')).not.toBeNull();
- expect(getTabKind('ghost:b')).toBeNull();
-
- // 全卸光
- syncGhostTabRegistrations([]);
- expect(getTabKind('ghost:a')).toBeNull();
- });
-
- it('清单没变 → 不重注册(plugin 身份稳定);换版 → 原位换新', () => {
- syncGhostTabRegistrations([ghost('a')]);
- const before = getTabKind('ghost:a');
- syncGhostTabRegistrations([ghost('a')]);
- expect(getTabKind('ghost:a')).toBe(before);
-
- const upgraded = ghost('a');
- upgraded.manifest.version = '2.0.0';
- syncGhostTabRegistrations([upgraded]);
- const after = getTabKind('ghost:a');
- expect(after).not.toBe(before);
- expect(after).not.toBeNull();
- });
-
- it('listGhostTabMenuMetas 只含 ghost 项,按 labelText 稳定排序', () => {
- syncGhostTabRegistrations([
- ghost('zeta', { html: 'p.html', position: 'tab', title: '备忘' }),
- ghost('alpha', { html: 'p.html', position: 'tab', title: '画廊' }),
- ]);
- expect(listGhostTabMenuMetas().map((m) => m.labelText)).toEqual(['备忘', '画廊']);
- });
-});
-
-describe('syncGhostPanelRegistrations · 按 position 分派两个注册表', () => {
- it("tab 型只进 Tab 注册表;停靠型只进顶层面板注册表", () => {
- syncGhostPanelRegistrations([
- ghost('tabbed'),
- ghost('docked', { html: 'panel.html', position: 'left' }),
- ]);
- expect(getTabKind('ghost:tabbed')).not.toBeNull();
- expect(hasPanelKind('ghost:tabbed')).toBe(false);
- expect(hasPanelKind('ghost:docked')).toBe(true);
- expect(getTabKind('ghost:docked')).toBeNull();
- });
-
- it('换版把 position 从 left 改成 tab → 顶层注销、页签注册(反向亦然)', () => {
- syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'left' })]);
- expect(hasPanelKind('ghost:m')).toBe(true);
-
- syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'tab' })]);
- expect(hasPanelKind('ghost:m')).toBe(false);
- expect(getTabKind('ghost:m')).not.toBeNull();
-
- syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'left' })]);
- expect(hasPanelKind('ghost:m')).toBe(true);
- expect(getTabKind('ghost:m')).toBeNull();
- });
-});
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
index 90fd6d7d51..26e55f6c2d 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
@@ -16,7 +16,7 @@ import { createGhostThemeInjector, observeHostTheme } from './ghostPanelTheme';
/**
* 意识面板体(webview 供片)—— 顶层停靠 pane(ghostPanels)与右侧栏页签
- * (ghostTabPlugins)共用的渲染内核,从 ghostPanels.tsx 原样抽出:
+ * (features/plugin/GhostPagePanelHost)共用的渲染内核,从 ghostPanels.tsx 原样抽出:
* 沙箱 webview 装载、主题注入、崩溃接管、媒体右键菜单,全部与宿主容器无关。
* 安全边界不变:分区/地址由 main 侧 webview 附加闸验明正身(webview-security),
* 本模块不因换容器多要任何特权。
@@ -81,7 +81,7 @@ export interface GhostPanelMediaMenuState {
* 目录(showItemInFolder)。菜单是宿主自绘(webview 里的右键经 Electron
* context-menu 事件转出,面板自己画不了也伪造不了),地址已过 main 闸换发,
* 两个动作走与聊天媒体完全相同的通用 IPC。
- * (导出给 pooledGhostPanelBody 复用 —— 常驻池形态的面板体右键走同一套菜单。)
+ * (页签形态的面板体右键走同一套菜单。)
*/
export function GhostPanelMediaMenu({
menu,
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelWebviewPool.ts b/apps/desktop/src/renderer/cindy-brain/ghostPanelWebviewPool.ts
deleted file mode 100644
index ca350f60d0..0000000000
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelWebviewPool.ts
+++ /dev/null
@@ -1,225 +0,0 @@
-/**
- * ghostPanelWebviewPool —— 钉住插件面板页签的 webview 常驻池(按 ghostId 分)。
- *
- * 为什么要 pool:面板页签的 webview 若随 React body 卸载而销毁(会话切换会整批
- * 换掉 PluginBodyHost),面板内的页面状态(滚动位置 / 输入 / JS 运行态)全丢,
- * 钉住页签"跨会话保留"就退化成"跨会话重加载"。做法与 browserWebviewPool 一致:
- * webview DOM 保活在脱离 tab 子树的"停车区" container,切换时用 vanilla
- * `appendChild` 把同一个节点搬进目标 slot —— DOM 移动不 detach guest webContents。
- *
- * **关键:不要用 React Portal**(同 browserWebviewPool 的裁决:Portal 跨
- * reconcile 的搬动会 remove + insert,中间一帧 webview detach 丢 webContents)。
- *
- * 与 browserWebviewPool 的三点不同:
- * - key 是 **ghostId** 而非 tabId:钉住语义是"跨会话同一块面板",各会话的页签
- * 实例共享同一个 webview;同会话内 singleton 已保证同 kind 至多一个页签。
- * - **无 LRU 容量位**:entry 只在面板页签首次可见时懒物化(见
- * pooledGhostPanelBody),数量上限 = 用户钉住的插件数,天然有界;取消钉住 /
- * 页签关闭 / 插件停用·卸载·换版都会显式 release。
- * - 主题注入 / dom-ready 重灌挂在 pool 层:面板停在停车区期间主机换肤,
- * 也要保持 token 同步,回到前台不闪错色。
- *
- * 沙箱边界零变化:partition / src 与 GhostChipPanelBody 完全同源,main 侧
- * will-attach-webview 附加闸只认分区与地址,不认宿主容器(webview-security)。
- * 沙箱生命周期纪律:插件沉睡 / 卸下时 syncGhostTabRegistrations 会调 sync()
- * 释放对应 entry —— 常驻只延长 DOM 存续,不延长沙箱生命周期。
- */
-
-import type { WebviewTag } from 'electron';
-
-import { GHOST_SCHEME, ghostPartition, type GhostManifest } from '../../shared/ghost';
-import { createGhostThemeInjector, observeHostTheme } from './ghostPanelTheme';
-
-export const GHOST_PANEL_POOL_CONTAINER_ID = 'ghost-panel-webview-pool';
-
-/**
- * 面板实例的"代际指纹":版本 / 语言 / 入口页任一变化都要求重建 webview
- * (原位升级要立刻跑新代码 —— 与 GhostChipPanelBody 的 effect deps 同语义)。
- */
-export function ghostPanelFingerprint(manifest: GhostManifest): string {
- return JSON.stringify([
- manifest.id,
- manifest.version,
- manifest.resolvedLocale,
- manifest.panel?.html ?? null,
- ]);
-}
-
-export interface GhostPanelPoolEntry {
- ghostId: string;
- fingerprint: string;
- /** 外层 wrapper(caller appendChild 到自己 slot;切走时搬回停车区)。 */
- wrapper: HTMLDivElement;
- /** 真 `<webview>`,挂在 wrapper 内部。 */
- webview: WebviewTag;
- /** guest 渲染进程没了(render-process-gone)。body 据此渲染错误接管态。 */
- crashed: boolean;
-}
-
-interface InternalEntry extends GhostPanelPoolEntry {
- dispose: () => void;
-}
-
-class GhostPanelWebviewPoolImpl {
- private entries = new Map<string, InternalEntry>();
- private container: HTMLDivElement | null = null;
- private crashListeners = new Set<(ghostId: string) => void>();
-
- /** 停车区容器(off-screen but attached,与 browserWebviewPool 同款技巧;
- * 不用 visibility:hidden —— 部分 webview 实现会因此暂停 paint)。 */
- private ensureContainer(): HTMLDivElement {
- if (this.container) return this.container;
- const existing = document.getElementById(GHOST_PANEL_POOL_CONTAINER_ID);
- if (existing instanceof HTMLDivElement) {
- this.container = existing;
- return existing;
- }
- const div = document.createElement('div');
- div.id = GHOST_PANEL_POOL_CONTAINER_ID;
- div.style.cssText =
- 'position:fixed;left:-9999px;top:0;width:1px;height:1px;pointer-events:none;';
- document.body.appendChild(div);
- this.container = div;
- return div;
- }
-
- /**
- * 取或创建 entry。无 panel.html 的清单返回 null(调用方按"无面板"降级)。
- * 指纹不一致时先 release 再重建 —— 原位升级 / 换语言立即生效。
- */
- acquire(manifest: GhostManifest): GhostPanelPoolEntry | null {
- const panelHtml = manifest.panel?.html;
- if (!panelHtml) return null;
- const fingerprint = ghostPanelFingerprint(manifest);
- const existing = this.entries.get(manifest.id);
- if (existing) {
- if (existing.fingerprint === fingerprint) return existing;
- this.release(manifest.id);
- }
- const container = this.ensureContainer();
- const wrapper = document.createElement('div');
- wrapper.dataset.poolGhostId = manifest.id;
- // slot 给 wrapper 多大宽高 webview 跟着拉伸;背景走面板底 token,首帧过渡
- // 贴主题(browserWebviewPool 同款处理,只是面板底色用 --panel-bg)。
- wrapper.style.cssText =
- 'position:relative;width:100%;height:100%;display:flex;background-color:var(--panel-bg);';
- const webview = document.createElement('webview') as WebviewTag;
- // partition / src 与 GhostChipPanelBody 完全同源;main 侧附加闸兜底验明正身。
- webview.setAttribute('partition', ghostPartition(manifest.id));
- webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${panelHtml}`);
- webview.setAttribute('style', 'display:flex;flex:1 1 auto;width:100%;height:100%;');
- wrapper.appendChild(webview);
-
- const entry: InternalEntry = {
- ghostId: manifest.id,
- fingerprint,
- wrapper,
- webview,
- crashed: false,
- dispose: () => undefined,
- };
-
- // 主题注入状态机(换肤去重 / dom-ready 无条件重灌)封装在 injector 内;
- // 突发属性变动合并成一次注入 —— 与 GhostChipPanelBody 同款节奏。
- const injector = createGhostThemeInjector(webview);
- let disposed = false;
- let themeTimer: ReturnType<typeof setTimeout> | null = null;
- const scheduleInjectTheme = () => {
- if (themeTimer !== null) return;
- themeTimer = setTimeout(() => {
- themeTimer = null;
- if (!disposed) injector.inject();
- }, 50);
- };
- const onDomReady = () => injector.onDomReady();
- const onGone = () => {
- if (disposed || entry.crashed) return;
- entry.crashed = true;
- this.fireCrash(entry.ghostId);
- };
- // 监听必须在 wrapper 接入 document 前装好(browserWebviewPool 同纪律):
- // 挂进停车区那一刻 guest 即开始加载,期间的崩溃不能丢。
- webview.addEventListener('dom-ready', onDomReady);
- webview.addEventListener('render-process-gone', onGone);
- const unobserveTheme = observeHostTheme(scheduleInjectTheme);
- entry.dispose = () => {
- disposed = true;
- injector.dispose();
- if (themeTimer !== null) clearTimeout(themeTimer);
- unobserveTheme();
- webview.removeEventListener('dom-ready', onDomReady);
- webview.removeEventListener('render-process-gone', onGone);
- };
-
- container.appendChild(wrapper);
- this.entries.set(manifest.id, entry);
- return entry;
- }
-
- /** 仅取已存在的 entry(懒物化判断用);不存在返回 null。 */
- peek(ghostId: string): GhostPanelPoolEntry | null {
- return this.entries.get(ghostId) ?? null;
- }
-
- /**
- * 显式销毁:wrapper 移出 DOM(guest webContents 随之被 Electron 销毁)。
- * 触发点:取消钉住后的页签卸载 / 关闭页签 / 插件停用·卸载·换版 / 崩溃重载。
- */
- release(ghostId: string): void {
- const entry = this.entries.get(ghostId);
- if (!entry) return;
- entry.dispose();
- entry.wrapper.remove();
- this.entries.delete(ghostId);
- }
-
- /**
- * 与"已装且启用、面板形态为页签"的清单对齐:不在清单里(停用 / 卸载 / 换
- * 形态)或指纹已变(原位升级 / 换语言)的 entry 全部释放。由
- * syncGhostTabRegistrations 在每次 ghosts 同步时调用 —— 沙箱生命周期纪律
- * (沉睡 / 抽离必须终止)在这里落地,常驻池不给被停用的插件续命。
- */
- sync(alive: ReadonlyArray<{ ghostId: string; fingerprint: string }>): void {
- const expected = new Map(alive.map((a) => [a.ghostId, a.fingerprint]));
- for (const [ghostId, entry] of [...this.entries]) {
- if (expected.get(ghostId) !== entry.fingerprint) this.release(ghostId);
- }
- }
-
- /**
- * 释放全部 entry。侧边栏宿主窗口切换(内嵌 ↔ 独立子窗口)时调用 —— 本
- * renderer 的 webview 即将失去宿主语义,留着就是僵尸实例(browserWebviewPool
- * 的 releaseAll 同款场景,MainLayout detach 转换 effect 一并调)。
- */
- releaseAll(): void {
- for (const ghostId of [...this.entries.keys()]) {
- this.release(ghostId);
- }
- }
-
- /** 订阅 guest 崩溃(body 据此切错误接管态;重载 = release + 重新 acquire)。 */
- onCrash(listener: (ghostId: string) => void): () => void {
- this.crashListeners.add(listener);
- return () => {
- this.crashListeners.delete(listener);
- };
- }
-
- private fireCrash(ghostId: string): void {
- for (const l of this.crashListeners) {
- try {
- l(ghostId);
- } catch {
- // listener 抛错不阻断池内状态推进
- }
- }
- }
-
- /** 调试 / 测试用:当前池内 ghostId 列表。 */
- inspectGhostIds(): string[] {
- return [...this.entries.keys()];
- }
-}
-
-/** 全局单例 —— 整个 renderer 进程共享一个池。 */
-export const ghostPanelWebviewPool = new GhostPanelWebviewPoolImpl();
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
index 205973e22f..5a716e7812 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
@@ -11,7 +11,6 @@ import { PanelChrome } from '../panels/PanelChrome';
import { registerPanelKind, unregisterPanelKind, type PanelComponentProps } from '../panels/registry';
import { extractIpcError } from '../utils/ipcError';
import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';
-import { syncGhostTabRegistrations } from './ghostTabPlugins';
import { ghostInstallErrorKey } from './installErrorKey';
import { pruneGhostSettingsSnapshots } from './ghostSettingsSnapshot';
import { useGhostRuntimeState } from './runtimeStates';
@@ -29,7 +28,7 @@ import { useGhostRuntimeState } from './runtimeStates';
* 树数据保留,重装即原位复活(§6 规则 5 的正式生效点)。
*
* 面板体(webview 供片/主题注入/崩溃接管/媒体右键)在 ghostPanelBody.tsx,
- * 与右侧栏页签形态(position:'tab',ghostTabPlugins.tsx)共用;本模块只管
+ * 与插件页页签形态(position:'tab',features/plugin/GhostPagePanelHost)共用;本模块只管
* 停靠形态(left / right)与两个注册表的同步入口。
*/
@@ -159,8 +158,8 @@ const registeredFingerprints = new Map<string, string>();
* 把注册表与"当前已装清单"对齐:新装的注册、卸下的注销、没变的不动。
* 停用(enabled=false)的意识视同不在场 —— 面板注销、布局里 pane 隐藏休眠,
* 重新启用时走同一条对齐路径复活(与"卸下再重装"共用 §6 规则 5 语义)。
- * position:'tab' 的面板不进本注册表,分派给右侧栏页签注册表(ghostTabPlugins);
- * 换版改 position 时,两边的差集注销各自兜住旧形态。
+ * position:'tab' 的面板不进任何常驻注册表(面板收束,2026-08):由插件页
+ * 独占承载(features/plugin/GhostPagePanelHost),离开插件页即卸载。
*/
export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {
// 顺手清设置区快照缓存的孤儿(卸载的意识不该在 localStorage 留位图);
@@ -170,12 +169,10 @@ export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {
// 气泡状态对齐(与快照 prune 不同:停用/失格的要强制还原,不只清卸载)——
// 气泡是"面板不可见 + 唯一恢复入口",失格后必须回停靠,不留死角。
reconcileGhostPanelBubbles(ghosts);
- // 页签形态与停靠形态同源同步:一次广播喂两个注册表,不各自订阅。
- syncGhostTabRegistrations(ghosts);
const seen = new Set<string>();
for (const { manifest, enabled } of ghosts) {
if (!manifest.panel) continue; // 无面板的意识(未来纯工具卡)不进注册表
- if (manifest.panel.position === 'tab') continue; // 页签形态归右侧栏注册表
+ if (manifest.panel.position === 'tab') continue; // 页签形态由插件页承载(面板收束)
if (enabled === false) continue; // 停用 = 休眠,不注册(注销走下方 seen 差集)
const kind = ghostPanelKind(manifest.id);
seen.add(kind);
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsx b/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsx
deleted file mode 100644
index 9538b5b70b..0000000000
--- a/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-import type { ReactNode } from 'react';
-import { Puzzle } from 'lucide-react';
-
-import { ghostPanelKind, type GhostManifest, type InstalledGhost } from '../../shared/ghost';
-import { registerTabKind, unregisterTabKind } from '../features/right-sidebar/registry';
-import { pruneGhostTabPins } from '../features/right-sidebar/lib/pinnedGhostTabs';
-import type { TabKindId, TabKindPlugin } from '../features/right-sidebar/types';
-import { GhostPanelError } from './ghostPanelBody';
-import { ghostPanelFingerprint, ghostPanelWebviewPool } from './ghostPanelWebviewPool';
-import { PooledGhostPanelBody } from './pooledGhostPanelBody';
-import { useGhostRuntimeState } from './runtimeStates';
-
-/**
- * 意识面板的右侧栏页签形态(panel.position: 'tab')接入 Tab 插件注册表。
- *
- * 与顶层停靠形态(ghostPanels.tsx)的关系:
- * - 同一数据源:syncGhostPanelRegistrations 是"已装清单"的唯一同步点
- * (启动 listSync + ghosts:changed 广播),按 position 分派到两个注册表,
- * 本模块不自建订阅;
- * - 同一面板体:webview 供片/主题注入/崩溃接管全部复用 ghostPanelBody,
- * 沙箱边界与特权面零变化(附加闸只认分区/地址,与宿主容器无关);
- * - 同一复活语义:停用/卸下 → unregisterTabKind,已开的 tab 落回 Shell 的
- * PlaceholderBody(数据保留);重新启用 → 重注册,原 tab 原位复活。
- *
- * 页签语义对齐 review:menu.singleton = true,每 session 至多一个;
- * kind 复用 ghostPanelKind 的 `ghost:<id>`(DB kind 列无枚举约束,可直存)。
- */
-
-/** 页签体:Shell 已提供容器与 TabBar,不再套 PanelChrome 标准头。
- * webview 托管在 ghostPanelWebviewPool(钉住 → 跨会话保活;未钉住 → 卸载即释,
- * 语义同旧版每次挂载新建);沙箱崩 / 熔断仍走停靠形态同款错误接管。 */
-function GhostTabBody({
- manifest,
- visible,
-}: {
- manifest: GhostManifest;
- visible: boolean;
-}): ReactNode {
- // 沙箱崩了/熔断 → 与停靠形态同款错误接管(GhostPanel broken 分支的等价物)。
- const runtimeState = useGhostRuntimeState(manifest.id);
- const broken = runtimeState === 'crashed' || runtimeState === 'fused';
- return (
- <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">
- {broken ? (
- <GhostPanelError manifest={manifest} state={runtimeState} />
- ) : (
- <PooledGhostPanelBody manifest={manifest} visible={visible} />
- )}
- </div>
- );
-}
-
-/** 由清单构造一份 Tab 插件契约(纯函数,方便单测直接断言 menu 形状)。 */
-export function buildGhostTabPlugin(manifest: GhostManifest): TabKindPlugin {
- const kind = ghostPanelKind(manifest.id) as TabKindId;
- const label = manifest.panel?.title ?? manifest.name;
- const TabPillTitle: TabKindPlugin['TabPillTitle'] = () => <>{label}</>;
- const TabPillIcon: NonNullable<TabKindPlugin['TabPillIcon']> = () => <Puzzle size={13} />;
- // active / shellVisible → 懒物化判据:页签首次真正可见才创建面板 webview。
- const TabBody: TabKindPlugin['TabBody'] = ({ active, shellVisible }) => (
- <GhostTabBody manifest={manifest} visible={active !== false && shellVisible !== false} />
- );
- return {
- kind,
- menu: {
- kind,
- // 插件名是用户内容进不了 i18n,走 labelText 原文;labelKey 只作兜底。
- labelKey: 'rightSidebar.tabs.kinds.ghostPanel',
- labelText: label,
- icon: Puzzle,
- // 排内置项之后;「+」菜单/空态的动态分组内部按 labelText 排
- // (listGhostTabMenuMetas),order 不参与组内排序。
- order: 100,
- enabled: true,
- // 与 review 同款单例:每 session 至多一个页签,已开则切过去。
- singleton: true,
- },
- TabPillTitle,
- TabPillIcon,
- TabBody,
- defaultState: () => null,
- };
-}
-
-/** 已注册页签插件:kind → 清单指纹(与 ghostPanels 的 fingerprint 语义一致)。 */
-const registeredTabFingerprints = new Map<string, string>();
-
-/**
- * 把 Tab 注册表与"当前已装清单"对齐:启用且 position:'tab' 的注册,
- * 消失/停用/换形态的注销。由 syncGhostPanelRegistrations 每次同步时调用。
- */
-export function syncGhostTabRegistrations(ghosts: InstalledGhost[]): void {
- const seen = new Set<string>();
- for (const { manifest, enabled } of ghosts) {
- if (manifest.panel?.position !== 'tab') continue;
- if (enabled === false) continue;
- const kind = ghostPanelKind(manifest.id);
- seen.add(kind);
- const fingerprint = JSON.stringify(manifest);
- if (registeredTabFingerprints.get(kind) === fingerprint) continue;
- // 原位升级换版:先注销旧注册再挂新的(registerTabKind 对重复 kind 抛错)。
- if (registeredTabFingerprints.has(kind)) unregisterTabKind(kind as TabKindId);
- registeredTabFingerprints.set(kind, fingerprint);
- registerTabKind(buildGhostTabPlugin(manifest));
- }
- for (const kind of [...registeredTabFingerprints.keys()]) {
- if (seen.has(kind)) continue;
- registeredTabFingerprints.delete(kind);
- unregisterTabKind(kind as TabKindId);
- }
- // 常驻池对齐同一份清单:停用 / 卸载 / 换形态 / 换版的面板 webview 就地释放
- // —— 沙箱生命周期纪律(沉睡、抽离必须终止)不因"钉住保活"打折。
- ghostPanelWebviewPool.sync(
- ghosts
- .filter((g) => g.enabled !== false && g.manifest.panel?.position === 'tab')
- .map((g) => ({ ghostId: g.manifest.id, fingerprint: ghostPanelFingerprint(g.manifest) })),
- );
- // 钉住偏好的孤儿清理:被卸载的插件不再占条目(停用不清 —— 重新启用时
- // 钉住状态原位复活,与页签"停用落 Placeholder、重启用复活"同语义)。
- pruneGhostTabPins(new Set(ghosts.map((g) => g.manifest.id)));
-}
-
-/** 仅测试用:清空本模块注册,保证用例间隔离。 */
-export function __resetGhostTabPluginsForTest(): void {
- for (const kind of [...registeredTabFingerprints.keys()]) {
- unregisterTabKind(kind as TabKindId);
- }
- registeredTabFingerprints.clear();
-}
diff --git a/apps/desktop/src/renderer/cindy-brain/pooledGhostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/pooledGhostPanelBody.tsx
deleted file mode 100644
index 1f4696e1bc..0000000000
--- a/apps/desktop/src/renderer/cindy-brain/pooledGhostPanelBody.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
-import type { ContextMenuEvent } from 'electron';
-
-import { isGhostTabPinned } from '@/features/right-sidebar/lib/pinnedGhostTabs';
-import type { GhostManifest } from '../../shared/ghost';
-import {
- GhostPanelError,
- GhostPanelMediaMenu,
- pickGhostPanelMediaUri,
- type GhostPanelMediaMenuState,
-} from './ghostPanelBody';
-import {
- GHOST_PANEL_POOL_CONTAINER_ID,
- ghostPanelWebviewPool,
-} from './ghostPanelWebviewPool';
-
-/**
- * PooledGhostPanelBody —— 面板页签形态的面板体,webview 托管在
- * ghostPanelWebviewPool(常驻池),React 只负责把 wrapper 搬进 / 搬出自己的 slot。
- *
- * 与 GhostChipPanelBody(每次挂载新建 webview,停靠形态继续用)的分工:
- * - 页签形态统一走本组件:挂载时收养池里的 wrapper,卸载时把 wrapper 停回
- * 停车区(钉住 → webview 保活,跨会话状态不丢)或释放(未钉住 → 维持
- * "仅当前会话"的既有语义,不白占内存);
- * - 懒物化:面板页签**首次可见**才创建 webview —— 钉住多个插件不会在启动 /
- * 切会话时把所有面板一起拉起;
- * - 崩溃接管:池层广播 render-process-gone,本组件切 GhostPanelError,
- * 「重载」= release + 重新 acquire(原地重挂载,不经主机)。
- *
- * 媒体右键菜单挂在"正在收养 wrapper 的 body"上(webview 事件监听随收养期
- * 增删):菜单坐标 / 浮层都属于当前宿主视图,停车区里的面板没有可弹的宿主。
- */
-export function PooledGhostPanelBody({
- manifest,
- visible,
-}: {
- manifest: GhostManifest;
- /** 页签当前是否真的可见(active 且侧栏展开)。懒物化判据。 */
- visible: boolean;
-}): ReactNode {
- const [crashed, setCrashed] = useState(
- () => ghostPanelWebviewPool.peek(manifest.id)?.crashed === true,
- );
- // 崩溃重载计数:release 后靠它驱动 effect 重跑重新 acquire。
- const [reloadGeneration, setReloadGeneration] = useState(0);
- const [mediaMenu, setMediaMenu] = useState<GhostPanelMediaMenuState | null>(null);
- const hostRef = useRef<HTMLDivElement | null>(null);
-
- // 池层崩溃广播 → 本组件错误接管态(停车区里崩的也要在下次看到时如实呈现)。
- useEffect(
- () =>
- ghostPanelWebviewPool.onCrash((ghostId) => {
- if (ghostId === manifest.id) setCrashed(true);
- }),
- [manifest.id],
- );
-
- // 物化 + 收养:可见(或已有 entry)→ acquire(指纹变化时池内自动重建)→
- // 把 wrapper 搬进 slot。useLayoutEffect 在 paint 前移 DOM,避免闪帧。
- // cleanup 只"停回停车区",不做释放决策 —— 释放归下面的 unmount effect,
- // 否则 active 切换(visible 翻转)就会把未钉住面板的 webview 错杀。
- useLayoutEffect(() => {
- if (crashed) return;
- const host = hostRef.current;
- if (!host) return;
- let entry = ghostPanelWebviewPool.peek(manifest.id);
- if (!entry && !visible) return; // 懒物化:没看过就不创建
- entry = ghostPanelWebviewPool.acquire(manifest);
- if (!entry) return; // 清单没有 panel.html(理论上注册时已过滤)
- if (entry.crashed) {
- setCrashed(true);
- return;
- }
- const wrapper = entry.wrapper;
- host.appendChild(wrapper);
- return () => {
- // release 后的旧 wrapper 已不归池持有,不能因 effect cleanup 被停回
- // 停车区(browserWebviewPool/BrowserTabBody 同款归属判断)。
- if (ghostPanelWebviewPool.peek(manifest.id)?.wrapper !== wrapper) {
- wrapper.remove();
- return;
- }
- const parking = document.getElementById(GHOST_PANEL_POOL_CONTAINER_ID);
- if (parking) parking.appendChild(wrapper);
- else wrapper.remove();
- };
- }, [manifest, visible, crashed, reloadGeneration]);
-
- // 收养期内的媒体右键菜单:与 GhostChipPanelBody 同一套过闸 + 自绘菜单。
- useEffect(() => {
- if (crashed) return;
- const entry = ghostPanelWebviewPool.peek(manifest.id);
- if (!entry) return;
- let disposed = false;
- const onContextMenu = (e: ContextMenuEvent) => {
- const uri = pickGhostPanelMediaUri(e.params, manifest.id);
- if (!uri) return;
- const pos = { x: e.params.x, y: e.params.y };
- void window.electronAPI.ghosts.resolvePanelMedia(uri, 'menu').then(
- ({ url, kind }) => {
- if (disposed) return;
- const active = document.activeElement;
- if (active instanceof HTMLElement) active.blur();
- setMediaMenu({ ...pos, url, kind: kind ?? 'image' });
- },
- () => {
- /* 过闸失败:静默不弹(与停靠形态同纪律)。 */
- },
- );
- };
- entry.webview.addEventListener('context-menu', onContextMenu);
- return () => {
- disposed = true;
- entry.webview.removeEventListener('context-menu', onContextMenu);
- setMediaMenu(null);
- };
- // visible / reloadGeneration 入依赖:懒物化与崩溃重载都可能在本 effect
- // 首跑之后才创建 entry,需要重跑补绑监听。
- }, [manifest.id, crashed, visible, reloadGeneration]);
-
- // 真正的释放决策只在组件 unmount(页签关闭 / 会话切换换批 / 插件注销):
- // 钉住 → 保活停车区;未钉住 → 释放,维持"仅当前会话"的旧语义。
- // manifest.id 走 ref 同步给 cleanup 闭包(BrowserTabBody 的 releaseTabIdRef 同款)。
- const ghostIdRef = useRef(manifest.id);
- ghostIdRef.current = manifest.id;
- useEffect(() => {
- return () => {
- const ghostId = ghostIdRef.current;
- if (!isGhostTabPinned(ghostId)) ghostPanelWebviewPool.release(ghostId);
- };
- }, []);
-
- if (crashed) {
- return (
- <GhostPanelError
- manifest={manifest}
- state="crashed"
- onReload={() => {
- ghostPanelWebviewPool.release(manifest.id);
- setCrashed(false);
- setReloadGeneration((g) => g + 1);
- }}
- />
- );
- }
- // data-ghost-webview:拖缝/拖面板期间 body.resizing-pane 指针穿透(与停靠形态同款)。
- return (
- <>
- <div ref={hostRef} 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/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 0d840d07fe..f53b292c93 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -40,7 +40,6 @@ import {
invalidateSessionCaches,
} from '@/features/right-sidebar/store';
import { browserWebviewPool } from '@/features/right-sidebar/lib/browserWebviewPool';
-import { ghostPanelWebviewPool } from '@/cindy-brain/ghostPanelWebviewPool';
import { markAllPtyDetached } from '@/features/right-sidebar/plugins/terminal/lib/xtermPool';
import {
bootstrapRsbWindowState,
@@ -836,9 +835,6 @@ export function MainLayout() {
if (rsbDetached) {
setIsRightSidebarMaximized(false);
browserWebviewPool.releaseAll();
- // 钉住插件面板的常驻池同场景同命运:宿主迁移后本 renderer 的面板 webview
- // 全是僵尸,子窗口接管时按需重建。
- ghostPanelWebviewPool.releaseAll();
// 终端 entry 的 ptyAttached 是 per-renderer 标记:宿主迁移后本窗的标记必然
// 过期(PTY sink 会被对方窗口 re-attach 抢走),两个方向都要复位,否则
// "弹出 → 合并回主窗"往返后 guard 跳过 re-attach,终端失活。
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPagePanelHost.tsx b/apps/desktop/src/renderer/features/plugin/GhostPagePanelHost.tsx
new file mode 100644
index 0000000000..0806717dcb
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/GhostPagePanelHost.tsx
@@ -0,0 +1,68 @@
+/**
+ * In-page host for tab-form Ghost panels, owned exclusively by the Plugin page.
+ *
+ * Inputs: the installed Ghost whose panel is open plus a close callback.
+ * Outputs: the sandboxed panel body beside the catalog; unmounting on route
+ * leave is the "面板收束" contract (panels never persist outside the Plugin page).
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ */
+
+import { Puzzle, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { GhostChipPanelBody, GhostPanelError } from '@/cindy-brain/ghostPanelBody';
+import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
+import type { InstalledGhost } from '../../../shared/ghost';
+
+/**
+ * 面板收束(设计定稿):插件小侧边只从插件页进入,同一时刻至多一个,
+ * 离开插件页(本组件随路由卸载)即关闭,不在右侧栏页签体系里常驻。
+ * 面板体(webview 供片/主题注入/崩溃接管)与停靠形态共用 ghostPanelBody,
+ * 沙箱边界零变化。
+ */
+export function GhostPagePanelHost({
+ ghost,
+ onClose,
+}: {
+ ghost: InstalledGhost;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation();
+ const { manifest } = ghost;
+ const runtimeState = useGhostRuntimeState(manifest.id);
+ const broken = runtimeState === 'crashed' || runtimeState === 'fused';
+ const width = Math.max(manifest.panel?.minWidth ?? 320, 320);
+ return (
+ <aside
+ className="flex h-full min-h-0 shrink-0 flex-col overflow-hidden border-l-[0.5px] border-[var(--border-default)] bg-[var(--panel-bg)]"
+ style={{ width }}
+ aria-label={manifest.panel?.title ?? manifest.name}
+ >
+ <div
+ className="flex h-11 shrink-0 items-center gap-2 border-b-[0.5px] border-[var(--border-default)] px-3"
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ <Puzzle size={14} className="shrink-0 text-[var(--text-secondary)]" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-13 font-medium text-[var(--text-primary)]">
+ {manifest.panel?.title ?? manifest.name}
+ </span>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={t('settings.ghosts.panelHost.close')}
+ className="grid size-7 shrink-0 place-items-center rounded-full text-[var(--text-secondary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <X size={15} aria-hidden="true" />
+ </button>
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
+ {broken ? (
+ <GhostPanelError manifest={manifest} state={runtimeState} />
+ ) : (
+ <GhostChipPanelBody manifest={manifest} />
+ )}
+ </div>
+ </aside>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index fd38c0161f..3cb9d79780 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -11,11 +11,13 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import {
AppWindow,
+ ArrowUp,
Bot,
ChevronDown,
Copy,
Cpu,
Download,
+ MessageCircle,
FileCode2,
FilePen,
FolderOpen,
@@ -59,6 +61,7 @@ import type { GhostPermissionItem, GhostToolDecl, InstalledGhost } from '../../.
import { type GhostPluginDetail } from './lib/ghostPluginViewModel';
import { GhostPluginIcon } from './GhostPluginIcon';
import { ghostPluginSummary } from './lib/ghostPluginDetailModel';
+import { ghostPrimaryAction } from './lib/ghostPluginViewModel';
import { PluginDetailTopBar, usePluginDetailScrolled } from './PluginDetailTopBar';
import './plugin-motion.css';
@@ -69,9 +72,12 @@ interface GhostPluginDetailViewProps {
enabledOverride?: boolean;
onBack: () => void;
onToggle: (enabled: boolean) => void;
+ /** 主动作:面板型「使用」(打开面板)/ 指令型「对话」;纯工具型不渲染主按钮。 */
onUse: () => void;
+ /** 头部更新 CTA:市场有新版本时走市场更新确认流。 */
onUpdate: () => void;
- updateLabel?: string;
+ /** ⋮ 菜单的兜底路径:从本地 .cindy 文件更新。 */
+ onUpdateFromFile: () => void;
/** 市场存在新版本时的目标版本号;设置后头部展示显著的更新按钮。 */
updateVersion?: string;
updateBusy?: boolean;
@@ -135,7 +141,7 @@ export function GhostPluginDetailView({
onToggle,
onUse,
onUpdate,
- updateLabel,
+ onUpdateFromFile,
updateVersion,
updateBusy = false,
onUninstall,
@@ -149,7 +155,9 @@ export function GhostPluginDetailView({
const [descriptionOverflows, setDescriptionOverflows] = useState(false);
const descriptionRef = useRef<HTMLParagraphElement>(null);
const enabled = enabledOverride ?? detail.enabled;
- const canUse = enabled && detail.canUse;
+ const primaryAction = ghostPrimaryAction(detail);
+ const primaryEnabled =
+ enabled && (primaryAction === 'panel' || (primaryAction === 'command' && detail.canUse));
const cindyCapabilities = detail.cindyCapabilities;
const hasConfiguration =
detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;
@@ -229,43 +237,86 @@ export function GhostPluginDetailView({
style={WINDOW_NO_DRAG_STYLE}
>
{updateVersion ? (
+ // 更新提级(设计定稿):有新版本时黑色主 CTA 直达市场更新确认流。
<button
type="button"
onClick={onUpdate}
disabled={updateBusy}
className={cn(
- 'inline-flex h-10 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5 text-13 font-medium text-[var(--text-primary)]',
- 'transition-[background-color,border-color,transform,opacity] duration-150 hover:border-[var(--text-tertiary)] hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',
+ 'inline-flex h-10 items-center justify-center gap-1.5 rounded-full px-5 text-13 font-medium',
+ 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)]',
+ 'transition-[background-color,transform,opacity] duration-150 hover:bg-[var(--accent-hover)] active:scale-[0.98]',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'disabled:cursor-wait disabled:opacity-40 disabled:active:scale-100',
+ 'disabled:cursor-wait disabled:opacity-60 disabled:active:scale-100',
)}
>
+ <ArrowUp size={14} aria-hidden="true" />
{updateVersion === detail.version
? t('settings.ghosts.market.update')
: t('settings.ghosts.market.updateTo', { version: updateVersion })}
</button>
) : null}
+ {primaryAction !== 'manage' ? (
+ <button
+ type="button"
+ onClick={onUse}
+ disabled={!primaryEnabled}
+ title={!enabled ? t('settings.ghosts.detail.useDisabled') : undefined}
+ className={cn(
+ 'plugin-detail-primary-action inline-flex h-10 min-w-[88px] items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-3 text-13 font-medium',
+ updateVersion
+ ? 'border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] hover:bg-[var(--surface-hover-soft)]'
+ : 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)] hover:bg-[var(--accent-hover)]',
+ 'transition-[background-color,transform,opacity] duration-150 active:scale-[0.98]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100',
+ )}
+ >
+ {primaryAction === 'command' ? (
+ <MessageCircle size={14} aria-hidden="true" />
+ ) : null}
+ {t(
+ primaryAction === 'panel'
+ ? 'settings.ghosts.detail.useAction'
+ : 'settings.ghosts.detail.chatAction',
+ )}
+ </button>
+ ) : null}
+ {/* 启用开关带明确文字(设计定稿):状态一目了然,点文字同样可切换。 */}
<button
type="button"
- onClick={onUse}
- disabled={!canUse}
- title={!enabled ? t('settings.ghosts.detail.useDisabled') : undefined}
+ onClick={() => {
+ if (!toggleDisabled) onToggle(!enabled);
+ }}
+ disabled={toggleDisabled}
+ aria-pressed={enabled}
+ aria-label={t('settings.ghosts.enableAria', { name: detail.name })}
className={cn(
- 'plugin-detail-primary-action inline-flex h-10 min-w-[88px] items-center justify-center whitespace-nowrap rounded-full px-3 text-13 font-medium',
- 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)]',
- 'transition-[background-color,transform,opacity] duration-150 hover:bg-[var(--accent-hover)] active:scale-[0.98]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100',
+ 'flex shrink-0 items-center gap-2 rounded-full py-1 pl-3 pr-1 transition-colors duration-150',
+ 'hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:cursor-not-allowed disabled:opacity-60',
)}
>
- {t('settings.ghosts.detail.useAction')}
+ <span
+ className={cn(
+ 'text-12',
+ enabled ? 'text-[var(--text-secondary)]' : 'text-[var(--text-tertiary)]',
+ )}
+ >
+ {t(
+ enabled
+ ? 'settings.ghosts.detail.enabledLabel'
+ : 'settings.ghosts.detail.disabledLabel',
+ )}
+ </span>
+ <Switch
+ checked={enabled}
+ disabled={toggleDisabled}
+ aria-hidden="true"
+ tabIndex={-1}
+ className="pointer-events-none"
+ />
</button>
- <Switch
- checked={enabled}
- onCheckedChange={onToggle}
- disabled={toggleDisabled}
- aria-label={t('settings.ghosts.enableAria', { name: detail.name })}
- />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
@@ -282,11 +333,11 @@ export function GhostPluginDetailView({
className="w-56 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-1.5 text-[var(--text-primary)] shadow-[var(--shadow-menu)]"
>
<DropdownMenuItem
- onSelect={onUpdate}
+ onSelect={onUpdateFromFile}
disabled={updateBusy}
className="h-10 rounded-lg px-3 text-13 focus:bg-[var(--surface-hover-soft)]"
>
- {updateLabel ?? t('settings.ghosts.detail.updateFromFile')}
+ {t('settings.ghosts.detail.updateFromFile')}
</DropdownMenuItem>
{onExport ? (
<DropdownMenuItem
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 547bff9511..8e6ee3c905 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -6,14 +6,33 @@
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
*/
-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type KeyboardEvent,
+ type ReactNode,
+} from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
-import { ChevronDown, ChevronRight, ChevronUp, Plus, Sparkles, Upload } from 'lucide-react';
+import {
+ ArrowUp,
+ Bot,
+ Check,
+ ChevronDown,
+ ChevronRight,
+ MessageCircle,
+ Plus,
+ SlidersHorizontal,
+ Sparkles,
+ Upload,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
-import { Tip } from '@/components/ui/tooltip';
import {
DropdownMenu,
DropdownMenuContent,
@@ -36,7 +55,6 @@ 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 { Switch } from '@/components/ui/switch';
import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';
import { findSplitChildByPanelKind } from '../../../shared/layoutTree';
import { resolveSystemLocale } from '../../../shared/locale';
@@ -57,22 +75,32 @@ import {
toGhostPluginDetail,
toGhostPluginListItem,
filterGhostPluginItems,
+ ghostPrimaryAction,
marketPresentationForInstalledGhost,
sortGhostPluginItemsByRecentUse,
type GhostPluginListItem,
} from './lib/ghostPluginViewModel';
+import {
+ batchSummary,
+ buildUpdateAllRows,
+ isBatchFinished,
+ updateRoundKey,
+ updateRow,
+ type UpdateAllRow,
+} from './lib/updateAllModel';
import { formatSetupGateDescription } from './lib/ghostSetupGateModel';
import {
PLUGIN_MANAGEMENT_CARD_GRID_CLASS,
PluginManagementLayout,
PluginManagementPage,
} from './PluginManagementLayout';
+import { GhostPagePanelHost } from './GhostPagePanelHost';
import { GhostPluginDetailView } from './GhostPluginDetailView';
+import { UpdateAllDialog } from './UpdateAllDialog';
import { GhostPluginIcon } from './GhostPluginIcon';
import { MarketPluginDetailView } from './MarketPluginDetailView';
import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker';
import {
- orderPluginCatalogItems,
pluginPresentationOrigin,
pluginUpdateForInstalledVersion,
type PluginPresentationOrigin,
@@ -83,7 +111,6 @@ import { usePluginMarketForegroundRefresh } from './lib/usePluginMarketForegroun
import { usePluginMarketLocaleRefresh } from './lib/usePluginMarketLocaleRefresh';
import './plugin-motion.css';
-const MAX_VISIBLE_INSTALLED_GHOSTS = 5;
const PLUGIN_CATALOG_TOOLBAR_CLASS =
'plugin-catalog-toolbar mb-5 flex items-center justify-between gap-4';
type PluginPresentationFilter = 'all' | PluginPresentationOrigin;
@@ -93,13 +120,24 @@ type PresentedGhostPluginItem = GhostPluginListItem & {
marketUpdate: PluginMarketItem | null;
};
-const PRESENTATION_FILTERS: readonly PluginPresentationFilter[] = [
+/** 推荐区来源过滤:本地装的必然在已安装区,不设「本地」档(设计定稿)。 */
+const RECOMMENDED_FILTERS: readonly PluginPresentationFilter[] = [
'all',
'public',
'organization',
- 'local',
];
+/** 「忽略本轮更新」的持久键(值 = updateRoundKey,版本集合变化后横幅自动回归)。 */
+const IGNORED_UPDATE_ROUND_KEY = 'cindy.pluginUpdates.ignoredRound';
+
+function readIgnoredRound(): string {
+ try {
+ return window.localStorage.getItem(IGNORED_UPDATE_ROUND_KEY) ?? '';
+ } catch {
+ return '';
+ }
+}
+
/**
* Ghost-backed Plugin page.
*
@@ -116,6 +154,8 @@ export function GhostPluginPage() {
const { user, mode, dataOwnerId } = useAuth();
const showEnterprise = user?.membershipKind === 'org';
const ghosts = useInstalledGhosts();
+ const ghostsRef = useRef(ghosts);
+ ghostsRef.current = ghosts;
const installedGhostIdsKey = ghosts
.map((ghost) => ghost.manifest.id)
.sort()
@@ -126,8 +166,9 @@ export function GhostPluginPage() {
.join('\0');
const [selectedId, setSelectedId] = useState<string | null>(null);
const [query, setQuery] = useState('');
- const [installedExpanded, setInstalledExpanded] = useState(false);
const [marketSnapshot, setMarketSnapshot] = useState<PluginMarketSnapshot | null>(null);
+ const [openPanelId, setOpenPanelId] = useState<string | null>(null);
+ const [ignoredRound, setIgnoredRound] = useState(readIgnoredRound);
const [originFilter, setOriginFilter] = useState<PluginPresentationFilter>('all');
const [marketDetail, setMarketDetail] = useState<PluginMarketDetail | null>(null);
const [marketBusyId, setMarketBusyId] = useState<string | null>(null);
@@ -327,10 +368,6 @@ export function GhostPluginPage() {
: allInstalledItems.filter((item) => item.origin !== 'organization'),
[allInstalledItems, showEnterprise],
);
- const installedShortcutItems = useMemo(
- () => sortGhostPluginItemsByRecentUse(installedItems, recentGhostIds),
- [installedItems, recentGhostIds],
- );
const searchedInstalledItems = useMemo(
() => filterGhostPluginItems(installedItems, query),
[installedItems, query],
@@ -347,22 +384,15 @@ export function GhostPluginPage() {
.includes(normalizedQuery);
});
}, [marketItems, query, showEnterprise]);
- const originFilters = useMemo(
+ const recommendedFilters = useMemo(
() =>
showEnterprise
- ? PRESENTATION_FILTERS
- : PRESENTATION_FILTERS.filter((filter) => filter !== 'organization'),
+ ? RECOMMENDED_FILTERS
+ : RECOMMENDED_FILTERS.filter((filter) => filter !== 'organization'),
[showEnterprise],
);
const effectiveOriginFilter =
!showEnterprise && originFilter === 'organization' ? 'all' : originFilter;
- const items = useMemo(
- () =>
- effectiveOriginFilter === 'all'
- ? searchedInstalledItems
- : searchedInstalledItems.filter((item) => item.origin === effectiveOriginFilter),
- [effectiveOriginFilter, searchedInstalledItems],
- );
const availableMarketItems = useMemo(
() =>
effectiveOriginFilter === 'all'
@@ -372,23 +402,81 @@ export function GhostPluginPage() {
),
[effectiveOriginFilter, searchedAvailableMarketItems],
);
- const catalogItems = useMemo(
- () => orderPluginCatalogItems(marketItems, items, availableMarketItems),
- [availableMarketItems, items, marketItems],
- );
- const originCounts = useMemo(() => {
+ const recommendedCounts = useMemo(() => {
const counts: Record<PluginPresentationOrigin, number> = {
public: 0,
organization: 0,
local: 0,
};
- for (const item of searchedInstalledItems) counts[item.origin] += 1;
for (const item of searchedAvailableMarketItems) {
counts[pluginPresentationOrigin(item)] += 1;
}
return counts;
- }, [searchedAvailableMarketItems, searchedInstalledItems]);
- const searchedItemCount = searchedInstalledItems.length + searchedAvailableMarketItems.length;
+ }, [searchedAvailableMarketItems]);
+
+ // ── 排序快照:进页(市场快照首次就绪)时排一次,页内交互不重排 ──
+ // 可更新的排最前,其余按最近使用;停留期间清未读/装更新都不许让卡片跳位。
+ const [orderSnapshot, setOrderSnapshot] = useState<string[] | null>(null);
+ useEffect(() => {
+ if (orderSnapshot !== null) return;
+ if (marketSnapshot === null) return;
+ const updatable = new Set(
+ installedItems.filter((item) => item.marketUpdate !== null).map((item) => item.id),
+ );
+ const byRecentUse = sortGhostPluginItemsByRecentUse(installedItems, recentGhostIds);
+ const ids = byRecentUse
+ .map((item, stableIndex) => ({ item, stableIndex }))
+ .sort((a, b) => {
+ const aUp = updatable.has(a.item.id) ? 0 : 1;
+ const bUp = updatable.has(b.item.id) ? 0 : 1;
+ if (aUp !== bUp) return aUp - bUp;
+ return a.stableIndex - b.stableIndex;
+ })
+ .map(({ item }) => item.id);
+ setOrderSnapshot(ids);
+ }, [orderSnapshot, marketSnapshot, installedItems, recentGhostIds]);
+ const displayInstalledItems = useMemo(() => {
+ if (orderSnapshot === null) return searchedInstalledItems;
+ const orderIndex = new Map(orderSnapshot.map((id, index) => [id, index]));
+ return searchedInstalledItems
+ .map((item, stableIndex) => ({ item, stableIndex }))
+ .sort((a, b) => {
+ const aIndex = orderIndex.get(a.item.id);
+ const bIndex = orderIndex.get(b.item.id);
+ if (aIndex !== undefined && bIndex !== undefined && aIndex !== bIndex) {
+ return aIndex - bIndex;
+ }
+ if (aIndex !== undefined && bIndex === undefined) return -1;
+ if (aIndex === undefined && bIndex !== undefined) return 1;
+ return a.stableIndex - b.stableIndex;
+ })
+ .map(({ item }) => item);
+ }, [orderSnapshot, searchedInstalledItems]);
+
+ // ── 更新横幅与批量更新(设计定稿:全部更新;扩权单独确认,绝不静默放行)──
+ const updatableInstalledItems = useMemo(
+ () => installedItems.filter((item) => item.marketUpdate !== null),
+ [installedItems],
+ );
+ const currentRoundKey = useMemo(() => updateRoundKey(marketItems), [marketItems]);
+ const bannerVisible =
+ updatableInstalledItems.length > 0 &&
+ (currentRoundKey === '' || ignoredRound !== currentRoundKey);
+ const handleIgnoreRound = useCallback(() => {
+ try {
+ window.localStorage.setItem(IGNORED_UPDATE_ROUND_KEY, currentRoundKey);
+ } catch {
+ // localStorage 不可用时仅本次会话内生效。
+ }
+ setIgnoredRound(currentRoundKey);
+ }, [currentRoundKey]);
+
+ const [updateRows, setUpdateRows] = useState<UpdateAllRow[] | null>(null);
+ const [updateDialogOpen, setUpdateDialogOpen] = useState(false);
+ const updateRowsRef = useRef<UpdateAllRow[]>([]);
+ const batchRunningRef = useRef(false);
+ const [batchRunning, setBatchRunning] = useState(false);
+ const finishToastShownRef = useRef(false);
const selectedGhost = selectedId
? (ghosts.find((ghost) => ghost.manifest.id === selectedId) ?? null)
: null;
@@ -408,8 +496,23 @@ export function GhostPluginPage() {
? pluginUpdateForInstalledVersion(selectedMarketInstall)
: null;
+ // ── 面板收束:页面独占的插件面板宿主;停用/卸载/换形态自动失效 ──
+ const openPanelGhost = useMemo(() => {
+ if (!openPanelId) return null;
+ const ghost = ghosts.find((candidate) => candidate.manifest.id === openPanelId);
+ if (!ghost) return null;
+ if (ghost.manifest.panel?.position !== 'tab') return null;
+ if (!effectiveEnabled(ghost.manifest.id, ghost.enabled)) return null;
+ return ghost;
+ }, [effectiveEnabled, ghosts, openPanelId]);
+ useEffect(() => {
+ if (openPanelId && !openPanelGhost) setOpenPanelId(null);
+ }, [openPanelGhost, openPanelId]);
+
const panelStatus = useMemo(() => {
if (!selectedDetail || selectedDetail.panelMinWidth === null) return null;
+ // 页签形态(面板收束):由插件页承载,没有停靠状态可言。
+ if (selectedDetail.tabPanel) return t('settings.ghosts.detail.panelPageHosted');
try {
const kind = ghostPanelKind(selectedDetail.id);
const docked =
@@ -519,6 +622,117 @@ export function GhostPluginPage() {
await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });
}, [confirm, confirmWithCheckbox, handleMarketUpdate, selectedDetail, selectedMarketUpdate, t]);
+ const handleUpdateFromFile = useCallback(async () => {
+ if (!selectedDetail) return;
+ await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });
+ }, [confirm, confirmWithCheckbox, selectedDetail, t]);
+
+ const patchUpdateRow = useCallback((pluginId: string, patch: Partial<UpdateAllRow>) => {
+ updateRowsRef.current = updateRow(updateRowsRef.current, pluginId, patch);
+ setUpdateRows(updateRowsRef.current);
+ }, []);
+ const maybeFinishBatch = useCallback(() => {
+ const rows = updateRowsRef.current;
+ if (rows.length === 0 || !isBatchFinished(rows) || finishToastShownRef.current) return;
+ finishToastShownRef.current = true;
+ const summary = batchSummary(rows);
+ toast.success(
+ t('settings.ghosts.updateAll.doneToast', {
+ done: summary.done,
+ rest: summary.skipped + summary.failed,
+ }),
+ );
+ }, [t]);
+ /** 批量更新 runner:串行走「取详情 → 权限 diff → 无扩权直接装 / 有扩权停待确认」。 */
+ const runBatchQueue = useCallback(async () => {
+ if (batchRunningRef.current) return;
+ batchRunningRef.current = true;
+ setBatchRunning(true);
+ try {
+ for (;;) {
+ const next = updateRowsRef.current.find((row) => row.status === 'pending');
+ if (!next) break;
+ patchUpdateRow(next.pluginId, { status: 'installing' });
+ try {
+ const detail = await window.electronAPI.pluginMarket.detail(next.pluginId);
+ const installedManifest = ghostsRef.current.find(
+ (ghost) => ghost.manifest.id === next.ghostId,
+ )?.manifest;
+ const diff = diffGhostPermissionItems(
+ installedManifest ?? detail.manifest,
+ detail.manifest,
+ );
+ if (diff.added.length > 0) {
+ // 扩权不自动放行:停在待确认,由用户在弹窗里逐项同意或跳过。
+ patchUpdateRow(next.pluginId, {
+ status: 'needs-confirm',
+ releaseId: detail.releaseId,
+ permissionDiff: diff,
+ });
+ continue;
+ }
+ await window.electronAPI.pluginMarket.install(next.pluginId, {
+ expectedReleaseId: detail.releaseId,
+ });
+ patchUpdateRow(next.pluginId, { status: 'done' });
+ } catch (error) {
+ patchUpdateRow(next.pluginId, {
+ status: 'failed',
+ errorText: t(pluginMarketErrorKey(error)),
+ });
+ }
+ }
+ } finally {
+ batchRunningRef.current = false;
+ setBatchRunning(false);
+ await refreshMarket();
+ maybeFinishBatch();
+ }
+ }, [maybeFinishBatch, patchUpdateRow, refreshMarket, t]);
+ const handleUpdateAll = useCallback(() => {
+ if (batchRunningRef.current) {
+ setUpdateDialogOpen(true);
+ return;
+ }
+ const installedVersionById = new Map(
+ ghostsRef.current.map((ghost) => [ghost.manifest.id, ghost.manifest.version]),
+ );
+ updateRowsRef.current = buildUpdateAllRows(
+ updatableInstalledItems.flatMap((item) => (item.marketUpdate ? [item.marketUpdate] : [])),
+ installedVersionById,
+ );
+ finishToastShownRef.current = false;
+ setUpdateRows(updateRowsRef.current);
+ setUpdateDialogOpen(true);
+ void runBatchQueue();
+ }, [runBatchQueue, updatableInstalledItems]);
+ const handleApproveExpansion = useCallback(
+ async (pluginId: string) => {
+ const row = updateRowsRef.current.find((candidate) => candidate.pluginId === pluginId);
+ if (!row?.releaseId) return;
+ patchUpdateRow(pluginId, { status: 'installing' });
+ try {
+ await window.electronAPI.pluginMarket.install(pluginId, {
+ expectedReleaseId: row.releaseId,
+ allowPermissionExpansion: true,
+ });
+ patchUpdateRow(pluginId, { status: 'done' });
+ } catch (error) {
+ patchUpdateRow(pluginId, { status: 'failed', errorText: t(pluginMarketErrorKey(error)) });
+ }
+ await refreshMarket();
+ maybeFinishBatch();
+ },
+ [maybeFinishBatch, patchUpdateRow, refreshMarket, t],
+ );
+ const handleSkipExpansion = useCallback(
+ (pluginId: string) => {
+ patchUpdateRow(pluginId, { status: 'skipped' });
+ maybeFinishBatch();
+ },
+ [maybeFinishBatch, patchUpdateRow],
+ );
+
const handleInstall = useCallback(async () => {
const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);
if (!picked || 'canceled' in picked) return;
@@ -622,11 +836,28 @@ export function GhostPluginPage() {
[confirm, ghosts, navigate, openGhostConfiguration, t],
);
+ /** 卡片/详情主动作分发:面板型开页面内面板,指令型起对话,工具型进管理。 */
+ const handlePrimaryAction = useCallback(
+ (item: Pick<GhostPluginListItem, 'id' | 'name' | 'tabPanel' | 'canUse'>) => {
+ const action = ghostPrimaryAction(item);
+ if (action === 'panel') {
+ setOpenPanelId(item.id);
+ return;
+ }
+ if (action === 'command') {
+ void handleUseGhost(item.id, item.name);
+ return;
+ }
+ setSelectedId(item.id);
+ },
+ [handleUseGhost],
+ );
+
const handleUse = useCallback(() => {
if (selectedGhost && selectedDetail) {
- void handleUseGhost(selectedGhost.manifest.id, selectedDetail.name);
+ handlePrimaryAction(selectedDetail);
}
- }, [handleUseGhost, selectedDetail, selectedGhost]);
+ }, [handlePrimaryAction, selectedDetail, selectedGhost]);
// 导出当前插件的 .cindy 包:main 侧打包安装目录 → 系统保存对话框落盘。
// 取消选择静默返回;成功/失败都如实 toast。
@@ -732,8 +963,8 @@ export function GhostPluginPage() {
refreshVisibleMarketIcons,
);
- const handleInstallFromMarket = useCallback(async () => {
- if (!marketDetail) return;
+ const runMarketInstallFlow = useCallback(async (marketDetailArg: PluginMarketDetail) => {
+ const marketDetail = marketDetailArg;
// 确认框等待期间也持有 lease。账号/模式切换会清除当前 lease,
// 旧确认回调恢复后必须先验权,不能在新会话里继续安装。
const marketBusyLease = acquireMarketBusy(marketDetail.pluginId);
@@ -821,7 +1052,9 @@ export function GhostPluginPage() {
name: result.ghost.manifest.name,
}),
);
- setMarketDetail(null);
+ setMarketDetail((current) =>
+ current?.pluginId === marketDetail.pluginId ? null : current,
+ );
setSelectedId(result.ghost.manifest.id);
await refreshMarket();
} catch (error) {
@@ -836,62 +1069,99 @@ export function GhostPluginPage() {
confirm,
ghosts,
isMarketBusyLeaseActive,
- marketDetail,
refreshMarket,
releaseMarketBusy,
t,
]);
+ const handleInstallFromMarket = useCallback(async () => {
+ if (!marketDetail) return;
+ await runMarketInstallFlow(marketDetail);
+ }, [marketDetail, runMarketInstallFlow]);
+ /** 推荐卡片上的直接「安装」:先取详情,再走与详情页相同的确认+安装流。 */
+ const handleInstallMarketItem = useCallback(
+ async (pluginId: string) => {
+ const marketBusyLease = acquireMarketBusy(pluginId);
+ if (!marketBusyLease) return;
+ let detail: PluginMarketDetail;
+ try {
+ detail = await window.electronAPI.pluginMarket.detail(pluginId);
+ } catch (error) {
+ if (isMarketBusyLeaseActive(marketBusyLease)) {
+ toast.error(t(pluginMarketErrorKey(error)));
+ }
+ releaseMarketBusy(marketBusyLease);
+ return;
+ }
+ releaseMarketBusy(marketBusyLease);
+ await runMarketInstallFlow(detail);
+ },
+ [acquireMarketBusy, isMarketBusyLeaseActive, releaseMarketBusy, runMarketInstallFlow, t],
+ );
+
+ // 面板收束:aside 只挂在插件页语境里(列表/详情/市场详情共用),
+ // 路由离开本页组件整体卸载 → webview 一并回收,绝不残留到别的界面。
+ const panelAside = openPanelGhost ? (
+ <GhostPagePanelHost ghost={openPanelGhost} onClose={() => setOpenPanelId(null)} />
+ ) : null;
if (marketDetail) {
return (
- <MarketPluginDetailView
- detail={marketDetail}
- busy={marketBusyId === marketDetail.pluginId}
- onBack={() => {
- marketDetailRequestRef.current += 1;
- setMarketDetail(null);
- }}
- onInstall={() => void handleInstallFromMarket()}
- onIconLoadError={handleMarketIconLoadError}
- />
+ <div className="flex h-full min-h-0 w-full">
+ <div className="min-w-0 flex-1">
+ <MarketPluginDetailView
+ detail={marketDetail}
+ busy={marketBusyId === marketDetail.pluginId}
+ onBack={() => {
+ marketDetailRequestRef.current += 1;
+ setMarketDetail(null);
+ }}
+ onInstall={() => void handleInstallFromMarket()}
+ onIconLoadError={handleMarketIconLoadError}
+ />
+ </div>
+ {panelAside}
+ </div>
);
}
if (selectedDetail) {
return (
- <GhostPluginDetailView
- ghost={selectedGhost}
- detail={selectedDetail}
- panelStatus={panelStatus}
- enabledOverride={
- selectedGhost
- ? effectiveEnabled(selectedGhost.manifest.id, selectedGhost.enabled)
- : undefined
- }
- onBack={() => setSelectedId(null)}
- onToggle={(enabled) => void handleToggle(selectedDetail.id, enabled, selectedDetail.name)}
- onUse={handleUse}
- onUpdate={() => void handleUpdate()}
- updateLabel={
- selectedMarketUpdate
- ? t('settings.ghosts.market.update')
- : undefined
- }
- updateVersion={
- selectedMarketUpdate?.version
- }
- updateBusy={selectedMarketUpdate !== null && marketBusyId !== null}
- onUninstall={() => void handleUninstall()}
- // 官方保留前缀(cindy-/filo-/xd-)的插件走本地装入会被拒,
- // 导出产物无法重装,不提供导出项。
- onExport={
- selectedGhost && !isOfficialGhostId(selectedDetail.id)
- ? () => void handleExport()
- : undefined
- }
- toggleDisabled={scopeDir !== null && selectedGhost !== null && !selectedGhost.enabled}
- onIconLoadError={handleMarketIconLoadError}
- />
+ <div className="flex h-full min-h-0 w-full">
+ <div className="min-w-0 flex-1">
+ <GhostPluginDetailView
+ ghost={selectedGhost}
+ detail={selectedDetail}
+ panelStatus={panelStatus}
+ enabledOverride={
+ selectedGhost
+ ? effectiveEnabled(selectedGhost.manifest.id, selectedGhost.enabled)
+ : undefined
+ }
+ onBack={() => setSelectedId(null)}
+ onToggle={(enabled) =>
+ void handleToggle(selectedDetail.id, enabled, selectedDetail.name)
+ }
+ onUse={handleUse}
+ onUpdate={() => void handleUpdate()}
+ onUpdateFromFile={() => void handleUpdateFromFile()}
+ updateVersion={selectedMarketUpdate?.version}
+ updateBusy={
+ (selectedMarketUpdate !== null && marketBusyId !== null) || batchRunning
+ }
+ onUninstall={() => void handleUninstall()}
+ // 官方保留前缀(cindy-/filo-/xd-)的插件走本地装入会被拒,
+ // 导出产物无法重装,不提供导出项。
+ onExport={
+ selectedGhost && !isOfficialGhostId(selectedDetail.id)
+ ? () => void handleExport()
+ : undefined
+ }
+ toggleDisabled={scopeDir !== null && selectedGhost !== null && !selectedGhost.enabled}
+ onIconLoadError={handleMarketIconLoadError}
+ />
+ </div>
+ {panelAside}
+ </div>
);
}
@@ -909,8 +1179,9 @@ export function GhostPluginPage() {
/>
}
>
- <main className="min-h-0 w-full flex-1 overflow-y-auto bg-[var(--surface)] [scrollbar-gutter:stable_both-edges]">
- <PluginManagementPage>
+ <div className="flex min-h-0 flex-1">
+ <main className="min-h-0 w-full min-w-0 flex-1 overflow-y-auto bg-[var(--surface)] [scrollbar-gutter:stable_both-edges]">
+ <PluginManagementPage>
<header className="plugin-motion-page-header pb-2">
<div className="min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3">
@@ -950,83 +1221,16 @@ export function GhostPluginPage() {
</div>
) : null}
- {installedShortcutItems.length > 0 ? (
- <section className="plugin-motion-page-section mt-5 border-b-[0.5px] border-[var(--border-default)] pb-5">
- <div className="mb-1 flex items-baseline gap-2">
- <h2 className="text-13 font-medium text-[var(--text-secondary)]">
- {t('settings.ghosts.page.installedTitle')}
- </h2>
- <span className="text-12 tabular-nums text-[var(--text-tertiary)]">
- {installedShortcutItems.length}
- </span>
- </div>
- <InstalledGhostQueue
- items={installedShortcutItems}
- expanded={installedExpanded}
- onExpandedChange={setInstalledExpanded}
- onSelect={setSelectedId}
- onIconLoadError={handleMarketIconLoadError}
- />
- </section>
- ) : null}
-
<section className="plugin-motion-page-section mt-6 min-w-0">
- <div className={PLUGIN_CATALOG_TOOLBAR_CLASS}>
- <div className="flex shrink-0 items-baseline gap-2 whitespace-nowrap">
- <h2 className="text-20 font-medium text-[var(--text-primary)]">
- {t('settings.ghosts.page.allTitle')}
- </h2>
- <span className="text-13 tabular-nums text-[var(--text-tertiary)]">
- {items.length + availableMarketItems.length}
- </span>
- </div>
- <div
- className="plugin-catalog-filters flex min-w-0 max-w-full items-center gap-1 overflow-x-auto"
- role="group"
- aria-label={t('settings.ghosts.page.filtersAria')}
- style={WINDOW_NO_DRAG_STYLE}
- >
- {originFilters.map((filter) => {
- const selected = effectiveOriginFilter === filter;
- const count = filter === 'all' ? searchedItemCount : originCounts[filter];
- return (
- <button
- key={filter}
- type="button"
- aria-pressed={selected}
- onClick={() => setOriginFilter(filter)}
- className={cn(
- 'shrink-0 select-none rounded-full px-3.5 py-2 text-12 transition-colors duration-150',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- selected
- ? 'bg-[var(--surface-chip)] text-[var(--text-primary)]'
- : 'text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
- )}
- >
- {filter === 'all'
- ? t('settings.ghosts.page.filterAll')
- : t(`settings.ghosts.page.origin.${filter}`)}
- <span className="ml-1.5 tabular-nums text-[var(--text-tertiary)]">
- {count}
- </span>
- </button>
- );
- })}
- </div>
+ <div className="mb-4 flex items-baseline gap-2">
+ <h2 className="text-20 font-medium text-[var(--text-primary)]">
+ {t('settings.ghosts.page.installedSection')}
+ </h2>
+ <span className="text-13 tabular-nums text-[var(--text-tertiary)]">
+ {searchedInstalledItems.length}
+ </span>
</div>
- {marketSnapshot?.unavailableReason ? (
- <p className="mb-4 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-12 text-[var(--text-secondary)]">
- {t(
- marketSnapshot.unavailableReason === 'authentication-required'
- ? 'settings.ghosts.market.authenticationRequired'
- : marketSnapshot.unavailableReason === 'not-configured'
- ? 'settings.ghosts.market.notConfigured'
- : 'settings.ghosts.market.unavailable',
- )}
- </p>
- ) : null}
-
{legacyRecoveryStatus ? (
<LegacyGhostRecoveryNotice
status={legacyRecoveryStatus}
@@ -1035,54 +1239,72 @@ export function GhostPluginPage() {
/>
) : null}
- {catalogItems.length > 0 ? (
+ {bannerVisible ? (
+ <div className="mb-4 flex items-center gap-4 rounded-xl border-[0.5px] border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3.5">
+ <span className="grid size-9 shrink-0 place-items-center rounded-full bg-[var(--surface-chip)] text-[var(--text-primary)]">
+ <ArrowUp size={16} aria-hidden="true" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="text-13 font-medium text-[var(--text-primary)]">
+ {t('settings.ghosts.page.updatesAvailable', {
+ count: updatableInstalledItems.length,
+ })}
+ </p>
+ <p className="truncate text-12 text-[var(--text-secondary)]">
+ {updatableInstalledItems
+ .map((item) => `${item.name} v${item.marketUpdate?.version ?? ''}`)
+ .join(' · ')}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={handleIgnoreRound}
+ className="shrink-0 rounded-full px-3 py-1.5 text-12 text-[var(--text-secondary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.ghosts.page.ignoreRound')}
+ </button>
+ <button
+ type="button"
+ onClick={handleUpdateAll}
+ disabled={batchRunning && !updateDialogOpen}
+ className="inline-flex h-9 shrink-0 items-center rounded-full bg-[var(--accent-cta-bg)] px-4 text-12 font-medium text-[var(--accent-pure-cta-fg)] transition-transform duration-150 hover:bg-[var(--accent-hover)] active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.ghosts.page.updateAll')}
+ </button>
+ </div>
+ ) : null}
+
+ {displayInstalledItems.length > 0 ? (
<div className={cn('plugin-motion-stagger', PLUGIN_MANAGEMENT_CARD_GRID_CLASS)}>
- {catalogItems.map((catalogItem) =>
- catalogItem.kind === 'installed' ? (
- <GhostPluginCard
- key={`installed:${catalogItem.item.id}`}
- item={catalogItem.item}
- sourceLabel={t(`settings.ghosts.page.origin.${catalogItem.item.origin}`)}
- onSelect={() => setSelectedId(catalogItem.item.id)}
- onAction={() =>
- void handleUseGhost(catalogItem.item.id, catalogItem.item.name)
- }
- updateVersion={catalogItem.item.marketUpdate?.version}
- updateBusy={catalogItem.item.marketUpdate !== null && marketBusyId !== null}
- onUpdate={
- catalogItem.item.marketUpdate
- ? () => void handleMarketUpdate(catalogItem.item.id)
- : undefined
- }
- effectiveEnabled={effectiveEnabled(
- catalogItem.item.id,
- catalogItem.item.enabled,
- )}
- toggleDisabled={scopeDir !== null && !catalogItem.item.enabled}
- onToggle={(enabled) =>
- void handleToggle(catalogItem.item.id, enabled, catalogItem.item.name)
- }
- onIconLoadError={handleMarketIconLoadError}
- />
- ) : (
- <MarketPluginCard
- key={`market:${catalogItem.item.pluginId}`}
- item={catalogItem.item}
- busy={marketBusyId !== null}
- onSelect={() => void handleSelectMarket(catalogItem.item.pluginId)}
- onIconLoadError={handleMarketIconLoadError}
- />
- ),
- )}
+ {displayInstalledItems.map((item) => (
+ <GhostPluginCard
+ key={item.id}
+ item={item}
+ sourceLabel={t(`settings.ghosts.page.origin.${item.origin}`)}
+ updateVersion={item.marketUpdate?.version}
+ updateBusy={
+ (item.marketUpdate !== null && marketBusyId !== null) || batchRunning
+ }
+ onUpdate={
+ item.marketUpdate
+ ? () => void handleMarketUpdate(item.id)
+ : undefined
+ }
+ effectiveEnabled={effectiveEnabled(item.id, item.enabled)}
+ onPrimary={() => handlePrimaryAction(item)}
+ onManage={() => setSelectedId(item.id)}
+ onIconLoadError={handleMarketIconLoadError}
+ />
+ ))}
</div>
) : !legacyRecoveryStatus ? (
<div className="rounded-xl border-[0.5px] border-[var(--border-default)] px-5 py-10 text-center">
<p className="text-13 text-[var(--text-secondary)]">
- {installedItems.length === 0 && marketItems.length === 0
+ {installedItems.length === 0
? t('settings.ghosts.empty')
: t('settings.ghosts.page.emptyFiltered')}
</p>
- {installedItems.length === 0 && marketItems.length === 0 ? (
+ {installedItems.length === 0 ? (
<p className="mt-1.5 text-12 text-[var(--text-tertiary)]">
{t('settings.ghosts.emptyHint')}
</p>
@@ -1090,8 +1312,102 @@ export function GhostPluginPage() {
</div>
) : null}
</section>
- </PluginManagementPage>
- </main>
+
+ {availableMarketItems.length > 0 ||
+ searchedAvailableMarketItems.length > 0 ||
+ marketSnapshot?.unavailableReason ? (
+ <section className="plugin-motion-page-section mt-10 min-w-0">
+ <div className={PLUGIN_CATALOG_TOOLBAR_CLASS}>
+ {/* 推荐区标题不带数字(设计定稿):数量感由卡片自身传达。 */}
+ <h2 className="shrink-0 whitespace-nowrap text-20 font-medium text-[var(--text-primary)]">
+ {t('settings.ghosts.page.recommendedSection')}
+ </h2>
+ <div
+ className="plugin-catalog-filters flex min-w-0 max-w-full items-center gap-1 overflow-x-auto"
+ role="group"
+ aria-label={t('settings.ghosts.page.filtersAria')}
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ {recommendedFilters.map((filter) => {
+ const selected = effectiveOriginFilter === filter;
+ const count =
+ filter === 'all'
+ ? searchedAvailableMarketItems.length
+ : recommendedCounts[filter];
+ return (
+ <button
+ key={filter}
+ type="button"
+ aria-pressed={selected}
+ onClick={() => setOriginFilter(filter)}
+ className={cn(
+ 'shrink-0 select-none rounded-full px-3.5 py-2 text-12 transition-colors duration-150',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ selected
+ ? 'bg-[var(--surface-chip)] text-[var(--text-primary)]'
+ : 'text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
+ )}
+ >
+ {filter === 'all'
+ ? t('settings.ghosts.page.filterAll')
+ : t(`settings.ghosts.page.origin.${filter}`)}
+ <span className="ml-1.5 tabular-nums text-[var(--text-tertiary)]">
+ {count}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {marketSnapshot?.unavailableReason ? (
+ <p className="mb-4 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-12 text-[var(--text-secondary)]">
+ {t(
+ marketSnapshot.unavailableReason === 'authentication-required'
+ ? 'settings.ghosts.market.authenticationRequired'
+ : marketSnapshot.unavailableReason === 'not-configured'
+ ? 'settings.ghosts.market.notConfigured'
+ : 'settings.ghosts.market.unavailable',
+ )}
+ </p>
+ ) : null}
+
+ {availableMarketItems.length > 0 ? (
+ <div className={cn('plugin-motion-stagger', PLUGIN_MANAGEMENT_CARD_GRID_CLASS)}>
+ {availableMarketItems.map((item) => (
+ <MarketPluginCard
+ key={item.pluginId}
+ item={item}
+ busy={marketBusyId !== null}
+ onSelect={() => void handleSelectMarket(item.pluginId)}
+ onInstall={() => void handleInstallMarketItem(item.pluginId)}
+ onIconLoadError={handleMarketIconLoadError}
+ />
+ ))}
+ </div>
+ ) : marketSnapshot?.unavailableReason ? null : (
+ <div className="rounded-xl border-[0.5px] border-[var(--border-default)] px-5 py-10 text-center">
+ <p className="text-13 text-[var(--text-secondary)]">
+ {t('settings.ghosts.page.emptyFiltered')}
+ </p>
+ </div>
+ )}
+ </section>
+ ) : null}
+ </PluginManagementPage>
+ </main>
+ {panelAside}
+ </div>
+ {updateRows ? (
+ <UpdateAllDialog
+ open={updateDialogOpen}
+ rows={updateRows}
+ iconByGhostId={new Map(ghosts.map((ghost) => [ghost.manifest.id, ghost.iconDataUrl]))}
+ onApprove={(pluginId) => void handleApproveExpansion(pluginId)}
+ onSkip={handleSkipExpansion}
+ onClose={() => setUpdateDialogOpen(false)}
+ />
+ ) : null}
</PluginManagementLayout>
);
}
@@ -1147,11 +1463,14 @@ export function MarketPluginCard({
item,
busy,
onSelect,
+ onInstall,
onIconLoadError,
}: {
item: PluginMarketItem;
busy: boolean;
onSelect: () => void;
+ /** 卡片直接安装(设计定稿:未安装卡片 = 「安装 + 详情」两个动作)。 */
+ onInstall?: () => void;
onIconLoadError: () => void;
}) {
const { t } = useTranslation();
@@ -1214,23 +1533,40 @@ export function MarketPluginCard({
</span>
</span>
</button>
- <button
- type="button"
- onClick={onSelect}
- disabled={busy || item.installState === 'conflict'}
- className={cn(
- 'inline-flex h-8 shrink-0 items-center gap-1.5 self-center rounded-lg border border-[var(--border-default)] px-3 text-12 font-medium text-[var(--text-primary)]',
- 'transition-[background-color,border-color,transform,opacity] duration-150 hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-40',
- )}
- >
- <ChevronRight size={13} aria-hidden="true" />
- {t(
- item.installState === 'conflict'
- ? 'settings.ghosts.market.conflict'
- : 'settings.ghosts.market.details',
- )}
- </button>
+ <div className="flex shrink-0 items-center gap-1.5 self-center">
+ <button
+ type="button"
+ onClick={onSelect}
+ disabled={busy || item.installState === 'conflict'}
+ className={cn(
+ 'inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-12 font-medium text-[var(--text-secondary)]',
+ 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-40',
+ )}
+ >
+ <ChevronRight size={13} aria-hidden="true" />
+ {t(
+ item.installState === 'conflict'
+ ? 'settings.ghosts.market.conflict'
+ : 'settings.ghosts.market.details',
+ )}
+ </button>
+ {onInstall ? (
+ <button
+ type="button"
+ onClick={onInstall}
+ disabled={busy || item.installState === 'conflict'}
+ aria-label={t('settings.ghosts.page.installAria', { name: item.name })}
+ className={cn(
+ 'inline-flex h-8 shrink-0 items-center rounded-full border border-[var(--border-default)] px-3.5 text-12 font-medium text-[var(--text-primary)]',
+ 'transition-[background-color,border-color,transform,opacity] duration-150 hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-40',
+ )}
+ >
+ {t('settings.ghosts.market.install')}
+ </button>
+ ) : null}
+ </div>
</article>
);
}
@@ -1307,246 +1643,183 @@ function GhostPluginActions({
);
}
-/** Compact installed Plugin card. */
+/**
+ * 已安装插件卡片(设计定稿):
+ * - 整卡可点 = 主动作(面板「使用」/ 指令「对话」/ 工具型与停用态进管理);
+ * - 无启用开关(收进详情页);滑杆图标 = 管理入口;
+ * - 更新 = 文字胶囊「更新到 vX」,无任何小圆点(绿点专职未读语义,PR-B 接入)。
+ */
export function GhostPluginCard({
item,
sourceLabel,
- onSelect,
- onAction,
- onUpdate,
updateVersion,
updateBusy = false,
- onToggle,
+ onUpdate,
effectiveEnabled,
- toggleDisabled = false,
+ onPrimary,
+ onManage,
onIconLoadError,
}: {
item: GhostPluginListItem;
sourceLabel?: string;
- onSelect: () => void;
- onAction: () => void;
- /** 市场存在新版本时的直达更新入口;与 updateVersion 同时提供。 */
- onUpdate?: () => void;
+ /** 市场存在新版本时的目标版本;与 onUpdate 同时提供。 */
updateVersion?: string;
updateBusy?: boolean;
- onToggle?: (enabled: boolean) => void;
+ onUpdate?: () => void;
effectiveEnabled?: boolean;
- toggleDisabled?: boolean;
+ onPrimary: () => void;
+ onManage: () => void;
onIconLoadError?: () => void;
}) {
const { t } = useTranslation();
+ const enabled = effectiveEnabled ?? item.enabled;
+ const primary = ghostPrimaryAction(item);
+ const cardAction = enabled && primary !== 'manage' ? onPrimary : onManage;
+ const handleCardKeyDown = (event: KeyboardEvent<HTMLElement>) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ cardAction();
+ };
+ let primaryControl: ReactNode;
+ if (!enabled) {
+ primaryControl = (
+ <CardPillButton onClick={onManage} label={t('settings.ghosts.page.manageAction')} />
+ );
+ } else if (primary === 'panel') {
+ primaryControl = (
+ <CardPillButton
+ onClick={onPrimary}
+ label={t('settings.ghosts.page.usePanelAction')}
+ ariaLabel={t('settings.ghosts.page.useAria', { name: item.name })}
+ />
+ );
+ } else if (primary === 'command') {
+ primaryControl = (
+ <CardPillButton
+ onClick={onPrimary}
+ icon={<MessageCircle size={13} aria-hidden="true" />}
+ label={t('settings.ghosts.page.chatAction')}
+ ariaLabel={t('settings.ghosts.page.chatAria', { name: item.name })}
+ />
+ );
+ } else {
+ primaryControl = (
+ <span className="flex items-center gap-1.5 whitespace-nowrap text-11 text-[var(--text-tertiary)]">
+ <Bot size={13} aria-hidden="true" />
+ {t('settings.ghosts.page.agentInvoked')}
+ </span>
+ );
+ }
return (
<article
+ role="button"
+ tabIndex={0}
+ onClick={cardAction}
+ onKeyDown={handleCardKeyDown}
+ aria-label={item.name}
className={cn(
- 'group flex min-h-[108px] w-full select-none items-start gap-4 rounded-xl border-[0.5px] border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-left',
+ 'group flex min-h-[108px] w-full cursor-pointer select-none items-start gap-4 rounded-xl border-[0.5px] border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-left',
'transition-[background-color,border-color,transform] duration-150 ease-out',
'hover:-translate-y-px hover:border-[var(--text-tertiary)] hover:bg-[var(--surface-hover-soft)]',
'active:translate-y-0 active:scale-[0.992]',
'motion-reduce:transform-none motion-reduce:transition-none',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ !enabled && 'opacity-60',
)}
>
- <button
- type="button"
- onClick={onSelect}
- className="flex min-w-0 flex-1 items-start gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- aria-label={item.name}
- >
- <GhostPluginIcon
- iconDataUrl={item.iconDataUrl}
- iconId={item.id}
- iconName={item.name}
- onIconLoadError={onIconLoadError}
- />
- <span className="flex min-w-0 flex-1 flex-col self-stretch pt-0.5">
- <span className="flex min-w-0 items-center gap-2">
- <span className="truncate text-15 font-medium text-[var(--text-primary)]">
- {item.name}
+ <GhostPluginIcon
+ iconDataUrl={item.iconDataUrl}
+ iconId={item.id}
+ iconName={item.name}
+ 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>
+ <span className="mt-1 block min-w-0 truncate text-11 text-[var(--text-tertiary)]">
+ {sourceLabel ? `${sourceLabel} · ` : ''}v{item.version}
+ {!updateVersion ? (
+ <span className="inline-flex items-center gap-1">
+ {' · '}
+ <Check size={11} className="inline" aria-hidden="true" />
+ {t('settings.ghosts.page.upToDate')}
</span>
- {updateVersion ? (
- <span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 font-medium leading-4 text-[var(--text-secondary)]">
- {t('settings.ghosts.market.updateAvailable')}
- </span>
- ) : null}
- </span>
- <span className="mt-1 flex min-w-0 items-center gap-1.5 text-11 text-[var(--text-tertiary)]">
- {sourceLabel ? (
- <>
- <span>{sourceLabel}</span>
- <span aria-hidden="true">·</span>
- </>
- ) : null}
- <span>v{item.version}</span>
- <span aria-hidden="true">·</span>
- <span className="truncate font-mono">{item.id}</span>
- </span>
- <span className="mt-1.5 line-clamp-2 text-13 leading-5 text-[var(--text-secondary)]">
- {item.description || item.id}
- </span>
+ ) : null}
+ {!enabled ? ` · ${t('settings.ghosts.disabledTag')}` : ''}
</span>
- </button>
- <div className="flex shrink-0 items-center gap-2 self-center">
- {onToggle ? (
- <Switch
- checked={effectiveEnabled ?? item.enabled}
- disabled={toggleDisabled}
- onCheckedChange={onToggle}
- aria-label={t('settings.ghosts.enableAria', { name: item.name })}
- />
- ) : null}
- {updateVersion && onUpdate ? (
- <button
- type="button"
- onClick={onUpdate}
- disabled={updateBusy}
- className={cn(
- 'inline-flex h-8 shrink-0 items-center justify-center self-center rounded-lg border border-[var(--border-default)] bg-transparent px-3 text-12 font-medium text-[var(--text-primary)]',
- 'transition-[background-color,border-color,transform,opacity] duration-150',
- 'hover:border-[var(--text-tertiary)] hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'disabled:cursor-wait disabled:opacity-40 disabled:active:scale-100',
- )}
- aria-label={t('settings.ghosts.market.updateAria', { name: item.name })}
- >
- {t('settings.ghosts.market.updateAction')}
- </button>
- ) : (
+ <span className="mt-1.5 line-clamp-2 text-13 leading-5 text-[var(--text-secondary)]">
+ {item.description || item.id}
+ </span>
+ </span>
+ {/* 右列控制区:自行消费点击,不冒泡到整卡主动作(纯冒泡拦截层,无独立语义)。 */}
+ <span
+ className="flex shrink-0 flex-col items-end justify-between gap-2 self-stretch"
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ <span className="flex items-center gap-1.5">
+ {updateVersion && onUpdate ? (
+ <button
+ type="button"
+ onClick={onUpdate}
+ disabled={updateBusy}
+ aria-label={t('settings.ghosts.page.updateAria', {
+ name: item.name,
+ version: updateVersion,
+ })}
+ className={cn(
+ 'inline-flex h-7 items-center gap-1 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-2.5 text-11 font-medium text-[var(--text-primary)]',
+ 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:cursor-wait disabled:opacity-40',
+ )}
+ >
+ <ArrowUp size={11} className="text-[var(--text-secondary)]" aria-hidden="true" />
+ {t('settings.ghosts.page.updateTo', { version: updateVersion })}
+ </button>
+ ) : null}
<button
type="button"
- onClick={onAction}
- disabled={!(effectiveEnabled ?? item.enabled) || !item.canUse}
- className={cn(
- 'inline-flex h-8 shrink-0 items-center justify-center self-center rounded-lg border border-[var(--border-default)] bg-transparent px-3 text-12 font-medium text-[var(--text-primary)]',
- 'transition-[background-color,border-color,transform,opacity] duration-150',
- 'hover:border-[var(--text-tertiary)] hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100',
- )}
- aria-label={t('settings.ghosts.page.useAria', { name: item.name })}
+ onClick={onManage}
+ aria-label={t('settings.ghosts.page.manageAria', { name: item.name })}
+ title={t('settings.ghosts.page.manageAction')}
+ className="grid size-7 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
- {t('settings.ghosts.page.useAction')}
+ <SlidersHorizontal size={14} aria-hidden="true" />
</button>
- )}
- </div>
+ </span>
+ {primaryControl}
+ </span>
</article>
);
}
-export function InstalledGhostShortcut({
- item,
- onSelect,
- onIconLoadError,
+function CardPillButton({
+ onClick,
+ label,
+ icon,
+ ariaLabel,
}: {
- item: GhostPluginListItem;
- onSelect: (id: string) => void;
- onIconLoadError?: () => void;
+ onClick: () => void;
+ label: string;
+ icon?: ReactNode;
+ ariaLabel?: string;
}) {
return (
- <Tip text={item.name} side="bottom" delay={250}>
- <button
- type="button"
- onClick={() => onSelect(item.id)}
- className={cn(
- 'group flex w-16 shrink-0 justify-center rounded-[12px] px-2 py-2',
- 'transition-transform duration-150 ease-out hover:-translate-y-px active:translate-y-0 active:scale-[0.98]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'motion-reduce:transform-none motion-reduce:transition-none',
- )}
- aria-label={item.name}
- >
- <GhostPluginIcon
- iconDataUrl={item.iconDataUrl}
- iconId={item.id}
- iconName={item.name}
- onIconLoadError={onIconLoadError}
- />
- </button>
- </Tip>
- );
-}
-
-/** Installed shortcuts share one wrapping queue in both collapsed and expanded states. */
-export function InstalledGhostQueue({
- items,
- expanded,
- onExpandedChange,
- onSelect,
- onIconLoadError,
-}: {
- items: readonly GhostPluginListItem[];
- expanded: boolean;
- onExpandedChange: (expanded: boolean) => void;
- onSelect: (id: string) => void;
- onIconLoadError?: () => void;
-}) {
- const { t } = useTranslation();
- const hasOverflow = items.length > MAX_VISIBLE_INSTALLED_GHOSTS;
- const visibleItems = expanded ? items : items.slice(0, MAX_VISIBLE_INSTALLED_GHOSTS);
-
- return (
- <div
- data-testid="installed-plugin-queue"
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={ariaLabel ?? label}
className={cn(
- 'flex min-w-0 flex-wrap items-center gap-1',
- expanded && 'plugin-motion-stagger',
+ 'inline-flex h-8 shrink-0 items-center justify-center gap-1.5 rounded-full bg-[var(--surface-chip)] px-3.5 text-12 font-medium text-[var(--text-primary)]',
+ 'transition-[background-color,transform] duration-150 hover:bg-[var(--surface-hover)] active:scale-[0.98]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
)}
>
- {visibleItems.map((item) => (
- <InstalledGhostShortcut
- key={item.id}
- item={item}
- onSelect={onSelect}
- onIconLoadError={onIconLoadError}
- />
- ))}
- {hasOverflow ? (
- <button
- key="installed-overflow-toggle"
- type="button"
- onClick={() => onExpandedChange(!expanded)}
- className={cn(
- 'group flex w-16 shrink-0 justify-center rounded-[12px] px-2 py-2',
- 'transition-transform duration-150 ease-out hover:-translate-y-px active:translate-y-0 active:scale-[0.98]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'motion-reduce:transform-none motion-reduce:transition-none',
- )}
- aria-expanded={expanded}
- aria-label={t(
- expanded
- ? 'settings.ghosts.page.installedCollapse'
- : 'settings.ghosts.page.installedExpand',
- { count: items.length - MAX_VISIBLE_INSTALLED_GHOSTS },
- )}
- >
- {expanded ? (
- <span className="flex size-12 items-center justify-center rounded-[22%] border-[0.5px] border-[color-mix(in_srgb,var(--border-default)_62%,transparent)] bg-[color-mix(in_srgb,var(--surface-chip)_58%,transparent)] text-[var(--text-secondary)] shadow-[var(--plugin-icon-shadow)] transition-colors duration-150 group-hover:bg-[color-mix(in_srgb,var(--surface-chip)_78%,transparent)]">
- <ChevronUp size={18} strokeWidth={1.8} aria-hidden="true" />
- </span>
- ) : (
- <span className="grid size-12 grid-cols-2 grid-rows-2 place-content-center gap-1 rounded-[22%] border-[0.5px] border-[color-mix(in_srgb,var(--border-default)_62%,transparent)] bg-[color-mix(in_srgb,var(--surface-chip)_58%,transparent)] p-2 shadow-[var(--plugin-icon-shadow)] transition-colors duration-150 group-hover:bg-[color-mix(in_srgb,var(--surface-chip)_78%,transparent)]">
- {items
- .slice(MAX_VISIBLE_INSTALLED_GHOSTS, MAX_VISIBLE_INSTALLED_GHOSTS + 3)
- .map((item) => (
- <span
- key={item.id}
- className="flex size-3.5 items-center justify-center overflow-hidden rounded-[5px] bg-[var(--surface-elevated)]"
- >
- <GhostPluginIcon
- iconDataUrl={item.iconDataUrl}
- iconId={item.id}
- iconName={item.name}
- size="mini"
- onIconLoadError={onIconLoadError}
- />
- </span>
- ))}
- <span className="col-start-2 row-start-2 flex size-3.5 items-center justify-center rounded-[5px] bg-[var(--surface-elevated)] text-[9px] font-medium tabular-nums text-[var(--text-secondary)]">
- +{items.length - MAX_VISIBLE_INSTALLED_GHOSTS}
- </span>
- </span>
- )}
- </button>
- ) : null}
- </div>
+ {icon}
+ {label}
+ </button>
);
}
diff --git a/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx b/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx
new file mode 100644
index 0000000000..f9e419e60d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx
@@ -0,0 +1,216 @@
+/**
+ * Batch plugin update dialog: auto rows stream through, permission
+ * expansions wait for explicit per-row consent.
+ *
+ * Inputs: live batch rows owned by the Plugin page runner plus row actions.
+ * Outputs: progress presentation only; no IPC and no batch policy here.
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ */
+
+import { useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import { Check, Loader2, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
+import { GhostPermissionDiffView } from '@/cindy-brain/GhostPermissionList';
+import { cn } from '@/lib/utils';
+import { GhostPluginIcon } from './GhostPluginIcon';
+import { isBatchFinished, type UpdateAllRow } from './lib/updateAllModel';
+
+interface UpdateAllDialogProps {
+ open: boolean;
+ rows: readonly UpdateAllRow[];
+ iconByGhostId: ReadonlyMap<string, string | undefined>;
+ onApprove: (pluginId: string) => void;
+ onSkip: (pluginId: string) => void;
+ /** 关弹窗;批量运行器继续在页面组件里跑(「后台继续」语义)。 */
+ onClose: () => void;
+}
+
+/** 单行状态徽标(纯文字 + 图标,不用彩色圆点——绿色专职未读语义)。 */
+function RowStatus({ row }: { row: UpdateAllRow }) {
+ const { t } = useTranslation();
+ if (row.status === 'done') {
+ return (
+ <span className="flex items-center gap-1.5 text-12 text-[var(--card-status-done)]">
+ <Check size={14} aria-hidden="true" />
+ {t('settings.ghosts.updateAll.statusDone')}
+ </span>
+ );
+ }
+ if (row.status === 'installing') {
+ return (
+ <span className="flex items-center gap-1.5 text-12 text-[var(--text-secondary)]">
+ <Loader2 size={13} className="animate-spin" aria-hidden="true" />
+ {t('settings.ghosts.updateAll.statusInstalling')}
+ </span>
+ );
+ }
+ if (row.status === 'skipped') {
+ return (
+ <span className="text-12 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.updateAll.statusSkipped')}
+ </span>
+ );
+ }
+ if (row.status === 'failed') {
+ return (
+ <span className="text-12 text-[var(--error-fg)]">
+ {row.errorText ?? t('settings.ghosts.updateAll.statusFailed')}
+ </span>
+ );
+ }
+ return (
+ <span className="text-12 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.updateAll.statusPending')}
+ </span>
+ );
+}
+
+export function UpdateAllDialog({
+ open,
+ rows,
+ iconByGhostId,
+ onApprove,
+ onSkip,
+ onClose,
+}: UpdateAllDialogProps) {
+ const { t } = useTranslation();
+ const [expandedId, setExpandedId] = useState<string | null>(null);
+ const finished = isBatchFinished(rows);
+ return (
+ <Dialog.Root open={open} onOpenChange={(next) => (next ? undefined : onClose())}>
+ <Dialog.Portal>
+ <Dialog.Overlay
+ className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]"
+ style={WINDOW_NO_DRAG_STYLE}
+ />
+ <Dialog.Content
+ className="fixed left-1/2 top-1/2 z-[10000] flex max-h-[70vh] w-[calc(100vw-48px)] max-w-[520px] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] shadow-[var(--shadow-menu)] focus:outline-none"
+ style={WINDOW_NO_DRAG_STYLE}
+ >
+ <div className="flex items-start gap-4 border-b-[0.5px] border-[var(--border-default)] px-6 py-5">
+ <div className="min-w-0 flex-1">
+ <Dialog.Title className="text-18 font-medium">
+ {t('settings.ghosts.updateAll.title', { count: rows.length })}
+ </Dialog.Title>
+ <Dialog.Description className="mt-1 text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.updateAll.description')}
+ </Dialog.Description>
+ </div>
+ <Dialog.Close
+ aria-label={t('settings.ghosts.detail.closeDialog')}
+ className="grid size-9 shrink-0 place-items-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <X size={17} aria-hidden="true" />
+ </Dialog.Close>
+ </div>
+ <div className="overflow-y-auto px-6 py-2">
+ {rows.map((row) => {
+ const expanded = row.status === 'needs-confirm' && expandedId === row.pluginId;
+ return (
+ <div
+ key={row.pluginId}
+ className="border-b-[0.5px] border-[var(--border-default)] py-3.5 last:border-b-0"
+ >
+ <div className="flex items-center gap-3">
+ <GhostPluginIcon
+ iconDataUrl={iconByGhostId.get(row.ghostId)}
+ iconId={row.ghostId}
+ iconName={row.name}
+ size="menu"
+ />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-13 font-medium leading-5">{row.name}</p>
+ <p className="text-11 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.updateAll.versionRange', {
+ from: row.fromVersion,
+ to: row.toVersion,
+ })}
+ {row.status === 'needs-confirm' ? (
+ <>
+ {' · '}
+ <span className="text-[var(--text-primary)]">
+ {t('settings.ghosts.updateAll.permissionChanged')}
+ </span>
+ </>
+ ) : null}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ {row.status === 'needs-confirm' ? (
+ <button
+ type="button"
+ aria-expanded={expanded}
+ onClick={() =>
+ setExpandedId((current) =>
+ current === row.pluginId ? null : row.pluginId,
+ )
+ }
+ className={cn(
+ 'inline-flex h-7 items-center rounded-full border border-[var(--border-default)] px-3 text-12 font-medium text-[var(--text-primary)]',
+ 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ {t(
+ expanded
+ ? 'settings.ghosts.updateAll.collapseDiff'
+ : 'settings.ghosts.updateAll.reviewDiff',
+ )}
+ </button>
+ ) : (
+ <RowStatus row={row} />
+ )}
+ </div>
+ </div>
+ {expanded && row.permissionDiff ? (
+ <div className="ml-9 mt-3 rounded-lg border-[0.5px] border-[var(--border-default)] bg-[var(--surface)] px-4 py-3">
+ <GhostPermissionDiffView diff={row.permissionDiff} />
+ <div className="mt-3 flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => onApprove(row.pluginId)}
+ className="inline-flex h-8 items-center rounded-full bg-[var(--accent-cta-bg)] px-4 text-12 font-medium text-[var(--accent-pure-cta-fg)] transition-transform duration-150 hover:bg-[var(--accent-hover)] active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.ghosts.updateAll.approve')}
+ </button>
+ <button
+ type="button"
+ onClick={() => onSkip(row.pluginId)}
+ className="inline-flex h-8 items-center rounded-full border border-[var(--border-default)] px-4 text-12 font-medium text-[var(--text-primary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.ghosts.updateAll.skip')}
+ </button>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+ })}
+ </div>
+ <div className="flex items-center justify-end gap-2 border-t-[0.5px] border-[var(--border-default)] px-6 py-4">
+ <button
+ type="button"
+ onClick={onClose}
+ className={cn(
+ 'inline-flex h-9 items-center rounded-full px-5 text-13 font-medium',
+ finished
+ ? 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)] hover:bg-[var(--accent-hover)]'
+ : 'border border-[var(--border-default)] text-[var(--text-primary)] hover:bg-[var(--surface-hover-soft)]',
+ 'transition-colors duration-150 active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ {t(
+ finished
+ ? 'settings.ghosts.updateAll.doneAction'
+ : 'settings.ghosts.updateAll.background',
+ )}
+ </button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
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 a5528cb774..dd38e0be5b 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -1,12 +1,13 @@
/**
- * Regression coverage for Plugin card actions, compact metadata, and queue focus continuity.
+ * Regression coverage for installed Plugin card actions (redesigned card:
+ * whole-card primary action, kind-specific primary button, manage entry),
+ * market card actions, and the legacy recovery notice.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
* @vitest-environment jsdom
*/
-import { fireEvent, render, screen, within } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
-import { useState, type ReactNode } from 'react';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
@@ -14,29 +15,37 @@ vi.mock('react-i18next', () => ({
vi.mock('@/contexts/AuthContext', () => ({
useAuth: () => ({ user: null, mode: 'signed-out', dataOwnerId: null }),
}));
-vi.mock('@/components/ui/tooltip', () => ({
- Tip: ({ text, children }: { text: string; children: ReactNode }) => (
- <span data-tooltip={text}>{children}</span>
- ),
-}));
import {
GhostPluginCard,
- InstalledGhostQueue,
- InstalledGhostShortcut,
MarketPluginCard,
LegacyGhostRecoveryNotice,
} from '../GhostPluginPage';
import type { GhostPluginListItem } from '../lib/ghostPluginViewModel';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
-const installedPlugin: GhostPluginListItem = {
+const commandPlugin: GhostPluginListItem = {
id: 'filo-google',
name: 'Filo Google',
description: 'Google services',
version: '1.0.0',
enabled: true,
canUse: true,
+ tabPanel: false,
+};
+
+const panelPlugin: GhostPluginListItem = {
+ ...commandPlugin,
+ id: 'signoff-board',
+ name: 'Signoff Board',
+ tabPanel: true,
+};
+
+const toolPlugin: GhostPluginListItem = {
+ ...commandPlugin,
+ id: 'pure-tool',
+ name: 'Pure Tool',
+ canUse: false,
};
const marketPlugin: PluginMarketItem = {
@@ -56,196 +65,136 @@ const marketPlugin: PluginMarketItem = {
enabled: null,
};
-function InstalledQueueHarness({ items }: { items: readonly GhostPluginListItem[] }) {
- const [expanded, setExpanded] = useState(false);
- return (
- <InstalledGhostQueue
- items={items}
- expanded={expanded}
- onExpandedChange={setExpanded}
- onSelect={vi.fn()}
- />
- );
-}
-
describe('GhostPluginCard', () => {
- it('shows the installed shortcut name through the shared Tooltip', () => {
- const onSelect = vi.fn();
- const { container } = render(
- <InstalledGhostShortcut item={installedPlugin} onSelect={onSelect} />,
- );
-
- const button = screen.getByRole('button', { name: 'Filo Google' });
- expect(container.querySelector('[data-tooltip="Filo Google"]')).toBeTruthy();
- expect(button.getAttribute('title')).toBeNull();
- fireEvent.click(button);
- expect(onSelect).toHaveBeenCalledWith('filo-google');
+ it('fires the primary action from the whole card for a command plugin', () => {
+ const onPrimary = vi.fn();
+ const onManage = vi.fn();
+ render(<GhostPluginCard item={commandPlugin} onPrimary={onPrimary} onManage={onManage} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Filo Google' }));
+ expect(onPrimary).toHaveBeenCalledTimes(1);
+ expect(onManage).not.toHaveBeenCalled();
+ // 指令型主按钮 = 「对话」。
+ expect(screen.getByRole('button', { name: 'settings.ghosts.page.chatAria' })).toBeTruthy();
});
- it('puts the collapse control after every installed plugin in the expanded queue', () => {
- const plugins = Array.from({ length: 7 }, (_, index) => ({
- ...installedPlugin,
- id: `plugin-${index + 1}`,
- name: `Plugin ${index + 1}`,
- }));
- const { container } = render(<InstalledQueueHarness items={plugins} />);
-
- expect(screen.getByRole('button', { name: 'Plugin 5' })).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'Plugin 6' })).toBeNull();
-
- const expand = screen.getByRole('button', {
- name: 'settings.ghosts.page.installedExpand',
- });
- expand.focus();
- fireEvent.click(expand);
-
- const queue = container.querySelector('[data-testid="installed-plugin-queue"]');
- const collapse = screen.getByRole('button', {
- name: 'settings.ghosts.page.installedCollapse',
- });
- expect(screen.getByRole('button', { name: 'Plugin 7' })).toBeTruthy();
- expect(queue?.lastElementChild).toBe(collapse);
- expect(within(collapse).queryByText('+2')).toBeNull();
- expect(collapse.querySelector('.lucide-chevron-up')).toBeTruthy();
- expect(document.activeElement).toBe(collapse);
-
- fireEvent.click(collapse);
- expect(document.activeElement).toBe(
- screen.getByRole('button', { name: 'settings.ghosts.page.installedExpand' }),
- );
- });
-
- it('opens the plugin detail from the card body without firing the action', () => {
- const onSelect = vi.fn();
- const onAction = vi.fn();
- render(<GhostPluginCard item={installedPlugin} onSelect={onSelect} onAction={onAction} />);
-
- const detailButton = screen.getByRole('button', { name: 'Filo Google' });
- fireEvent.click(detailButton);
+ it('labels the primary button 使用 for a tab-panel plugin', () => {
+ const onPrimary = vi.fn();
+ render(<GhostPluginCard item={panelPlugin} onPrimary={onPrimary} onManage={vi.fn()} />);
- expect(onSelect).toHaveBeenCalledTimes(1);
- expect(onAction).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.page.useAria' }));
+ expect(onPrimary).toHaveBeenCalledTimes(1);
});
- it('routes projected icon failures from installed cards and shortcuts to market recovery', () => {
- const onIconLoadError = vi.fn();
- const projected = {
- ...installedPlugin,
- iconDataUrl: 'https://plugins.example.invalid/icon.png?signature=current',
- };
- const { container, rerender } = render(
- <GhostPluginCard
- item={projected}
- onSelect={vi.fn()}
- onAction={vi.fn()}
- onIconLoadError={onIconLoadError}
- />,
- );
+ it('routes the manage icon to detail without firing the primary action', () => {
+ const onPrimary = vi.fn();
+ const onManage = vi.fn();
+ render(<GhostPluginCard item={commandPlugin} onPrimary={onPrimary} onManage={onManage} />);
- fireEvent.error(container.querySelector('img') as HTMLImageElement);
- expect(onIconLoadError).toHaveBeenCalledTimes(1);
-
- rerender(
- <InstalledGhostQueue
- items={[projected]}
- expanded={false}
- onExpandedChange={vi.fn()}
- onSelect={vi.fn()}
- onIconLoadError={onIconLoadError}
- />,
- );
- fireEvent.error(container.querySelector('img') as HTMLImageElement);
- expect(onIconLoadError).toHaveBeenCalledTimes(2);
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.page.manageAria' }));
+ expect(onManage).toHaveBeenCalledTimes(1);
+ expect(onPrimary).not.toHaveBeenCalled();
});
- it('surfaces the market update state with a badge and a direct update action', () => {
- const onAction = vi.fn();
+ it('shows the update pill and keeps it from triggering the card action', () => {
+ const onPrimary = vi.fn();
const onUpdate = vi.fn();
render(
<GhostPluginCard
- item={installedPlugin}
- onSelect={vi.fn()}
- onAction={onAction}
+ item={commandPlugin}
+ updateVersion="1.1.0"
+ onPrimary={onPrimary}
+ onManage={vi.fn()}
onUpdate={onUpdate}
- updateVersion="1.1.1"
/>,
);
- expect(screen.getByText('settings.ghosts.market.updateAvailable')).toBeTruthy();
- // Metadata keeps only the installed version; the pending version stays out of
- // the crowded metadata row (surfaced by the badge and the detail header instead).
- expect(screen.getByText('v1.0.0')).toBeTruthy();
- expect(screen.queryByText('v1.1.1')).toBeNull();
-
- const updateButton = screen.getByRole('button', {
- name: 'settings.ghosts.market.updateAria',
- });
- fireEvent.click(updateButton);
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.page.updateAria' }));
expect(onUpdate).toHaveBeenCalledTimes(1);
- expect(onAction).not.toHaveBeenCalled();
- // The direct Use entry is replaced by Update while a new release is pending.
- expect(screen.queryByRole('button', { name: 'settings.ghosts.page.useAria' })).toBeNull();
+ expect(onPrimary).not.toHaveBeenCalled();
+ // 有更新时不显示「已是最新」。
+ expect(screen.queryByText(/upToDate/)).toBeNull();
});
- it('keeps the update action interactive while Use is locked, and blocks it when busy', () => {
- const onUpdate = vi.fn();
+ it('blocks the update pill while a market operation is running', () => {
render(
<GhostPluginCard
- item={{ ...installedPlugin, enabled: false, canUse: false }}
- onSelect={vi.fn()}
- onAction={vi.fn()}
- onUpdate={onUpdate}
- updateVersion="1.1.1"
+ item={commandPlugin}
+ updateVersion="1.1.0"
updateBusy
+ onPrimary={vi.fn()}
+ onManage={vi.fn()}
+ onUpdate={vi.fn()}
/>,
);
- const updateButton = screen.getByRole('button', {
- name: 'settings.ghosts.market.updateAria',
- }) as HTMLButtonElement;
- expect(updateButton.disabled).toBe(true);
- fireEvent.click(updateButton);
- expect(onUpdate).not.toHaveBeenCalled();
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'settings.ghosts.page.updateAria',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ });
+
+ it('sends a tool-only plugin to manage and renders no primary button', () => {
+ const onPrimary = vi.fn();
+ const onManage = vi.fn();
+ render(<GhostPluginCard item={toolPlugin} onPrimary={onPrimary} onManage={onManage} />);
+
+ expect(screen.getByText('settings.ghosts.page.agentInvoked')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Pure Tool' }));
+ expect(onManage).toHaveBeenCalledTimes(1);
+ expect(onPrimary).not.toHaveBeenCalled();
});
- it('disables Use when an installed plugin has no command', () => {
+ it('sends a disabled plugin to manage and shows no enable switch on the card', () => {
+ const onPrimary = vi.fn();
+ const onManage = vi.fn();
render(
<GhostPluginCard
- item={{ ...installedPlugin, canUse: false }}
- onSelect={vi.fn()}
- onAction={vi.fn()}
+ item={{ ...commandPlugin, enabled: false }}
+ effectiveEnabled={false}
+ onPrimary={onPrimary}
+ onManage={onManage}
/>,
);
+ // 启用开关收进详情页(设计定稿):卡片上不再有 switch。
+ expect(screen.queryByRole('switch')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Filo Google' }));
+ expect(onManage).toHaveBeenCalledTimes(1);
+ expect(onPrimary).not.toHaveBeenCalled();
expect(
- (screen.getByRole('button', { name: 'settings.ghosts.page.useAria' }) as HTMLButtonElement)
- .disabled,
- ).toBe(true);
+ screen.getByRole('button', { name: 'settings.ghosts.page.manageAction' }),
+ ).toBeTruthy();
});
- it('renders project-scope enabled state and respects the global-disabled lock', () => {
- render(
+ it('routes projected icon failures to market recovery', () => {
+ const onIconLoadError = vi.fn();
+ const projected = {
+ ...commandPlugin,
+ iconDataUrl: 'https://plugins.example.invalid/icon.png?signature=current',
+ };
+ const { container } = render(
<GhostPluginCard
- item={{ ...installedPlugin, enabled: false, canUse: false }}
- onSelect={vi.fn()}
- onAction={vi.fn()}
- onToggle={vi.fn()}
- effectiveEnabled={false}
- toggleDisabled
+ item={projected}
+ onPrimary={vi.fn()}
+ onManage={vi.fn()}
+ onIconLoadError={onIconLoadError}
/>,
);
- const toggle = screen.getByRole('switch', { name: 'settings.ghosts.enableAria' });
- expect((toggle as HTMLButtonElement).disabled).toBe(true);
- expect(toggle.getAttribute('data-state')).toBe('unchecked');
+ fireEvent.error(container.querySelector('img') as HTMLImageElement);
+ expect(onIconLoadError).toHaveBeenCalledTimes(1);
});
it('renders a functional media symbol when the plugin package has no icon', () => {
const { container } = render(
<GhostPluginCard
- item={{ ...installedPlugin, id: 'lizi-mivo', name: 'Lizi Mivo' }}
- onSelect={vi.fn()}
- onAction={vi.fn()}
+ item={{ ...commandPlugin, id: 'lizi-mivo', name: 'Lizi Mivo' }}
+ onPrimary={vi.fn()}
+ onManage={vi.fn()}
/>,
);
@@ -256,9 +205,9 @@ describe('GhostPluginCard', () => {
it('renders the Mermaid fallback symbol on the theme elevated surface', () => {
const { container } = render(
<GhostPluginCard
- item={{ ...installedPlugin, id: 'cindy-mermaid', name: 'Cindy Mermaid' }}
- onSelect={vi.fn()}
- onAction={vi.fn()}
+ item={{ ...commandPlugin, id: 'cindy-mermaid', name: 'Cindy Mermaid' }}
+ onPrimary={vi.fn()}
+ onManage={vi.fn()}
/>,
);
@@ -266,6 +215,27 @@ describe('GhostPluginCard', () => {
expect(fallbackIcon).toBeTruthy();
expect(fallbackIcon?.parentElement?.className).toContain('var(--surface-elevated)');
});
+});
+
+describe('MarketPluginCard', () => {
+ it('exposes both 详情 and 安装 actions for a not-installed plugin', () => {
+ const onSelect = vi.fn();
+ const onInstall = vi.fn();
+ render(
+ <MarketPluginCard
+ item={marketPlugin}
+ busy={false}
+ onSelect={onSelect}
+ onInstall={onInstall}
+ onIconLoadError={vi.fn()}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.page.installAria' }));
+ expect(onInstall).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByText('settings.ghosts.market.details'));
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ });
it('keeps fixed market metadata on one line while truncating long identities', () => {
render(
@@ -294,6 +264,7 @@ describe('GhostPluginCard', () => {
item={{ ...marketPlugin, installState: 'conflict' }}
busy={false}
onSelect={vi.fn()}
+ onInstall={vi.fn()}
onIconLoadError={vi.fn()}
/>,
);
@@ -302,12 +273,20 @@ describe('GhostPluginCard', () => {
expect((cardBody as HTMLButtonElement).disabled).toBe(true);
expect(cardBody.className).toContain('disabled:cursor-not-allowed');
expect(cardBody.className).not.toContain('disabled:cursor-wait');
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'settings.ghosts.page.installAria',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
rerender(
<MarketPluginCard
item={marketPlugin}
busy
onSelect={vi.fn()}
+ onInstall={vi.fn()}
onIconLoadError={vi.fn()}
/>,
);
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 36cdcf4438..bcdabfed33 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -99,6 +99,7 @@ const detail: GhostPluginDetail = {
version: '1.2.3',
enabled: true,
canUse: true,
+ tabPanel: false,
author: 'XD',
contents: ['code'],
permissions: [],
@@ -145,6 +146,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
onUninstall={vi.fn()}
toggleDisabled={false}
/>,
@@ -193,6 +195,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
onUninstall={vi.fn()}
toggleDisabled={false}
onIconLoadError={onIconLoadError}
@@ -223,6 +226,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={onUpdate}
+ onUpdateFromFile={vi.fn()}
updateVersion={detail.version}
onUninstall={vi.fn()}
toggleDisabled={false}
@@ -258,7 +262,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={onUpdate}
- updateLabel="Update from market"
+ onUpdateFromFile={vi.fn()}
updateVersion="1.2.4"
updateBusy
onUninstall={vi.fn()}
@@ -275,7 +279,11 @@ describe('Ghost plugin detail sections', () => {
screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
{ button: 0, ctrlKey: false },
);
- const menuUpdate = screen.getByRole('menuitem', { name: 'Update from market' });
+ // ⋮ 菜单固定为「从文件更新」兜底路径(市场更新已提级到头部 CTA),
+ // 更新进行中同样置灰。
+ const menuUpdate = screen.getByRole('menuitem', {
+ name: 'settings.ghosts.detail.updateFromFile',
+ });
expect(menuUpdate.getAttribute('aria-disabled')).toBe('true');
fireEvent.click(menuUpdate);
expect(onUpdate).not.toHaveBeenCalled();
@@ -298,6 +306,7 @@ describe('Ghost plugin detail sections', () => {
onToggle: vi.fn(),
onUse: vi.fn(),
onUpdate: vi.fn(),
+ onUpdateFromFile: vi.fn(),
onUninstall: vi.fn(),
toggleDisabled: false,
};
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
new file mode 100644
index 0000000000..988724f2df
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Unit coverage for the update-all batch model: row extraction, transitions,
+ * settlement predicates, and the ignore-round identity key.
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import type { PluginMarketItem } from '../../../../shared/pluginMarket';
+import {
+ batchSummary,
+ buildUpdateAllRows,
+ isBatchFinished,
+ isBatchSettled,
+ updateRoundKey,
+ updateRow,
+} from '../lib/updateAllModel';
+
+function marketItem(overrides: Partial<PluginMarketItem>): PluginMarketItem {
+ return {
+ pluginId: 'release-a',
+ ghostId: 'ghost-a',
+ name: 'Ghost A',
+ description: '',
+ author: null,
+ scope: 'public',
+ organizationId: null,
+ defaultInstall: false,
+ releaseId: 'release-1',
+ version: '1.1.0',
+ publishedAt: '2026-08-01T00:00:00.000Z',
+ icon: null,
+ installState: 'update-available',
+ enabled: true,
+ ...overrides,
+ };
+}
+
+describe('buildUpdateAllRows', () => {
+ it('extracts only update-available items and keeps snapshot order', () => {
+ const rows = buildUpdateAllRows(
+ [
+ marketItem({ pluginId: 'p1', ghostId: 'g1', version: '2.0.0' }),
+ marketItem({ pluginId: 'p2', ghostId: 'g2', installState: 'installed' }),
+ marketItem({ pluginId: 'p3', ghostId: 'g3', installState: 'not-installed' }),
+ marketItem({ pluginId: 'p4', ghostId: 'g4', version: '0.2.0' }),
+ ],
+ new Map([
+ ['g1', '1.0.0'],
+ ['g4', '0.1.0'],
+ ]),
+ );
+
+ expect(rows.map((row) => row.pluginId)).toEqual(['p1', 'p4']);
+ expect(rows[0]).toMatchObject({
+ ghostId: 'g1',
+ fromVersion: '1.0.0',
+ toVersion: '2.0.0',
+ status: 'pending',
+ });
+ });
+});
+
+describe('batch transitions', () => {
+ const rows = buildUpdateAllRows(
+ [
+ marketItem({ pluginId: 'p1', ghostId: 'g1' }),
+ marketItem({ pluginId: 'p2', ghostId: 'g2' }),
+ ],
+ new Map(),
+ );
+
+ it('updates a single row immutably', () => {
+ const next = updateRow(rows, 'p1', { status: 'done' });
+ expect(next[0].status).toBe('done');
+ expect(rows[0].status).toBe('pending');
+ expect(next[1].status).toBe('pending');
+ });
+
+ it('settles when nothing auto-advances, finishes only after confirms resolve', () => {
+ let next = updateRow(rows, 'p1', { status: 'done' });
+ next = updateRow(next, 'p2', { status: 'needs-confirm' });
+ // needs-confirm 不再自动推进,但用户还没处理 → settled 而未 finished。
+ expect(isBatchSettled(next)).toBe(true);
+ expect(isBatchFinished(next)).toBe(false);
+
+ next = updateRow(next, 'p2', { status: 'skipped' });
+ expect(isBatchFinished(next)).toBe(true);
+ expect(batchSummary(next)).toEqual({ done: 1, skipped: 1, failed: 0 });
+ });
+});
+
+describe('updateRoundKey', () => {
+ it('is stable across ordering and changes when any target version changes', () => {
+ const a = [
+ marketItem({ pluginId: 'p1', ghostId: 'g1', version: '1.1.0' }),
+ marketItem({ pluginId: 'p2', ghostId: 'g2', version: '2.0.0' }),
+ ];
+ const b = [a[1], a[0]];
+ expect(updateRoundKey(a)).toBe(updateRoundKey(b));
+ const c = [a[0], marketItem({ pluginId: 'p2', ghostId: 'g2', version: '2.0.1' })];
+ expect(updateRoundKey(c)).not.toBe(updateRoundKey(a));
+ // 非可更新项不参与身份键。
+ expect(
+ updateRoundKey([...a, marketItem({ ghostId: 'g9', installState: 'installed' })]),
+ ).toBe(updateRoundKey(a));
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index c62e02b780..ea581a38c8 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -23,9 +23,28 @@ export interface GhostPluginListItem {
version: string;
enabled: boolean;
canUse: boolean;
+ /** 声明了右侧栏页签面板(panel.position:'tab'),主动作为「使用」(打开面板)。 */
+ tabPanel: boolean;
trust?: GhostTrustInfo;
iconDataUrl?: string;
}
+
+/**
+ * 卡片主动作的三分法(与设计稿一致):
+ * - `panel`:有页签面板 → 「使用」直接打开面板;
+ * - `command`:只有 $指令 → 「对话」把指令插进输入框起话题;
+ * - `manage`:纯工具型(Agent 对话中自动调用)→ 无主按钮,点卡片进管理页。
+ * 停靠形态(left/right)的面板由布局树承载,不算 panel 主动作。
+ */
+export type GhostPrimaryAction = 'panel' | 'command' | 'manage';
+
+export function ghostPrimaryAction(
+ item: Pick<GhostPluginListItem, 'tabPanel' | 'canUse'>,
+): GhostPrimaryAction {
+ if (item.tabPanel) return 'panel';
+ if (item.canUse) return 'command';
+ return 'manage';
+}
export interface GhostPluginDetail extends GhostPluginListItem {
trust: GhostTrustInfo;
author: string | null;
@@ -165,6 +184,7 @@ export function toGhostPluginListItem(
version: manifest.version,
enabled: ghost.enabled,
canUse: Boolean(manifest.command),
+ tabPanel: manifest.panel?.position === 'tab',
trust: ghost.trust ?? {
level: 'unverified',
publisherSigned: false,
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
new file mode 100644
index 0000000000..8e603bad6f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
@@ -0,0 +1,103 @@
+/**
+ * Pure state model for the "update all plugins" batch flow.
+ *
+ * Inputs: market items and installed Ghost manifests.
+ * Outputs: serially consumable rows whose transitions the dialog renders;
+ * no IPC here so the batch policy stays unit-testable.
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ */
+
+import type { GhostPermissionDiff } from '../../../../shared/ghost';
+import type { PluginMarketItem } from '../../../../shared/pluginMarket';
+
+/**
+ * 批量更新策略(设计定稿):权限无变化的自动串行完成;权限有扩张的
+ * 停在 `needs-confirm`,由用户逐项同意或跳过,绝不自动放行扩权。
+ */
+export type UpdateAllRowStatus =
+ | 'pending'
+ | 'installing'
+ | 'done'
+ | 'needs-confirm'
+ | 'skipped'
+ | 'failed';
+
+export interface UpdateAllRow {
+ pluginId: string;
+ ghostId: string;
+ name: string;
+ fromVersion: string;
+ toVersion: string;
+ status: UpdateAllRowStatus;
+ /** 目标 release(needs-confirm 时由运行器填充,approve 用它做并发防护)。 */
+ releaseId?: string;
+ /** 扩权详情(status 为 needs-confirm 时由运行器填充)。 */
+ permissionDiff?: GhostPermissionDiff;
+ /** status 为 failed 时的用户可读错误(已经过 i18n 映射)。 */
+ errorText?: string;
+}
+
+/** 从市场快照萃取可更新行;顺序即执行顺序(与列表快照顺序一致,稳定)。 */
+export function buildUpdateAllRows(
+ marketItems: readonly PluginMarketItem[],
+ installedVersionById: ReadonlyMap<string, string>,
+): UpdateAllRow[] {
+ return marketItems
+ .filter((item) => item.installState === 'update-available')
+ .map((item) => ({
+ pluginId: item.pluginId,
+ ghostId: item.ghostId,
+ name: item.name,
+ fromVersion: installedVersionById.get(item.ghostId) ?? '',
+ toVersion: item.version,
+ status: 'pending' as const,
+ }));
+}
+
+/** 单行状态迁移(不可变更新,供 React state 直接消费)。 */
+export function updateRow(
+ rows: readonly UpdateAllRow[],
+ pluginId: string,
+ patch: Partial<UpdateAllRow>,
+): UpdateAllRow[] {
+ return rows.map((row) => (row.pluginId === pluginId ? { ...row, ...patch } : row));
+}
+
+/** 批次是否已收敛:没有任何行还会自行推进(pending/installing)。 */
+export function isBatchSettled(rows: readonly UpdateAllRow[]): boolean {
+ return rows.every((row) => row.status !== 'pending' && row.status !== 'installing');
+}
+
+/** 批次是否完全结束:连待确认的扩权行都已被用户处理。 */
+export function isBatchFinished(rows: readonly UpdateAllRow[]): boolean {
+ return isBatchSettled(rows) && rows.every((row) => row.status !== 'needs-confirm');
+}
+
+/** 完成摘要:成功 / 跳过 / 失败计数,供收尾 toast 使用。 */
+export function batchSummary(rows: readonly UpdateAllRow[]): {
+ done: number;
+ skipped: number;
+ failed: number;
+} {
+ let done = 0;
+ let skipped = 0;
+ let failed = 0;
+ for (const row of rows) {
+ if (row.status === 'done') done += 1;
+ else if (row.status === 'skipped') skipped += 1;
+ else if (row.status === 'failed') failed += 1;
+ }
+ return { done, skipped, failed };
+}
+
+/**
+ * 「忽略本轮」的身份键:同一批可更新集合(id@目标版本)只被忽略一次,
+ * 任何插件出现更新的版本变化都会产生新键,横幅随之重新出现。
+ */
+export function updateRoundKey(marketItems: readonly PluginMarketItem[]): string {
+ return marketItems
+ .filter((item) => item.installState === 'update-available')
+ .map((item) => `${item.ghostId}@${item.version}`)
+ .sort()
+ .join('|');
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
index 0f9c12a7a3..81d97f5bef 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
@@ -18,7 +18,6 @@ import { useTranslation } from 'react-i18next';
import { FileDiff, FolderTree, Globe, ListTodo, Terminal } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
-import { listGhostTabMenuMetas, useTabKindRegistryVersion } from './registry';
import type { TabKindId, TabKindMenuMeta } from './types';
const DROPDOWN_WIDTH = 220;
@@ -182,9 +181,6 @@ export function AddTabDropdown({ anchorRef, onClose, onSelect, existingKinds }:
const enabled = MENU_ITEMS.filter((m) => m.enabled).sort((a, b) => a.order - b.order);
const coming = MENU_ITEMS.filter((m) => !m.enabled).sort((a, b) => a.order - b.order);
- // 插件页签(panel.position:'tab')动态分组:随装/卸/停用增减,版本号驱动重渲。
- useTabKindRegistryVersion();
- const ghostItems = listGhostTabMenuMetas();
return createPortal(
<div
@@ -233,31 +229,6 @@ export function AddTabDropdown({ anchorRef, onClose, onSelect, existingKinds }:
/>
);
})}
- {ghostItems.length > 0 && (
- <>
- <div className="mx-1 my-1 h-px bg-[var(--border-default)]" />
- <GroupHeader label={t('rightSidebar.tabs.menu.pluginGroup')} />
- {ghostItems.map((m) => {
- const alreadyOpen = m.singleton && existingKinds?.has(m.kind);
- return (
- <DropdownItem
- key={m.kind}
- icon={m.icon}
- // 插件名是用户内容原文(labelText),labelKey 只作兜底。
- label={m.labelText ?? t(m.labelKey)}
- trailing={
- alreadyOpen ? (
- <span className="text-[10px] text-[var(--text-tertiary)]">
- {t('rightSidebar.tabs.menu.alreadyOpen')}
- </span>
- ) : undefined
- }
- onClick={() => onSelect(m.kind)}
- />
- );
- })}
- </>
- )}
{coming.length > 0 && (
<>
<div className="mx-1 my-1 h-px bg-[var(--border-default)]" />
diff --git a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx
index 310c1c762c..203452d35f 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx
@@ -5,18 +5,14 @@
* 行右侧用 chevron 而非快捷键(快捷键在代码里没绑定,画 kbd 会骗用户)。
* 严格走 token(规则 16),不写 hex。
*
- * 插件页签行(panel.position:'tab' 的意识,2026-07-24):
- * - 恰好 1 个启用中 → 直接显示它自己(插件名一行);
- * - ≥2 个 → 收进一行可折叠分组(「插件面板」),展开逐个列出。
+ * 插件面板不再出现在这里(面板收束,2026-08):页签形态的插件面板由
+ * 插件页独占承载,入口只在 /plugins。
*/
-import { useState } from 'react';
-import { ChevronRight, FileDiff, FolderOpen, Globe, ListTodo, Puzzle, Terminal } from 'lucide-react';
+import { ChevronRight, FileDiff, FolderOpen, Globe, ListTodo, Terminal } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import type { TFunction } from 'i18next';
import { cn } from '@/lib/utils';
-import type { TabKindId, TabKindMenuMeta } from './types';
interface EmptyStateProps {
onAddFileTab: () => void;
@@ -24,9 +20,6 @@ interface EmptyStateProps {
onAddTerminalTab: () => void;
onAddReviewTab: () => void;
onAddBackgroundTasksTab: () => void;
- /** 启用中的插件页签 menu 项(listGhostTabMenuMetas 产物);缺省/空 = 不渲染插件行。 */
- ghostTabMetas?: TabKindMenuMeta[];
- onAddGhostTab?: (kind: TabKindId) => void;
}
export function EmptyState({
@@ -35,8 +28,6 @@ export function EmptyState({
onAddTerminalTab,
onAddReviewTab,
onAddBackgroundTasksTab,
- ghostTabMetas = [],
- onAddGhostTab,
}: EmptyStateProps) {
const { t } = useTranslation();
return (
@@ -88,18 +79,6 @@ export function EmptyState({
sub={t('rightSidebar.tabs.empty.terminalSub')}
onClick={onAddTerminalTab}
/>
- {ghostTabMetas.length === 1 && (
- // 恰好一个启用中的插件页签:直接显示它自己(插件名原文,不进 i18n)。
- <ActionRow
- icon={ghostTabMetas[0].icon}
- label={ghostTabMetas[0].labelText ?? t(ghostTabMetas[0].labelKey)}
- sub={t('rightSidebar.tabs.empty.pluginSub')}
- onClick={() => onAddGhostTab?.(ghostTabMetas[0].kind)}
- />
- )}
- {ghostTabMetas.length >= 2 && (
- <GhostGroupRows metas={ghostTabMetas} onAdd={onAddGhostTab} t={t} />
- )}
</div>
<p className="px-1 text-[11px] text-[var(--text-tertiary)]">
{t('rightSidebar.tabs.empty.addMoreHint')}
@@ -108,57 +87,6 @@ export function EmptyState({
);
}
-/**
- * 多个插件页签时的折叠分组:一行「插件面板」expander,展开后逐个列出。
- * 展开态不持久化 —— EmptyState 本身是临时画面,记忆没有意义。
- */
-function GhostGroupRows({
- metas,
- onAdd,
- t,
-}: {
- metas: TabKindMenuMeta[];
- onAdd?: (kind: TabKindId) => void;
- t: TFunction;
-}) {
- const [open, setOpen] = useState(false);
- return (
- <>
- <button
- type="button"
- aria-expanded={open}
- onClick={() => setOpen((v) => !v)}
- className="group flex w-full items-center gap-3.5 border-b border-[var(--border-default)] px-1 py-3 text-left transition-colors hover:bg-[var(--surface-hover)]"
- >
- <Puzzle size={16} className="text-[var(--text-secondary)]" />
- <span className="flex flex-1 flex-col gap-0.5">
- <span className="text-[14px] font-medium text-[var(--text-primary)]">
- {t('rightSidebar.tabs.empty.pluginGroup')}
- </span>
- <span className="text-[11px] text-[var(--text-tertiary)]">
- {t('rightSidebar.tabs.empty.pluginGroupSub', { count: metas.length })}
- </span>
- </span>
- <ChevronRight
- size={14}
- className={cn('text-[var(--text-tertiary)] transition-transform', open && 'rotate-90')}
- />
- </button>
- {open &&
- metas.map((m) => (
- <ActionRow
- key={m.kind}
- icon={m.icon}
- label={m.labelText ?? t(m.labelKey)}
- sub={t('rightSidebar.tabs.empty.pluginSub')}
- onClick={() => onAdd?.(m.kind)}
- inset
- />
- ))}
- </>
- );
-}
-
function ActionRow({
icon: Icon,
label,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
index 1c49f30ab7..1f89f33599 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
@@ -30,12 +30,7 @@ import { RightSidebarMaximize } from '@/components/layout/RightSidebarMaximize';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
import { TabBar, TabStrip } from './TabBar';
import { EmptyState } from './EmptyState';
-import {
- getTabKind,
- hydrateTabState,
- listGhostTabMenuMetas,
- useTabKindRegistryVersion,
-} from './registry';
+import { getTabKind, hydrateTabState } from './registry';
import {
addOrFocusSingletonTab,
addTab,
@@ -48,15 +43,6 @@ import {
setTabCloseInterceptor,
subscribe,
} from './store';
-import {
- AUTO_PINNED_GHOST_TAB_STATE,
- getLastFocusedPinnedGhostKind,
- ghostIdOfTabKind,
- isAutoPinnedGhostTabState,
- isGhostTabPinned,
- setLastFocusedPinnedGhostKind,
- useGhostTabPinsVersion,
-} from './lib/pinnedGhostTabs';
import type { TabKindHostContext, TabKindId, TabState } from './types';
// Side-effect import:触发各 plugin 模块顶层 registerTabKind(...)。Phase 3 注册
// file-browser;Phase 5 注册 web-browser。Shell 不直接消费 plugin 实例,只通过
@@ -64,8 +50,6 @@ import type { TabKindHostContext, TabKindId, TabState } from './types';
import './plugins';
import { initRsbBrowserBridge } from './lib/rsbBrowserBridge';
import { initPopupRouter, setPopupFallbackSession } from './lib/popupRouter';
-import { requestRightSidebarVisibility } from './lib/sidebarCommands';
-import { readPanelCollapsed } from '@/layout/collapsePrefs';
const log = createLogger('rightSidebar.shell');
/**
@@ -213,97 +197,23 @@ export function RightSidebarShell({
const tabs = bucket.tabs;
const activeTabId = bucket.activeTabId;
- // 插件页签(panel.position:'tab')随装/卸/停用动态注册,版本号驱动重渲——
- // EmptyState 的插件行与「+」菜单动态分组都吃这份数据。
- const tabRegistryVersion = useTabKindRegistryVersion();
- // 注册表是模块级 Map,不在 React 数据流里 —— 版本号是唯一变化信号,拿它当 dep。
- const ghostTabMetas = useMemo(() => listGhostTabMenuMetas(), [tabRegistryVersion]);
-
- // 钉住偏好版本号:钉/取消钉都要驱动下方维护 effect 与 pill 重渲。
- const ghostPinsVersion = useGhostTabPinsVersion();
-
- // 钉住面板页签的跨会话维护(hydrate 之后跑,幂等,串行 await 防 reorder 竞态):
- // 1) 清扫:自动补挂(state 带 autoPinned 标记)但插件已不再钉住的页签关掉
- // —— 取消钉住在别的会话里也要收干净,不留残影;用户手动开的页签无标记,
- // 不受清扫影响(取消钉住 = 回到"仅当前会话"语义)。
- // 2) 补挂:钉住且已注册(启用中)的面板页签,本会话没有 → 追加。默认
- // activate:false 不抢焦点;会话本来就没有激活 tab 时兜底激活,避免
- // "有 pill 无内容"的空面板。
- // 3) 粘性激活:上一会话正看着某钉住面板 → 切会话后把同一面板带到前台
- // (每个 sessionId 只做一次,用户随后在本会话内的切换不被打扰)。
- // 「带到前台」包括把收着的侧栏打开:目标会话侧栏收着(新会话默认收)时,
- // 只激活 tab 用户什么都看不见,钉住的"跨对话保留"承诺就断了。仅在
- // 上一会话侧栏是展开的(用户确实正看着)时才请求展开;上一会话本来就
- // 收着 → 用户没在看面板,切会话不弹窗打扰。detached 形态下该请求走
- // userInitiated:false 语义,不会把子窗口抢到前台。
- // 插件被停用时 kind 未注册 → 跳过补挂;已存在的页签保留(落 Placeholder,
- // 与"停用隐藏、重启用复活"的既有语义一致)。
- const stickyAppliedSessionRef = useRef<string | null>(null);
+ // 面板收束(2026-08):插件页签不再注册进右侧栏。历史会话里持久化的
+ // `ghost:*` tab 是旧形态残留,发现即静默关闭 —— 这些 kind 已无渲染方,
+ // 留着只会落到 PlaceholderBody 变成"敬请期待"的死页签。
useEffect(() => {
- if (!sessionId || !bucket.hydrated) return;
- let cancelled = false;
- const run = async () => {
- // 1) 清扫
- for (const tab of bucket.tabs) {
- if (cancelled) return;
- const gid = ghostIdOfTabKind(tab.kind);
- if (!gid) continue;
- if (isAutoPinnedGhostTabState(tab.state) && !isGhostTabPinned(gid)) {
- try {
- await closeTab(sessionId, tab.id);
- } catch (err) {
- log.error('pinned ghost tab sweep failed', { sessionId, tabId: tab.id, err });
- }
- }
- }
- // 2) 补挂
- for (const meta of listGhostTabMenuMetas()) {
- if (cancelled) return;
- const gid = ghostIdOfTabKind(meta.kind);
- if (!gid || !isGhostTabPinned(gid)) continue;
- if (getBucket(sessionId).tabs.some((t) => t.kind === meta.kind)) continue;
- try {
- await addTab(sessionId, meta.kind, AUTO_PINNED_GHOST_TAB_STATE, { activate: false });
- } catch (err) {
- // 典型失败:MAX_TABS_PER_SESSION 满。补挂失败不重试,本会话手动管理。
- log.error('pinned ghost tab auto-add failed', { sessionId, kind: meta.kind, err });
- }
- }
- if (cancelled) return;
- // 3) 粘性激活 + 空激活位兜底
- const applySticky = stickyAppliedSessionRef.current !== sessionId;
- const prevSessionId = stickyAppliedSessionRef.current;
- stickyAppliedSessionRef.current = sessionId;
- const now = getBucket(sessionId);
- let target: string | null = null;
- const stickyKind = applySticky ? getLastFocusedPinnedGhostKind() : null;
- if (stickyKind) {
- target = now.tabs.find((t) => t.kind === stickyKind)?.id ?? null;
- if (
- target !== null &&
- prevSessionId !== null && // 首帧(启动进第一个会话)不算"切换",不弹
- !readPanelCollapsed('right-tabs', { sessionId: prevSessionId }, true) &&
- readPanelCollapsed('right-tabs', { sessionId }, true)
- ) {
- requestRightSidebarVisibility('open', { sessionId, userInitiated: false });
- }
- }
- if (!target && now.activeTabId === null && now.tabs.length > 0) {
- target = now.tabs[0].id;
- }
- if (target && target !== now.activeTabId) {
+ if (!bucket.hydrated || !sessionId) return;
+ const legacyGhostTabs = bucket.tabs.filter((tab) => tab.kind.startsWith('ghost:'));
+ if (legacyGhostTabs.length === 0) return;
+ void (async () => {
+ for (const tab of legacyGhostTabs) {
try {
- await setActiveTab(sessionId, target);
+ await closeTab(sessionId, tab.id);
} catch (err) {
- log.error('pinned ghost tab activate failed', { sessionId, target, err });
+ log.error('legacy ghost tab prune failed', { sessionId, tabId: tab.id, err });
}
}
- };
- void run();
- return () => {
- cancelled = true;
- };
- }, [sessionId, bucket.hydrated, bucket.tabs, ghostPinsVersion, tabRegistryVersion]);
+ })();
+ }, [bucket.hydrated, bucket.tabs, sessionId]);
// 关掉最后一个 tab → 通知 host 自动收起侧栏。只在 tab 数「从 >0 变 0」的转变时
// 触发,不是"等于 0"就触发:
@@ -340,9 +250,6 @@ export function RightSidebarShell({
const action = isSingleton
? addOrFocusSingletonTab(sessionId, kind, initialState)
: addTab(sessionId, kind, initialState);
- // 新开 tab 即成为焦点:是钉住面板 → 记粘性焦点,其余 → 清。
- // (addOrFocusSingletonTab 已同步写入默认钉住条目,此处读到的是新状态。)
- setLastFocusedPinnedGhostKind(kind);
void action.catch((err) => {
// TODO(Phase 7): toast 暴露 RIGHT_SIDEBAR_TOO_MANY_TABS / STATE_TOO_LARGE 等错误码。
log.error('handleAdd failed', { sessionId, kind, err });
@@ -364,9 +271,6 @@ export function RightSidebarShell({
const handleActivate = useCallback(
(tabId: string) => {
if (!sessionId) return;
- // 用户显式聚焦:钉住面板 → 记粘性焦点(切会话跟着走);其它 tab → 清。
- const kind = getBucket(sessionId).tabs.find((t) => t.id === tabId)?.kind ?? null;
- setLastFocusedPinnedGhostKind(kind);
void setActiveTab(sessionId, tabId).catch((err) => {
log.error('handleActivate failed', { sessionId, tabId, err });
});
@@ -398,8 +302,6 @@ export function RightSidebarShell({
: (activeIndex + (direction === 'next' ? 1 : -1) + tabs.length) % tabs.length;
const nextTabId = tabs[nextIndex]?.id;
if (!nextTabId || nextTabId === activeTabId) return false;
- // 快捷键轮换也是显式聚焦 —— 与 handleActivate 同口径维护粘性焦点。
- setLastFocusedPinnedGhostKind(tabs[nextIndex]?.kind ?? null);
void setActiveTab(sessionId, nextTabId).catch((err) => {
log.error('cycle right sidebar tab failed', { sessionId, direction, nextTabId, err });
});
@@ -604,8 +506,6 @@ export function RightSidebarShell({
onAddBackgroundTasksTab={() => handleAdd('background-tasks')}
onAddBrowserTab={() => handleAdd('web-browser')}
onAddTerminalTab={() => handleAdd('terminal')}
- ghostTabMetas={ghostTabMetas}
- onAddGhostTab={handleAdd}
/>
) : (
// 所有 tab 都挂载,只切换可见性(规则 7:杜绝切顶层 tab 时 plugin 内部 state /
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index 718260ce67..a378bbeb40 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@ -26,7 +26,6 @@ import {
GitPullRequestArrow,
UsersRound,
ListTodo,
- Pin,
Plus,
Puzzle,
X,
@@ -49,12 +48,6 @@ import {
} from '@/components/ui/dropdown-menu';
import { AddTabDropdown } from './AddTabDropdown';
import { getTabKind, hydrateTabState } from './registry';
-import {
- ghostIdOfTabKind,
- isGhostTabPinned,
- setGhostTabPinned,
- useGhostTabPinsVersion,
-} from './lib/pinnedGhostTabs';
import type { BuiltinTabKindId, TabKindId, TabState } from './types';
interface TabBarProps {
@@ -296,12 +289,6 @@ export function TabStrip({
tabId: string;
} | null>(null);
const closeContextMenu = () => setContextMenu(null);
- // 右键菜单的钉住项:菜单开着时钉住状态被别处改掉也要跟着换文案。
- useGhostTabPinsVersion();
- const contextMenuTab = contextMenu
- ? tabs.find((tab) => tab.id === contextMenu.tabId) ?? null
- : null;
- const contextMenuGhostId = contextMenuTab ? ghostIdOfTabKind(contextMenuTab.kind) : null;
// 溢出渐变遮罩:只在对应侧**真的有溢出**时才启用那一侧的 fade。
// 历史坑(2026-07-01):全量常开的 fade-mask 会把首尾 active pill 的 1px border
@@ -481,21 +468,6 @@ export function TabStrip({
>
{contextMenu && (
<>
- {contextMenuGhostId && (
- <DropdownMenuItem
- onClick={() => {
- closeContextMenu();
- setGhostTabPinned(contextMenuGhostId, !isGhostTabPinned(contextMenuGhostId));
- }}
- className="h-7 px-2.5 rounded-md text-[13px] leading-none text-[var(--msg-assistant-text)] focus:bg-[var(--cmd-palette-item-hover)]"
- >
- {t(
- isGhostTabPinned(contextMenuGhostId)
- ? 'rightSidebar.tabs.contextMenu.unpin'
- : 'rightSidebar.tabs.contextMenu.pin',
- )}
- </DropdownMenuItem>
- )}
<DropdownMenuItem
onClick={() => {
const id = contextMenu.tabId;
@@ -565,11 +537,6 @@ function TabPill({
const FallbackIcon = iconForTabKind(tab.kind);
const TitleNode = plugin?.TabPillTitle;
const IconNode = plugin?.TabPillIcon;
- // 图钉状态订阅(钉/取消钉 → pill 重渲)。hook 必须无条件调用,非插件页签
- // 只是不消费返回值。
- useGhostTabPinsVersion();
- const ghostId = ghostIdOfTabKind(tab.kind);
- const pinned = ghostId !== null && isGhostTabPinned(ghostId);
// raw tab.state 可能是 null(Phase 2 旧 tab 没 hydrate)或旧 schema —— 必须先
// 规范化再喂给 plugin 的 Title/Icon,否则 plugin 内 `state.xxx` 直接 NPE。
// 走 store 持久化时是 raw,展示前由 hydrateTabState 兜底 / 校正。
@@ -637,30 +604,6 @@ function TabPill({
)}
</span>
</button>
- {ghostId && (
- // 插件面板页签专属的图钉切换:钉住态常驻显形(它同时是状态指示——用户
- // 一眼看出这个面板会跟着所有对话走);未钉住态 hover 显形(纯动作按钮,
- // 常态不占视觉注意力)。颜色只用灰阶文字 token,不引入新强调色。
- <button
- type="button"
- data-no-drag
- onClick={(e) => {
- e.stopPropagation();
- setGhostTabPinned(ghostId, !pinned);
- }}
- aria-label={pinned ? t('rightSidebar.tabs.unpinAria') : t('rightSidebar.tabs.pinAria')}
- title={pinned ? t('rightSidebar.tabs.unpinAria') : t('rightSidebar.tabs.pinAria')}
- aria-pressed={pinned}
- className={cn(
- 'inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full transition-opacity hover:text-[var(--text-primary)]',
- pinned
- ? 'text-[var(--text-secondary)]'
- : 'text-[var(--text-tertiary)] opacity-0 focus-visible:opacity-100 group-hover:opacity-100',
- )}
- >
- <Pin size={10} />
- </button>
- )}
<button
type="button"
data-no-drag
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx
index 6ee8e55bf0..3d3dac43e2 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx
@@ -1,40 +1,30 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { Puzzle } from 'lucide-react';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
import { EmptyState } from '../EmptyState';
-import type { TabKindMenuMeta } from '../types';
afterEach(() => cleanup());
-function ghostMeta(id: string, label: string): TabKindMenuMeta {
- return {
- kind: `ghost:${id}`,
- labelKey: 'rightSidebar.tabs.kinds.ghostPanel',
- labelText: label,
- icon: Puzzle,
- order: 100,
- enabled: true,
- singleton: true,
- };
+function renderEmptyState() {
+ return render(
+ <EmptyState
+ onAddFileTab={vi.fn()}
+ onAddReviewTab={vi.fn()}
+ onAddBackgroundTasksTab={vi.fn()}
+ onAddBrowserTab={vi.fn()}
+ onAddTerminalTab={vi.fn()}
+ />,
+ );
}
describe('EmptyState add-more hint', () => {
it('renders a non-interactive hint for the existing top add button', () => {
- render(
- <EmptyState
- onAddFileTab={vi.fn()}
- onAddReviewTab={vi.fn()}
- onAddBackgroundTasksTab={vi.fn()}
- onAddBrowserTab={vi.fn()}
- onAddTerminalTab={vi.fn()}
- />,
- );
+ renderEmptyState();
const hint = screen.getByText('rightSidebar.tabs.empty.addMoreHint');
expect(hint.tagName).toBe('P');
@@ -45,65 +35,9 @@ describe('EmptyState add-more hint', () => {
});
});
-describe('EmptyState 插件页签行(1 个直显 / ≥2 折叠)', () => {
- it('恰好 1 个启用中的插件 → 直接显示插件自己的行,点击回传 kind', () => {
- const onAddGhostTab = vi.fn();
- render(
- <EmptyState
- onAddFileTab={vi.fn()}
- onAddReviewTab={vi.fn()}
- onAddBackgroundTasksTab={vi.fn()}
- onAddBrowserTab={vi.fn()}
- onAddTerminalTab={vi.fn()}
- ghostTabMetas={[ghostMeta('art', '画廊')]}
- onAddGhostTab={onAddGhostTab}
- />,
- );
-
- // 直显插件名原文,没有折叠分组行
- fireEvent.click(screen.getByText('画廊'));
- expect(onAddGhostTab).toHaveBeenCalledWith('ghost:art');
- expect(screen.queryByText('rightSidebar.tabs.empty.pluginGroup')).toBeNull();
- });
-
- it('≥2 个 → 折叠分组:默认收起,展开后逐个列出并可点击', () => {
- const onAddGhostTab = vi.fn();
- render(
- <EmptyState
- onAddFileTab={vi.fn()}
- onAddReviewTab={vi.fn()}
- onAddBackgroundTasksTab={vi.fn()}
- onAddBrowserTab={vi.fn()}
- onAddTerminalTab={vi.fn()}
- ghostTabMetas={[ghostMeta('art', '画廊'), ghostMeta('memo', '备忘')]}
- onAddGhostTab={onAddGhostTab}
- />,
- );
-
- // 收起态:只有分组行,不见具体插件
- const groupRow = screen.getByText('rightSidebar.tabs.empty.pluginGroup');
- expect(screen.queryByText('画廊')).toBeNull();
- expect(screen.queryByText('备忘')).toBeNull();
-
- fireEvent.click(groupRow);
- fireEvent.click(screen.getByText('备忘'));
- expect(onAddGhostTab).toHaveBeenCalledWith('ghost:memo');
-
- // 再点分组行收回去
- fireEvent.click(groupRow);
- expect(screen.queryByText('画廊')).toBeNull();
- });
-
- it('没有插件(缺省)→ 不渲染任何插件行', () => {
- render(
- <EmptyState
- onAddFileTab={vi.fn()}
- onAddReviewTab={vi.fn()}
- onAddBackgroundTasksTab={vi.fn()}
- onAddBrowserTab={vi.fn()}
- onAddTerminalTab={vi.fn()}
- />,
- );
+describe('EmptyState 面板收束(2026-08)', () => {
+ it('不再渲染任何插件页签入口(插件面板只从插件页进入)', () => {
+ renderEmptyState();
expect(screen.queryByText('rightSidebar.tabs.empty.pluginGroup')).toBeNull();
expect(screen.queryByText('rightSidebar.tabs.empty.pluginSub')).toBeNull();
});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
index 2bc33eead5..1548f1eb1c 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
@@ -40,7 +40,6 @@ import {
type SidebarVisibilityRequestOptions,
} from '../lib/sidebarCommands';
import { _resetStore, closeTab, getBucket } from '../store';
-import { setGhostTabPinned, setLastFocusedPinnedGhostKind } from '../lib/pinnedGhostTabs';
import { writePanelCollapsed } from '@/layout/collapsePrefs';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
@@ -875,137 +874,3 @@ describe('RightSidebarShell 跨 session popup 归属', () => {
expect(requests).toHaveLength(0);
});
});
-
-describe('RightSidebarShell 钉住面板粘性展开(切会话把收着的侧栏打开)', () => {
- let tabsIpc: RightSidebarTabsIpcStub;
- let requests: Array<{
- visibility: SidebarVisibilityRequest;
- opts: SidebarVisibilityRequestOptions;
- }>;
- let unsubVisibility: () => void;
-
- const GHOST_KIND = 'ghost:pr-signoff';
-
- beforeEach(() => {
- Object.defineProperty(HTMLElement.prototype, 'scrollTo', {
- configurable: true,
- value: vi.fn(),
- });
- localStorage.clear();
- _resetStore();
- _resetRsbBrowserBridgeForTests();
- _resetPopupRouterForTests();
- _resetSidebarCommandsForTests();
- setLastFocusedPinnedGhostKind(null);
- rsbBrowserCommandListeners = [];
- rsbBrowserPopupListeners = [];
- eagerSpawnAndReport.mockClear();
- eagerSpawnAndReport.mockImplementation(async () => undefined);
- requests = [];
- unsubVisibility = onRequestRightSidebarVisibility((visibility, opts) => {
- requests.push({ visibility, opts });
- });
- setGhostTabPinned('pr-signoff', true); // 无条目 = 不算钉住,先钉上
- tabsIpc = makeRightSidebarTabsIpc();
- // 两个任务都带同一块钉住面板页签(补挂在真环境由注册表驱动,单测无插件
- // 注册,直接让存档里就有)。
- tabsIpc.list.mockImplementation(async () => ({
- tabs: [{ id: 'tab-ghost', kind: GHOST_KIND, state: null }],
- activeTabId: 'tab-ghost',
- }));
- installElectronApi(tabsIpc);
- });
-
- afterEach(() => {
- unsubVisibility();
- setLastFocusedPinnedGhostKind(null);
- _resetSidebarCommandsForTests();
- _resetStore();
- _resetRsbBrowserBridgeForTests();
- _resetPopupRouterForTests();
- localStorage.clear();
- delete (window as unknown as { electronAPI?: unknown }).electronAPI;
- });
-
- function renderShell(sessionId: string): ReturnType<typeof render> {
- return render(
- createElement(RightSidebarShell, {
- sessionId,
- workdir: '/tmp/repo',
- remoteHostId: null,
- isMac: true,
- unifiedTopbar: true,
- }),
- );
- }
-
- function rerenderShell(view: ReturnType<typeof render>, sessionId: string): void {
- view.rerender(
- createElement(RightSidebarShell, {
- sessionId,
- workdir: '/tmp/repo',
- remoteHostId: null,
- isMac: true,
- unifiedTopbar: true,
- }),
- );
- }
-
- it('上一会话正看着钉住面板且侧栏展开 → 切会话请求展开收着的侧栏', async () => {
- writePanelCollapsed('right-tabs', { sessionId: 's1' }, false); // s1 侧栏展开
- // s2 无存档 = 默认收着
-
- const view = renderShell('s1');
- await waitFor(() => expect(getBucket('s1').tabs).toHaveLength(1));
- setLastFocusedPinnedGhostKind(GHOST_KIND); // 用户正看着钉住面板
-
- rerenderShell(view, 's2');
- await waitFor(() => expect(requests.length).toBeGreaterThan(0));
- expect(requests[0].visibility).toBe('open');
- expect(requests[0].opts.sessionId).toBe('s2');
- // 程序自发的跟随,不是用户手势:detached 形态下不得抢前台。
- expect(requests[0].opts.userInitiated).toBe(false);
- });
-
- it('上一会话侧栏本来就收着 → 不弹', async () => {
- writePanelCollapsed('right-tabs', { sessionId: 's1' }, true); // s1 也收着
-
- const view = renderShell('s1');
- await waitFor(() => expect(getBucket('s1').tabs).toHaveLength(1));
- setLastFocusedPinnedGhostKind(GHOST_KIND);
-
- rerenderShell(view, 's2');
- await waitFor(() => expect(getBucket('s2').tabs).toHaveLength(1));
- await act(async () => {
- await Promise.resolve();
- });
- expect(requests).toHaveLength(0);
- });
-
- it('没有粘性焦点(用户没在看面板) → 不弹', async () => {
- writePanelCollapsed('right-tabs', { sessionId: 's1' }, false);
-
- const view = renderShell('s1');
- await waitFor(() => expect(getBucket('s1').tabs).toHaveLength(1));
- // 不设粘性焦点
-
- rerenderShell(view, 's2');
- await waitFor(() => expect(getBucket('s2').tabs).toHaveLength(1));
- await act(async () => {
- await Promise.resolve();
- });
- expect(requests).toHaveLength(0);
- });
-
- it('首帧(启动进第一个任务)不算切换 → 不弹', async () => {
- writePanelCollapsed('right-tabs', { sessionId: 's1' }, true);
- setLastFocusedPinnedGhostKind(GHOST_KIND);
-
- renderShell('s1');
- await waitFor(() => expect(getBucket('s1').tabs).toHaveLength(1));
- await act(async () => {
- await Promise.resolve();
- });
- expect(requests).toHaveLength(0);
- });
-});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBarGhostPin.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBarGhostPin.test.tsx
deleted file mode 100644
index e4dd08e146..0000000000
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBarGhostPin.test.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-// @vitest-environment jsdom
-/**
- * TabPill 图钉按钮 —— 插件面板页签专属的钉住切换。
- * i18n 走 key 透传(TabBar.test.tsx 同款),断言直接用 key。
- */
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-import { TabStrip } from '../TabBar';
-import {
- _resetGhostTabPinsForTest,
- isGhostTabPinned,
- markGhostTabOpened,
-} from '../lib/pinnedGhostTabs';
-import type { TabState } from '../types';
-
-const GHOST_TAB: TabState = { id: 'tab-ghost', kind: 'ghost:cindy-art', state: null };
-const FILE_TAB: TabState = { id: 'tab-file', kind: 'file-browser', state: null };
-const PIN_ARIA = 'rightSidebar.tabs.pinAria';
-const UNPIN_ARIA = 'rightSidebar.tabs.unpinAria';
-
-function renderStrip(tabs: TabState[] = [GHOST_TAB, FILE_TAB]) {
- render(
- <TabStrip
- tabs={tabs}
- activeTabId={null}
- onActivate={vi.fn()}
- onClose={vi.fn()}
- onReorder={vi.fn()}
- onAdd={vi.fn()}
- />,
- );
-}
-
-beforeEach(() => {
- _resetGhostTabPinsForTest();
-});
-afterEach(() => cleanup());
-
-describe('TabPill 图钉按钮', () => {
- it('插件页签渲染图钉按钮,非插件页签不渲染', () => {
- markGhostTabOpened('cindy-art');
- renderStrip();
- const unpinButtons = screen.getAllByRole('button', { name: UNPIN_ARIA });
- expect(unpinButtons).toHaveLength(1);
- // file-browser pill 内没有图钉(全 DOM 只有插件 pill 这一颗)
- expect(screen.queryAllByRole('button', { name: PIN_ARIA })).toHaveLength(0);
- });
-
- it('未钉住 → 按钮语义是「钉住」,点击写入钉住状态', () => {
- renderStrip();
- const pin = screen.getByRole('button', { name: PIN_ARIA });
- expect(pin.getAttribute('aria-pressed')).toBe('false');
- expect(pin.hasAttribute('data-no-drag')).toBe(true);
- fireEvent.click(pin);
- expect(isGhostTabPinned('cindy-art')).toBe(true);
- // 状态翻转后按钮变「取消钉住」且常驻显形(aria-pressed=true)
- const unpin = screen.getByRole('button', { name: UNPIN_ARIA });
- expect(unpin.getAttribute('aria-pressed')).toBe('true');
- });
-
- it('钉住中 → 点击取消钉住', () => {
- markGhostTabOpened('cindy-art');
- renderStrip();
- fireEvent.click(screen.getByRole('button', { name: UNPIN_ARIA }));
- expect(isGhostTabPinned('cindy-art')).toBe(false);
- expect(screen.getByRole('button', { name: PIN_ARIA })).toBeTruthy();
- });
-});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.ts
index f4f9c58879..741de8d6a3 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.ts
@@ -20,7 +20,6 @@ import {
_resetTabKindRegistry,
getTabKind,
hydrateTabState,
- listGhostTabMenuMetas,
listTabKindMenuMetas,
registerTabKind,
unregisterTabKind,
@@ -121,41 +120,6 @@ describe('TabKindRegistry', () => {
});
});
- describe('listGhostTabMenuMetas', () => {
- it('only returns ghost:* kinds, sorted by labelText', () => {
- registerTabKind(makePlugin('file-browser', 10));
- registerTabKind(
- makePlugin('ghost:zeta' as TabKindId, 100, {
- menu: {
- kind: 'ghost:zeta' as TabKindId,
- labelKey: 'stub.ghost',
- labelText: '备忘',
- icon: Globe,
- order: 100,
- enabled: true,
- singleton: true,
- },
- }),
- );
- registerTabKind(
- makePlugin('ghost:alpha' as TabKindId, 100, {
- menu: {
- kind: 'ghost:alpha' as TabKindId,
- labelKey: 'stub.ghost',
- labelText: '画廊',
- icon: Globe,
- order: 100,
- enabled: true,
- singleton: true,
- },
- }),
- );
- expect(listGhostTabMenuMetas().map((m) => m.labelText)).toEqual(['备忘', '画廊']);
- // 内置项不混入
- expect(listGhostTabMenuMetas().some((m) => m.kind === 'file-browser')).toBe(false);
- });
- });
-
describe('getTabKind', () => {
it('returns null for unregistered kind', () => {
expect(getTabKind('terminal')).toBeNull();
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/storeGhostTabPins.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/storeGhostTabPins.test.ts
deleted file mode 100644
index 869d28c98c..0000000000
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/storeGhostTabPins.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-// @vitest-environment jsdom
-
-/**
- * store × pinnedGhostTabs 联动单测:
- * - addTab({activate:false}) 不抢激活位(cache 与 IPC 都不动 active);
- * - addOrFocusSingletonTab 打开插件页签 → 默认写入钉住条目;
- * - closeTab 关闭钉住中的插件页签 → 钉住条目清除(= 取消钉住并关闭);
- * - closeTab IPC 失败回滚 → 钉住条目保留。
- * IPC 桩与 store.test.ts 同款(内存版 rightSidebarTabs)。
- */
-
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import * as store from '../store';
-import {
- _resetGhostTabPinsForTest,
- isGhostTabPinned,
-} from '../lib/pinnedGhostTabs';
-
-vi.mock('@/features/device-link/remoteProjectsStore', () => ({
- getSessionDeviceId: () => undefined,
-}));
-
-type IpcStub = {
- list: ReturnType<typeof vi.fn>;
- upsert: ReturnType<typeof vi.fn>;
- close: ReturnType<typeof vi.fn>;
- setActive: ReturnType<typeof vi.fn>;
- reorder: ReturnType<typeof vi.fn>;
-};
-
-function makeIpcStub(): IpcStub {
- return {
- list: vi.fn().mockResolvedValue({ tabs: [], activeTabId: null }),
- upsert: vi.fn().mockResolvedValue({ ok: true }),
- close: vi.fn().mockResolvedValue({ ok: true }),
- setActive: vi.fn().mockResolvedValue({ ok: true }),
- reorder: vi.fn().mockResolvedValue({ ok: true }),
- };
-}
-
-function installIpc(stub: IpcStub): void {
- (window as unknown as {
- electronAPI: { localDb: { rightSidebarTabs: IpcStub }; platform: string };
- }).electronAPI = {
- localDb: { rightSidebarTabs: stub },
- platform: 'darwin',
- };
-}
-
-const SID = 's-pin-test';
-
-describe('store × pinnedGhostTabs', () => {
- let ipc: IpcStub;
-
- beforeEach(async () => {
- store._resetStore();
- _resetGhostTabPinsForTest();
- ipc = makeIpcStub();
- installIpc(ipc);
- await store.ensureHydrated(SID);
- });
-
- it('addTab activate:false:激活位不动,IPC 不发 setActive', async () => {
- const first = await store.addTab(SID, 'file-browser');
- expect(store.getBucket(SID).activeTabId).toBe(first.id);
- ipc.setActive.mockClear();
-
- const added = await store.addTab(SID, 'ghost:cindy-art', { autoPinned: true }, {
- activate: false,
- });
- const bucket = store.getBucket(SID);
- expect(bucket.tabs.map((t) => t.id)).toEqual([first.id, added.id]);
- expect(bucket.activeTabId).toBe(first.id);
- expect(ipc.setActive).not.toHaveBeenCalled();
- });
-
- it('addOrFocusSingletonTab 打开插件页签 → 默认钉住;非插件 kind 不写条目', async () => {
- expect(isGhostTabPinned('cindy-art')).toBe(false);
- await store.addOrFocusSingletonTab(SID, 'ghost:cindy-art');
- expect(isGhostTabPinned('cindy-art')).toBe(true);
- await store.addOrFocusSingletonTab(SID, 'review');
- expect(isGhostTabPinned('review')).toBe(false);
- });
-
- it('closeTab 关闭钉住中的插件页签 → 取消钉住(条目清除)', async () => {
- const tab = await store.addOrFocusSingletonTab(SID, 'ghost:cindy-art');
- expect(isGhostTabPinned('cindy-art')).toBe(true);
- await store.closeTab(SID, tab.id);
- expect(isGhostTabPinned('cindy-art')).toBe(false);
- expect(store.getBucket(SID).tabs).toEqual([]);
- });
-
- it('closeTab IPC 失败回滚 → 页签还在,钉住状态原样保留', async () => {
- const tab = await store.addOrFocusSingletonTab(SID, 'ghost:cindy-art');
- ipc.close.mockRejectedValueOnce(new Error('db down'));
- await expect(store.closeTab(SID, tab.id)).rejects.toThrow('db down');
- expect(store.getBucket(SID).tabs.map((t) => t.id)).toEqual([tab.id]);
- expect(isGhostTabPinned('cindy-art')).toBe(true);
- });
-});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/pinnedGhostTabs.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/pinnedGhostTabs.test.ts
deleted file mode 100644
index 85e1aeb75a..0000000000
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/pinnedGhostTabs.test.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-// @vitest-environment jsdom
-/**
- * pinnedGhostTabs —— 图钉偏好三态语义与粘性焦点的单测。
- * localStorage 走 jsdom 内置实现;模块级单例用 _resetGhostTabPinsForTest 隔离用例。
- */
-import { beforeEach, describe, expect, it } from 'vitest';
-
-import {
- _resetGhostTabPinsForTest,
- AUTO_PINNED_GHOST_TAB_STATE,
- clearGhostTabPinOnClose,
- getLastFocusedPinnedGhostKind,
- ghostIdOfTabKind,
- isAutoPinnedGhostTabState,
- isGhostTabPinned,
- listPinnedGhostIds,
- markGhostTabOpened,
- pruneGhostTabPins,
- setGhostTabPinned,
- setLastFocusedPinnedGhostKind,
- subscribeGhostTabPins,
-} from '../pinnedGhostTabs';
-
-describe('pinnedGhostTabs', () => {
- beforeEach(() => {
- _resetGhostTabPinsForTest();
- });
-
- it('未打开过的插件不算钉住(无条目 = 出厂态)', () => {
- expect(isGhostTabPinned('cindy-art')).toBe(false);
- expect(listPinnedGhostIds()).toEqual([]);
- });
-
- it('markGhostTabOpened:首次打开默认钉住', () => {
- markGhostTabOpened('cindy-art');
- expect(isGhostTabPinned('cindy-art')).toBe(true);
- expect(listPinnedGhostIds()).toEqual(['cindy-art']);
- });
-
- it('markGhostTabOpened 不覆盖用户显式的 pinned:false', () => {
- setGhostTabPinned('cindy-art', false);
- markGhostTabOpened('cindy-art');
- expect(isGhostTabPinned('cindy-art')).toBe(false);
- });
-
- it('钉住偏好持久化到 localStorage,新模块实例可回读', () => {
- markGhostTabOpened('cindy-art');
- const raw = localStorage.getItem('rightSidebar.ghostTabPins');
- expect(raw).toBeTruthy();
- expect(JSON.parse(raw as string)['cindy-art'].pinned).toBe(true);
- });
-
- it('clearGhostTabPinOnClose:只清 pinned:true(回到出厂态),保留 pinned:false', () => {
- markGhostTabOpened('cindy-art');
- clearGhostTabPinOnClose('cindy-art');
- expect(isGhostTabPinned('cindy-art')).toBe(false);
- // 出厂态:再次打开重新默认钉住
- markGhostTabOpened('cindy-art');
- expect(isGhostTabPinned('cindy-art')).toBe(true);
-
- setGhostTabPinned('cindy-mermaid', false);
- clearGhostTabPinOnClose('cindy-mermaid');
- // 显式取消钉住的条目不被关闭动作抹掉:再次打开仍不钉住
- markGhostTabOpened('cindy-mermaid');
- expect(isGhostTabPinned('cindy-mermaid')).toBe(false);
- });
-
- it('pruneGhostTabPins:被卸载的插件条目清除,在装的保留', () => {
- markGhostTabOpened('cindy-art');
- setGhostTabPinned('cindy-mermaid', false);
- pruneGhostTabPins(new Set(['cindy-art']));
- expect(listPinnedGhostIds()).toEqual(['cindy-art']);
- // mermaid 的 override 已被清:重新打开回到默认钉住
- markGhostTabOpened('cindy-mermaid');
- expect(isGhostTabPinned('cindy-mermaid')).toBe(true);
- });
-
- it('订阅者在任何写入时收到通知', () => {
- let calls = 0;
- const off = subscribeGhostTabPins(() => {
- calls += 1;
- });
- markGhostTabOpened('cindy-art');
- setGhostTabPinned('cindy-art', false);
- off();
- setGhostTabPinned('cindy-art', true);
- expect(calls).toBe(2);
- });
-
- it('粘性焦点:只有钉住中的面板 kind 会被记住,其它一律清空', () => {
- markGhostTabOpened('cindy-art');
- setLastFocusedPinnedGhostKind('ghost:cindy-art');
- expect(getLastFocusedPinnedGhostKind()).toBe('ghost:cindy-art');
- // 聚焦非插件页签 → 清
- setLastFocusedPinnedGhostKind('file-browser');
- expect(getLastFocusedPinnedGhostKind()).toBeNull();
- // 聚焦未钉住的插件页签 → 也清
- setLastFocusedPinnedGhostKind('ghost:cindy-art');
- setGhostTabPinned('cindy-art', false);
- // 取消钉住的瞬间粘性焦点同步失效
- expect(getLastFocusedPinnedGhostKind()).toBeNull();
- });
-
- it('取消钉住 / 关闭清条目时,指向该插件的粘性焦点跟着失效', () => {
- markGhostTabOpened('cindy-art');
- setLastFocusedPinnedGhostKind('ghost:cindy-art');
- clearGhostTabPinOnClose('cindy-art');
- expect(getLastFocusedPinnedGhostKind()).toBeNull();
- });
-
- it('ghostIdOfTabKind:只认 ghost: 前缀', () => {
- expect(ghostIdOfTabKind('ghost:cindy-art')).toBe('cindy-art');
- expect(ghostIdOfTabKind('file-browser')).toBeNull();
- expect(ghostIdOfTabKind('ghost:')).toBeNull();
- });
-
- it('autoPinned 标记判定', () => {
- expect(isAutoPinnedGhostTabState(AUTO_PINNED_GHOST_TAB_STATE)).toBe(true);
- expect(isAutoPinnedGhostTabState(null)).toBe(false);
- expect(isAutoPinnedGhostTabState({ autoPinned: false })).toBe(false);
- expect(isAutoPinnedGhostTabState('autoPinned')).toBe(false);
- });
-});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/pinnedGhostTabs.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/pinnedGhostTabs.ts
deleted file mode 100644
index 81820e2d73..0000000000
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/pinnedGhostTabs.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * pinnedGhostTabs —— 插件面板页签的「图钉」偏好(全局,跨会话)。
- *
- * 语义(三态,只持久化用户触碰过的插件,未触碰 = 无条目):
- * - 无条目:从未打开过(或钉住关闭后回到出厂态)。打开面板页签时默认钉住
- * (markGhostTabOpened 写入 pinned:true)。
- * - pinned:true:钉住 —— RightSidebarShell 在每个会话自动补挂该面板页签,
- * 面板 webview 走常驻池跨会话保活。
- * - pinned:false:用户显式取消钉住 —— 页签回到"仅当前会话"语义,后续再
- * 打开也不自动回到钉住(尊重显式 override,直到用户重新钉住)。
- * - 关闭一个**钉住中**的页签 = 取消钉住并关闭(否则自动补挂会立刻加回来,
- * 页签"关不掉");清的是 pinned:true 条目本身(回到出厂态,下次打开重新
- * 默认钉住)。pinned:false 条目不在关闭路径清除,保留用户的显式选择。
- *
- * 存储:localStorage 单 key + 模块级单一真源(useSyncExternalStore 订阅)。
- * 页签 pill / Shell / 独立子窗口宿主都读同一份;只存 override 不存全量默认,
- * 遵循 docs/dev-rules/configuration-and-overrides.md §2(恢复默认 = 删条目)。
- *
- * 粘性焦点(lastFocusedPinnedKind)是纯运行时状态,不落盘:记录"用户正看着
- * 哪个钉住面板",切换会话时 Shell 据此把同一面板带到前台,这正是图钉的核心
- * 体验(面板视图不随会话切换消失)。
- */
-
-import { useSyncExternalStore } from 'react';
-
-import { createLogger } from '@/lib/logger';
-import { GHOST_PANEL_KIND_PREFIX } from '../../../../shared/ghost';
-import type { TabKindId } from '../types';
-
-const log = createLogger('rightSidebar.pinnedGhostTabs');
-
-const STORAGE_KEY = 'rightSidebar.ghostTabPins';
-
-interface StoredPinEntry {
- pinned: boolean;
- /** ISO 8601 —— 最近一次写入时间,仅供人工排查,逻辑不消费。 */
- updatedAt: string;
-}
-
-type Stored = Record<string, StoredPinEntry>;
-
-let cache: Stored | null = null;
-let version = 0;
-const listeners = new Set<() => void>();
-/** 运行时粘性焦点:用户最近聚焦的钉住面板页签 kind(不持久化)。 */
-let lastFocusedPinnedKind: TabKindId | null = null;
-
-/**
- * 自动补挂页签的 state 标记。带此标记的页签是 Shell 替用户加的 —— 取消钉住后
- * 由 Shell 清扫关闭;用户**手动**打开的页签不带标记,取消钉住后按原语义留在
- * 它所在的会话里。
- */
-export const AUTO_PINNED_GHOST_TAB_STATE: Readonly<{ autoPinned: true }> = { autoPinned: true };
-
-export function isAutoPinnedGhostTabState(state: unknown): boolean {
- return (
- typeof state === 'object' &&
- state !== null &&
- (state as { autoPinned?: unknown }).autoPinned === true
- );
-}
-
-/** `ghost:<id>` → `<id>`;不是插件面板页签 kind 返回 null。 */
-export function ghostIdOfTabKind(kind: string): string | null {
- if (!kind.startsWith(GHOST_PANEL_KIND_PREFIX)) return null;
- const id = kind.slice(GHOST_PANEL_KIND_PREFIX.length);
- return id.length > 0 ? id : null;
-}
-
-function loadFromStorage(): Stored {
- try {
- if (typeof localStorage === 'undefined') return {};
- const raw = localStorage.getItem(STORAGE_KEY);
- if (!raw) return {};
- const parsed = JSON.parse(raw) as unknown;
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
- const out: Stored = {};
- for (const [id, v] of Object.entries(parsed as Record<string, unknown>)) {
- if (!v || typeof v !== 'object') continue;
- const entry = v as Partial<StoredPinEntry>;
- if (typeof entry.pinned !== 'boolean') continue;
- out[id] = {
- pinned: entry.pinned,
- updatedAt: typeof entry.updatedAt === 'string' ? entry.updatedAt : '',
- };
- }
- return out;
- } catch (err) {
- // JSON / localStorage 异常 → 静默回退空表(等价于全部出厂默认)。
- log.warn('failed to load stored pins:', err);
- return {};
- }
-}
-
-function writeToStorage(next: Stored): void {
- try {
- if (typeof localStorage === 'undefined') return;
- localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
- } catch (err) {
- // quota / 隐私模式等 → 本次运行内仍生效,重启后回默认。
- log.warn('failed to write stored pins:', err);
- }
-}
-
-function getStored(): Stored {
- if (cache === null) cache = loadFromStorage();
- return cache;
-}
-
-function commit(next: Stored): void {
- cache = next;
- version += 1;
- writeToStorage(next);
- // 粘性焦点跟随钉住状态:焦点面板不再钉住时立即失效,避免会话切换时
- // Shell 把一个已取消钉住的面板强行带到前台。
- if (lastFocusedPinnedKind) {
- const gid = ghostIdOfTabKind(lastFocusedPinnedKind);
- if (!gid || next[gid]?.pinned !== true) lastFocusedPinnedKind = null;
- }
- for (const l of listeners) l();
-}
-
-/** 该插件面板当前是否钉住(无条目 = 未打开过,不算钉住)。 */
-export function isGhostTabPinned(ghostId: string): boolean {
- return getStored()[ghostId]?.pinned === true;
-}
-
-/** 当前所有钉住中的插件 id。Shell 自动补挂用。 */
-export function listPinnedGhostIds(): string[] {
- return Object.entries(getStored())
- .filter(([, entry]) => entry.pinned)
- .map(([id]) => id);
-}
-
-/**
- * 用户显式打开插件面板页签时调(addOrFocusSingletonTab 汇聚点):
- * 无条目 → 按默认钉住写入;已有条目(true / false 都是)→ 保持不动。
- */
-export function markGhostTabOpened(ghostId: string): void {
- const stored = getStored();
- if (stored[ghostId]) return;
- commit({ ...stored, [ghostId]: { pinned: true, updatedAt: new Date().toISOString() } });
-}
-
-/** 显式钉住 / 取消钉住(pill 图钉按钮、右键菜单)。 */
-export function setGhostTabPinned(ghostId: string, pinned: boolean): void {
- const stored = getStored();
- if (stored[ghostId]?.pinned === pinned) return;
- commit({ ...stored, [ghostId]: { pinned, updatedAt: new Date().toISOString() } });
-}
-
-/**
- * 关闭钉住页签的收尾:清掉 pinned:true 条目(回到出厂态)。
- * pinned:false 条目保留 —— 那是用户的显式"别钉住",关闭动作不该抹掉它。
- */
-export function clearGhostTabPinOnClose(ghostId: string): void {
- const stored = getStored();
- if (stored[ghostId]?.pinned !== true) return;
- const next = { ...stored };
- delete next[ghostId];
- commit(next);
-}
-
-/** 已装清单同步点调用:插件被卸载后,遗留的钉住条目一并清除。 */
-export function pruneGhostTabPins(installedIds: ReadonlySet<string>): void {
- const stored = getStored();
- let changed = false;
- const next: Stored = {};
- for (const [id, entry] of Object.entries(stored)) {
- if (installedIds.has(id)) next[id] = entry;
- else changed = true;
- }
- if (changed) commit(next);
-}
-
-/**
- * 用户显式聚焦某 tab 时调(点 pill / 新开 / 快捷键轮换)。传入被聚焦 tab 的
- * kind:是钉住中的面板页签 → 记为粘性焦点;其它任何 tab → 清空(用户已经
- * 在看别的东西,切会话不该再把面板顶回前台)。**不要**在"会话切换导致的
- * 被动 active 变化"里调 —— 那会在粘性激活生效前把它误清掉。
- */
-export function setLastFocusedPinnedGhostKind(kind: TabKindId | null): void {
- if (kind !== null) {
- const gid = ghostIdOfTabKind(kind);
- if (!gid || !isGhostTabPinned(gid)) {
- lastFocusedPinnedKind = null;
- return;
- }
- }
- lastFocusedPinnedKind = kind;
-}
-
-export function getLastFocusedPinnedGhostKind(): TabKindId | null {
- return lastFocusedPinnedKind;
-}
-
-export function subscribeGhostTabPins(listener: () => void): () => void {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
-}
-
-export function getGhostTabPinsVersion(): number {
- return version;
-}
-
-/** 组件侧订阅:pin 状态变化 → 版本号变化 → 重渲染。 */
-export function useGhostTabPinsVersion(): number {
- return useSyncExternalStore(subscribeGhostTabPins, getGhostTabPinsVersion);
-}
-
-/** 仅测试用:清空模块状态与持久层。 */
-export function _resetGhostTabPinsForTest(): void {
- cache = {};
- version += 1;
- lastFocusedPinnedKind = null;
- try {
- if (typeof localStorage !== 'undefined') localStorage.removeItem(STORAGE_KEY);
- } catch {
- // 测试环境无 localStorage 时忽略
- }
- for (const l of listeners) l();
-}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/registry.ts b/apps/desktop/src/renderer/features/right-sidebar/registry.ts
index 621b2440b5..2e375143ed 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/registry.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/registry.ts
@@ -80,7 +80,7 @@ export function registerTabKind(plugin: TabKindPlugin, hot?: HotContextLike | nu
}
/**
- * 注销 plugin —— 插件页签的意识停用/卸下时由 ghostTabPlugins 调用,幂等;
+ * 注销 plugin —— 动态注册的 kind 退场时调用,幂等;
* 内置 plugin 不注销。已打开的同 kind tab 落回 Shell 的 PlaceholderBody,
* tab 数据保留,重新注册即原位复活(对齐顶层面板「未安装隐藏、重装复活」语义)。
*/
@@ -115,17 +115,6 @@ export function listTabKindMenuMetas(): TabKindMenuMeta[] {
.sort((a, b) => a.order - b.order);
}
-/**
- * 启用中的插件页签 menu 项(kind 前缀 `ghost:`),「+」菜单动态分组与空态
- * 「1 个直显 / 多个折叠」共用。按 labelText(插件名)稳定排序。
- */
-export function listGhostTabMenuMetas(): TabKindMenuMeta[] {
- return Array.from(REGISTRY.values())
- .map((p) => p.menu)
- .filter((menu) => menu.kind.startsWith('ghost:') && !menu.hiddenFromMenu)
- .sort((a, b) => (a.labelText ?? a.kind).localeCompare(b.labelText ?? b.kind));
-}
-
/** 仅测试 / dev hot-reload 用:清空 registry。production 不应调用。 */
export function _resetTabKindRegistry(): void {
REGISTRY.clear();
diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.ts
index 48c544050b..c0b46db0e9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts
@@ -21,11 +21,6 @@ import { extractIpcError } from '@/utils/ipcError';
import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
import { getTabKind } from './registry';
import { unmarkPopupSpawnedTab } from './lib/popupTabs';
-import {
- clearGhostTabPinOnClose,
- ghostIdOfTabKind,
- markGhostTabOpened,
-} from './lib/pinnedGhostTabs';
import type { TabKindId, TabState } from './types';
const log = createLogger('rightSidebar.store');
@@ -588,11 +583,6 @@ export async function addOrFocusSingletonTab(
kind: TabKindId,
initialState: unknown = null,
): Promise<TabState> {
- // 用户显式打开插件面板的唯一汇聚点(「+」菜单 / EmptyState / agent
- // open-ghost-tab 都走这里):首次打开按默认写入钉住条目(见 pinnedGhostTabs
- // 的三态语义);已有显式 override(含 pinned:false)保持不动。
- const openedGhostId = ghostIdOfTabKind(kind);
- if (openedGhostId) markGhostTabOpened(openedGhostId);
const bucket = getBucket(sessionId);
const existing = bucket.tabs.find((t) => t.kind === kind);
if (existing) {
@@ -818,15 +808,7 @@ export async function closeTab(
throw err;
}
});
- // 关闭钉住中的插件面板页签 = 取消钉住并关闭:不清的话 Shell 的自动补挂会把
- // 它立刻加回来,页签"关不掉"。挂在变更段成功之后 —— close 失败回滚时 tab
- // 还在,钉住状态必须原样保留。所有关闭入口(pill X / 右键菜单 / ⌘W /
- // closeAllTabs / agent tab-op)都汇聚到本函数,语义不会因入口不同而漂移。
- const closedGhostId = ghostIdOfTabKind(tab.kind);
- if (!closedGhostId) return mutation;
- return mutation.then(() => {
- clearGhostTabPinOnClose(closedGhostId);
- });
+ return mutation;
}
/** 关闭某个 session bucket 的全部 tab,逐个走 closeTab 以触发 plugin cleanup。 */
diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.ts
index 8af1684d48..622e4faac2 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts
@@ -17,7 +17,8 @@ import type { TabCloseInterceptor } from './store';
* - `file-browser` / `web-browser`:Phase 3 / Phase 5 注册真实 plugin。
* - `terminal` / `review`:占位扩展点,Phase 1 在「+」dropdown 里灰显;未来注册新 plugin 时只需在此 union 添加值 + 调 `registerTabKind`,壳子不动。
* - `ghost:<id>`:panel.position:'tab' 的插件面板页签,由
- * renderer/cindy-brain/ghostTabPlugins.tsx 随已装清单动态注册/注销
+ * 历史形态(面板收束前)由页签注册表动态注册;2026-08 起页签面板改由
+ * 插件页承载,该前缀仅存在于旧会话持久化数据,Shell 发现即静默关闭
* (字符串与顶层布局的 ghostPanelKind 同形,DB kind 列无枚举约束可直存)。
*/
export type BuiltinTabKindId =
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 100ef8c269..11efb2f6ff 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2873,12 +2873,15 @@
"clearSearch": "Clear Plugin Search",
"addPlugin": "Add plugin",
"addPluginAria": "Plugin add options",
+ "installedSection": "Installed",
+ "recommendedSection": "Recommended",
+ "updatesAvailable": "{{count}} plugin updates available",
+ "updateAll": "Update all",
+ "ignoreRound": "Ignore this round",
+ "updateTo": "Update to v{{version}}",
+ "updateAria": "Update {{name}} to v{{version}}",
"createWithCindy": "Create with Cindy",
"createPrompt": "I want to create a Cindy plugin. First call ghost_forge_guide to get the handbook's table of contents, read chapter 0 (design alignment) first, then read the relevant chapters via the section parameter (at minimum the sandbox red-lines and packaging chapters) before writing any code; do not start implementing yet. Begin by asking questions: prefer option-based question cards, one key decision per card with your recommended choice marked, and proactively surface design options I may not know about — such as the UI form (docked panel, right-sidebar tab, chat card, or no UI), a $ command word, launch mode, network access, and whether a settings page is needed. Step by step, confirm the problem to solve, target users, interaction flow, required tools and connections, permission boundaries, and acceptance criteria. After I confirm the design, implement and validate it according to the specification, then call ghost_forge_pack to package and install the plugin.",
- "installedTitle": "Installed Plugins",
- "installedExpand": "Show {{count}} more installed plugins",
- "installedCollapse": "Hide additional installed plugins",
- "allTitle": "All plugins",
"filterAll": "All",
"filtersAria": "Filter plugins by source",
"origin": {
@@ -2887,8 +2890,15 @@
"local": "Local"
},
"emptyFiltered": "No matching plugins",
- "useAction": "Use",
- "useAria": "Use {{name}}"
+ "useAria": "Use {{name}}",
+ "usePanelAction": "Use",
+ "chatAction": "Chat",
+ "chatAria": "Chat with {{name}}",
+ "manageAction": "Manage",
+ "manageAria": "Manage {{name}}",
+ "agentInvoked": "Invoked by Agent",
+ "upToDate": "Up to date",
+ "installAria": "Install {{name}}"
},
"market": {
"scopeAria": "Filter plugin sources",
@@ -2902,9 +2912,6 @@
"install": "Install",
"details": "Details",
"update": "Update from market",
- "updateAvailable": "Update available",
- "updateAction": "Update",
- "updateAria": "Update {{name}}",
"updateTo": "Update to v{{version}}",
"installed": "Installed",
"conflict": "Plugin ID conflict",
@@ -3128,6 +3135,7 @@
"openLocation": "Open install location",
"panelDocked": "Docked · min width {{min}}px",
"panelNotDocked": "Not docked (no layout record yet)",
+ "panelPageHosted": "Opens from the Plugin page · closes when you leave",
"panelNone": "This plugin has no panel",
"customSlotTitle": "Plugin custom settings area",
"dangerTitle": "Uninstall plugin",
@@ -3167,6 +3175,9 @@
"descriptionExpand": "Show more",
"descriptionCollapse": "Show less",
"useAction": "Use Plugin",
+ "chatAction": "Chat",
+ "enabledLabel": "Enabled",
+ "disabledLabel": "Disabled",
"useDisabled": "Enable this Plugin before using it",
"moreActions": "More Plugin Actions",
"updateFromFile": "Update from .cindy File…",
@@ -3216,6 +3227,27 @@
"workspace": {
"dialogTitle": "Choose a project folder",
"dialogMessage": "Plugin “{{name}}” is asking you to choose a project folder to create a session in the sidebar"
+ },
+ "panelHost": {
+ "close": "Close panel"
+ },
+ "updateAll": {
+ "title": "Update all · {{count}} plugins",
+ "description": "Updates without permission changes finish automatically; permission expansions need your per-item approval.",
+ "versionRange": "v{{from}} → v{{to}}",
+ "permissionChanged": "Permissions changed",
+ "reviewDiff": "Review & confirm",
+ "collapseDiff": "Collapse",
+ "approve": "Approve & update",
+ "skip": "Skip",
+ "statusPending": "Queued",
+ "statusInstalling": "Updating…",
+ "statusDone": "Updated",
+ "statusSkipped": "Skipped",
+ "statusFailed": "Update failed",
+ "background": "Continue in background",
+ "doneAction": "Done",
+ "doneToast": "Batch update finished: {{done}} updated, {{rest}} not completed"
}
},
"mcp": {
@@ -3885,13 +3917,10 @@
"addAria": "Add tab",
"addFailed": "Failed to add tab",
"tabCloseAria": "Close tab",
- "pinAria": "Pin — keep in all sessions",
- "unpinAria": "Unpin — keep only in this session",
"menu": {
"addLabel": "Add tab",
"comingSoon": "Coming soon",
- "alreadyOpen": "Open",
- "pluginGroup": "Plugins"
+ "alreadyOpen": "Open"
},
"kinds": {
"fileBrowser": "File browser",
@@ -3912,9 +3941,7 @@
"contextMenu": {
"close": "Close",
"closeOthers": "Close others",
- "closeAll": "Close all",
- "pin": "Pin",
- "unpin": "Unpin"
+ "closeAll": "Close all"
},
"empty": {
"eyebrow": "Right Sidebar",
@@ -3930,9 +3957,6 @@
"browserSub": "Browser",
"openTerminal": "Open terminal",
"terminalSub": "Terminal",
- "pluginSub": "Plugin",
- "pluginGroup": "Plugin panels",
- "pluginGroupSub": "{{count}} plugins",
"addMoreHint": "Use the + button at the top to choose more panel types"
},
"placeholderHint": "{{kind}} — content coming in a later phase"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 7896b247b7..4dec965f17 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2872,12 +2872,15 @@
"clearSearch": "プラグイン検索をクリア",
"addPlugin": "プラグインを追加",
"addPluginAria": "プラグイン追加オプション",
+ "installedSection": "インストール済み",
+ "recommendedSection": "おすすめ",
+ "updatesAvailable": "{{count}} 件のプラグイン更新があります",
+ "updateAll": "すべて更新",
+ "ignoreRound": "今回は無視",
+ "updateTo": "v{{version}} に更新",
+ "updateAria": "{{name}} を v{{version}} に更新",
"createWithCindy": "Cindy で作成",
"createPrompt": "Cindy プラグインを作成したいです。まず ghost_forge_guide を呼び出してハンドブックの目次を取得し、最初に第 0 章「設計のすり合わせ」を読み、その後 section パラメータで関連する章(少なくともサンドボックスの禁止事項とパッケージ化の章)を読み込んでから着手してください。すぐに実装を始めないでください。質問から始めてください:選択肢付きの質問カードを優先し、1 枚のカードでは 1 つの重要な判断に絞り、あなたのおすすめを明示した上で、私が気づきにくい設計オプション(UI 形態:ドッキングパネル / 右サイドバーのタブ / チャットカード / UI なし、$ 呼び出しコマンド、起動モード、ネットワーク接続の要否、設定ページの要否など)を積極的に提示して選ばせてください。解決する課題、対象ユーザー、操作フロー、必要なツールと接続、権限の境界、受け入れ条件を段階的に確認してください。設計を確認した後、仕様に沿って実装と検証を行い、最後に ghost_forge_pack を呼び出してプラグインをパッケージ化し、インストールしてください。",
- "installedTitle": "インストール済みプラグイン",
- "installedExpand": "インストール済みプラグインをさらに {{count}} 件表示",
- "installedCollapse": "追加のインストール済みプラグインを隠す",
- "allTitle": "すべてのプラグイン",
"filterAll": "すべて",
"filtersAria": "提供元でプラグインを絞り込む",
"origin": {
@@ -2886,8 +2889,15 @@
"local": "ローカル"
},
"emptyFiltered": "一致するプラグインがありません",
- "useAction": "使用",
- "useAria": "{{name}} を使用"
+ "useAria": "{{name}} を使用",
+ "usePanelAction": "使う",
+ "chatAction": "会話",
+ "chatAria": "{{name}} と会話",
+ "manageAction": "管理",
+ "manageAria": "{{name}} を管理",
+ "agentInvoked": "Agent が自動で呼び出し",
+ "upToDate": "最新です",
+ "installAria": "{{name}} をインストール"
},
"market": {
"scopeAria": "プラグインの提供元を絞り込む",
@@ -2901,9 +2911,6 @@
"install": "インストール",
"details": "詳細",
"update": "マーケットから更新",
- "updateAvailable": "更新あり",
- "updateAction": "更新",
- "updateAria": "{{name}}を更新",
"updateTo": "v{{version}} に更新",
"installed": "インストール済み",
"conflict": "プラグイン ID の競合",
@@ -3127,6 +3134,7 @@
"openLocation": "インストール場所を開く",
"panelDocked": "ドッキング済み · 最小幅 {{min}}px",
"panelNotDocked": "未ドッキング(レイアウトに位置記録なし)",
+ "panelPageHosted": "プラグインページから開く · 離れると自動的に閉じます",
"panelNone": "このプラグインにパネルはありません",
"customSlotTitle": "プラグインのカスタム設定エリア",
"dangerTitle": "プラグインをアンインストール",
@@ -3166,6 +3174,9 @@
"descriptionExpand": "もっと見る",
"descriptionCollapse": "折りたたむ",
"useAction": "Plugin を使用",
+ "chatAction": "会話",
+ "enabledLabel": "有効",
+ "disabledLabel": "無効",
"useDisabled": "使用する前に Plugin を有効にしてください",
"moreActions": "その他の Plugin 操作",
"updateFromFile": ".cindy ファイルから更新…",
@@ -3215,6 +3226,27 @@
"workspace": {
"dialogTitle": "プロジェクトフォルダを選択",
"dialogMessage": "プラグイン「{{name}}」がサイドバーにセッションを作成するため、プロジェクトフォルダの選択を求めています"
+ },
+ "panelHost": {
+ "close": "パネルを閉じる"
+ },
+ "updateAll": {
+ "title": "すべて更新 · {{count}} 件",
+ "description": "権限に変更がない更新は自動で完了します。権限が拡張される更新は項目ごとに確認が必要です。",
+ "versionRange": "v{{from}} → v{{to}}",
+ "permissionChanged": "権限に変更あり",
+ "reviewDiff": "確認する",
+ "collapseDiff": "閉じる",
+ "approve": "同意して更新",
+ "skip": "スキップ",
+ "statusPending": "待機中",
+ "statusInstalling": "更新中…",
+ "statusDone": "更新済み",
+ "statusSkipped": "スキップ済み",
+ "statusFailed": "更新に失敗",
+ "background": "バックグラウンドで続行",
+ "doneAction": "完了",
+ "doneToast": "一括更新が完了:{{done}} 件更新、{{rest}} 件未完了"
}
},
"mcp": {
@@ -3883,13 +3915,10 @@
"addAria": "タブを追加",
"addFailed": "タブを追加できませんでした",
"tabCloseAria": "タブを閉じる",
- "pinAria": "ピン留め — すべてのセッションで保持",
- "unpinAria": "ピン留め解除 — このセッションのみ保持",
"menu": {
"addLabel": "タブを追加",
"comingSoon": "近日対応",
- "alreadyOpen": "開いています",
- "pluginGroup": "プラグイン"
+ "alreadyOpen": "開いています"
},
"kinds": {
"fileBrowser": "ファイルブラウザ",
@@ -3910,9 +3939,7 @@
"contextMenu": {
"close": "閉じる",
"closeOthers": "他のタブを閉じる",
- "closeAll": "すべて閉じる",
- "pin": "ピン留め",
- "unpin": "ピン留め解除"
+ "closeAll": "すべて閉じる"
},
"empty": {
"eyebrow": "右サイドバー",
@@ -3928,9 +3955,6 @@
"browserSub": "Browser",
"openTerminal": "ターミナルを開く",
"terminalSub": "Terminal",
- "pluginSub": "Plugin",
- "pluginGroup": "プラグインパネル",
- "pluginGroupSub": "{{count}} 個のプラグイン",
"addMoreHint": "上部の + ボタンからほかのパネルタイプを選択できます"
},
"placeholderHint": "{{kind}} — コンテンツは後続フェーズで追加されます"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 7ae1b63f49..9828eef3e3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2872,12 +2872,15 @@
"clearSearch": "플러그인 검색 지우기",
"addPlugin": "플러그인 추가",
"addPluginAria": "플러그인 추가 옵션",
+ "installedSection": "설치됨",
+ "recommendedSection": "추천",
+ "updatesAvailable": "플러그인 업데이트 {{count}}개 사용 가능",
+ "updateAll": "모두 업데이트",
+ "ignoreRound": "이번은 무시",
+ "updateTo": "v{{version}}(으)로 업데이트",
+ "updateAria": "{{name}}을(를) v{{version}}(으)로 업데이트",
"createWithCindy": "Cindy로 만들기",
"createPrompt": "Cindy 플러그인을 만들고 싶습니다. 먼저 ghost_forge_guide를 호출해 핸드북 목차를 받고, 우선 0장 「설계 맞추기」를 읽은 뒤 section 매개변수로 관련 장(최소한 샌드박스 금지선과 패키징 장)을 읽고 나서 작업을 시작하세요. 바로 구현을 시작하지 마세요. 질문부터 시작하세요: 선택지가 있는 질문 카드를 우선 사용하고, 카드 한 장에는 핵심 결정 하나만 담아 추천안을 표시하며, 제가 모를 수 있는 설계 옵션(UI 형태: 도킹 패널 / 오른쪽 사이드바 탭 / 채팅 카드 / UI 없음, $ 호출 명령어, 시작 모드, 네트워크 사용 여부, 설정 페이지 필요 여부 등)을 먼저 보여 주고 고르게 해 주세요. 해결할 문제, 대상 사용자, 상호작용 흐름, 필요한 도구와 연결, 권한 경계, 완료 기준을 단계적으로 확인해 주세요. 설계를 확인한 뒤 규격에 따라 구현하고 검증한 다음, 마지막으로 ghost_forge_pack을 호출해 플러그인을 패키징하고 설치해 주세요.",
- "installedTitle": "설치된 플러그인",
- "installedExpand": "설치된 플러그인 {{count}}개 더 보기",
- "installedCollapse": "추가 설치 플러그인 숨기기",
- "allTitle": "모든 플러그인",
"filterAll": "전체",
"filtersAria": "출처별 플러그인 필터",
"origin": {
@@ -2886,8 +2889,15 @@
"local": "로컬"
},
"emptyFiltered": "일치하는 플러그인이 없습니다",
- "useAction": "사용",
- "useAria": "{{name}} 사용"
+ "useAria": "{{name}} 사용",
+ "usePanelAction": "사용",
+ "chatAction": "대화",
+ "chatAria": "{{name}}과(와) 대화",
+ "manageAction": "관리",
+ "manageAria": "{{name}} 관리",
+ "agentInvoked": "Agent가 자동 호출",
+ "upToDate": "최신 상태",
+ "installAria": "{{name}} 설치"
},
"market": {
"scopeAria": "플러그인 출처 필터",
@@ -2901,9 +2911,6 @@
"install": "설치",
"details": "상세",
"update": "마켓에서 업데이트",
- "updateAvailable": "업데이트 가능",
- "updateAction": "업데이트",
- "updateAria": "{{name}} 업데이트",
"updateTo": "v{{version}}(으)로 업데이트",
"installed": "설치됨",
"conflict": "플러그인 ID 충돌",
@@ -3127,6 +3134,7 @@
"openLocation": "설치 위치 열기",
"panelDocked": "도킹됨 · 최소 너비 {{min}}px",
"panelNotDocked": "도킹되지 않음(레이아웃에 위치 기록 없음)",
+ "panelPageHosted": "플러그인 페이지에서 열림 · 벗어나면 자동으로 닫힘",
"panelNone": "이 플러그인에는 패널이 없습니다",
"customSlotTitle": "플러그인 사용자 정의 설정 영역",
"dangerTitle": "플러그인 제거",
@@ -3166,6 +3174,9 @@
"descriptionExpand": "더 보기",
"descriptionCollapse": "접기",
"useAction": "Plugin 사용",
+ "chatAction": "대화",
+ "enabledLabel": "사용 중",
+ "disabledLabel": "사용 안 함",
"useDisabled": "사용하기 전에 Plugin을 활성화하세요",
"moreActions": "Plugin 추가 작업",
"updateFromFile": ".cindy 파일에서 업데이트…",
@@ -3215,6 +3226,27 @@
"workspace": {
"dialogTitle": "프로젝트 폴더 선택",
"dialogMessage": "플러그인 \"{{name}}\"이(가) 사이드바에 세션을 만들기 위해 프로젝트 폴더 선택을 요청합니다"
+ },
+ "panelHost": {
+ "close": "패널 닫기"
+ },
+ "updateAll": {
+ "title": "모두 업데이트 · {{count}}개",
+ "description": "권한 변경이 없는 업데이트는 자동으로 완료됩니다. 권한이 확장되는 업데이트는 항목별 확인이 필요합니다.",
+ "versionRange": "v{{from}} → v{{to}}",
+ "permissionChanged": "권한 변경됨",
+ "reviewDiff": "확인",
+ "collapseDiff": "접기",
+ "approve": "동의 후 업데이트",
+ "skip": "건너뛰기",
+ "statusPending": "대기 중",
+ "statusInstalling": "업데이트 중…",
+ "statusDone": "업데이트됨",
+ "statusSkipped": "건너뜀",
+ "statusFailed": "업데이트 실패",
+ "background": "백그라운드에서 계속",
+ "doneAction": "완료",
+ "doneToast": "일괄 업데이트 완료: {{done}}개 업데이트, {{rest}}개 미완료"
}
},
"mcp": {
@@ -3883,13 +3915,10 @@
"addAria": "탭 추가",
"addFailed": "탭을 추가하지 못했습니다",
"tabCloseAria": "탭 닫기",
- "pinAria": "고정 — 모든 세션에서 유지",
- "unpinAria": "고정 해제 — 현재 세션에서만 유지",
"menu": {
"addLabel": "탭 추가",
"comingSoon": "지원 예정",
- "alreadyOpen": "열림",
- "pluginGroup": "플러그인"
+ "alreadyOpen": "열림"
},
"kinds": {
"fileBrowser": "파일 브라우저",
@@ -3910,9 +3939,7 @@
"contextMenu": {
"close": "닫기",
"closeOthers": "다른 탭 닫기",
- "closeAll": "모두 닫기",
- "pin": "고정",
- "unpin": "고정 해제"
+ "closeAll": "모두 닫기"
},
"empty": {
"eyebrow": "오른쪽 사이드바",
@@ -3928,9 +3955,6 @@
"browserSub": "Browser",
"openTerminal": "터미널 열기",
"terminalSub": "Terminal",
- "pluginSub": "Plugin",
- "pluginGroup": "플러그인 패널",
- "pluginGroupSub": "플러그인 {{count}}개",
"addMoreHint": "위쪽 + 버튼에서 다른 패널 유형을 선택할 수 있어요"
},
"placeholderHint": "{{kind}} — 콘텐츠는 이후 단계에서 추가됩니다"
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 64f23587b3..5897069da3 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2872,12 +2872,15 @@
"clearSearch": "清除插件搜索",
"addPlugin": "添加插件",
"addPluginAria": "插件添加选项",
+ "installedSection": "已安装",
+ "recommendedSection": "推荐",
+ "updatesAvailable": "{{count}} 个插件有可用更新",
+ "updateAll": "全部更新",
+ "ignoreRound": "忽略本轮",
+ "updateTo": "更新到 v{{version}}",
+ "updateAria": "将 {{name}} 更新到 v{{version}}",
"createWithCindy": "使用 Cindy 创建",
"createPrompt": "我要创建一个 Cindy 插件。请先调用 ghost_forge_guide 获取手册目录,先读第 0 章「设计对齐」,再用 section 参数读透相关章节(动手前至少读完沙箱红线与打包流程两章),不要直接开始实现。先从提问开始:优先用带选项的提问卡片,每张卡片聚焦一个关键决策并标注你的推荐项,把我可能不知道的设计选项主动摆出来让我选——比如界面形态(停靠面板、右侧栏页签、对话卡片还是无界面)、$ 点名词、启动模式、是否联网、是否需要设置页;并逐步确认插件要解决的问题、目标用户、交互流程、所需工具与连接、权限边界和验收标准。设计确认后,再按规范实现并自检;最后调用 ghost_forge_pack 打包并安装插件。",
- "installedTitle": "已安装的插件",
- "installedExpand": "展开另外 {{count}} 个已安装插件",
- "installedCollapse": "收起其他已安装插件",
- "allTitle": "全部插件",
"filterAll": "全部",
"filtersAria": "按来源筛选插件",
"origin": {
@@ -2886,8 +2889,15 @@
"local": "本地"
},
"emptyFiltered": "没有找到匹配的插件",
- "useAction": "使用",
- "useAria": "使用 {{name}}"
+ "useAria": "使用 {{name}}",
+ "usePanelAction": "使用",
+ "chatAction": "对话",
+ "chatAria": "与 {{name}} 对话",
+ "manageAction": "管理",
+ "manageAria": "管理 {{name}}",
+ "agentInvoked": "Agent 自动调用",
+ "upToDate": "已是最新",
+ "installAria": "安装 {{name}}"
},
"market": {
"scopeAria": "筛选插件来源",
@@ -2901,9 +2911,6 @@
"install": "安装",
"details": "详情",
"update": "从市场更新",
- "updateAvailable": "可更新",
- "updateAction": "更新",
- "updateAria": "更新 {{name}}",
"updateTo": "更新到 v{{version}}",
"installed": "已安装",
"conflict": "插件标识冲突",
@@ -3127,6 +3134,7 @@
"openLocation": "打开安装位置",
"panelDocked": "已停靠 · 最小宽 {{min}}px",
"panelNotDocked": "未停靠(布局中暂无位置记录)",
+ "panelPageHosted": "从插件页打开 · 离开插件页自动关闭",
"panelNone": "这个插件不含面板",
"customSlotTitle": "插件自定义设置区",
"dangerTitle": "卸载插件",
@@ -3166,6 +3174,9 @@
"descriptionExpand": "展开",
"descriptionCollapse": "收起",
"useAction": "使用",
+ "chatAction": "对话",
+ "enabledLabel": "已启用",
+ "disabledLabel": "已停用",
"useDisabled": "请先开启插件",
"moreActions": "更多插件操作",
"updateFromFile": "从 .cindy 文件更新…",
@@ -3215,6 +3226,27 @@
"workspace": {
"dialogTitle": "选择项目文件夹",
"dialogMessage": "插件「{{name}}」请求你选择一个项目文件夹,用于在侧边栏创建任务"
+ },
+ "panelHost": {
+ "close": "关闭面板"
+ },
+ "updateAll": {
+ "title": "全部更新 · {{count}} 个插件",
+ "description": "权限无变化的更新会自动完成;涉及权限变更的需要你逐项确认。",
+ "versionRange": "v{{from}} → v{{to}}",
+ "permissionChanged": "权限有变更",
+ "reviewDiff": "查看并确认",
+ "collapseDiff": "收起",
+ "approve": "同意并更新",
+ "skip": "跳过此项",
+ "statusPending": "排队中",
+ "statusInstalling": "更新中…",
+ "statusDone": "已更新",
+ "statusSkipped": "已跳过",
+ "statusFailed": "更新失败",
+ "background": "后台继续",
+ "doneAction": "完成",
+ "doneToast": "批量更新完成:{{done}} 个已更新,{{rest}} 个未完成"
}
},
"mcp": {
@@ -3883,13 +3915,10 @@
"addAria": "添加标签",
"addFailed": "添加标签失败",
"tabCloseAria": "关闭标签",
- "pinAria": "钉住,在所有任务中保留",
- "unpinAria": "取消钉住,仅保留在当前任务",
"menu": {
"addLabel": "添加标签",
"comingSoon": "即将支持",
- "alreadyOpen": "已打开",
- "pluginGroup": "插件"
+ "alreadyOpen": "已打开"
},
"kinds": {
"fileBrowser": "文件浏览器",
@@ -3910,9 +3939,7 @@
"contextMenu": {
"close": "关闭",
"closeOthers": "关闭其他",
- "closeAll": "关闭所有",
- "pin": "钉住",
- "unpin": "取消钉住"
+ "closeAll": "关闭所有"
},
"empty": {
"eyebrow": "右侧栏",
@@ -3928,9 +3955,6 @@
"browserSub": "Browser",
"openTerminal": "打开终端",
"terminalSub": "Terminal",
- "pluginSub": "插件",
- "pluginGroup": "插件面板",
- "pluginGroupSub": "{{count}} 个插件",
"addMoreHint": "可通过顶部 + 按钮选择更多面板类型"
},
"placeholderHint": "{{kind}} — 内容将在后续阶段加入"
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 13b31ba8b1..e45423a483 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -332,7 +332,7 @@ export type GhostLaunchMode = (typeof GHOST_LAUNCH_MODES)[number];
/**
* 面板显示形态(相对主聊天窗)。left = 顶层布局树停靠 pane(缺省);
* 'tab' = 不进布局树,作为右侧栏(right-tabs)里的每会话单例页签
- * (2026-07-24 定案,注册链路见 renderer/cindy-brain/ghostTabPlugins.tsx)。
+ * (2026-08 面板收束:页签面板由插件页 GhostPagePanelHost 独占承载)。
* right 已退役(2026-07-25 Lizi 定案:右侧是右侧边栏的地盘,插件面板默认
* 挤过去体验差;用户想放右边用拖拽换位即可)——旧包声明的 right 在校验期
* 归一化为 left(已装插件每次启动都重过校验,硬拒会把存量插件打没;兼容
@@ -1865,7 +1865,7 @@ export function ghostWebviewEntryPaths(manifest: GhostManifest): string[] {
* 装入带面板的意识后,把面板停进布局树(main 侧随 install 调用)。
* - 树上已有同 kind 的 pane(重装)→ 返回 null:不动树,位置记忆保留、原位复活;
* - 意识没声明面板 → null;
- * - position:'tab' → null:页签形态不进布局树,由右侧栏页签(ghostTabPlugins)承载;
+ * - position:'tab' → null:页签形态不进布局树,由插件页(GhostPagePanelHost)承载;
* - 否则停在聊天区左侧,宽度占比/最小宽取清单声明。
* 卸下时**不做**逆操作 —— 树数据保留正是"重装复活"的记忆来源(§6 规则 5)。
*/