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): 插件停靠面板最小化为可拖动浮动气泡(chat-head)

Lizi1718b8c0f231
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 7d6ad6a747..cc73bfc879 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -456,10 +456,13 @@ describe('FORGE_GUIDE', () => {
'panel.position',
'右侧栏页签',
// 2026-07-25 标准头系统按钮:主机画标题条,systemButtons 逐个关
- // (maximize 撑满 / detach 独立窗口);§2 样例与 §5 面板章节同步。
+ // (maximize 撑满 / detach 独立窗口 / minimize 气泡);§2 样例与 §5
+ // 面板章节同步。
'systemButtons',
'撑满内容区',
'在独立窗口中打开',
+ 'minimize',
+ '最小化为浮动气泡',
]) {
expect(FORGE_GUIDE).toContain(marker);
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index b72fb73b34..e3f2206ab7 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -719,8 +719,8 @@ my-ghost/
// top/bottom 暂未支持(排期中)
// panel.systemButtons(可选,仅停靠形态):标准头系统按钮开关,缺省全开、
// 声明 false 逐个关闭。当前一批:maximize(撑满内容区)、detach(在独立
- // 窗口中打开)。标题条本体恒由主机绘制、关不掉;未知键拒装;
- // position:"tab" 时声明本字段拒装
+ // 窗口中打开)、minimize(最小化为浮动气泡)。标题条本体恒由主机绘制、
+ // 关不掉;未知键拒装;position:"tab" 时声明本字段拒装
"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时必填——凭证收单界面,见 §4.7)
"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动
}
@@ -2232,13 +2232,15 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);
拒装。两种形态的面板代码完全一样(同一 panel.html,供片/主题/媒体规则不变),
只是宿主容器不同;页签形态请把界面做成自适应宽度;
- 停靠形态的**标题条(标准头)由主机绘制**:标题(\`panel.title\`)+ 一批系统
- 按钮(当前:「撑满内容区」与「在独立窗口中打开」——用户可把你的面板抽进
- 自己的 OS 窗口,关窗/合并即回停靠原位,面板代码零感知;后续新增的系统按钮
+ 按钮(当前:「撑满内容区」、「在独立窗口中打开」——用户可把你的面板抽进
+ 自己的 OS 窗口,关窗/合并即回停靠原位——以及「最小化为浮动气泡」——用户
+ 可把面板收成一枚可拖动的圆形气泡悬浮在主窗最上层,点击气泡即回停靠原位,
+ 气泡位置与最小化状态重启保留;三者面板代码全程零感知;后续新增的系统按钮
也长在这里)。你的 panel.html 只画标题条以下的部分,**不要自己再画一条
标题栏**。不想要某颗系统按钮时在身份卡声明
- \`"systemButtons": { "maximize": false, "detach": false }\` 逐个关闭(缺省
- 全开;标题条本体关不掉;未知键拒装;\`position:"tab"\` 没有标准头,声明本
- 字段拒装);
+ \`"systemButtons": { "maximize": false, "detach": false, "minimize": false }\`
+ 逐个关闭(缺省全开;标题条本体关不掉;未知键拒装;\`position:"tab"\` 没有
+ 标准头,声明本字段拒装);
- 与电子脑同源,用 \`BroadcastChannel('<自定名>')\` 通信(电子脑发,面板收);
- 取自己的媒体:\`cindy-ghost://<id>/media/<指纹><后缀>\`(主机查账验归属,别人的图 404);
- 重启回放:\`fetch('cindy-ghost://<id>/gallery')\` 返回本意识作品清单 \`[{src, caption}]\`;
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx
new file mode 100644
index 0000000000..fbffd92957
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx
@@ -0,0 +1,281 @@
+/**
+ * GhostPanelBubbleLayer —— 最小化插件面板的浮动气泡层(安卓聊天气泡式)。
+ *
+ * 挂在 MainLayout(GhostMediaLightboxHost 旁),portal 到 document.body:
+ * - 每个「已装 && 启用 && 停靠形态 && 已最小化 && 未抽离独立窗」的插件
+ * 一枚 48px 圆形气泡,z-[9900](在内容 chrome 之上、拖拽浮层 9998/9999
+ * 与弹窗 10000+ 之下);
+ * - 脸 = 插件图标(InstalledGhost.iconDataUrl,主窗拿不到 cindy-ghost://,
+ * data URL 直接 <img>;缺图标兜底 lucide Ghost);
+ * - 拖拽走 PanelDragController 的性能口径:热路径零 React,translate3d
+ * 直改 DOM;拖动期间挂 body.resizing-pane 让 webview 指针穿透;4px 阈值
+ * 区分点击与拖动(windowDrag.tsx 同款);
+ * - 动效时序(2026-07-25 Lizi 定案"两段都要有戏"):收起 → 面板宽度先
+ * 折叠到 0,等 300ms 圆圈渐显、幽灵再跳进来;点球展开 → 幽灵先跳走、
+ * 圆圈再渐隐,计时器到点(260ms)才真正 restore,面板宽度展开回停靠位
+ * (编排见 globals.css;面板侧提交时序在 ghostPanels.tsx,减弱动效自动停);
+ * - 拖后落点持久化,重启保留;没拖过的气泡从右下角向上堆(计算不落盘,
+ * 窗口缩放自动重排);渲染时 clamp 到视口,y 下限避开顶部 46px 拖动带。
+ */
+
+import { useEffect, useRef, useState, type ReactNode } from 'react';
+import { createPortal } from 'react-dom';
+import { Ghost } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { ghostPanelKind, type GhostManifest } from '../../shared/ghost';
+import {
+ restoreGhostPanel,
+ setGhostPanelBubblePosition,
+ useGhostPanelBubbleState,
+} from '../lib/ghostPanelBubbleState';
+import { isGhostPanelKindDetached, useGhostPanelWindowsState } from '../lib/ghostPanelWindowState';
+import { useInstalledGhosts } from './useInstalledGhosts';
+
+const BUBBLE_SIZE = 48;
+const EDGE_MARGIN = 12;
+const STACK_GAP = 8;
+const DRAG_THRESHOLD_PX = 4;
+/** 顶部 46px 是窗口拖动带(§6 规则 3),气泡不进去。 */
+const TOP_FLOOR = 46 + EDGE_MARGIN;
+/** 点球展开:幽灵跳走(160ms)+ 圆圈渐隐(120ms 延迟 + 140ms)的总时长,
+ * 到点才真正 restore(与 globals.css 的 exit 编排对齐)。 */
+const EXIT_MS = 260;
+
+/** 视口 clamp(渲染与落点共用;store 里不 clamp,换屏不破坏存值)。 */
+function clampToViewport(x: number, y: number): { x: number; y: number } {
+ const maxX = Math.max(EDGE_MARGIN, window.innerWidth - BUBBLE_SIZE - EDGE_MARGIN);
+ const maxY = Math.max(TOP_FLOOR, window.innerHeight - BUBBLE_SIZE - EDGE_MARGIN);
+ return {
+ x: Math.min(maxX, Math.max(EDGE_MARGIN, x)),
+ y: Math.min(maxY, Math.max(TOP_FLOOR, y)),
+ };
+}
+
+/** 没拖过的气泡默认位:右下角向上堆(defaultIndex 只数无存储位置的)。 */
+function defaultPosition(defaultIndex: number): { x: number; y: number } {
+ return {
+ x: window.innerWidth - BUBBLE_SIZE - EDGE_MARGIN,
+ y: window.innerHeight - BUBBLE_SIZE - EDGE_MARGIN - defaultIndex * (BUBBLE_SIZE + STACK_GAP),
+ };
+}
+
+interface BubbleProps {
+ manifest: GhostManifest;
+ iconDataUrl: string | undefined;
+ /** 渲染基准位(已 clamp)。 */
+ pos: { x: number; y: number };
+}
+
+function Bubble({ manifest, iconDataUrl, pos }: BubbleProps): ReactNode {
+ const { t } = useTranslation();
+ const elRef = useRef<HTMLButtonElement | null>(null);
+ const [imgBroken, setImgBroken] = useState(false);
+ /** 点击后进入"缩没退场"态:播 .ghost-bubble-exit,计时器到点才 restore。 */
+ const [exiting, setExiting] = useState(false);
+ const exitTimerRef = useRef(0);
+ // 拖拽全程 ref,热路径零 React(性能口径见文件头)。
+ const dragRef = useRef<{
+ pointerId: number;
+ startClientX: number;
+ startClientY: number;
+ baseX: number;
+ baseY: number;
+ dragging: boolean;
+ lastX: number;
+ lastY: number;
+ } | null>(null);
+ const draggedRef = useRef(false);
+
+ // 基准位变化(store 更新/默认位重排/窗口缩放)时回写 transform ——
+ // 非拖动期间 transform 完全由 React 渲染值决定。
+ useEffect(() => {
+ const el = elRef.current;
+ if (el && !dragRef.current?.dragging) {
+ el.style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0)`;
+ }
+ }, [pos.x, pos.y]);
+
+ // 卸载时清退场计时器(restore 本身是 store 调用,晚到也无害,但别留悬垂)。
+ useEffect(() => () => window.clearTimeout(exitTimerRef.current), []);
+
+ const endDragCleanup = () => {
+ document.body.classList.remove('resizing-pane');
+ document.body.style.userSelect = '';
+ };
+
+ const onPointerDown = (e: React.PointerEvent<HTMLButtonElement>) => {
+ if (e.button !== 0 || dragRef.current || exiting) return;
+ dragRef.current = {
+ pointerId: e.pointerId,
+ startClientX: e.clientX,
+ startClientY: e.clientY,
+ baseX: pos.x,
+ baseY: pos.y,
+ dragging: false,
+ lastX: pos.x,
+ lastY: pos.y,
+ };
+ // jsdom 没有 setPointerCapture,包一层照常走点击/拖动逻辑。
+ try {
+ elRef.current?.setPointerCapture(e.pointerId);
+ } catch {
+ /* noop */
+ }
+ };
+
+ const onPointerMove = (e: React.PointerEvent<HTMLButtonElement>) => {
+ const d = dragRef.current;
+ if (!d || e.pointerId !== d.pointerId) return;
+ const dx = e.clientX - d.startClientX;
+ const dy = e.clientY - d.startClientY;
+ if (!d.dragging) {
+ if (Math.hypot(dx, dy) < DRAG_THRESHOLD_PX) return;
+ d.dragging = true;
+ // webview 指针穿透 + 禁选中(与拖缝/拖面板同款方案)。
+ document.body.classList.add('resizing-pane');
+ document.body.style.userSelect = 'none';
+ }
+ const next = clampToViewport(d.baseX + dx, d.baseY + dy);
+ d.lastX = next.x;
+ d.lastY = next.y;
+ const el = elRef.current;
+ if (el) el.style.transform = `translate3d(${next.x}px, ${next.y}px, 0)`;
+ };
+
+ const finishDrag = (persist: boolean) => {
+ const d = dragRef.current;
+ if (!d) return;
+ dragRef.current = null;
+ try {
+ elRef.current?.releasePointerCapture(d.pointerId);
+ } catch {
+ /* noop */
+ }
+ if (!d.dragging) return; // 纯点击:等 onClick 走退场→恢复时序
+ endDragCleanup();
+ draggedRef.current = true; // 吞掉随后的合成 click
+ if (persist) {
+ setGhostPanelBubblePosition(manifest.id, d.lastX, d.lastY);
+ } else {
+ // 取消:回滚到拖前基准位
+ const el = elRef.current;
+ if (el) el.style.transform = `translate3d(${d.baseX}px, ${d.baseY}px, 0)`;
+ }
+ };
+
+ const onClick = () => {
+ if (draggedRef.current) {
+ draggedRef.current = false;
+ return;
+ }
+ if (exiting) return;
+ // 展开的"过程感":幽灵先跳走、圆圈再渐隐(共 EXIT_MS),到点才真正恢复
+ // 面板(面板侧再接宽度展开,见 ghostPanels.tsx 的 ghost-panel-enter)。
+ setExiting(true);
+ exitTimerRef.current = window.setTimeout(() => restoreGhostPanel(manifest.id), EXIT_MS);
+ };
+
+ const name = manifest.panel?.title ?? manifest.name;
+ return (
+ <button
+ ref={elRef}
+ type="button"
+ data-testid={`ghost-panel-bubble-${manifest.id}`}
+ aria-label={t('ghostPanelBubble.restoreAria', { name })}
+ title={t('ghostPanelBubble.restoreAria', { name })}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={() => finishDrag(true)}
+ onPointerCancel={() => finishDrag(false)}
+ onClick={onClick}
+ // 按钮本体只管位置(translate3d)与命中区,不带视觉——圆圈(描边/底色/
+ // 阴影)与幽灵分层,动画各编各的(见 globals.css 悬浮球一节)。
+ // 描边四轮定(2026-07-25 Lizi):border-default 太浅 → accent-emphasis
+ // 太深 → text-tertiary 中间档(亮色中灰/暗色中灰);2px 太粗 → 1px。
+ className={`ghost-bubble group fixed left-0 top-0 z-[9900] flex h-12 w-12 cursor-pointer items-center justify-center will-change-transform ${
+ exiting ? 'ghost-bubble-exit' : 'ghost-bubble-enter'
+ }`}
+ style={{ transform: `translate3d(${pos.x}px, ${pos.y}px, 0)` }}
+ >
+ <span
+ aria-hidden
+ className="ghost-bubble-circle absolute inset-0 rounded-full border border-[var(--text-tertiary)] bg-[var(--surface-elevated)] shadow-xl transition-colors group-hover:bg-[var(--surface-chip)]"
+ />
+ <span className="ghost-bubble-face-jump relative flex items-center justify-center">
+ {iconDataUrl && !imgBroken ? (
+ <img
+ src={iconDataUrl}
+ alt=""
+ draggable={false}
+ className="h-8 w-8 rounded-full object-cover"
+ onError={() => setImgBroken(true)}
+ />
+ ) : (
+ <span className="ghost-bubble-face inline-flex">
+ <Ghost size={22} className="text-[var(--text-primary)]" />
+ </span>
+ )}
+ </span>
+ </button>
+ );
+}
+
+/** 气泡层:空名单不渲染;窗口缩放防抖重渲以重算 clamp/默认位。 */
+export function GhostPanelBubbleLayer(): ReactNode {
+ const ghosts = useInstalledGhosts();
+ const bubbles = useGhostPanelBubbleState();
+ // 订阅抽离状态:detach 期间气泡隐藏,合并回来自动复现。
+ useGhostPanelWindowsState();
+
+ const [, setResizeTick] = useState(0);
+ useEffect(() => {
+ let timer = 0;
+ const onResize = () => {
+ window.clearTimeout(timer);
+ timer = window.setTimeout(() => setResizeTick((v) => v + 1), 100);
+ };
+ window.addEventListener('resize', onResize);
+ return () => {
+ window.clearTimeout(timer);
+ window.removeEventListener('resize', onResize);
+ };
+ }, []);
+
+ const minimized = ghosts.filter(
+ (g) =>
+ g.enabled !== false &&
+ g.manifest.panel !== undefined &&
+ g.manifest.panel.position !== 'tab' &&
+ bubbles[g.manifest.id]?.minimized === true &&
+ !isGhostPanelKindDetached(ghostPanelKind(g.manifest.id)),
+ );
+ if (minimized.length === 0) return null;
+
+ let defaultIndex = 0;
+ const items = minimized.map((g) => {
+ const entry = bubbles[g.manifest.id];
+ const hasPos = Number.isFinite(entry?.x) && Number.isFinite(entry?.y);
+ const base = hasPos
+ ? { x: entry.x as number, y: entry.y as number }
+ : defaultPosition(defaultIndex++);
+ return {
+ ghost: g,
+ pos: clampToViewport(base.x, base.y),
+ };
+ });
+
+ return createPortal(
+ <>
+ {items.map(({ ghost, pos }) => (
+ <Bubble
+ key={ghost.manifest.id}
+ manifest={ghost.manifest}
+ iconDataUrl={ghost.iconDataUrl}
+ pos={pos}
+ />
+ ))}
+ </>,
+ document.body,
+ );
+}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx
new file mode 100644
index 0000000000..0cce10488b
--- /dev/null
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx
@@ -0,0 +1,118 @@
+// @vitest-environment jsdom
+// GhostPanelBubbleLayer:最小化气泡的渲染 / 点击恢复(先缩没后还原) /
+// 拖后吞点击 / detach 隐藏。
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';
+import {
+ __resetGhostPanelBubbleStateForTest,
+ getGhostPanelBubbleState,
+ minimizeGhostPanel,
+} from '../../lib/ghostPanelBubbleState';
+import {
+ __resetGhostPanelWindowsStateForTest,
+ __setGhostPanelWindowsStateForTest,
+} from '../../lib/ghostPanelWindowState';
+import { __resetInstalledGhostsStoreForTest } from '../useInstalledGhosts';
+import { GhostPanelBubbleLayer } from '../GhostPanelBubbleLayer';
+
+// 仓库同款 i18n mock:t 返回 key(带参拼上,便于断言)。
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, args?: Record<string, unknown>) =>
+ args ? `${key}:${JSON.stringify(args)}` : key,
+ }),
+}));
+
+function ghost(id: string, enabled = true): InstalledGhost {
+ const manifest: GhostManifest = {
+ schemaVersion: 2,
+ id,
+ name: `${id} 插件`,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['panel'],
+ panel: { title: `${id} 面板`, html: 'panel.html' },
+ };
+ return { manifest, dir: `/fake/${id}`, enabled };
+}
+
+function stubGhostsBridge(ghosts: InstalledGhost[]): void {
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ ghosts: {
+ listSync: () => ({ ghosts }),
+ onChanged: () => () => undefined,
+ },
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ __resetGhostPanelBubbleStateForTest();
+ __resetGhostPanelWindowsStateForTest();
+ __resetInstalledGhostsStoreForTest();
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+});
+
+describe('GhostPanelBubbleLayer', () => {
+ it('已最小化的插件渲染气泡(aria 带面板名);未最小化不渲染', () => {
+ stubGhostsBridge([ghost('a'), ghost('b')]);
+ minimizeGhostPanel('a');
+ render(<GhostPanelBubbleLayer />);
+ expect(screen.getByTestId('ghost-panel-bubble-a')).toBeTruthy();
+ expect(screen.queryByTestId('ghost-panel-bubble-b')).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'ghostPanelBubble.restoreAria:{"name":"a 面板"}' }),
+ ).toBeTruthy();
+ });
+
+ it('点击气泡 → 先播缩没退场,~140ms 后恢复停靠、气泡卸载', async () => {
+ stubGhostsBridge([ghost('a')]);
+ minimizeGhostPanel('a');
+ render(<GhostPanelBubbleLayer />);
+ fireEvent.click(screen.getByTestId('ghost-panel-bubble-a'));
+ // 点击后不是立刻恢复:退场动画窗口内仍处于最小化态
+ expect(getGhostPanelBubbleState().a?.minimized).toBe(true);
+ await waitFor(() => {
+ expect(getGhostPanelBubbleState().a?.minimized).not.toBe(true);
+ });
+ await waitFor(() => {
+ expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull();
+ });
+ });
+
+ it('拖动(>4px)后松手:位置持久化、随后的 click 被吞、仍保持最小化', () => {
+ stubGhostsBridge([ghost('a')]);
+ minimizeGhostPanel('a');
+ render(<GhostPanelBubbleLayer />);
+ const bubble = screen.getByTestId('ghost-panel-bubble-a');
+ fireEvent.pointerDown(bubble, { button: 0, pointerId: 1, clientX: 500, clientY: 500 });
+ fireEvent.pointerMove(bubble, { pointerId: 1, clientX: 460, clientY: 420 });
+ fireEvent.pointerUp(bubble, { pointerId: 1, clientX: 460, clientY: 420 });
+ fireEvent.click(bubble);
+ const entry = getGhostPanelBubbleState().a;
+ expect(entry?.minimized).toBe(true); // 拖后 click 被吞,没有触发恢复
+ expect(Number.isFinite(entry?.x) && Number.isFinite(entry?.y)).toBe(true);
+ expect(document.body.classList.contains('resizing-pane')).toBe(false); // 拖完清理
+ });
+
+ it('已抽离独立窗口的插件不画气泡(合并回来自动复现)', () => {
+ stubGhostsBridge([ghost('a')]);
+ minimizeGhostPanel('a');
+ __setGhostPanelWindowsStateForTest({ a: { detached: true, lastOpen: true, open: true } });
+ const { rerender } = render(<GhostPanelBubbleLayer />);
+ expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull();
+ __setGhostPanelWindowsStateForTest({});
+ rerender(<GhostPanelBubbleLayer />);
+ expect(screen.getByTestId('ghost-panel-bubble-a')).toBeTruthy();
+ });
+
+ it('停用的插件不画气泡', () => {
+ stubGhostsBridge([ghost('a', false)]);
+ minimizeGhostPanel('a');
+ render(<GhostPanelBubbleLayer />);
+ expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
index 38e4d68895..f555426fb5 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
@@ -2,6 +2,11 @@
import { afterEach, describe, expect, it } from 'vitest';
import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';
+import {
+ __resetGhostPanelBubbleStateForTest,
+ getGhostPanelBubbleState,
+ minimizeGhostPanel,
+} from '../../lib/ghostPanelBubbleState';
import { __resetPanelRegistryForTest, hasPanelKind, listPanelKinds } from '../../panels/registry';
import {
__resetGhostPanelsForTest,
@@ -27,6 +32,7 @@ function ghost(id: string, panel?: GhostManifest['panel'] | null, enabled = true
afterEach(() => {
__resetPanelRegistryForTest();
__resetGhostPanelsForTest();
+ __resetGhostPanelBubbleStateForTest();
});
describe('syncGhostPanelRegistrations · 注册表与已装清单对齐', () => {
@@ -57,6 +63,24 @@ describe('syncGhostPanelRegistrations · 注册表与已装清单对齐', () =>
expect(hasPanelKind('ghost:a')).toBe(false);
expect(hasPanelKind('ghost:b')).toBe(false);
});
+
+ it('同步时对齐气泡状态:卸载删条目、停用强制还原(不留死角)', () => {
+ minimizeGhostPanel('gone');
+ minimizeGhostPanel('disabled');
+ syncGhostPanelRegistrations([ghost('disabled', undefined, false)]);
+ const bubbles = getGhostPanelBubbleState();
+ expect(bubbles.gone).toBeUndefined();
+ expect(bubbles.disabled?.minimized).not.toBe(true);
+ });
+
+ it('同步时对齐气泡状态:卸载删条目、停用强制还原(不留死角)', () => {
+ minimizeGhostPanel('gone');
+ minimizeGhostPanel('disabled');
+ syncGhostPanelRegistrations([ghost('disabled', undefined, false)]);
+ const bubbles = getGhostPanelBubbleState();
+ expect(bubbles.gone).toBeUndefined();
+ expect(bubbles.disabled?.minimized).not.toBe(true);
+ });
});
describe('pickGhostPanelMediaUri · 右键命中参数挑媒体地址', () => {
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
index c1895d5ab4..4938a88cc9 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
@@ -1,6 +1,7 @@
-import { useEffect, useState, type ReactNode } from 'react';
+import { useEffect, useRef, useState, type ReactNode } from 'react';
import { ghostPanelKind, type GhostManifest, type InstalledGhost } from '../../shared/ghost';
+import { minimizeGhostPanel, reconcileGhostPanelBubbles } from '../lib/ghostPanelBubbleState';
import { usePanelMaximize } from '../layout/panelMaximize';
import { usePanelWidth } from '../layout/paneWidths';
import { PanelChrome } from '../panels/PanelChrome';
@@ -30,6 +31,19 @@ import { useGhostRuntimeState } from './runtimeStates';
// 兼容既有导入点(测试等):粗筛纯函数随面板体一起搬家,原路径继续可用。
export { pickGhostPanelMediaUri } from './ghostPanelBody';
+/**
+ * 停靠面板入场动画的"启动首屏豁免窗":凡是这个时刻之后才挂载的 GhostPanel
+ * (点气泡展开、独立窗合并回来、装入、启用)都播宽度展开(ghost-panel-enter,
+ * 见 globals.css),不再"先占宽再出现"(2026-07-25 Lizi:出现要丝滑);
+ * 启动首屏全家同帧就位,不各展各的——本模块在 LayoutRoot 首帧前装载
+ * (ensureGhostPanelsRegistered 走 sendSync),首屏挂载与模块装载几乎同刻,
+ * 1.5s 窗口足够宽;极端慢启动多播一次展开也无害。
+ */
+const PANEL_ENTER_ARMED_AT = Date.now() + 1500;
+/** 最小化折叠动画时长:与 globals.css 的 ghost-panel-collapse 对齐,
+ * 到点才真正提交 minimized(随后气泡侧再等 300ms 入场,接力不抢戏)。 */
+const PANEL_EXIT_MS = 180;
+
/** 意识面板宿主:标准头(PanelChrome)+ 沙箱自绘面板体(崩溃时错误接管)。 */
function GhostPanel({
manifest,
@@ -44,6 +58,7 @@ function GhostPanel({
// 关闭 = 不把对应入参交给标准头,按钮不长出(标题条本体恒在)。
const maximizeEnabled = manifest.panel?.systemButtons?.maximize !== false;
const detachEnabled = manifest.panel?.systemButtons?.detach !== false;
+ const minimizeEnabled = manifest.panel?.systemButtons?.minimize !== false;
// 换版更新把按钮关掉时,若面板正撑满,自动还原 —— 否则按钮没了、态出不去。
useEffect(() => {
if (!maximizeEnabled && isMaximized) maximize?.toggle(kind);
@@ -51,32 +66,64 @@ function GhostPanel({
// 沙箱崩了 → 面板原地进入错误接管态。
const runtimeState = useGhostRuntimeState(manifest.id);
const broken = runtimeState === 'crashed' || runtimeState === 'fused';
+ // 挂载即定(useState 初始化跑一次):启动首屏后出现的面板播宽度展开。
+ const [enter] = useState(() => Date.now() >= PANEL_ENTER_ARMED_AT);
+ // 点最小化 → 先播宽度折叠(closing),计时器到点才真正提交 minimized;
+ // 减弱动效直接提交;撑满态是 flex-1(宽度动画不生效),也直接提交,
+ // LayoutRoot 的可见性 effect 会顺手清撑满。
+ const [closing, setClosing] = useState(false);
+ const closeTimerRef = useRef(0);
+ useEffect(() => () => window.clearTimeout(closeTimerRef.current), []);
+ const beginMinimize = (): void => {
+ if (closing) return;
+ const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;
+ if (reduced || isMaximized) {
+ minimizeGhostPanel(manifest.id);
+ return;
+ }
+ setClosing(true);
+ closeTimerRef.current = window.setTimeout(() => minimizeGhostPanel(manifest.id), PANEL_EXIT_MS);
+ };
return (
- <section
- data-panel-drag-root={kind}
- // 侧边分割线由布局引擎统一绘制(LayoutRoot layout-divider),面板不自画。
+ // 外层壳管布局占宽(出现/收起的宽度动画只动这层),内层 section 恒为
+ // 实宽被裁切——展开像"拉开抽屉"露出成形的面板,webview 不逐帧改宽。
+ <div
className={
isMaximized
- ? 'flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]'
- : 'flex h-full shrink-0 flex-col overflow-hidden bg-[var(--panel-bg)]'
+ ? 'flex h-full min-w-0 flex-1'
+ : `h-full shrink-0 overflow-hidden${enter ? ' ghost-panel-enter' : ''}${
+ closing ? ' ghost-panel-exit' : ''
+ }`
}
style={isMaximized ? undefined : { width }}
>
- <PanelChrome
- title={manifest.panel?.title ?? manifest.name}
- panelKind={maximizeEnabled ? kind : undefined}
- onDetach={
- detachEnabled
- ? () => void window.electronAPI?.ghostPanelWindow?.setDetached(manifest.id, true)
- : undefined
+ <section
+ data-panel-drag-root={kind}
+ // 侧边分割线由布局引擎统一绘制(LayoutRoot layout-divider),面板不自画。
+ className={
+ isMaximized
+ ? 'flex h-full w-full min-w-0 flex-col overflow-hidden bg-[var(--panel-bg)]'
+ : 'flex h-full shrink-0 flex-col overflow-hidden bg-[var(--panel-bg)]'
}
- />
- {broken ? (
- <GhostPanelError manifest={manifest} state={runtimeState} />
- ) : (
- <GhostChipPanelBody manifest={manifest} />
- )}
- </section>
+ style={isMaximized ? undefined : { width }}
+ >
+ <PanelChrome
+ title={manifest.panel?.title ?? manifest.name}
+ panelKind={maximizeEnabled ? kind : undefined}
+ onMinimize={minimizeEnabled ? beginMinimize : undefined}
+ onDetach={
+ detachEnabled
+ ? () => void window.electronAPI?.ghostPanelWindow?.setDetached(manifest.id, true)
+ : undefined
+ }
+ />
+ {broken ? (
+ <GhostPanelError manifest={manifest} state={runtimeState} />
+ ) : (
+ <GhostChipPanelBody manifest={manifest} />
+ )}
+ </section>
+ </div>
);
}
@@ -95,6 +142,9 @@ export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {
// 本函数是"已装清单"的唯一同步点(启动 + ghosts:changed),挂这里最省。
// 注意用全量清单(含沉睡)——沉睡只是不注册面板,快照仍然有效。
pruneGhostSettingsSnapshots(ghosts.map((g) => g.manifest.id));
+ // 气泡状态对齐(与快照 prune 不同:停用/失格的要强制还原,不只清卸载)——
+ // 气泡是"面板不可见 + 唯一恢复入口",失格后必须回停靠,不留死角。
+ reconcileGhostPanelBubbles(ghosts);
// 页签形态与停靠形态同源同步:一次广播喂两个注册表,不各自订阅。
syncGhostTabRegistrations(ghosts);
const seen = new Set<string>();
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 4c02ef3da0..9c73ed58b3 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -13,6 +13,7 @@ import { Sidebar } from '@/components/sidebar/Sidebar';
import { LayoutRoot } from '@/layout/LayoutRoot';
import { PanelDragController } from '@/layout/PanelDragController';
import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';
+import { GhostPanelBubbleLayer } from '@/cindy-brain/GhostPanelBubbleLayer';
import { ContentAvailableWidthProvider } from '@/layout/paneWidths';
import {
migrateLegacySidebarCollapsed,
@@ -1258,6 +1259,10 @@ export function MainLayout() {
推送到本窗口,这里弹标准 ImageLightbox(整窗一份,纯监听无 UI)。
sessionId = 当前聊天会话 → lightbox 里「发送到对话」可用。 */}
<GhostMediaLightboxHost sessionId={rightSidebarSessionId ?? undefined} />
+ {/* 最小化插件面板的浮动气泡层(portal 到 body,z-[9900];点击气泡
+ 恢复停靠,拖动换位并持久化)。设置页等接管态也保持在场——气泡是
+ 被最小化面板的唯一恢复入口。 */}
+ <GhostPanelBubbleLayer />
{/* Windows 顶层浮层 chrome:窗口控制按钮(min/max/close),所有路由常驻
(含设置页),永远钉在窗口角,开/关右栏都不动 —— 解决「右栏作为 <main>
sibling 会把窗口按钮挤左」的问题。no-drag(按钮可点),周围窗口拖拽区由
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 215a587a56..88cdc40be1 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3087,12 +3087,16 @@
"panelChrome": {
"maximizeAria": "Maximize panel",
"restoreAria": "Restore panel size",
- "detachAria": "Open in a new window"
+ "detachAria": "Open in a new window",
+ "minimizeAria": "Minimize to floating bubble"
},
"ghostPanelWindow": {
"mergeBack": "Merge back into main window",
"unavailable": "This plugin panel is currently unavailable"
},
+ "ghostPanelBubble": {
+ "restoreAria": "Restore {{name}} panel"
+ },
"rightSidebar": {
"ariaLabel": "Right sidebar",
"window": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index b9dc1f7fb1..66fa2d5e08 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3086,12 +3086,16 @@
"panelChrome": {
"maximizeAria": "パネルを最大化",
"restoreAria": "パネルのサイズを元に戻す",
- "detachAria": "新しいウィンドウで開く"
+ "detachAria": "新しいウィンドウで開く",
+ "minimizeAria": "フローティングバブルに最小化"
},
"ghostPanelWindow": {
"mergeBack": "メインウィンドウに戻す",
"unavailable": "このプラグインパネルは現在利用できません"
},
+ "ghostPanelBubble": {
+ "restoreAria": "{{name}} パネルを元に戻す"
+ },
"rightSidebar": {
"ariaLabel": "右サイドバー",
"window": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 540243e5a3..6644848abd 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3086,12 +3086,16 @@
"panelChrome": {
"maximizeAria": "패널 최대화",
"restoreAria": "패널 크기 복원",
- "detachAria": "새 창에서 열기"
+ "detachAria": "새 창에서 열기",
+ "minimizeAria": "플로팅 버블로 최소화"
},
"ghostPanelWindow": {
"mergeBack": "메인 창으로 되돌리기",
"unavailable": "이 플러그인 패널은 현재 사용할 수 없습니다"
},
+ "ghostPanelBubble": {
+ "restoreAria": "{{name}} 패널 복원"
+ },
"rightSidebar": {
"ariaLabel": "오른쪽 사이드바",
"window": {
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 021a50d0c5..35ad748fd8 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3086,12 +3086,16 @@
"panelChrome": {
"maximizeAria": "撑满内容区",
"restoreAria": "还原面板大小",
- "detachAria": "在独立窗口中打开"
+ "detachAria": "在独立窗口中打开",
+ "minimizeAria": "最小化为浮动气泡"
},
"ghostPanelWindow": {
"mergeBack": "合并回主窗口",
"unavailable": "该插件面板当前不可用"
},
+ "ghostPanelBubble": {
+ "restoreAria": "恢复 {{name}} 面板"
+ },
"rightSidebar": {
"ariaLabel": "右侧边栏",
"window": {
diff --git a/apps/desktop/src/renderer/layout/LayoutRoot.tsx b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
index 57c70cff79..6ee610bcfd 100644
--- a/apps/desktop/src/renderer/layout/LayoutRoot.tsx
+++ b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
@@ -11,6 +11,7 @@ import {
ensureGhostPanelsRegistered,
useGhostPanelsSync,
} from '../cindy-brain/ghostPanels';
+import { isGhostPanelKindMinimized, useGhostPanelBubbleState } from '../lib/ghostPanelBubbleState';
import { isGhostPanelKindDetached, useGhostPanelWindowsState } from '../lib/ghostPanelWindowState';
import { registerBuiltinPanels } from '../panels/builtinPanels';
import { getPanelKind } from '../panels/registry';
@@ -52,18 +53,23 @@ const CHAT_MIN_PX = 400;
const NON_CHAT_FLOOR_PX = 120;
/**
- * pane 是否在本窗口渲染:未注册 kind(未安装/停用的插件残留)与已抽离进
- * 独立窗口的面板都不渲染 —— 树数据一律保留,重装/合并即原位恢复
- * (architecture-invariants「已抽离的面板允许保留在存档中但不渲染」)。
+ * pane 是否在本窗口渲染:未注册 kind(未安装/停用的插件残留)、已抽离进
+ * 独立窗口、以及已最小化为浮动气泡的面板都不渲染 —— 树数据一律保留,
+ * 重装/合并/恢复即原位复活(architecture-invariants「已抽离的面板允许保留
+ * 在存档中但不渲染」)。
*/
function isPanelKindVisible(kind: string): boolean {
- return getPanelKind(kind) !== null && !isGhostPanelKindDetached(kind);
+ return (
+ getPanelKind(kind) !== null &&
+ !isGhostPanelKindDetached(kind) &&
+ !isGhostPanelKindMinimized(kind)
+ );
}
/** 单个 pane 的挂载点:查注册表渲染;不可见 kind = 隐藏(数据保留在树里)。 */
function PanelHost({ node }: { node: PaneNode }): ReactNode {
const def = getPanelKind(node.panelKind);
- if (!def || isGhostPanelKindDetached(node.panelKind)) return null;
+ if (!def || !isPanelKindVisible(node.panelKind)) return null;
const Component = def.Component;
return <Component paneId={node.id} />;
}
@@ -343,8 +349,10 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
// 装/卸广播 → 注册表对齐 + 重渲(卸下不动布局树,靠这里让引擎重过滤在场面板)。
const ghostSyncVersion = useGhostPanelsSync();
- // 抽离状态广播 → 重渲(isPanelKindVisible 读的是模块级镜像,靠这个 hook 感知变化)。
+ // 抽离/气泡状态变化 → 重渲(isPanelKindVisible 读的是模块级镜像,靠这两个
+ // hook 感知变化)。
const ghostWindowsState = useGhostPanelWindowsState();
+ const ghostBubbleState = useGhostPanelBubbleState();
// 首帧同步读取(sendSync):布局在第一帧就位,不出现默认布局闪现。
const [layout, setLayout] = useState<Layout>(() => window.electronAPI.layout.getStateSync().layout);
@@ -372,7 +380,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
// isPanelKindVisible 的隐式数据源(模块级镜像),必须进 deps 才能感知抽离变化。
const widths = useMemo(
() => computePanelWidths(layout, liveFractions, avail),
- [layout, liveFractions, avail, ghostWindowsState],
+ [layout, liveFractions, avail, ghostWindowsState, ghostBubbleState],
);
// chat 实际渲染宽 ≈ 可用宽 − 可见非 chat 面板宽度之和(拖缝余量用,见
// RootDividerPropsExtra;折叠面板的误差偏保守)。
@@ -394,7 +402,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
void window.electronAPI.layout.set(fixed).catch(() => undefined);
}, 250);
return () => clearTimeout(timer);
- }, [availCtx, ghostSyncVersion, ghostWindowsState, layout, liveFractions, suppressNonChatPanels]);
+ }, [availCtx, ghostBubbleState, ghostSyncVersion, ghostWindowsState, layout, liveFractions, suppressNonChatPanels]);
// 撑满目标失效自动还原:面板被卸下/停用(kind 注销)、抽离进独立窗口或
// pane 离开树时清态,免得下次回来以陈年撑满态惊回。接管态(设置页)只是
@@ -407,7 +415,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
c.children.some((ch) => ch.node.type === 'pane' && ch.node.panelKind === maximizedKind) &&
isPanelKindVisible(maximizedKind);
if (!present) setMaximizedKind(null);
- }, [layout, ghostSyncVersion, ghostWindowsState, maximizedKind, suppressNonChatPanels]);
+ }, [layout, ghostBubbleState, ghostSyncVersion, ghostWindowsState, maximizedKind, suppressNonChatPanels]);
const content = layout.content;
let body: ReactNode;
diff --git a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
new file mode 100644
index 0000000000..4c10098ccc
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
@@ -0,0 +1,139 @@
+// @vitest-environment jsdom
+// ghostPanelBubbleState:localStorage 持久化的气泡最小化状态。
+import { afterEach, describe, expect, it } from 'vitest';
+
+import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';
+import {
+ __resetGhostPanelBubbleStateForTest,
+ getGhostPanelBubbleState,
+ isGhostPanelKindMinimized,
+ minimizeGhostPanel,
+ reconcileGhostPanelBubbles,
+ restoreGhostPanel,
+ setGhostPanelBubblePosition,
+} from '../ghostPanelBubbleState';
+
+const KEY = 'xdt:ghostPanelBubble:v1';
+
+function ghost(
+ id: string,
+ opts: { enabled?: boolean; position?: 'left' | 'tab'; minimizeButton?: boolean; panel?: boolean } = {},
+): InstalledGhost {
+ const manifest: GhostManifest = {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: opts.panel === false ? ['tool'] : ['panel'],
+ ...(opts.panel === false
+ ? {}
+ : {
+ panel: {
+ html: 'panel.html',
+ ...(opts.position !== undefined ? { position: opts.position } : {}),
+ ...(opts.minimizeButton === false ? { systemButtons: { minimize: false } } : {}),
+ },
+ }),
+ };
+ return { manifest, dir: `/fake/${id}`, enabled: opts.enabled ?? true };
+}
+
+afterEach(() => {
+ __resetGhostPanelBubbleStateForTest();
+});
+
+describe('ghostPanelBubbleState · sanitize', () => {
+ it('坏 JSON / 非对象 → 空表', () => {
+ window.localStorage.setItem(KEY, '{{{');
+ expect(getGhostPanelBubbleState()).toEqual({});
+ __resetGhostPanelBubbleStateForTest();
+ window.localStorage.setItem(KEY, '[1,2]');
+ expect(getGhostPanelBubbleState()).toEqual({});
+ });
+
+ it('minimized 非布尔整条丢;x/y 非双双有限数则略去;空条目不留', () => {
+ window.localStorage.setItem(
+ KEY,
+ JSON.stringify({
+ bad: { minimized: 'yes', x: 1, y: 2 },
+ halfpos: { minimized: true, x: 10 },
+ floaty: { minimized: true, x: 10.6, y: 20.2 },
+ empty: { minimized: false },
+ good: { minimized: false, x: 5, y: 6 },
+ }),
+ );
+ expect(getGhostPanelBubbleState()).toEqual({
+ halfpos: { minimized: true },
+ floaty: { minimized: true, x: 11, y: 20 },
+ good: { minimized: false, x: 5, y: 6 },
+ });
+ });
+});
+
+describe('ghostPanelBubbleState · 最小化/恢复/位置', () => {
+ it('minimize → restore 往返:位置保留;无位置的还原条目清除;持久化可重读', () => {
+ minimizeGhostPanel('a');
+ expect(isGhostPanelKindMinimized('ghost:a')).toBe(true);
+ setGhostPanelBubblePosition('a', 100.4, 200.6);
+ restoreGhostPanel('a');
+ expect(isGhostPanelKindMinimized('ghost:a')).toBe(false);
+ expect(getGhostPanelBubbleState().a).toEqual({ minimized: false, x: 100, y: 201 });
+
+ // 持久化载荷可直接重读(模拟重启的数据面)
+ minimizeGhostPanel('b');
+ setGhostPanelBubblePosition('b', 1, 2);
+ const raw = JSON.parse(window.localStorage.getItem(KEY) ?? '{}');
+ expect(raw.b).toEqual({ minimized: true, x: 1, y: 2 });
+
+ // 无位置的还原条目直接清除
+ minimizeGhostPanel('c');
+ restoreGhostPanel('c');
+ expect(getGhostPanelBubbleState().c).toBeUndefined();
+ });
+
+ it('谓词:非 ghost 前缀恒 false', () => {
+ minimizeGhostPanel('a');
+ expect(isGhostPanelKindMinimized('chat-main')).toBe(false);
+ expect(isGhostPanelKindMinimized('right-tabs')).toBe(false);
+ });
+});
+
+describe('ghostPanelBubbleState · reconcile(与已装清单对齐)', () => {
+ it('卸载删条目;停用/tab/关按钮强制还原(留位置);合格的不动', () => {
+ minimizeGhostPanel('gone');
+ minimizeGhostPanel('disabled');
+ setGhostPanelBubblePosition('disabled', 9, 9);
+ minimizeGhostPanel('tabbed');
+ minimizeGhostPanel('nobtn');
+ minimizeGhostPanel('stays');
+
+ reconcileGhostPanelBubbles([
+ ghost('disabled', { enabled: false }),
+ ghost('tabbed', { position: 'tab' }),
+ ghost('nobtn', { minimizeButton: false }),
+ ghost('stays'),
+ ]);
+
+ const state = getGhostPanelBubbleState();
+ expect(state.gone).toBeUndefined();
+ expect(state.disabled).toEqual({ minimized: false, x: 9, y: 9 });
+ expect(state.tabbed).toBeUndefined(); // 无位置的还原条目清除
+ expect(state.nobtn).toBeUndefined();
+ expect(state.stays).toEqual({ minimized: true });
+ });
+});
+
+describe('ghostPanelBubbleState · 变化信号(引用替换)', () => {
+ it('只有真实变化才替换表引用(useSyncExternalStore 的更新信号)', () => {
+ const before = getGhostPanelBubbleState();
+ reconcileGhostPanelBubbles([ghost('x')]); // 无条目 → 无变化,同一引用
+ expect(getGhostPanelBubbleState()).toBe(before);
+ minimizeGhostPanel('x'); // commit 替换引用
+ expect(getGhostPanelBubbleState()).not.toBe(before);
+ const after = getGhostPanelBubbleState();
+ minimizeGhostPanel('x'); // 已最小化,幂等短路,不替换
+ expect(getGhostPanelBubbleState()).toBe(after);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts b/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
new file mode 100644
index 0000000000..919118acdd
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
@@ -0,0 +1,179 @@
+/**
+ * ghostPanelBubbleState —— 插件停靠面板「最小化为浮动气泡」的 renderer 端状态。
+ *
+ * 纯视图态,renderer 自有(localStorage 持久化,重启保留),不经 main:
+ * 与 maximize(会话态)/ detach(main 持久化)三分天下——气泡既要重启保留
+ * 又不涉及窗口/进程,localStorage 恰好(键规范照 state/modelVisibilityPrefs.ts)。
+ *
+ * 形如 { [ghostId]: { minimized, x?, y? } }:
+ * - minimized:面板是否收进气泡(LayoutRoot 据此隐藏停靠 pane,树不动);
+ * - x/y:气泡视口位置(左上角 px)。恢复面板时**保留**,重最小化回老位置;
+ * 只在首次真实拖放后才写入——没拖过的气泡由气泡层按默认位停靠,
+ * 窗口缩放自动重排。位置不在 store 里 clamp(渲染时按当前视口 clamp,
+ * 大屏存的位置换小屏不被破坏性改写)。
+ *
+ * reconcile 语义对齐 main/ghost-panel-window controller:卸载删条目;停用/
+ * 无 panel/tab 形态/身份卡关按钮 → 强制还原(留位置)——气泡永不成死角。
+ */
+
+import { useSyncExternalStore } from 'react';
+
+import { GHOST_PANEL_KIND_PREFIX, type InstalledGhost } from '../../shared/ghost';
+
+const STORAGE_KEY = 'xdt:ghostPanelBubble:v1';
+
+export interface GhostPanelBubbleEntry {
+ minimized: boolean;
+ x?: number;
+ y?: number;
+}
+
+export type GhostPanelBubbleMap = Record<string, GhostPanelBubbleEntry>;
+
+let cache: GhostPanelBubbleMap | null = null;
+const subscribers = new Set<() => void>();
+
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
+}
+
+/** 解析并清洗持久化数据:坏形态整条丢弃,x/y 必须双双有限数否则略去。 */
+function sanitize(raw: unknown): GhostPanelBubbleMap {
+ if (!isPlainObject(raw)) return {};
+ const out: GhostPanelBubbleMap = {};
+ for (const [id, entry] of Object.entries(raw)) {
+ if (!isPlainObject(entry)) continue;
+ if (typeof entry.minimized !== 'boolean') continue;
+ const hasPos = Number.isFinite(entry.x) && Number.isFinite(entry.y);
+ if (!entry.minimized && !hasPos) continue; // 空条目不留
+ out[id] = {
+ minimized: entry.minimized,
+ ...(hasPos ? { x: Math.round(entry.x as number), y: Math.round(entry.y as number) } : {}),
+ };
+ }
+ return out;
+}
+
+function load(): GhostPanelBubbleMap {
+ try {
+ const raw = window.localStorage.getItem(STORAGE_KEY);
+ if (!raw) return {};
+ return sanitize(JSON.parse(raw));
+ } catch {
+ return {};
+ }
+}
+
+function ensureLoaded(): GhostPanelBubbleMap {
+ if (cache === null) cache = load();
+ return cache;
+}
+
+/** 整表替换 + 持久化 + 通知(引用变化即订阅者更新信号)。 */
+function commit(next: GhostPanelBubbleMap): void {
+ cache = next;
+ try {
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+ } catch {
+ // 持久化失败不拦交互(隐私模式等),内存态照常生效
+ }
+ subscribers.forEach((cb) => cb());
+}
+
+export function getGhostPanelBubbleState(): GhostPanelBubbleMap {
+ return ensureLoaded();
+}
+
+/** 布局过滤谓词(非 hook,LayoutRoot 纯函数路径用)。非 ghost 面板恒 false。 */
+export function isGhostPanelKindMinimized(panelKind: string): boolean {
+ if (!panelKind.startsWith(GHOST_PANEL_KIND_PREFIX)) return false;
+ const ghostId = panelKind.slice(GHOST_PANEL_KIND_PREFIX.length);
+ return ensureLoaded()[ghostId]?.minimized === true;
+}
+
+/** 收进气泡(保留既有位置,重最小化回老位置)。 */
+export function minimizeGhostPanel(ghostId: string): void {
+ const cur = ensureLoaded();
+ if (cur[ghostId]?.minimized === true) return;
+ commit({ ...cur, [ghostId]: { ...cur[ghostId], minimized: true } });
+}
+
+/** 从气泡恢复停靠(位置保留;入场滑入由 GhostPanel 挂载时机自判)。 */
+export function restoreGhostPanel(ghostId: string): void {
+ const cur = ensureLoaded();
+ const entry = cur[ghostId];
+ if (!entry || entry.minimized === false) return;
+ const next = { ...cur };
+ const hasPos = Number.isFinite(entry.x) && Number.isFinite(entry.y);
+ if (hasPos) next[ghostId] = { ...entry, minimized: false };
+ else delete next[ghostId]; // 没位置的还原条目是空信息,不留
+ commit(next);
+}
+
+/** 气泡拖放落点(视口 px,取整)。 */
+export function setGhostPanelBubblePosition(ghostId: string, x: number, y: number): void {
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return;
+ const cur = ensureLoaded();
+ const entry = cur[ghostId] ?? { minimized: false };
+ commit({ ...cur, [ghostId]: { ...entry, x: Math.round(x), y: Math.round(y) } });
+}
+
+/**
+ * 与"当前已装清单"对齐(syncGhostPanelRegistrations 每次同步时调):
+ * 卸载删条目;失去气泡资格(停用/无 panel/tab 形态/身份卡关按钮)强制还原。
+ */
+export function reconcileGhostPanelBubbles(
+ ghosts: readonly Pick<InstalledGhost, 'manifest' | 'enabled'>[],
+): void {
+ const cur = ensureLoaded();
+ const ids = Object.keys(cur);
+ if (ids.length === 0) return;
+ const byId = new Map(ghosts.map((g) => [g.manifest.id, g]));
+ let changed = false;
+ const next: GhostPanelBubbleMap = { ...cur };
+ for (const id of ids) {
+ const ghost = byId.get(id);
+ if (!ghost) {
+ delete next[id];
+ changed = true;
+ continue;
+ }
+ const eligible =
+ ghost.enabled !== false &&
+ ghost.manifest.panel !== undefined &&
+ ghost.manifest.panel.position !== 'tab' &&
+ ghost.manifest.panel.systemButtons?.minimize !== false;
+ if (!eligible && next[id].minimized) {
+ const entry = next[id];
+ const hasPos = Number.isFinite(entry.x) && Number.isFinite(entry.y);
+ if (hasPos) next[id] = { ...entry, minimized: false };
+ else delete next[id];
+ changed = true;
+ }
+ }
+ if (changed) commit(next);
+}
+
+function subscribe(cb: () => void): () => void {
+ ensureLoaded();
+ subscribers.add(cb);
+ return () => {
+ subscribers.delete(cb);
+ };
+}
+
+/** React hook:订阅全量表(commit 替换对象引用 = 更新信号)。 */
+export function useGhostPanelBubbleState(): GhostPanelBubbleMap {
+ return useSyncExternalStore(subscribe, getGhostPanelBubbleState);
+}
+
+/** 仅测试用。 */
+export function __resetGhostPanelBubbleStateForTest(): void {
+ cache = null;
+ subscribers.clear();
+ try {
+ window.localStorage.removeItem(STORAGE_KEY);
+ } catch {
+ // ignore
+ }
+}
diff --git a/apps/desktop/src/renderer/panels/PanelChrome.tsx b/apps/desktop/src/renderer/panels/PanelChrome.tsx
index ffcc4b903f..f2c1f782d7 100644
--- a/apps/desktop/src/renderer/panels/PanelChrome.tsx
+++ b/apps/desktop/src/renderer/panels/PanelChrome.tsx
@@ -1,5 +1,5 @@
import type { CSSProperties, ReactNode } from 'react';
-import { Maximize2, Minimize2, PictureInPicture2 } from 'lucide-react';
+import { Maximize2, Minimize2, Minus, PictureInPicture2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
@@ -19,6 +19,8 @@ import { usePanelMaximize } from '../layout/panelMaximize';
*
* 右端系统按钮(一批,由引擎统一长出,面板作者无感;身份卡
* panel.systemButtons 可逐个关闭):
+ * - 「最小化为浮动气泡」(minimize):传 onMinimize 即得,点击把面板收成
+ * 可拖动的圆形气泡(状态在 renderer/lib/ghostPanelBubbleState.ts);
* - 「独立窗口」(detach):传 onDetach 即得,点击把面板抽进自己的 OS 窗口
* (状态机在 main 的 ghost-panel-window/controller.ts);
* - 「撑满内容区」(maximize):传 panelKind 即得,状态在 LayoutRoot 的
@@ -40,9 +42,17 @@ export interface PanelChromeProps {
panelKind?: string;
/** 传入即长出「独立窗口」系统按钮(排在撑满按钮左侧),点击回调归调用方。 */
onDetach?: () => void;
+ /** 传入即长出「最小化为浮动气泡」系统按钮(排在独立窗口按钮左侧)。 */
+ onMinimize?: () => void;
}
-export function PanelChrome({ title, actions, panelKind, onDetach }: PanelChromeProps): ReactNode {
+export function PanelChrome({
+ title,
+ actions,
+ panelKind,
+ onDetach,
+ onMinimize,
+}: PanelChromeProps): ReactNode {
const { t } = useTranslation();
const maximize = usePanelMaximize();
const showMaximize = panelKind !== undefined && maximize !== null;
@@ -91,9 +101,19 @@ export function PanelChrome({ title, actions, panelKind, onDetach }: PanelChrome
<div className="min-w-0 truncate text-[12px] font-medium text-[var(--text-secondary)]">
{title}
</div>
- {(actions || showMaximize || onDetach) && (
+ {(actions || showMaximize || onDetach || onMinimize) && (
<div className="flex shrink-0 items-center gap-0.5">
{actions}
+ {onMinimize && (
+ <button
+ type="button"
+ aria-label={t('panelChrome.minimizeAria')}
+ onClick={onMinimize}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full text-[var(--titlebar-icon)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ >
+ <Minus size={14} />
+ </button>
+ )}
{onDetach && (
<button
type="button"
diff --git a/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx b/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx
index 98b7a3b900..3713ccaa3a 100644
--- a/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx
+++ b/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx
@@ -86,4 +86,28 @@ describe('PanelChrome · 撑满系统按钮', () => {
expect(hole.style.left).toBe(`${CHROME_ACTIONS_GEOMETRY.defaultLeft}px`);
expect(hole.style.width).toBe(`${CHROME_ACTIONS_GEOMETRY.clusterWidth}px`);
});
+
+ it('传 onMinimize → 长出气泡最小化按钮并触发回调;三按钮 DOM 顺序 minimize→detach→maximize', () => {
+ const onMinimize = vi.fn();
+ render(
+ <PanelMaximizeContext.Provider value={{ maximizedKind: null, toggle: () => undefined }}>
+ <PanelChrome
+ title="测试面板"
+ panelKind="ghost:demo"
+ onDetach={() => undefined}
+ onMinimize={onMinimize}
+ />
+ </PanelMaximizeContext.Provider>,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'panelChrome.minimizeAria' }));
+ expect(onMinimize).toHaveBeenCalledTimes(1);
+ const labels = screen
+ .getAllByRole('button')
+ .map((b) => b.getAttribute('aria-label'));
+ expect(labels).toEqual([
+ 'panelChrome.minimizeAria',
+ 'panelChrome.detachAria',
+ 'panelChrome.maximizeAria',
+ ]);
+ });
});
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 548b76f430..b0aa4c33ab 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -1480,3 +1480,66 @@ body.resizing-pane [data-ghost-webview] {
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
}
+
+/* ── 插件面板悬浮球(GhostPanelBubbleLayer)────────────────────────────
+ 动效按 engineering-conventions §7 红线:只动 transform/opacity、动画挂
+ HTML wrapper(不挂 SVG)、常驻循环仅 hover 期间播放、减弱动效时停用。
+ 任何动画都不压在气泡按钮本体上 —— 按钮的 transform 是位置(translate3d),
+ 压同一元素会把气泡顶到 (0,0);圆圈与幽灵各自分层(.ghost-bubble-circle /
+ .ghost-bubble-face-jump)编排。
+ 时序(2026-07-25 Lizi 定案"两段都要有戏"):
+ 出现 = 面板收走 → 等 300ms → 圆圈渐显(160ms)→ 幽灵跳进来(240ms,回弹);
+ 消失 = 幽灵跳走(160ms)→ 圆圈渐隐(120ms 延迟 + 140ms)→ 面板滑入。 */
+@keyframes ghost-bubble-circle-in {
+ from { transform: scale(0.85); opacity: 0; }
+ to { transform: scale(1); opacity: 1; }
+}
+@keyframes ghost-bubble-circle-out {
+ to { transform: scale(0.9); opacity: 0; }
+}
+@keyframes ghost-bubble-ghost-in {
+ 0% { transform: translateY(12px) scale(0.4); opacity: 0; }
+ 65% { transform: translateY(-4px) scale(1.08); opacity: 1; }
+ 100% { transform: none; opacity: 1; }
+}
+@keyframes ghost-bubble-ghost-out {
+ to { transform: translateY(-14px) scale(0.4); opacity: 0; }
+}
+@keyframes ghost-bubble-bob {
+ 0%, 100% { transform: translateY(0); }
+ 50% { transform: translateY(-3px); }
+}
+.ghost-bubble-enter .ghost-bubble-circle {
+ animation: ghost-bubble-circle-in 160ms ease-out 300ms backwards;
+}
+.ghost-bubble-enter .ghost-bubble-face-jump {
+ animation: ghost-bubble-ghost-in 240ms cubic-bezier(0.34, 1.4, 0.64, 1) 420ms backwards;
+}
+.ghost-bubble-exit .ghost-bubble-face-jump {
+ animation: ghost-bubble-ghost-out 160ms ease-in forwards;
+}
+.ghost-bubble-exit .ghost-bubble-circle {
+ animation: ghost-bubble-circle-out 140ms ease-in 120ms forwards;
+}
+.ghost-bubble:hover .ghost-bubble-face {
+ animation: ghost-bubble-bob 1.1s ease-in-out infinite;
+}
+/* 停靠面板出现/收起(气泡展开/合并/装入/启用出现,点最小化收起;启动首屏
+ 豁免与提交时序都在 ghostPanels.tsx):外层壳宽度 0↔实宽 折叠展开。
+ 这是 §7 compositor-only 的窄例外(同登录 handoff 的容器形变口径):
+ 一次性、有状态含义;内容层定实宽被外壳裁切,webview 不逐帧重排。
+ keyframes 缺省端取元素实宽(inline style),不用变量传宽。 */
+@keyframes ghost-panel-expand { from { width: 0; } }
+@keyframes ghost-panel-collapse { to { width: 0; } }
+.ghost-panel-enter { animation: ghost-panel-expand 200ms ease-out; }
+/* exit 在 enter 之后声明:出现瞬间就点收起时,后者整段覆盖前者。 */
+.ghost-panel-exit { animation: ghost-panel-collapse 180ms ease-in forwards; }
+@media (prefers-reduced-motion: reduce) {
+ .ghost-bubble-enter .ghost-bubble-circle,
+ .ghost-bubble-enter .ghost-bubble-face-jump,
+ .ghost-bubble-exit .ghost-bubble-circle,
+ .ghost-bubble-exit .ghost-bubble-face-jump,
+ .ghost-panel-enter,
+ .ghost-panel-exit,
+ .ghost-bubble:hover .ghost-bubble-face { animation: none; }
+}
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index f6ca288473..9a84d891e1 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -216,6 +216,15 @@ describe('ghost · 清单校验', () => {
expect(
bothOff.ok && (bothOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,
).toEqual({ maximize: false, detach: false });
+ const minimizeOff = withPanel({ systemButtons: { minimize: false } });
+ expect(
+ minimizeOff.ok &&
+ (minimizeOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,
+ ).toEqual({ minimize: false });
+ const allOff = withPanel({ systemButtons: { maximize: false, detach: false, minimize: false } });
+ expect(
+ allOff.ok && (allOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,
+ ).toEqual({ maximize: false, detach: false, minimize: false });
expect(withPanel({ systemButtons: {} }).ok).toBe(true);
expect(withPanel({ systemButtons: { maximize: true, detach: true } }).ok).toBe(true);
// 非对象 / 未知键 / 非布尔值:收词明确拒绝(规则 9)
@@ -223,6 +232,8 @@ describe('ghost · 清单校验', () => {
expect(withPanel({ systemButtons: { refresh: false } }).ok).toBe(false);
expect(withPanel({ systemButtons: { maximize: 'no' } }).ok).toBe(false);
expect(withPanel({ systemButtons: { detach: 0 } }).ok).toBe(false);
+ expect(withPanel({ systemButtons: { minimize: 0 } }).ok).toBe(false);
+ expect(withPanel({ position: 'tab', systemButtons: { minimize: false } }).ok).toBe(false);
// 页签形态没有标准头:声明即拒(与 minWidth/defaultFraction 同款语义)
expect(withPanel({ position: 'tab', systemButtons: { maximize: false } }).ok).toBe(false);
// 缺省(不声明)不产出字段
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 4d8378d4eb..c24a40c7b3 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -320,12 +320,12 @@ export interface GhostPanelDecl {
defaultFraction?: number;
/**
* 标准头系统按钮开关(2026-07-25):缺省全开,声明 false 逐个关闭。
- * 当前一批:maximize =「撑满内容区」、detach =「在独立窗口中打开」。
- * 标准头本体(标题条)恒由主机绘制、不可关——可配置的只是系统按钮;
- * 'tab' 形态没有标准头,声明本字段拒装。未知键按规则 9 收词明确拒绝,
- * 新按钮上线时在这里扩键。
+ * 当前一批:maximize =「撑满内容区」、detach =「在独立窗口中打开」、
+ * minimize =「最小化为浮动气泡」。标准头本体(标题条)恒由主机绘制、
+ * 不可关——可配置的只是系统按钮;'tab' 形态没有标准头,声明本字段拒装。
+ * 未知键按规则 9 收词明确拒绝,新按钮上线时在这里扩键。
*/
- systemButtons?: { maximize?: boolean; detach?: boolean };
+ systemButtons?: { maximize?: boolean; detach?: boolean; minimize?: boolean };
}
/**
@@ -2182,7 +2182,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
return { ok: false, reason: 'panel.systemButtons 必须是对象(如 { "maximize": false })' };
}
// 收词明确拒绝未知键(规则 9):新系统按钮上线时在白名单里扩键。
- const knownButtons = ['maximize', 'detach'];
+ const knownButtons = ['maximize', 'detach', 'minimize'];
for (const key of Object.keys(sb)) {
if (!knownButtons.includes(key)) {
return { ok: false, reason: `panel.systemButtons 只认 ${knownButtons.join(' / ')},未知键:${key}` };
@@ -2193,9 +2193,11 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
const maximize = (sb as Record<string, unknown>).maximize;
const detach = (sb as Record<string, unknown>).detach;
+ const minimize = (sb as Record<string, unknown>).minimize;
systemButtons = {
...(typeof maximize === 'boolean' ? { maximize } : {}),
...(typeof detach === 'boolean' ? { detach } : {}),
+ ...(typeof minimize === 'boolean' ? { minimize } : {}),
};
}
let position: GhostPanelPosition | undefined;