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): 底栏状态卡基建:focusTraversal、statusBarCards、popover portalContainer

Zhang Yunjinac2bca604eed
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index 850bc625a1..06d3ef22e4 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -26,6 +26,7 @@ import type { TFunction } from 'i18next';
import { summarizeCodexRateLimitReset } from '@cindy/maker-shared/session-controls';
import { cn } from '@/lib/utils';
+import { handOffTabFromCard } from '@/lib/focusTraversal';
import { TASK_USAGE_ACCOUNT, type UsageAccountLocation } from '@/lib/usageAccountLocation';
import {
DAILY_SOFT_LIMIT_FACTOR,
@@ -36,6 +37,10 @@ import {
formatTurnCostUsd,
} from '@/lib/usageFormat';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import {
+ registerStatusBarCard,
+ type StatusBarCardHandle,
+} from '@/lib/statusBarCards';
import { useApiKey } from '@/hooks/useApiKey';
import { useClaudeOAuthConnected } from '@/hooks/useClaudeOAuthConnected';
import { useClaudeSessionRoute } from '@/hooks/useClaudeSessionRoute';
@@ -1058,6 +1063,11 @@ export function TodaySpendChip({
const quotaCardSessionUsage = toQuotaHoverCardSessionUsage(sessionUsage, sessionTokens);
const quotaCardTurnUsage = toQuotaHoverCardTurnUsage(latestTurnUsage, t);
const [quotaPopoverOpen, setQuotaPopoverOpen] = React.useState(false);
+ // 浮层宿主:紧跟触发器之后(见 popover.tsx 的 portalContainer 注释)。portal 到 body
+ // 末尾时,键盘焦点一旦进卡就再也 Tab 不回底栏(用户实测)。
+ const [quotaPopoverPortalHost, setQuotaPopoverPortalHost] = React.useState<HTMLDivElement | null>(
+ null,
+ );
const [resetListOpen, setResetListOpen] = React.useState(false);
const quotaPopoverOpenTimerRef = React.useRef<number | null>(null);
const quotaPopoverCloseTimerRef = React.useRef<number | null>(null);
@@ -1069,6 +1079,8 @@ export function TodaySpendChip({
const quotaPopoverTriggerRef = React.useRef<HTMLElement>(null);
const quotaPopoverContentRef = React.useRef<HTMLDivElement>(null);
const quotaPopoverDashboardButtonRef = React.useRef<HTMLButtonElement>(null);
+ // 底栏卡片互斥协调器的本实例句柄(见 statusBarCards:认实例,不认种类)。
+ const statusCardHandleRef = React.useRef<StatusBarCardHandle | null>(null);
const setQuotaPopoverFocusTarget = React.useCallback((node: HTMLElement | null) => {
quotaPopoverTriggerRef.current = node;
}, []);
@@ -1092,6 +1104,18 @@ export function TodaySpendChip({
quotaPopoverFocusTakenRef.current = false;
quotaPopoverOpenSourceRef.current = null;
if (!shouldRestoreFocus) return;
+ // Tab 已把焦点交给卡片外**仍然存在**的控件时不要抢回触发器:关闭路径
+ // (focus-outside → onOpenChange(false))会比浏览器的 Tab 目标更早执行,抢回焦点
+ // 就把 Tab 正要去的控件顶掉,实测表现为焦点在 trigger 与卡片之间反复弹、永远走不到
+ // 右边下一枚 chip(用户实测)。焦点在卡片里(Escape)、或卡片正在卸载而焦点即将掉
+ // 到 body(形态切换)时,照旧归还 —— 那两种情况下不归还就是用户丢焦点。
+ const activeElement = document.activeElement;
+ const focusStillOwned =
+ quotaPopoverTriggerRef.current === activeElement ||
+ quotaPopoverContentRef.current?.contains(activeElement) === true;
+ const focusLostOrDetached =
+ activeElement === null || activeElement === document.body || !activeElement.isConnected;
+ if (!focusStillOwned && !focusLostOrDetached) return;
quotaPopoverRestoringFocusRef.current = true;
quotaPopoverTriggerRef.current?.focus({ preventScroll: true });
quotaPopoverRestoringFocusRef.current = false;
@@ -1145,6 +1169,30 @@ export function TodaySpendChip({
scheduleQuotaPopoverOpen();
}, [scheduleQuotaPopoverOpen]);
+ // 底栏状态卡片互斥(用户要求"该窗体为唯一窗体"):本卡展开时请求独占(另一张立刻收起),
+ // 收起时让位;另一张卡展开时由协调器回调到这里立刻收起。
+ // 句柄认**本实例**:分屏可能同时挂载多份底栏,按种类登记会互相顶掉关闭回调。
+ React.useEffect(() => {
+ const handle = registerStatusBarCard('quota', () => {
+ keepQuotaPopoverOpen();
+ setQuotaPopoverOpen(false);
+ restoreQuotaPopoverFocus();
+ });
+ statusCardHandleRef.current = handle;
+ return () => {
+ statusCardHandleRef.current = null;
+ handle.unregister();
+ };
+ }, [keepQuotaPopoverOpen, restoreQuotaPopoverFocus]);
+ React.useEffect(() => {
+ if (!quotaPopoverOpen) {
+ statusCardHandleRef.current?.release();
+ return;
+ }
+ // 注册 effect 更早声明,挂载时句柄已就位;若还没就位(首帧即开着)则下帧重试。
+ statusCardHandleRef.current?.request();
+ }, [quotaPopoverOpen]);
+
const quotaPopoverContextRef = React.useRef({
identity: JSON.stringify([
sessionId,
@@ -1664,8 +1712,23 @@ export function TodaySpendChip({
{labelNode}
</button>
</PopoverTrigger>
+ {/* 浮层挂到触发器紧跟其后的宿主:DOM 顺序 = 视觉顺序,Tab 才能从卡片继续走到
+ 右边下一枚 chip(原实现 portal 到 body 末尾,焦点进卡后就出不来了)。 */}
+ <div ref={setQuotaPopoverPortalHost} className="contents" />
<PopoverContent
ref={quotaPopoverContentRef}
+ portalContainer={quotaPopoverPortalHost}
+ // Radix 给 FocusScope 写死 `loop:true`(见 popover.tsx):Tab 在卡内永远环回。
+ // 把两个 Tab 边缘接过来,让 Tab 能从卡片走到右边下一枚 chip(用户实测)。
+ onKeyDownCapture={(event) => {
+ if (event.key !== 'Tab') return;
+ const cardRoot = event.currentTarget;
+ if (!(cardRoot instanceof HTMLElement)) return;
+ if (handOffTabFromCard(cardRoot, event)) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }}
side="top"
align="end"
sideOffset={8}
diff --git a/apps/desktop/src/renderer/components/ui/popover.tsx b/apps/desktop/src/renderer/components/ui/popover.tsx
index 888d4558f6..6e21d0f9d0 100644
--- a/apps/desktop/src/renderer/components/ui/popover.tsx
+++ b/apps/desktop/src/renderer/components/ui/popover.tsx
@@ -11,9 +11,19 @@ const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ComponentRef<typeof PopoverPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
->(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (
- <PopoverPrimitive.Portal>
+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> & {
+ /**
+ * 浮层要挂到哪个节点(缺省 = body 末尾)。
+ *
+ * 底栏卡片必须传:portal 到 body 时它的 DOM 位置在文档最末,文档内它后面再没有
+ * 下一个可 Tab 节点,焦点一旦进卡就**再也回不到底栏**(用户实测:Tab 到用量卡后
+ * 翻多少次都到不了右边的窗口卡)。挂到触发器紧跟其后的宿主里,DOM 顺序 = 视觉顺序,
+ * Tab 就能从卡片继续走到右边下一枚 chip。
+ */
+ portalContainer?: HTMLElement | null;
+ }
+>(({ className, align = 'center', sideOffset = 4, portalContainer, ...props }, ref) => (
+ <PopoverPrimitive.Portal container={portalContainer ?? undefined}>
<PopoverPrimitive.Content
ref={ref}
align={align}
diff --git a/apps/desktop/src/renderer/lib/__tests__/focusTraversal.test.tsx b/apps/desktop/src/renderer/lib/__tests__/focusTraversal.test.tsx
new file mode 100644
index 0000000000..bbd1cccd3e
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/focusTraversal.test.tsx
@@ -0,0 +1,77 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it } from 'vitest';
+import { cleanup, fireEvent, render } from '@testing-library/react';
+import { useState } from 'react';
+
+import { handOffTabFromCard } from '../focusTraversal';
+
+/**
+ * 模拟底栏形态:触发器、紧随其后的浮层宿主(卡内若干可聚焦元素)、
+ * 宿主之后的下一枚 chip —— 与底栏修复后的 DOM 顺序一致。
+ */
+function CardHarness({ extraInsideMiddle }: { extraInsideMiddle?: boolean }) {
+ const [host, setHost] = useState<HTMLDivElement | null>(null);
+ return (
+ <>
+ <button type="button" id="usage-chip">用量明细</button>
+ <div ref={setHost} data-testid="card-host">
+ {host && (
+ <div id="card-root" data-testid="card-root">
+ <button type="button" id="card-region">卡内滚动区</button>
+ {extraInsideMiddle && <button type="button" id="card-middle">卡内中间</button>}
+ <button type="button" id="card-last">卡内最后一档</button>
+ </div>
+ )}
+ </div>
+ <button type="button" id="ctx-chip">任务上下文窗口</button>
+ <button type="button" id="ring">点击压缩上下文</button>
+ </>
+ );
+}
+
+describe('handOffTabFromCard', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('Tab 在卡内最后一个可 Tab 边缘时,把焦点交出卡外(下一枚 chip)', () => {
+ render(<CardHarness />);
+ const cardRoot = document.getElementById('card-root')!;
+ const last = document.getElementById('card-last')!;
+ const ctxChip = document.getElementById('ctx-chip')!;
+
+ last.focus();
+ const handled = handOffTabFromCard(cardRoot, { shiftKey: false });
+ expect(handled).toBe(true);
+ expect(document.activeElement).toBe(ctxChip);
+ });
+
+ it('Shift+Tab 在卡内第一个可 Tab 边缘时,把焦点交出卡外(上一枚 chip / 触发器)', () => {
+ render(<CardHarness />);
+ const cardRoot = document.getElementById('card-root')!;
+ document.getElementById('card-region')!.focus();
+ const usage = document.getElementById('usage-chip')!;
+
+ expect(handOffTabFromCard(cardRoot, { shiftKey: true })).toBe(true);
+ expect(document.activeElement).toBe(usage);
+ });
+
+ it('卡内中间元素的 Tab 不接管(让浏览器的自然顺序继续走)', () => {
+ render(<CardHarness extraInsideMiddle />);
+ const cardRoot = document.getElementById('card-root')!;
+ document.getElementById('card-region')!.focus();
+ expect(handOffTabFromCard(cardRoot, { shiftKey: false })).toBe(false);
+ // 自然行为:调用方不 preventDefault,浏览器把焦点走到下一个元素(中间档)。
+ expect(document.activeElement).toBe(document.getElementById('card-region'));
+ fireEvent.keyDown(document.getElementById('card-region')!, { key: 'Tab' });
+ expect(document.activeElement).toBe(document.getElementById('card-region'));
+ });
+
+ it('焦点不在卡内时不做任何事', () => {
+ render(<CardHarness />);
+ const cardRoot = document.getElementById('card-root')!;
+ document.getElementById('ctx-chip')!.focus();
+ expect(handOffTabFromCard(cardRoot, { shiftKey: false })).toBe(false);
+ expect(document.activeElement).toBe(document.getElementById('ctx-chip'));
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/__tests__/statusBarCards.test.ts b/apps/desktop/src/renderer/lib/__tests__/statusBarCards.test.ts
new file mode 100644
index 0000000000..3a1ed55484
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/statusBarCards.test.ts
@@ -0,0 +1,109 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ registerStatusBarCard,
+ resetStatusBarCardsForTest,
+} from '../statusBarCards';
+
+beforeEach(() => {
+ resetStatusBarCardsForTest();
+});
+
+/**
+ * 协调器的语义:`request()` = 「本实例成为唯一展开的卡片」,于是**立即通知所有其它登记实例关闭**
+ * (包括从未真正展开过的那些 —— 它们的 close 是幂等的,关一张没开的卡不产生副作用)。
+ * 要点是「自己不关自己」与「同种类的另一张也会被关」。
+ */
+describe('statusBarCards 互斥协调器', () => {
+ it('跨种类互斥:展开的那张让另一张立刻收起,自己不关自己', () => {
+ const closeQuota = vi.fn();
+ const closeWindow = vi.fn();
+ registerStatusBarCard('quota', closeQuota);
+ const windowCard = registerStatusBarCard('context-window', closeWindow);
+
+ windowCard.request();
+ expect(closeQuota).toHaveBeenCalledTimes(1);
+ expect(closeWindow).not.toHaveBeenCalled();
+ });
+
+ it('同种类的第二个实例也能抢到独占权(分屏同时挂载两份底栏)', () => {
+ // 分屏 / Orca 面板会同时挂载多个会话视图:按种类登记会互相顶掉关闭回调,
+ // 让两张档位卡一起亮着 —— 这正是本协调器要守住的不变量。
+ const closePaneA = vi.fn();
+ const closePaneB = vi.fn();
+ const paneA = registerStatusBarCard('context-window', closePaneA);
+ const paneB = registerStatusBarCard('context-window', closePaneB);
+
+ paneB.request();
+ expect(closePaneA).toHaveBeenCalledTimes(1);
+ expect(closePaneB).not.toHaveBeenCalled();
+
+ paneA.request();
+ expect(closePaneB).toHaveBeenCalledTimes(1);
+ });
+
+ it('同一实例重复 request 是幂等的(不会反复关别人)', () => {
+ const closeQuota = vi.fn();
+ registerStatusBarCard('quota', closeQuota);
+ const windowCard = registerStatusBarCard('context-window', vi.fn());
+
+ windowCard.request();
+ windowCard.request();
+ expect(closeQuota).toHaveBeenCalledTimes(1);
+ });
+
+ it('release 只对自己生效:非独占者 release 不会把独占位让给别人', () => {
+ const closeQuota = vi.fn();
+ const quota = registerStatusBarCard('quota', closeQuota);
+ const windowCard = registerStatusBarCard('context-window', vi.fn());
+
+ quota.request();
+ windowCard.release(); // window 从来不是独占者 → 这次 release 应当无效
+ windowCard.request(); // 仍然能正常抢到独占(并关掉 quota)
+ expect(closeQuota).toHaveBeenCalledTimes(1);
+ });
+
+ it('release 之后同类实例可以再次抢到独占权', () => {
+ const closeQuota = vi.fn();
+ registerStatusBarCard('quota', closeQuota);
+ const windowCard = registerStatusBarCard('context-window', vi.fn());
+
+ windowCard.request();
+ windowCard.release();
+ windowCard.request();
+ expect(closeQuota).toHaveBeenCalledTimes(2);
+ });
+
+ it('卸载(unregister)会清掉自己的登记,并让出独占位', () => {
+ const closeQuota = vi.fn();
+ const quota = registerStatusBarCard('quota', closeQuota);
+ const windowCard = registerStatusBarCard('context-window', vi.fn());
+
+ windowCard.request();
+ expect(closeQuota).toHaveBeenCalledTimes(1); // window 抢到独占 → quota 被关
+ windowCard.unregister();
+ windowCard.request(); // 已注销:句柄不再有任何协调权限
+ expect(closeQuota).toHaveBeenCalledTimes(1);
+
+ // 独占位已让出 → quota 成为独占者;此时库里已无其它实例,自然没有新的关闭调用。
+ quota.request();
+ expect(closeQuota).toHaveBeenCalledTimes(1);
+ });
+
+ it('同种类先注册者卸载后,后注册者仍是有效独占者且不再关已注销实例', () => {
+ const closePaneA = vi.fn();
+ const closePaneB = vi.fn();
+ const paneA = registerStatusBarCard('context-window', closePaneA);
+ const paneB = registerStatusBarCard('context-window', closePaneB);
+
+ paneA.request(); // 同种类的另一份在登记表里 → 会收到关闭(真实 chip 里这是幂等的)
+ expect(closePaneB).toHaveBeenCalledTimes(1);
+ paneA.unregister();
+ closePaneB.mockClear();
+
+ paneB.request();
+ expect(closePaneA).not.toHaveBeenCalled();
+ expect(closePaneB).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/focusTraversal.ts b/apps/desktop/src/renderer/lib/focusTraversal.ts
new file mode 100644
index 0000000000..da17eadae7
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/focusTraversal.ts
@@ -0,0 +1,80 @@
+/**
+ * 底栏卡片的 Tab 走廊:把「卡片内最后一个/第一个可 Tab 边缘」的 Tab 交出卡外。
+ *
+ * 为什么需要:Radix 的 `PopoverContentImpl` 给 FocusScope 写死 `loop: true`
+ * (trapped 才跟随 modal),Tab 在卡内永远环回 —— 键盘焦点一旦进卡,就再也走不到
+ * 底栏右边下一枚 chip(用户实测:Tab 到「用量明细」卡后停在原地)。
+ * Radix 不透传 `loop`,所以我们在它之前(React 的 onKeyDownCapture 先于同元素的
+ * onKeyDown bubble)接管卡的两个 Tab 边缘:
+ * - Tab 在**最后一个**可 Tab 边 → 焦点交给卡外 DOM 序的下一个可 Tab 元素;
+ * - Shift+Tab 在**第一个**可 Tab 边 → 焦点交给卡外 DOM 序的上一个(回到触发器方向)。
+ * 卡内其余 Tab 行为不变(多行卡的行间移动照旧自然进行)。
+ */
+
+/** 文档序的全部可 Tab 元素(可见性判据与 Radix FocusScope 的 getTabbableCandidates 同源)。 */
+function collectTabbables(root: Document): HTMLElement[] {
+ const nodes: HTMLElement[] = [];
+ const walkerRoot = root.documentElement ?? root.body;
+ if (!walkerRoot) return nodes;
+ const walker = root.createTreeWalker(walkerRoot, NodeFilter.SHOW_ELEMENT, {
+ acceptNode: (node) => {
+ const element = node as HTMLElement;
+ const isHiddenInput = element instanceof HTMLInputElement && element.type === 'hidden';
+ if (element.hasAttribute('disabled') || element.hidden || isHiddenInput) {
+ return NodeFilter.FILTER_SKIP;
+ }
+ return element.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
+ },
+ });
+ while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement);
+ return nodes.filter((element) => !isHiddenForFocus(element));
+}
+
+function isHiddenForFocus(node: HTMLElement): boolean {
+ if (node.ownerDocument.defaultView?.getComputedStyle(node).visibility === 'hidden') return true;
+ let cursor: HTMLElement | null = node;
+ while (cursor) {
+ if (cursor.ownerDocument.defaultView?.getComputedStyle(cursor).display === 'none') return true;
+ cursor = cursor.parentElement;
+ }
+ return false;
+}
+
+/**
+ * Tab 出卡:`cardRoot` 是浮层内容根(`PopoverContent` 渲染的元素)。
+ * 返回 true = 本次 Tab 已被接管(调用方应阻止默认行为与 Radix 的环回)。
+ */
+export function handOffTabFromCard(
+ cardRoot: HTMLElement,
+ event: { shiftKey: boolean },
+): boolean {
+ const tabbables = collectTabbables(cardRoot.ownerDocument);
+ if (tabbables.length === 0) return false;
+ const active = cardRoot.ownerDocument.activeElement;
+ if (!(active instanceof HTMLElement) || !cardRoot.contains(active)) return false;
+
+ const activeIndex = tabbables.indexOf(active);
+ if (activeIndex === -1) return false;
+ const lastInside = (() => {
+ for (let i = tabbables.length - 1; i >= 0; i -= 1) {
+ if (cardRoot.contains(tabbables[i]!)) return i;
+ }
+ return -1;
+ })();
+ const firstInside = tabbables.findIndex((element) => cardRoot.contains(element));
+ if (lastInside === -1 || firstInside === -1) return false;
+
+ if (!event.shiftKey && active === tabbables[lastInside]!) {
+ const next = tabbables[lastInside + 1];
+ if (!next) return false;
+ next.focus();
+ return true;
+ }
+ if (event.shiftKey && active === tabbables[firstInside]!) {
+ const previous = firstInside > 0 ? tabbables[firstInside - 1]! : null;
+ if (!previous) return false;
+ previous.focus();
+ return true;
+ }
+ return false;
+}
diff --git a/apps/desktop/src/renderer/lib/statusBarCards.ts b/apps/desktop/src/renderer/lib/statusBarCards.ts
new file mode 100644
index 0000000000..b8f33a1c64
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/statusBarCards.ts
@@ -0,0 +1,68 @@
+/**
+ * statusBarCards —— 底栏状态卡片(货币 chip 的「用量明细」卡、任务窗口 chip 的档位卡)的
+ * **互斥**协调器:同一时刻只允许展开一张。打开一张会立刻请求另一张关闭 —— 用户要求
+ * 「该窗体为唯一窗体,显示 ¥ 的窗体就不要显示 [] 的,反之亦然」。
+ *
+ * 悬浮卡的节奏(打开延迟 / 离开宽限)也放在这里:两张卡必须是同一套手感,
+ * 各写一份数字必然漂移(`TodaySpendChip` 的 `QUOTA_POPOVER_*` 与本模块取值一致)。
+ *
+ * **登记单位是「实例」而不是「卡片种类」**:分屏 / Orca 面板会同时挂载多个会话视图,
+ * 于是同一种卡片可能同时存在两份(两个 chip 各有自己的 `open` state)。若只按种类登记,
+ * 后挂载的那份会覆盖先挂载那份的关闭回调,且「种类已经是当前」会让第二份跳过关闭动作,
+ * 两张卡就会一起亮着。所以句柄持有 token,`request()` 认的是「我这个实例」。
+ */
+
+/** 悬浮后延迟这么久才展开(与用量卡一致):扫过去不该弹卡。 */
+export const STATUS_CARD_HOVER_OPEN_DELAY_MS = 300;
+/** 指针离开后的宽限:够移到卡片上,不至于闪一下就没。 */
+export const STATUS_CARD_HOVER_CLOSE_GRACE_MS = 200;
+
+export type StatusBarCardId = 'quota' | 'context-window';
+
+/** 一个卡片实例的协调句柄(由 `registerStatusBarCard` 返回)。 */
+export type StatusBarCardHandle = {
+ /** 声明本实例成为当前展开的卡片:其它实例(含同种类的另一张)立刻关闭。 */
+ request: () => void;
+ /** 本实例收起时让出「当前卡片」位置(不然后续 request 会误判成"已经是我")。 */
+ release: () => void;
+ /** 本实例卸载:注销登记(若自己是当前卡片,位置一并让出)。 */
+ unregister: () => void;
+};
+
+const registrations = new Map<symbol, { id: StatusBarCardId; close: () => void }>();
+let activeToken: symbol | null = null;
+
+/** 注册某张卡片实例的「立刻关闭」入口;返回句柄(卸载时调用 `unregister`)。 */
+export function registerStatusBarCard(id: StatusBarCardId, close: () => void): StatusBarCardHandle {
+ const token = Symbol(id);
+ registrations.set(token, { id, close });
+ // 注销后的句柄不再有任何协调权限:卸载路径可能把清理排在下一次 request 之后执行,
+ // 已销毁的实例不该再抢独占位、也不该再把别人关掉。
+ let registered = true;
+ return {
+ request() {
+ if (!registered) return;
+ if (activeToken === token) return;
+ activeToken = token;
+ // 关掉所有**其它实例**:包括同种类的另一张(分屏场景),这是本协调器的全部意义。
+ for (const [otherToken, entry] of [...registrations]) {
+ if (otherToken !== token) entry.close();
+ }
+ },
+ release() {
+ if (!registered) return;
+ if (activeToken === token) activeToken = null;
+ },
+ unregister() {
+ registered = false;
+ registrations.delete(token);
+ if (activeToken === token) activeToken = null;
+ },
+ };
+}
+
+/** 仅供测试:清掉跨用例的注册状态。 */
+export function resetStatusBarCardsForTest(): void {
+ registrations.clear();
+ activeToken = null;
+}