Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 右侧栏插件面板页签支持图钉,默认钉住、跨对话保留
Lizi81086ba93a5d
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelWebviewPool.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelWebviewPool.test.tsnew file mode 100644index 0000000000..8be1c9432c--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanelWebviewPool.test.ts@@ -0,0 +1,121 @@+// @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/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsxindex ce8c4622c7..90fd6d7d51 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx@@ -67,7 +67,7 @@ export function GhostPanelError({}/** 面板媒体右键菜单的一次弹出:坐标(宿主窗口系)+ 主机换发的地址与类别。 */-interface GhostPanelMediaMenuState {+export interface GhostPanelMediaMenuState {x: number;y: number;/** 主机拼装的 cindy-media:// 地址(过闸产物,直接喂通用媒体 IPC)。 */@@ -81,8 +81,9 @@ interface GhostPanelMediaMenuState {* 目录(showItemInFolder)。菜单是宿主自绘(webview 里的右键经 Electron* context-menu 事件转出,面板自己画不了也伪造不了),地址已过 main 闸换发,* 两个动作走与聊天媒体完全相同的通用 IPC。+ * (导出给 pooledGhostPanelBody 复用 —— 常驻池形态的面板体右键走同一套菜单。)*/-function GhostPanelMediaMenu({+export function GhostPanelMediaMenu({menu,onClose,}: {diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelWebviewPool.ts b/apps/desktop/src/renderer/cindy-brain/ghostPanelWebviewPool.tsnew file mode 100644index 0000000000..ca350f60d0--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelWebviewPool.ts@@ -0,0 +1,225 @@+/**+ * 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/ghostTabPlugins.tsx b/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsxindex 08032a37b7..9538b5b70b 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsx+++ b/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsx@@ -3,8 +3,11 @@ 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 { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';+import { GhostPanelError } from './ghostPanelBody';+import { ghostPanelFingerprint, ghostPanelWebviewPool } from './ghostPanelWebviewPool';+import { PooledGhostPanelBody } from './pooledGhostPanelBody';import { useGhostRuntimeState } from './runtimeStates';/**@@ -23,8 +26,16 @@ import { useGhostRuntimeState } from './runtimeStates';* kind 复用 ghostPanelKind 的 `ghost:<id>`(DB kind 列无枚举约束,可直存)。*/-/** 页签体:Shell 已提供容器与 TabBar,不再套 PanelChrome 标准头。 */-function GhostTabBody({ manifest }: { manifest: GhostManifest }): ReactNode {+/** 页签体: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';@@ -33,7 +44,7 @@ function GhostTabBody({ manifest }: { manifest: GhostManifest }): ReactNode {{broken ? (<GhostPanelError manifest={manifest} state={runtimeState} />) : (- <GhostChipPanelBody manifest={manifest} />+ <PooledGhostPanelBody manifest={manifest} visible={visible} />)}</div>);@@ -45,7 +56,10 @@ export function buildGhostTabPlugin(manifest: GhostManifest): TabKindPlugin {const label = manifest.panel?.title ?? manifest.name;const TabPillTitle: TabKindPlugin['TabPillTitle'] = () => <>{label}</>;const TabPillIcon: NonNullable<TabKindPlugin['TabPillIcon']> = () => <Puzzle size={13} />;- const TabBody: TabKindPlugin['TabBody'] = () => <GhostTabBody manifest={manifest} />;+ // active / shellVisible → 懒物化判据:页签首次真正可见才创建面板 webview。+ const TabBody: TabKindPlugin['TabBody'] = ({ active, shellVisible }) => (+ <GhostTabBody manifest={manifest} visible={active !== false && shellVisible !== false} />+ );return {kind,menu: {@@ -94,6 +108,16 @@ export function syncGhostTabRegistrations(ghosts: InstalledGhost[]): void {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)));}/** 仅测试用:清空本模块注册,保证用例间隔离。 */diff --git a/apps/desktop/src/renderer/cindy-brain/pooledGhostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/pooledGhostPanelBody.tsxnew file mode 100644index 0000000000..1f4696e1bc--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/pooledGhostPanelBody.tsx@@ -0,0 +1,155 @@+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.tsxindex f53b292c93..0d840d07fe 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -40,6 +40,7 @@ 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,@@ -835,6 +836,9 @@ 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/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex d66e4eb3b4..8b3f328095 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -48,6 +48,15 @@ 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 实例,只通过@@ -208,6 +217,78 @@ export function RightSidebarShell({// 注册表是模块级 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 只做一次,用户随后在本会话内的切换不被打扰)。+ // 插件被停用时 kind 未注册 → 跳过补挂;已存在的页签保留(落 Placeholder,+ // 与"停用隐藏、重启用复活"的既有语义一致)。+ const stickyAppliedSessionRef = useRef<string | null>(null);+ 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;+ 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 && now.activeTabId === null && now.tabs.length > 0) {+ target = now.tabs[0].id;+ }+ if (target && target !== now.activeTabId) {+ try {+ await setActiveTab(sessionId, target);+ } catch (err) {+ log.error('pinned ghost tab activate failed', { sessionId, target, err });+ }+ }+ };+ void run();+ return () => {+ cancelled = true;+ };+ }, [sessionId, bucket.hydrated, bucket.tabs, ghostPinsVersion, tabRegistryVersion]);+// 关掉最后一个 tab → 通知 host 自动收起侧栏。只在 tab 数「从 >0 变 0」的转变时// 触发,不是"等于 0"就触发:// - hydrated 后首帧 prev===null 不触发(区分"刚加载出来就是空"与"关到空");@@ -243,6 +324,9 @@ 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 });@@ -264,6 +348,9 @@ 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 });});@@ -295,6 +382,8 @@ 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 });});diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsxindex a378bbeb40..718260ce67 100644--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx@@ -26,6 +26,7 @@ import {GitPullRequestArrow,UsersRound,ListTodo,+ Pin,Plus,Puzzle,X,@@ -48,6 +49,12 @@ 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 {@@ -289,6 +296,12 @@ 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@@ -468,6 +481,21 @@ 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>+ )}<DropdownMenuItemonClick={() => {const id = contextMenu.tabId;@@ -537,6 +565,11 @@ 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 兜底 / 校正。@@ -604,6 +637,30 @@ 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>+ )}<buttontype="button"data-no-dragdiff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBarGhostPin.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBarGhostPin.test.tsxnew file mode 100644index 0000000000..e4dd08e146--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBarGhostPin.test.tsx@@ -0,0 +1,73 @@+// @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__/storeGhostTabPins.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/storeGhostTabPins.test.tsnew file mode 100644index 0000000000..869d28c98c--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/storeGhostTabPins.test.ts@@ -0,0 +1,101 @@+// @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.tsnew file mode 100644index 0000000000..85e1aeb75a--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/pinnedGhostTabs.test.ts@@ -0,0 +1,123 @@+// @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.tsnew file mode 100644index 0000000000..81820e2d73--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/pinnedGhostTabs.ts@@ -0,0 +1,224 @@+/**+ * 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/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.tsindex b554420594..48c544050b 100644--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts@@ -21,6 +21,11 @@ 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');@@ -486,13 +491,18 @@ export async function ensureHydrated(sessionId: string): Promise<void> {* 不需要对称的"回滚回调":IPC 失败回滚时 store 自己走 `forgetClosedTab(id)` 把* 挂在这个 tabId 上的旁路记录(含 popup 标记)清掉 —— 与关闭路径同一个收尾函数。* 否则 DB / IPC 异常期间反复触发 popup,标记集合会随进程生命周期无界增长。+ *+ * `opts.activate === false`:追加 tab 但**不抢激活位**(cache 与 DB 的 active 都+ * 保持原样)。钉住面板的跨会话自动补挂用 —— 用户切到某会话时补挂的页签不该+ * 把他正看着的 tab 顶掉。默认 true 维持既有语义(用户手动加 tab = 看它)。*/export async function addTab(sessionId: string,kind: TabKindId,initialState: unknown = null,- opts?: { onOptimisticAdd?: (tabId: string) => void },+ opts?: { onOptimisticAdd?: (tabId: string) => void; activate?: boolean },): Promise<TabState> {+ const activate = opts?.activate !== false;const prev = getBucket(sessionId);if (prev.tabs.length >= MAX_TABS_PER_SESSION) {throw new Error(`session ${sessionId} already has ${MAX_TABS_PER_SESSION} tabs (limit reached)`);@@ -503,7 +513,10 @@ export async function addTab(const id = makeTabId();const position = prev.tabs.length;const newTab: TabState = { id, kind, state: initialState };- setBucket(sessionId, { tabs: [...prev.tabs, newTab], activeTabId: id });+ setBucket(sessionId, {+ tabs: [...prev.tabs, newTab],+ activeTabId: activate ? id : prev.activeTabId,+ });try {opts?.onOptimisticAdd?.(id);} catch {@@ -520,7 +533,7 @@ export async function addTab(const create = (async () => {await ipc.upsert({ id, sessionId, kind, position, state: initialState });rowCommitted = true;- await ipc.setActive({ sessionId, id });+ if (activate) await ipc.setActive({ sessionId, id });})();const persisted = create.then(() => true,@@ -575,6 +588,11 @@ 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) {@@ -666,7 +684,7 @@ export async function closeTab(}}- return enqueueCloseMutation(sessionId, async () => {+ const mutation = enqueueCloseMutation(sessionId, async () => {// 队列内重取快照:排在前面的关闭可能已经动过这个 bucket(甚至已经关掉了本// tab)。用旧快照算 nextTabs / 回滚基线正是并发出错的根源。const prev = getBucket(sessionId);@@ -800,6 +818,15 @@ 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);+ });}/** 关闭某个 session bucket 的全部 tab,逐个走 closeTab 以触发 plugin cleanup。 */diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 55d28e600a..86bd4977bb 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3674,6 +3674,8 @@"addAria": "Add tab","addFailed": "Failed to add tab","tabCloseAria": "Close tab",+ "pinAria": "Pin — keep in all conversations",+ "unpinAria": "Unpin — keep only in this conversation","menu": {"addLabel": "Add tab","comingSoon": "Coming soon",@@ -3699,7 +3701,9 @@"contextMenu": {"close": "Close","closeOthers": "Close others",- "closeAll": "Close all"+ "closeAll": "Close all",+ "pin": "Pin",+ "unpin": "Unpin"},"empty": {"eyebrow": "Right Sidebar",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex ee48322951..507d9cfd96 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3673,6 +3673,8 @@"addAria": "タブを追加","addFailed": "タブを追加できませんでした","tabCloseAria": "タブを閉じる",+ "pinAria": "ピン留め — すべてのセッションで保持",+ "unpinAria": "ピン留め解除 — このセッションのみ保持","menu": {"addLabel": "タブを追加","comingSoon": "近日対応",@@ -3698,7 +3700,9 @@"contextMenu": {"close": "閉じる","closeOthers": "他のタブを閉じる",- "closeAll": "すべて閉じる"+ "closeAll": "すべて閉じる",+ "pin": "ピン留め",+ "unpin": "ピン留め解除"},"empty": {"eyebrow": "右サイドバー",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 55fda0801d..7c761f403f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3673,6 +3673,8 @@"addAria": "탭 추가","addFailed": "탭을 추가하지 못했습니다","tabCloseAria": "탭 닫기",+ "pinAria": "고정 — 모든 세션에서 유지",+ "unpinAria": "고정 해제 — 현재 세션에서만 유지","menu": {"addLabel": "탭 추가","comingSoon": "지원 예정",@@ -3698,7 +3700,9 @@"contextMenu": {"close": "닫기","closeOthers": "다른 탭 닫기",- "closeAll": "모두 닫기"+ "closeAll": "모두 닫기",+ "pin": "고정",+ "unpin": "고정 해제"},"empty": {"eyebrow": "오른쪽 사이드바",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 3c310b8cf3..4c10df564a 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3673,6 +3673,8 @@"addAria": "添加标签","addFailed": "添加标签失败","tabCloseAria": "关闭标签",+ "pinAria": "钉住,在所有对话中保留",+ "unpinAria": "取消钉住,仅保留在当前对话","menu": {"addLabel": "添加标签","comingSoon": "即将支持",@@ -3698,7 +3700,9 @@"contextMenu": {"close": "关闭","closeOthers": "关闭其他",- "closeAll": "关闭所有"+ "closeAll": "关闭所有",+ "pin": "钉住",+ "unpin": "取消钉住"},"empty": {"eyebrow": "右侧栏",diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 6e4fcf9606..7e8199a6e8 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -184,6 +184,10 @@ issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mod个人微信连接在设置页中的产品名称;先登记为 proposed,待产品术语评审后再决定是否固化。+### Pin++右侧栏插件面板页签的图钉:钉住 = 面板在所有对话中保留。动词对:Pin=钉住 / Unpin=取消钉住。2026-07-31 随图钉功能提出,待裁决。+### Region badge桌面登录页标题旁的品牌红胶囊(DESIGN.md §16.3),指徽标这个 UI 元素本身。徽标上的标签值另立条目(region-code-cn / region-code-dev)——本条 en 为 Region badge、各语言译文均非英文原词,caseStandardFor 天然返回 null,所以本条约束不到标签值,也无需写 checkCase。作为待产品裁决术语登记:尚未拍板是否改为可译文案(如「中国大陆版 / Mainland China」),先登记以免后续界面自造“国内版/中国版/开发版”等多套说法。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 40cb311a31..4cf9be1404 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -597,6 +597,17 @@"note": "中文一律「插件」,不保留英文原词(现状 94:4)。历史上 Ghost / Plugin 两种叫法并存,对外统一为「插件」。","exempt": []},+ {+ "id": "pin",+ "status": "proposed",+ "en": "Pin",+ "translations": {+ "zh-CN": "钉住",+ "ja": "ピン留め",+ "ko": "고정"+ },+ "note": "右侧栏插件面板页签的图钉:钉住 = 面板在所有对话中保留。动词对:Pin=钉住 / Unpin=取消钉住。2026-07-31 随图钉功能提出,待裁决。"+ },{"id": "project","status": "decided",