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): 侧边栏 mod+1..9 快速切换对话并按住修饰键浮现序号徽标 (#1184)

Kafeifei541d0a9b52dd
diff --git a/apps/desktop/src/main/__tests__/appShortcuts.test.ts b/apps/desktop/src/main/__tests__/appShortcuts.test.ts
index 8ea28af9dd..5481e2aba3 100644
--- a/apps/desktop/src/main/__tests__/appShortcuts.test.ts
+++ b/apps/desktop/src/main/__tests__/appShortcuts.test.ts
@@ -6,7 +6,9 @@ import {
appShortcutScopesOverlap,
comboToElectronAccelerator,
createAppShortcutComboFromEvent,
+ findAppShortcutConflict,
formatAppShortcutCombo,
+ getAppShortcutDefinition,
getEffectiveAppShortcuts,
isAppShortcutAvailableOnPlatform,
isAppShortcutComboBindable,
@@ -14,6 +16,7 @@ import {
matchesKeyboardEvent,
normalizeAppShortcutCombo,
normalizeAppShortcutOverrides,
+ SWITCH_SESSION_SHORTCUT_IDS,
type AppShortcutCombo,
} from '../../shared/appShortcuts';
import { isMacReservedShortcut, isWindowsReservedShortcut } from '../../shared/keyboardReserved';
@@ -315,3 +318,82 @@ describe('shared reserved-shortcut tables (extracted from voice-input)', () => {
expect(isWindowsReservedShortcut({ code: 'Tab', meta: false, ctrl: true, alt: false, shift: true })).toBe(false);
});
});
+
+describe('switch-session slots (mod+1..9)', () => {
+ it('binds the nine slots to Digit1..9 in order with mod per platform', () => {
+ expect(SWITCH_SESSION_SHORTCUT_IDS).toHaveLength(9);
+ SWITCH_SESSION_SHORTCUT_IDS.forEach((id, index) => {
+ const def = getAppShortcutDefinition(id);
+ expect(def.scope).toBe('app');
+ expect(def.rebindable).toBe(true);
+ expect(def.hiddenInSettings).toBe(true);
+ expect(def.getDefaultCombos('darwin')).toEqual([combo(`Digit${index + 1}`, { meta: true })]);
+ expect(def.getDefaultCombos('win32')).toEqual([combo(`Digit${index + 1}`, { ctrl: true })]);
+ expect(def.getDefaultCombos('linux')).toEqual([combo(`Digit${index + 1}`, { ctrl: true })]);
+ });
+ });
+
+ it('default combos convert to accelerators and display labels', () => {
+ const mac = getAppShortcutDefinition('switch-session-1').getDefaultCombos('darwin')[0];
+ expect(comboToElectronAccelerator(mac, 'darwin')).toBe('Command+1');
+ expect(formatAppShortcutCombo(mac, 'darwin')).toBe('⌘1');
+ const win = getAppShortcutDefinition('switch-session-9').getDefaultCombos('win32')[0];
+ expect(comboToElectronAccelerator(win, 'win32')).toBe('Ctrl+9');
+ expect(formatAppShortcutCombo(win, 'win32')).toBe('Ctrl+9');
+ });
+
+ it('default combos are not reserved on either platform', () => {
+ for (const id of SWITCH_SESSION_SHORTCUT_IDS) {
+ const def = getAppShortcutDefinition(id);
+ expect(isMacReservedShortcut(def.getDefaultCombos('darwin')[0])).toBe(false);
+ expect(isWindowsReservedShortcut(def.getDefaultCombos('win32')[0])).toBe(false);
+ }
+ });
+
+ // 升级路径:老版本用户把可改绑快捷键改绑到 mod+N(当时空闲、写入合法),
+ // 升级后与隐藏槽位默认撞键。冲突只在写入时校验、load 不重查,且隐藏条目
+ // 用户看不到也解不开 —— 生效表合并必须让用户 override 获胜,否则一次按键
+ // 双动作并发。
+ it('stale user override wins over a hidden slot default (upgrade path)', () => {
+ const stale = combo('Digit1', { meta: true });
+ const effective = getEffectiveAppShortcuts({ 'toggle-sidebar': stale }, 'darwin');
+ expect(effective.get('toggle-sidebar')).toEqual([stale]);
+ expect(effective.get('switch-session-1')).toEqual([]);
+ expect(effective.get('switch-session-2')).toEqual([combo('Digit2', { meta: true })]);
+ });
+
+ it('binding onto an un-overridden hidden slot default is not a conflict', () => {
+ expect(findAppShortcutConflict('toggle-sidebar', combo('Digit1', { meta: true }), {}, 'darwin')).toBeNull();
+ });
+
+ // registry 之外体系(语音输入)的历史键位同样让隐藏槽位默认让位 ——
+ // 消费端把语音快捷键转成 combo 后经 yieldToCombos 传入。
+ it('hidden slot defaults yield to external combos (voice input shortcut)', () => {
+ const voiceCombo = combo('Digit3', { ctrl: true });
+ const effective = getEffectiveAppShortcuts({}, 'win32', [voiceCombo]);
+ expect(effective.get('switch-session-3')).toEqual([]);
+ expect(effective.get('switch-session-4')).toEqual([combo('Digit4', { ctrl: true })]);
+ // 可见条目不受 yieldToCombos 影响
+ expect(effective.get('toggle-sidebar')).toEqual([combo('KeyB', { ctrl: true })]);
+ });
+
+ it('visible defaults still conflict as before', () => {
+ expect(findAppShortcutConflict('toggle-sidebar', combo('KeyF', { meta: true }), {}, 'darwin')).toBe(
+ 'find-in-page',
+ );
+ });
+
+ // 让位范围严格限定 yieldsToUserBindings 槽位:save-file / open-settings 等
+ // 同样 hiddenInSettings 的惯例键不让位 —— 否则把别的键改绑到 ⌘S 会被放行,
+ // 用户静默失去保存快捷键(Codex review P2)。
+ it('conventional hidden defaults (save-file / open-settings) neither yield nor stop conflicting', () => {
+ const sCombo = combo('KeyS', { meta: true });
+ expect(findAppShortcutConflict('find-in-page', sCombo, {}, 'darwin')).toBe('save-file');
+ expect(findAppShortcutConflict('find-in-page', combo('Comma', { meta: true }), {}, 'darwin')).toBe(
+ 'open-settings',
+ );
+ // 防御:即便异常写入了撞 ⌘S 的 override,save-file 的默认也不被过滤。
+ const effective = getEffectiveAppShortcuts({ 'find-in-page': sCombo }, 'darwin');
+ expect(effective.get('save-file')).toEqual([sCombo]);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
index 3142104589..5ddccc2a77 100644
--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
@@ -30,7 +30,7 @@ import {
import { useVoiceInputModelSelection } from '@/hooks/useVoiceInputModelSelection';
import { useVoiceInputUsageStats } from '@/hooks/useVoiceInputUsageStats';
import { useVoiceInputHistory } from '@/hooks/useVoiceInputHistory';
-import { getAppShortcutCombos } from '@/lib/appShortcutStore';
+import { getAppShortcutCombos, getAppShortcutOverrides } from '@/lib/appShortcutStore';
import { toast } from '@/lib/toast';
import {
APP_SHORTCUT_DEFINITIONS,
@@ -1392,14 +1392,19 @@ export function VoiceInputSection() {
[schedulePermissionRefresh, setShortcut, t],
);
- const getAppShortcutEntries = useCallback(
- (): AppShortcutComboEntry[] =>
- APP_SHORTCUT_DEFINITIONS.map((def) => ({
- id: def.id,
- combos: getAppShortcutCombos(def.id),
- })),
- [],
- );
+ const getAppShortcutEntries = useCallback((): AppShortcutComboEntry[] => {
+ // 未被 override 的让位槽位(switch-session-*,yieldsToUserBindings)不算
+ // 占用:语音录制提交后 appShortcutStore 会经 yieldToCombos 压掉该槽位
+ // 默认,用户显式录制获胜 —— 与 findAppShortcutConflict 对 app 快捷键
+ // 改绑的放行同一规则,否则存量语音绑定能赢、新录制却被卡死。
+ const overrides = getAppShortcutOverrides();
+ return APP_SHORTCUT_DEFINITIONS.filter(
+ (def) => !(def.yieldsToUserBindings && overrides[def.id] === undefined),
+ ).map((def) => ({
+ id: def.id,
+ combos: getAppShortcutCombos(def.id),
+ }));
+ }, []);
const handleShortcutKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLButtonElement>) => {
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index e0535af103..e18284a20f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -29,6 +29,15 @@ import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
import { useCCSessions } from '@/hooks/useCCSessions';
import { refreshPendingAlerts, usePendingAlertAttention } from '@/hooks/usePendingAlertAttention';
+import { useAppShortcut } from '@/hooks/useAppShortcut';
+import { useModifierHold } from '@/hooks/useModifierHold';
+import { isSecondaryWindow } from '@/lib/secondaryWindow';
+import { getAppShortcutCombos, getAppShortcutPlatform } from '@/lib/appShortcutStore';
+import {
+ formatAppShortcutCombo,
+ SWITCH_SESSION_SHORTCUT_IDS,
+} from '../../../shared/appShortcuts';
+import { setSessionOrdinalBadges } from './sidebar/sessionOrdinalBadges';
import { useSidebarCollapsedState } from '../feature-context';
import { stripTrailingPathSeparators } from '../../../shared/pathText';
import { useRefreshWorktrees } from '@/contexts/WorktreeContext';
@@ -1493,6 +1502,80 @@ function ExpandedView({
[navigate, clearNotification, markAutomationSessionRunsRead],
);
+ /* ---- mod+1..9 快速切换对话 + 按住修饰键浮现序号徽标(复刻 Codex 桌面版) ----
+ * 序号口径 = getVisibleSidebarSessionIds 的渲染顺序(含置顶区),与 shift 范围
+ * 多选 / 删除后跳转同一权威实现。副窗不启用:副窗侧栏默认折叠,快捷键切副窗
+ * 自己的列表反直觉。搜索 overlay 打开(search.trimmed 非空)时同样让路:
+ * overlay 盖住列表,槽位仍指向被盖住的行会无提示跳到看不见的目标,徽标也
+ * 被遮住。折叠态自然失效:隐藏 wrapper 里的行被可见性过滤剔除,handler
+ * 拿不到目标返回 false 让路。 */
+ const sessionSwitchEnabled = !isSecondaryWindow() && !search.trimmed;
+ const handleSwitchSessionSlot = useCallback(
+ (slotIndex: number) => {
+ const visibleIds = getVisibleSidebarSessionIds(sidebarScrollRef.current);
+ const id = visibleIds[slotIndex];
+ if (!id) return false;
+ // 复用行点击唯一入口,继承清通知 / 同对话去重 / Orca 角色路由。
+ void handleSessionClick(id);
+ return true;
+ },
+ [handleSessionClick],
+ );
+ useAppShortcut('switch-session-1', () => handleSwitchSessionSlot(0), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-2', () => handleSwitchSessionSlot(1), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-3', () => handleSwitchSessionSlot(2), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-4', () => handleSwitchSessionSlot(3), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-5', () => handleSwitchSessionSlot(4), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-6', () => handleSwitchSessionSlot(5), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-7', () => handleSwitchSessionSlot(6), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-8', () => handleSwitchSessionSlot(7), { enabled: sessionSwitchEnabled });
+ useAppShortcut('switch-session-9', () => handleSwitchSessionSlot(8), { enabled: sessionSwitchEnabled });
+
+ // 按住态徽标 map:按当前可见顺序构建,并在按住期间用 MutationObserver 跟随
+ // 列表变化重建 —— 后台事件(自动化会话冒顶、远程会话上线等)可实时重排列表,
+ // 徽标必须与执行侧 handler 的实时取值保持同一口径,否则显示的序号会指向
+ // 重排前的行。标签取生效组合的显示形(mac '⌘1' / win 'Ctrl+1',跟随用户
+ // 改绑),删除绑定或让位后的槽位无徽标。写入 sessionOrdinalBadges 模块
+ // store,由 SessionItem / SessionCard 精准订阅。
+ const switchModifierHeld = useModifierHold({ enabled: sessionSwitchEnabled });
+ useEffect(() => {
+ if (!switchModifierHeld) return;
+ let lastSerialized: string | null = null;
+ const rebuild = () => {
+ const visibleIds = getVisibleSidebarSessionIds(sidebarScrollRef.current);
+ const platform = getAppShortcutPlatform();
+ const badges = new Map<string, string>();
+ SWITCH_SESSION_SHORTCUT_IDS.forEach((shortcutId, index) => {
+ const sessionId = visibleIds[index];
+ if (!sessionId) return;
+ const combo = getAppShortcutCombos(shortcutId)[0];
+ if (!combo) return;
+ badges.set(sessionId, formatAppShortcutCombo(combo, platform));
+ });
+ // 内容级去重:徽标自身的插入/移除同样触发 observer 回调,相同内容不再
+ // 写 store,切断 set → 渲染 → observe → set 的空转循环。
+ const serialized = JSON.stringify([...badges]);
+ if (serialized === lastSerialized) return;
+ lastSerialized = serialized;
+ setSessionOrdinalBadges(badges);
+ };
+ rebuild();
+ const root = sidebarScrollRef.current;
+ const observer = root == null ? null : new MutationObserver(rebuild);
+ if (root != null && observer != null) {
+ observer.observe(root, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['class', 'hidden'],
+ });
+ }
+ return () => {
+ observer?.disconnect();
+ setSessionOrdinalBadges(null);
+ };
+ }, [switchModifierHeld]);
+
/* ---- Project 行内的 + 按钮:对标顶部 "+ New"——预填该 project 的 workingDir 后进 draft 路由 ----
* patchNewMakerDraft({ workingDir }) 把目录写进 transient draft store,
* 然后 navigate('/cc-agent/new');NewMakerDraftRoute 渲染时 vendor 用 draft.vendor(用户上次选择)。
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index c98155dfaf..3ae97f5625 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -32,6 +32,7 @@ import { WorktreeBadge } from '@/components/sidebar/WorktreeBadge';
import { SessionStatusIcon } from './SessionStatusIcon';
import { ScheduleBindingBadge } from './ScheduleBindingBadge';
import { AutomationTimerIcon } from './AutomationTimerIcon';
+import { SessionOrdinalBadgeKbd, useSessionOrdinalBadge } from './sessionOrdinalBadges';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import { makerChatStore } from '@/lib/makerChatStore';
import {
@@ -127,6 +128,8 @@ export function SessionCard({
}: SessionCardProps) {
const { t } = useTranslation();
const navigate = useNavigate();
+ // mod+1..9 序号徽标:模块 store 按 sessionId 精准订阅,非按住态恒为 null。
+ const ordinalBadgeLabel = useSessionOrdinalBadge(session.id);
// 灵动岛同源的 per-session 实时活动(执行中逐步活动 + 等待交互态)。
const islandActivity = useAgentIslandActivity(session.id);
const isPinned = session.pinnedAt != null;
@@ -612,6 +615,7 @@ export function SessionCard({
onArchiveNow={() => onAction(session.id, 'archive-now')}
canUnarchive={!remoteWritesBlocked}
onUnarchive={handleUnarchiveSelect}
+ yieldToOrdinalBadge={ordinalBadgeLabel != null}
/>
)}
</div>
@@ -809,6 +813,26 @@ export function SessionCard({
</div>
)}
+ {/* mod+1..9 序号徽标(按住修饰键浮现,见 sessionOrdinalBadges):贴右上
+ 时间槽位置(TimeActionsSlot 同步让位),卡片多行故不垂直居中;z-20
+ 压过 hover 操作钮,pointer-events-none 不挡点击。前景色与时间同色系,
+ kbd 内 text-current + currentColor 底自动跟随。编辑态让位给重命名
+ 输入框。 */}
+ {!isEditing && ordinalBadgeLabel != null && (
+ <span
+ className={cn(
+ 'pointer-events-none absolute right-2 top-2 z-20 flex',
+ isActive
+ ? 'text-sidebar-item-active-foreground'
+ : isMuted
+ ? 'text-[var(--text-disabled)]'
+ : 'text-[var(--text-tertiary)]',
+ )}
+ >
+ <SessionOrdinalBadgeKbd label={ordinalBadgeLabel} />
+ </span>
+ )}
+
{/* 右键菜单——与 SessionItem 同款 coordinate-anchored DropdownMenu */}
{!isEditing && (
<DropdownMenu
@@ -950,6 +974,7 @@ function TimeActionsSlot({
onOpenMenu,
onArchiveNow,
onUnarchive,
+ yieldToOrdinalBadge = false,
}: {
sessionId: string;
activityIso: string;
@@ -965,6 +990,8 @@ function TimeActionsSlot({
onOpenMenu: (e: ReactMouseEvent<HTMLButtonElement>) => void;
onArchiveNow: () => void;
onUnarchive: () => void;
+ /** mod+1..9 序号徽标出现时让位:徽标独占右缘,不与时间/badge 并排。 */
+ yieldToOrdinalBadge?: boolean;
}) {
const { t } = useTranslation();
return (
@@ -975,7 +1002,7 @@ function TimeActionsSlot({
// duration 与操作钮的渐显同拍(120ms),让位/回归一进一出同步。
'flex items-center gap-1 transition-opacity duration-[120ms]',
!archivePending && 'group-hover/card:opacity-0',
- (menuOpen || archivePending) && 'opacity-0',
+ (menuOpen || archivePending || yieldToOrdinalBadge) && 'opacity-0',
)}
>
<WorktreeBadge sessionId={sessionId} size={11} className="size-3.5" />
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index fbbe2fc7ed..dd5d95fd9f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -77,6 +77,7 @@ import { loadScheduleSidebarIndexRuns, type ScheduleSidebarIndexRun } from '@/fe
import { useSchedulesSnapshot } from '@/features/scheduler/lib/schedulesStore';
import { scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBinding';
import { ScheduleBindingBadge } from './ScheduleBindingBadge';
+import { SessionOrdinalBadgeKbd, useSessionOrdinalBadge } from './sessionOrdinalBadges';
import { SessionProjectMoveSubmenu } from './SessionProjectMoveSubmenu';
import type { SessionMoveTarget } from './sessionMoveTarget';
import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
@@ -195,6 +196,9 @@ export const SessionItem = memo(function SessionItem({
}: SessionItemProps) {
const { t } = useTranslation();
const prRefs = usePrRefsForSession(session.id);
+ // mod+1..9 序号徽标:模块 store 按 sessionId 精准订阅(性能不变量第 2 条),
+ // 非按住态恒为 null,不惊动 memo。
+ const ordinalBadgeLabel = useSessionOrdinalBadge(session.id);
const isPinned = session.pinnedAt != null;
const isEmpty = isEmptyDraftSession(session);
// 取 userSendAt 与 updatedAt 中较新的值,兼容存量 DB 行(旧版只写 userSendAt),
@@ -764,6 +768,8 @@ export const SessionItem = memo(function SessionItem({
!archivePending && 'group-hover:opacity-0 group-focus-within/slot:opacity-0',
menuPos !== null && 'opacity-0',
archivePending && 'opacity-0',
+ // mod+1..9 序号徽标出现时同样让位:徽标独占行尾,不与时间/badge 并排。
+ ordinalBadgeLabel != null && 'opacity-0',
)}
>
<WorktreeBadge sessionId={session.id} size={12} className="size-4" />
@@ -933,6 +939,22 @@ export const SessionItem = memo(function SessionItem({
</div>
)}
+ {/* mod+1..9 序号徽标(按住修饰键浮现,见 sessionOrdinalBadges):绝对定位
+ 在右侧时间槽位置(与行 pr-2 对齐),时间/badge 容器同步让位淡出;
+ z-20 压过 hover 操作钮,pointer-events-none 不挡点击。前景色给到
+ 容器:普通行次级灰、active 反色行用 active foreground,kbd 内
+ text-current + currentColor 底自动跟随。编辑态让位给重命名输入框。 */}
+ {!isEditing && ordinalBadgeLabel != null && (
+ <span
+ className={cn(
+ 'pointer-events-none absolute inset-y-0 right-2 z-20 flex items-center',
+ isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon',
+ )}
+ >
+ <SessionOrdinalBadgeKbd label={ordinalBadgeLabel} />
+ </span>
+ )}
+
{/* 右键菜单:与 ProjectNode 同款 coordinate-anchored DropdownMenu —
隐形 fixed-position trigger 锚定到 onContextMenu 捕获的鼠标坐标,
Radix 自动处理打开/关闭、ESC、点外面关闭等行为。 */}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionOrdinalBadges.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionOrdinalBadges.tsx
new file mode 100644
index 0000000000..0eaa9cbc40
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionOrdinalBadges.tsx
@@ -0,0 +1,65 @@
+import { useSyncExternalStore } from 'react';
+
+/**
+ * 对话切换序号徽标(mod+1..9 快速切换, 复刻 Codex 桌面版交互)。
+ *
+ * 按住主修饰键超过阈值时, CCAgentSidebarUpper 按侧边栏当前可见顺序
+ * (getVisibleSidebarSessionIds, 与快捷键执行同一口径)构建
+ * sessionId → 显示标签('⌘1' / 'Ctrl+1')的映射写入本模块级 store; 松开清空。
+ *
+ * 不走 props / context 而用 useSyncExternalStore 精准订阅, 是为了守住
+ * SessionItem 的性能不变量(见其文件头注释): 行内订阅必须按 sessionId 取
+ * primitive —— map 更替时只有标签真正变化的行(前 9 行)重渲染, 其余几百行
+ * snapshot 恒为 null, React 不触碰它们。
+ */
+
+type SessionOrdinalBadgeMap = ReadonlyMap<string, string> | null;
+
+let currentBadges: SessionOrdinalBadgeMap = null;
+const listeners = new Set<() => void>();
+
+export function setSessionOrdinalBadges(next: SessionOrdinalBadgeMap): void {
+ if (next === currentBadges) return;
+ currentBadges = next;
+ for (const listener of [...listeners]) listener();
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** 行组件读取自己的序号徽标标签; 不在前 9 个可见对话内(或未按住)返回 null。 */
+export function useSessionOrdinalBadge(sessionId: string): string | null {
+ return useSyncExternalStore(subscribe, () => currentBadges?.get(sessionId) ?? null);
+}
+
+/**
+ * 徽标本体(对齐 Codex 原版观感): 无边框、currentColor 10% 透明底、大圆角。
+ * 文字与底色都继承 current —— 定位容器负责给出前景色(普通行次级灰、active
+ * 反色行浅色), Light/Dark 与 active 态自动适配, 不引入新 token。徽标出现时
+ * 行内时间/badge 由各自容器让位淡出, 徽标独占行尾。纯视觉提示, aria-hidden。
+ */
+export function SessionOrdinalBadgeKbd({ label }: { label: string }) {
+ // mac 显示形是「修饰符号 + 键名」直排(如 ⌘1)。⌃⌥⇧⌘ 这类符号在 UI 字体
+ // 里字形明显小于数字且基线偏高, 整串渲染像上标 —— 拆开后给符号略大字号
+ // 补偿, 加 1px 间距, 与 Codex 原版观感对齐。非 mac(Ctrl+1)整串原样。
+ const macParts = label.match(/^([⌃⌥⇧⌘]+)(.+)$/);
+ return (
+ <kbd
+ aria-hidden
+ className="flex select-none items-center gap-px rounded-md bg-[color-mix(in_srgb,currentColor_10%,transparent)] px-1.5 py-[2px] text-11 font-normal leading-none text-current"
+ >
+ {macParts ? (
+ <>
+ <span className="text-[13px] leading-none">{macParts[1]}</span>
+ <span>{macParts[2]}</span>
+ </>
+ ) : (
+ label
+ )}
+ </kbd>
+ );
+}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useModifierHold.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useModifierHold.test.ts
new file mode 100644
index 0000000000..75e8197917
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useModifierHold.test.ts
@@ -0,0 +1,127 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+
+import { useModifierHold } from '../useModifierHold';
+
+const platformMock = vi.hoisted(() => ({ value: 'darwin' }));
+
+vi.mock('../../lib/appShortcutStore', () => ({
+ getAppShortcutPlatform: () => platformMock.value,
+}));
+
+function dispatchKey(type: 'keydown' | 'keyup', init: KeyboardEventInit) {
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent(type, init));
+ });
+}
+
+describe('useModifierHold', () => {
+ beforeEach(() => {
+ platformMock.value = 'darwin';
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ delete document.body.dataset.appShortcutRecording;
+ });
+
+ it('activates only after holding meta past the delay on darwin', () => {
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ expect(result.current).toBe(false);
+ act(() => vi.advanceTimersByTime(499));
+ expect(result.current).toBe(false);
+ act(() => vi.advanceTimersByTime(1));
+ expect(result.current).toBe(true);
+ dispatchKey('keyup', { key: 'Meta', metaKey: false });
+ expect(result.current).toBe(false);
+ });
+
+ it('quick combos (meta pressed briefly) never activate', () => {
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ dispatchKey('keydown', { key: 'c', metaKey: true });
+ dispatchKey('keyup', { key: 'c', metaKey: true });
+ dispatchKey('keyup', { key: 'Meta', metaKey: false });
+ act(() => vi.advanceTimersByTime(1000));
+ expect(result.current).toBe(false);
+ });
+
+ it('stays held while other keys are pressed with the modifier down', () => {
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(500));
+ expect(result.current).toBe(true);
+ dispatchKey('keydown', { key: '1', metaKey: true });
+ dispatchKey('keyup', { key: '1', metaKey: true });
+ expect(result.current).toBe(true);
+ });
+
+ it('window blur resets the held state (lost keyup)', () => {
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(500));
+ expect(result.current).toBe(true);
+ act(() => {
+ window.dispatchEvent(new Event('blur'));
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it('pointermove without the modifier clears a stuck hold (keyup swallowed by native menu)', () => {
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(500));
+ expect(result.current).toBe(true);
+ act(() => {
+ window.dispatchEvent(new MouseEvent('pointermove', { metaKey: false }));
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it('pointermove with the modifier held does not disturb the hold', () => {
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(500));
+ act(() => {
+ window.dispatchEvent(new MouseEvent('pointermove', { metaKey: true }));
+ });
+ expect(result.current).toBe(true);
+ });
+
+ it('tracks ctrl instead of meta off darwin', () => {
+ platformMock.value = 'win32';
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(1000));
+ expect(result.current).toBe(false);
+ dispatchKey('keyup', { key: 'Meta', metaKey: false });
+ dispatchKey('keydown', { key: 'Control', ctrlKey: true });
+ act(() => vi.advanceTimersByTime(500));
+ expect(result.current).toBe(true);
+ });
+
+ it('is suppressed while the settings shortcut recorder is active', () => {
+ document.body.dataset.appShortcutRecording = '1';
+ const { result } = renderHook(() => useModifierHold());
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(1000));
+ expect(result.current).toBe(false);
+ });
+
+ it('enabled=false keeps the state off and drops listeners', () => {
+ const { result, rerender } = renderHook(({ enabled }) => useModifierHold({ enabled }), {
+ initialProps: { enabled: true },
+ });
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(500));
+ expect(result.current).toBe(true);
+ rerender({ enabled: false });
+ expect(result.current).toBe(false);
+ dispatchKey('keydown', { key: 'Meta', metaKey: true });
+ act(() => vi.advanceTimersByTime(1000));
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useModifierHold.ts b/apps/desktop/src/renderer/hooks/useModifierHold.ts
new file mode 100644
index 0000000000..57d0e6292a
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useModifierHold.ts
@@ -0,0 +1,84 @@
+import { useEffect, useState } from 'react';
+
+import { getAppShortcutPlatform } from '../lib/appShortcutStore';
+
+export interface UseModifierHoldOptions {
+ /** false 时不挂监听且状态归零。默认 true。 */
+ enabled?: boolean;
+ /** 按住多久才算 hold(ms)。默认 500。 */
+ delayMs?: number;
+}
+
+const DEFAULT_HOLD_DELAY_MS = 500;
+
+/**
+ * 「按住主修饰键」检测: mac ⌘ / 其它平台 Ctrl 持续按住 delayMs 后返回 true,
+ * 松开立即回落 false。给「按住修饰键浮现快捷键提示」类 UI 做门控 —— 延迟的
+ * 意义是 ⌘C / ⌘1 等快速组合根本来不及触发提示, 只有真正按住犹豫的用户才看到。
+ *
+ * 修饰键状态直接读每次 keydown / keyup / pointermove 的 metaKey / ctrlKey
+ * (松开修饰键的 keyup 里对应 flag 已为 false, 松开其它键不受影响), 不跟踪
+ * 具体键位。pointermove 兜底覆盖「keyup 被吞」的场景 —— 按住修饰键期间打开
+ * 原生上下文菜单再松开, keyup 不会投递到 renderer, 靠下一次鼠标移动的真实
+ * flags 复位。window blur 兜底复位 —— mac 上按住 ⌘ 点别的窗口会丢 keyup,
+ * 不兜底状态会卡在按住态。设置页快捷键录制期间(body dataset 旗标, 与
+ * useAppShortcut 同口径)一律视为未按住, 录制时按修饰键是常态, 不该弹提示。
+ */
+export function useModifierHold(options: UseModifierHoldOptions = {}): boolean {
+ const { enabled = true, delayMs = DEFAULT_HOLD_DELAY_MS } = options;
+ const [held, setHeld] = useState(false);
+
+ useEffect(() => {
+ if (!enabled) {
+ setHeld(false);
+ return;
+ }
+ const isDarwin = getAppShortcutPlatform() === 'darwin';
+ let timer: number | null = null;
+ let active = false;
+
+ const sync = (modifierDown: boolean) => {
+ if (modifierDown) {
+ if (active || timer != null) return;
+ timer = window.setTimeout(() => {
+ timer = null;
+ active = true;
+ setHeld(true);
+ }, delayMs);
+ return;
+ }
+ if (timer != null) {
+ window.clearTimeout(timer);
+ timer = null;
+ }
+ if (active) {
+ active = false;
+ setHeld(false);
+ }
+ };
+
+ const probe = (event: { metaKey: boolean; ctrlKey: boolean }) => {
+ if (document.body.dataset.appShortcutRecording === '1') {
+ sync(false);
+ return;
+ }
+ sync(isDarwin ? event.metaKey : event.ctrlKey);
+ };
+ const reset = () => sync(false);
+
+ window.addEventListener('keydown', probe, true);
+ window.addEventListener('keyup', probe, true);
+ window.addEventListener('pointermove', probe, true);
+ window.addEventListener('blur', reset);
+ return () => {
+ window.removeEventListener('keydown', probe, true);
+ window.removeEventListener('keyup', probe, true);
+ window.removeEventListener('pointermove', probe, true);
+ window.removeEventListener('blur', reset);
+ if (timer != null) window.clearTimeout(timer);
+ setHeld(false);
+ };
+ }, [enabled, delayMs]);
+
+ return held;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5a823cdb87..077936dab1 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2786,6 +2786,42 @@
"open-terminal": {
"label": "Open terminal",
"description": "Open a terminal in the right sidebar (focuses the existing one)"
+ },
+ "switch-session-1": {
+ "label": "Go to session 1",
+ "description": "Jump to the 1st visible session in the sidebar"
+ },
+ "switch-session-2": {
+ "label": "Go to session 2",
+ "description": "Jump to the 2nd visible session in the sidebar"
+ },
+ "switch-session-3": {
+ "label": "Go to session 3",
+ "description": "Jump to the 3rd visible session in the sidebar"
+ },
+ "switch-session-4": {
+ "label": "Go to session 4",
+ "description": "Jump to the 4th visible session in the sidebar"
+ },
+ "switch-session-5": {
+ "label": "Go to session 5",
+ "description": "Jump to the 5th visible session in the sidebar"
+ },
+ "switch-session-6": {
+ "label": "Go to session 6",
+ "description": "Jump to the 6th visible session in the sidebar"
+ },
+ "switch-session-7": {
+ "label": "Go to session 7",
+ "description": "Jump to the 7th visible session in the sidebar"
+ },
+ "switch-session-8": {
+ "label": "Go to session 8",
+ "description": "Jump to the 8th visible session in the sidebar"
+ },
+ "switch-session-9": {
+ "label": "Go to session 9",
+ "description": "Jump to the 9th visible session in the sidebar"
}
},
"none": "Not set",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 6fd07b3d1d..9f259a7008 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2785,6 +2785,42 @@
"open-terminal": {
"label": "ターミナルを開く",
"description": "右サイドバーでターミナルを開きます(既に開いている場合はフォーカス)"
+ },
+ "switch-session-1": {
+ "label": "1番目のセッションに移動",
+ "description": "サイドバーに表示されている1番目のセッションに移動します"
+ },
+ "switch-session-2": {
+ "label": "2番目のセッションに移動",
+ "description": "サイドバーに表示されている2番目のセッションに移動します"
+ },
+ "switch-session-3": {
+ "label": "3番目のセッションに移動",
+ "description": "サイドバーに表示されている3番目のセッションに移動します"
+ },
+ "switch-session-4": {
+ "label": "4番目のセッションに移動",
+ "description": "サイドバーに表示されている4番目のセッションに移動します"
+ },
+ "switch-session-5": {
+ "label": "5番目のセッションに移動",
+ "description": "サイドバーに表示されている5番目のセッションに移動します"
+ },
+ "switch-session-6": {
+ "label": "6番目のセッションに移動",
+ "description": "サイドバーに表示されている6番目のセッションに移動します"
+ },
+ "switch-session-7": {
+ "label": "7番目のセッションに移動",
+ "description": "サイドバーに表示されている7番目のセッションに移動します"
+ },
+ "switch-session-8": {
+ "label": "8番目のセッションに移動",
+ "description": "サイドバーに表示されている8番目のセッションに移動します"
+ },
+ "switch-session-9": {
+ "label": "9番目のセッションに移動",
+ "description": "サイドバーに表示されている9番目のセッションに移動します"
}
},
"none": "未設定",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8857a41de2..a65386f036 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2785,6 +2785,42 @@
"open-terminal": {
"label": "터미널 열기",
"description": "오른쪽 사이드바에서 터미널을 엽니다(이미 열려 있으면 포커스)"
+ },
+ "switch-session-1": {
+ "label": "1번째 세션으로 이동",
+ "description": "사이드바에 표시된 1번째 세션으로 이동합니다"
+ },
+ "switch-session-2": {
+ "label": "2번째 세션으로 이동",
+ "description": "사이드바에 표시된 2번째 세션으로 이동합니다"
+ },
+ "switch-session-3": {
+ "label": "3번째 세션으로 이동",
+ "description": "사이드바에 표시된 3번째 세션으로 이동합니다"
+ },
+ "switch-session-4": {
+ "label": "4번째 세션으로 이동",
+ "description": "사이드바에 표시된 4번째 세션으로 이동합니다"
+ },
+ "switch-session-5": {
+ "label": "5번째 세션으로 이동",
+ "description": "사이드바에 표시된 5번째 세션으로 이동합니다"
+ },
+ "switch-session-6": {
+ "label": "6번째 세션으로 이동",
+ "description": "사이드바에 표시된 6번째 세션으로 이동합니다"
+ },
+ "switch-session-7": {
+ "label": "7번째 세션으로 이동",
+ "description": "사이드바에 표시된 7번째 세션으로 이동합니다"
+ },
+ "switch-session-8": {
+ "label": "8번째 세션으로 이동",
+ "description": "사이드바에 표시된 8번째 세션으로 이동합니다"
+ },
+ "switch-session-9": {
+ "label": "9번째 세션으로 이동",
+ "description": "사이드바에 표시된 9번째 세션으로 이동합니다"
}
},
"none": "설정 안 됨",
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 c2ee2bd507..eea09612d1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2785,6 +2785,42 @@
"open-terminal": {
"label": "打开命令行",
"description": "在右侧栏打开终端(已打开则聚焦)"
+ },
+ "switch-session-1": {
+ "label": "切换到第 1 个对话",
+ "description": "跳转到侧边栏第 1 个可见对话"
+ },
+ "switch-session-2": {
+ "label": "切换到第 2 个对话",
+ "description": "跳转到侧边栏第 2 个可见对话"
+ },
+ "switch-session-3": {
+ "label": "切换到第 3 个对话",
+ "description": "跳转到侧边栏第 3 个可见对话"
+ },
+ "switch-session-4": {
+ "label": "切换到第 4 个对话",
+ "description": "跳转到侧边栏第 4 个可见对话"
+ },
+ "switch-session-5": {
+ "label": "切换到第 5 个对话",
+ "description": "跳转到侧边栏第 5 个可见对话"
+ },
+ "switch-session-6": {
+ "label": "切换到第 6 个对话",
+ "description": "跳转到侧边栏第 6 个可见对话"
+ },
+ "switch-session-7": {
+ "label": "切换到第 7 个对话",
+ "description": "跳转到侧边栏第 7 个可见对话"
+ },
+ "switch-session-8": {
+ "label": "切换到第 8 个对话",
+ "description": "跳转到侧边栏第 8 个可见对话"
+ },
+ "switch-session-9": {
+ "label": "切换到第 9 个对话",
+ "description": "跳转到侧边栏第 9 个可见对话"
}
},
"none": "未设置",
diff --git a/apps/desktop/src/renderer/lib/appShortcutStore.ts b/apps/desktop/src/renderer/lib/appShortcutStore.ts
index 2e91c999a0..041a4c3890 100644
--- a/apps/desktop/src/renderer/lib/appShortcutStore.ts
+++ b/apps/desktop/src/renderer/lib/appShortcutStore.ts
@@ -5,6 +5,7 @@ import {
type AppShortcutId,
type AppShortcutOverrides,
} from '../../shared/appShortcuts';
+import { voiceInputShortcutToAppShortcutCombo } from '../voice-input/appShortcutConflict';
/**
* renderer 侧应用级快捷键状态单例。
@@ -14,15 +15,36 @@ import {
* 与 main 消费端跑同一份 registry 代码, 判定不漂移。之后订阅
* app-shortcuts:changed 广播热更新, 设置页改绑立即对所有监听生效。
*
+ * 语音输入的键盘快捷键是 registry 之外的用户键位: 历史设置可能占着
+ * mod+1..9 等隐藏槽位默认组合, 这里把它作为 yieldToCombos 传入合并
+ * (隐藏槽位让位, 语音快捷键获胜), 并订阅语音设置变更热更新。registry
+ * 消费端全部走本 store, 让位对 useAppShortcut 监听与序号徽标同时生效。
+ *
* 非 Electron 环境 (单测 jsdom) 下退化为纯默认值。
*/
let platform = 'darwin';
let effective = new Map<AppShortcutId, AppShortcutCombo[]>();
let overridesSnapshot: AppShortcutOverrides = {};
+let voiceYieldCombos: AppShortcutCombo[] = [];
const listeners = new Set<() => void>();
let initialized = false;
+function recomputeEffective(): void {
+ effective = getEffectiveAppShortcuts(overridesSnapshot, platform, voiceYieldCombos);
+}
+
+function readVoiceYieldCombos(): AppShortcutCombo[] {
+ try {
+ const shortcut = window.electronAPI?.voiceInput?.getDataSnapshot()?.settings?.shortcut;
+ if (!shortcut) return [];
+ const combo = voiceInputShortcutToAppShortcutCombo(shortcut);
+ return combo ? [combo] : [];
+ } catch {
+ return [];
+ }
+}
+
function ensureInitialized(): void {
if (initialized) return;
initialized = true;
@@ -37,13 +59,23 @@ function ensureInitialized(): void {
}
api.onChanged((payload) => {
overridesSnapshot = normalizeAppShortcutOverrides(payload?.overrides, platform);
- effective = getEffectiveAppShortcuts(overridesSnapshot, platform);
+ recomputeEffective();
listeners.forEach((cb) => cb());
});
+ voiceYieldCombos = readVoiceYieldCombos();
+ try {
+ window.electronAPI?.voiceInput?.onDataChanged(() => {
+ voiceYieldCombos = readVoiceYieldCombos();
+ recomputeEffective();
+ listeners.forEach((cb) => cb());
+ });
+ } catch {
+ // 语音订阅不可用时保持启动快照, 不影响其余快捷键。
+ }
} else if (typeof navigator !== 'undefined' && !/Mac|iPhone|iPad/.test(navigator.platform)) {
platform = 'win32';
}
- effective = getEffectiveAppShortcuts(overridesSnapshot, platform);
+ recomputeEffective();
}
/** 某 id 当前生效的组合列表; 平台不可用返回空数组 (消费端据此不挂监听)。 */
diff --git a/apps/desktop/src/shared/appShortcuts.ts b/apps/desktop/src/shared/appShortcuts.ts
index 3ac5912b14..a1d04e8b88 100644
--- a/apps/desktop/src/shared/appShortcuts.ts
+++ b/apps/desktop/src/shared/appShortcuts.ts
@@ -51,10 +51,37 @@ export const APP_SHORTCUT_IDS = [
'browser-forward',
'browser-reload',
'cycle-permission-mode',
+ 'switch-session-1',
+ 'switch-session-2',
+ 'switch-session-3',
+ 'switch-session-4',
+ 'switch-session-5',
+ 'switch-session-6',
+ 'switch-session-7',
+ 'switch-session-8',
+ 'switch-session-9',
] as const;
export type AppShortcutId = (typeof APP_SHORTCUT_IDS)[number];
+/**
+ * 侧边栏对话切换槽位: mod+1..9 跳转到侧边栏第 N 个可见对话(含置顶区, 按渲染
+ * 顺序, 与 getVisibleSidebarSessionIds 同一口径)。逐 id 注册以完整复用改绑 /
+ * 冲突检测 / accelerator 转换体系; 消费端与按住修饰键浮现的序号徽标见
+ * renderer CCAgentSidebarUpper。数组序 = 槽位序 (index 0 ↔ 数字键 1)。
+ */
+export const SWITCH_SESSION_SHORTCUT_IDS = [
+ 'switch-session-1',
+ 'switch-session-2',
+ 'switch-session-3',
+ 'switch-session-4',
+ 'switch-session-5',
+ 'switch-session-6',
+ 'switch-session-7',
+ 'switch-session-8',
+ 'switch-session-9',
+] as const satisfies readonly AppShortcutId[];
+
export interface AppShortcutDefinition {
id: AppShortcutId;
scope: AppShortcutScope;
@@ -65,6 +92,16 @@ export interface AppShortcutDefinition {
rebindable: boolean;
/** true = 不在设置页快捷键列表展示 (仍正常生效, 如 ⌘, 打开设置)。 */
hiddenInSettings?: boolean;
+ /**
+ * true = 本条目的默认组合对用户既有绑定让位: 与其它 id 的 override 或
+ * registry 之外体系的用户键位 (yieldToCombos) 撞键时, 默认组合被压制
+ * (该槽位等效无绑定), 写入侧 findAppShortcutConflict 也不把它算作占用。
+ * 只用于「批量占键的次要便捷槽位」(switch-session-*): 它们隐藏在设置页
+ * 之外, 用户看不到也解不开, 不让位就会一次按键双动作。save-file / ⌘, 等
+ * 惯例键虽也 hiddenInSettings 但**不得**设本字段 —— 否则用户把别的键改绑
+ * 到 ⌘S 会被放行并静默丢失保存快捷键。
+ */
+ yieldsToUserBindings?: boolean;
/**
* true = darwin 上唯一触发路径是应用菜单 accelerator (无 renderer /
* before-input-event fallback)。改绑时必须能转换为 Electron accelerator
@@ -284,6 +321,21 @@ export const APP_SHORTCUT_DEFINITIONS: ReadonlyArray<AppShortcutDefinition> = [
rebindable: true,
getDefaultCombos: (platform) => [modCombo('KeyR', platform), combo('F5')],
},
+ // 对话切换 9 槽位 (见 SWITCH_SESSION_SHORTCUT_IDS 注释)。设置页不逐条展示
+ // (9 行同构条目刷屏), 但 label/description i18n 仍需齐全 —— 改绑冲突提示
+ // 会引用占用者 label。
+ ...SWITCH_SESSION_SHORTCUT_IDS.map(
+ (id, index): AppShortcutDefinition => ({
+ id,
+ scope: 'app',
+ labelKey: `settings.shortcuts.items.${id}.label`,
+ descriptionKey: `settings.shortcuts.items.${id}.description`,
+ rebindable: true,
+ hiddenInSettings: true,
+ yieldsToUserBindings: true,
+ getDefaultCombos: (platform) => [modCombo(`Digit${index + 1}`, platform)],
+ }),
+ ),
];
const DEFINITION_MAP: ReadonlyMap<AppShortcutId, AppShortcutDefinition> = new Map(
@@ -382,20 +434,52 @@ export function normalizeAppShortcutOverrides(raw: unknown, platform: string): A
* 默认值 + override 合并出每个 id 的生效组合列表。override 为单 combo 时
* 整体替换默认列表; null (删除绑定) → 空列表; 平台不可用的 id 不出现在
* 结果里 (消费端对 undefined / 空列表自动不挂监听)。
+ *
+ * yieldsToUserBindings 条目的默认组合对用户既有绑定让位: 冲突只在写入时
+ * 校验, 历史版本合法写下的绑定可能与后续版本新增的批量默认撞键 (如
+ * switch-session-* 一次性占入 mod+1..9)。这些槽位不在设置页出现, 用户
+ * 看不到占用者也无法解绑, 若不让位则一次按键触发两个动作。让位后该槽位
+ * 等效无绑定 (消费端与序号徽标端对空组合天然兼容); 其余条目 —— 包括
+ * save-file / open-settings 等同样 hiddenInSettings 的惯例键 —— 不让位,
+ * 维持既有行为 (见 yieldsToUserBindings 字段注释)。让位对象有两类:
+ * 1. 本 registry 内其它 id 的用户 override (overrides 参数);
+ * 2. registry 之外体系的用户键位 (yieldToCombos 参数, 如语音输入的键盘
+ * 快捷键) —— 由知道该体系的消费端传入; 无此类消费的调用点 (如 main 的
+ * 菜单 accelerator, 这些隐藏槽位本就不进菜单) 不传即可, 行为不变。
*/
export function getEffectiveAppShortcuts(
overrides: AppShortcutOverrides,
platform: string,
+ yieldToCombos: ReadonlyArray<AppShortcutCombo> = [],
): Map<AppShortcutId, AppShortcutCombo[]> {
+ const overrideEntries: Array<{ scope: AppShortcutScope; combo: AppShortcutCombo }> = [];
+ for (const def of APP_SHORTCUT_DEFINITIONS) {
+ if (!isAppShortcutAvailableOnPlatform(def.id, platform)) continue;
+ const override = overrides[def.id];
+ if (override) overrideEntries.push({ scope: def.scope, combo: override });
+ }
const result = new Map<AppShortcutId, AppShortcutCombo[]>();
for (const def of APP_SHORTCUT_DEFINITIONS) {
if (!isAppShortcutAvailableOnPlatform(def.id, platform)) continue;
const override = overrides[def.id];
if (override === null) {
result.set(def.id, []);
- } else {
- result.set(def.id, override ? [override] : def.getDefaultCombos(platform));
+ continue;
+ }
+ if (override) {
+ result.set(def.id, [override]);
+ continue;
+ }
+ let combos = def.getDefaultCombos(platform);
+ if (def.yieldsToUserBindings) {
+ combos = combos.filter(
+ (c) =>
+ !overrideEntries.some(
+ (o) => appShortcutScopesOverlap(def.scope, o.scope) && appShortcutCombosEqual(o.combo, c),
+ ) && !yieldToCombos.some((y) => appShortcutCombosEqual(y, c)),
+ );
}
+ result.set(def.id, combos);
}
return result;
}
@@ -686,6 +770,12 @@ export function findAppShortcutConflict(
for (const def of APP_SHORTCUT_DEFINITIONS) {
if (def.id === id) continue;
if (!appShortcutScopesOverlap(selfDef.scope, def.scope)) continue;
+ // 未被 override 的让位槽位默认不构成占用: 用户显式改绑获胜 ——
+ // getEffectiveAppShortcuts 会让该槽位的默认让位。否则用户想绑这些
+ // 组合时会被一个设置页里看不到、也无法解绑的条目永久卡死。范围严格
+ // 限定 yieldsToUserBindings, 不含 save-file 等惯例隐藏键 (那些仍占用,
+ // 新绑定照常报冲突)。
+ if (def.yieldsToUserBindings && overrides[def.id] === undefined) continue;
const combos = effective.get(def.id);
if (combos?.some((c) => appShortcutCombosEqual(c, comboValue))) return def.id;
}