mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-15 12:55:51 +00:00
修复在 dev 模式下按下 Ctrl+O 切换 transcript 视图时 React 抛出
"Rendered fewer hooks than expected" 崩溃的问题。
## 根因分析
项目中有大量 hook(useState / useMemo / useRef / useSyncExternalStore 等)
被包裹在 `feature()` 三元表达式中条件调用,例如:
const value = feature('X') ? useHook() : defaultValue;
在 build 模式下 `feature()` 是编译时常量,死代码消除会移除未使用的分支,
hooks 数量在编译后是确定的。但在 dev 模式下(scripts/dev.ts 注入
--feature 启用全部 31 个 feature),`feature()` 是运行时调用,
但始终返回 true,因此所有 hooks 都会被调用,原本不会出问题。
真正的触发器是 REPL.tsx 第 5381 行的提前返回:
if (screen === 'transcript') { return transcriptReturn; }
当用户按下 Ctrl+O 进入 transcript 模式时,该提前返回之后的所有 hooks
(如 displayedAgentMessages 的 useMemo)都不会被调用,导致 React 在
下一次渲染时检测到 hooks 数量与上次不一致而崩溃。
此外,其他文件中也存在相同的条件式 hook 模式——虽然 dev 模式下
feature() 返回 true,所以这些路径实际上不会被触发,但它们是
潜在的隐患:若将来有人通过环境变量关闭某个 feature,
同样的崩溃会立即出现。
## 修复策略
采用统一模式:**始终无条件调用 hook,将 feature() gate 应用到值上**。
// Before (unsafe — hook count varies by feature flag)
const value = feature('X') ? useHook() : defaultValue;
// After (safe — hook always called, gate on the value)
const rawValue = useHook();
const value = feature('X') ? rawValue : defaultValue;
## 修改清单
### 核心修复(REPL.tsx)
- 将 `displayedAgentMessages` useMemo 及依赖变量(viewedTask /
viewedTeammateTask / viewedAgentTask / usesSyncMessages /
rawAgentMessages / displayedMessages)从 transcript 提前返回
之后移至之前,确保两模式下 hooks 调用顺序一致
- 修复 `disableMessageActions` / `useAssistantHistory` /
`voiceIntegration` 的条件式 hook 调用
### 条件式 hook 修复(11 个文件)
- src/hooks/useGlobalKeybindings.tsx — isBriefOnly / toggleBrief
keybinding 改为 isActive 门控
- src/hooks/useReplBridge.tsx — 5 个 BRIDGE_MODE 选值改为无条件调用
- src/hooks/useVoiceIntegration.tsx — 4 个 VOICE_MODE 选值修复
- src/components/PromptInput/Notifications.tsx — 4 个 feature 选值修复
- src/components/PromptInput/PromptInput.tsx — briefOwnsGap /
companionSpeaking 修复
- src/components/PromptInput/PromptInputFooterLeftSide.tsx — 4 个
VOICE_MODE 选值修复
- src/components/PromptInput/PromptInputQueuedCommands.tsx — isBriefOnly
- src/components/Spinner.tsx — briefEnvEnabled 修复
- src/components/TextInput.tsx — voiceState / audioLevels /
animationFrame 修复
- src/components/messages/AttachmentMessage.tsx — isDemoEnv 修复
- src/components/messages/UserPromptMessage.tsx — isBriefOnly /
viewingAgentTaskId / briefEnvEnabled 修复
- src/components/messages/UserToolResultMessage/UserToolSuccessMessage.tsx
— isBriefOnly 修复
### 其他修复
- src/components/FeedbackSurvey/useFrustrationDetection.ts — 将 3 个
提前返回合并为 shouldSkip 变量,handleTranscriptSelect 提前 return
- src/hooks/useIssueFlagBanner.ts — useRef 移到 USER_TYPE 检查之前
- src/hooks/useUpdateNotification.ts — useState 改为 useRef,
避免版本号变化触发不必要重渲染
### 构建/开发配置
- build.ts — 添加 `sourcemap: 'linked'`
- scripts/dev.ts — NODE_ENV 从 'production' 改为 'development'
Closes #434
245 lines
8.9 KiB
TypeScript
245 lines
8.9 KiB
TypeScript
/**
|
|
* Component that registers global keybinding handlers.
|
|
*
|
|
* Must be rendered inside KeybindingSetup to have access to the keybinding context.
|
|
* This component renders nothing - it just registers the keybinding handlers.
|
|
*/
|
|
import { feature } from 'bun:bundle';
|
|
import { useCallback } from 'react';
|
|
import { instances } from '@anthropic/ink';
|
|
import { useKeybinding } from '../keybindings/useKeybinding.js';
|
|
import type { Screen } from '../screens/REPL.js';
|
|
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js';
|
|
import {
|
|
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
|
|
logEvent,
|
|
} from '../services/analytics/index.js';
|
|
import { useAppState, useSetAppState } from '../state/AppState.js';
|
|
import { count } from '../utils/array.js';
|
|
import { getTerminalPanel } from '../utils/terminalPanel.js';
|
|
|
|
type Props = {
|
|
screen: Screen;
|
|
setScreen: React.Dispatch<React.SetStateAction<Screen>>;
|
|
showAllInTranscript: boolean;
|
|
setShowAllInTranscript: React.Dispatch<React.SetStateAction<boolean>>;
|
|
messageCount: number;
|
|
onEnterTranscript?: () => void;
|
|
onExitTranscript?: () => void;
|
|
virtualScrollActive?: boolean;
|
|
searchBarOpen?: boolean;
|
|
};
|
|
|
|
/**
|
|
* Registers global keybinding handlers for:
|
|
* - ctrl+t: Toggle todo list
|
|
* - ctrl+o: Toggle transcript mode
|
|
* - ctrl+e: Toggle showing all messages in transcript
|
|
* - ctrl+c/escape: Exit transcript mode
|
|
*/
|
|
export function GlobalKeybindingHandlers({
|
|
screen,
|
|
setScreen,
|
|
showAllInTranscript,
|
|
setShowAllInTranscript,
|
|
messageCount,
|
|
onEnterTranscript,
|
|
onExitTranscript,
|
|
virtualScrollActive,
|
|
searchBarOpen = false,
|
|
}: Props): null {
|
|
const expandedView = useAppState(s => s.expandedView);
|
|
const setAppState = useSetAppState();
|
|
|
|
// Toggle todo list (ctrl+t) - cycles through views
|
|
const handleToggleTodos = useCallback(() => {
|
|
logEvent('tengu_toggle_todos', {
|
|
is_expanded: expandedView === 'tasks',
|
|
});
|
|
setAppState(prev => {
|
|
const { getAllInProcessTeammateTasks } =
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
require('../tasks/InProcessTeammateTask/InProcessTeammateTask.js') as typeof import('../tasks/InProcessTeammateTask/InProcessTeammateTask.js');
|
|
const hasTeammates = count(getAllInProcessTeammateTasks(prev.tasks), t => t.status === 'running') > 0;
|
|
|
|
if (hasTeammates) {
|
|
// Both exist: none → tasks → teammates → none
|
|
switch (prev.expandedView) {
|
|
case 'none':
|
|
return { ...prev, expandedView: 'tasks' as const };
|
|
case 'tasks':
|
|
return { ...prev, expandedView: 'teammates' as const };
|
|
case 'teammates':
|
|
return { ...prev, expandedView: 'none' as const };
|
|
}
|
|
}
|
|
// Only tasks: none ↔ tasks
|
|
return {
|
|
...prev,
|
|
expandedView: prev.expandedView === 'tasks' ? ('none' as const) : ('tasks' as const),
|
|
};
|
|
});
|
|
}, [expandedView, setAppState]);
|
|
|
|
// Toggle transcript mode (ctrl+o). Two-way prompt ↔ transcript.
|
|
// Brief view has its own dedicated toggle on ctrl+shift+b.
|
|
const isBriefOnlyState = useAppState(s => s.isBriefOnly);
|
|
const handleToggleTranscript = useCallback(() => {
|
|
if (feature('KAIROS') || feature('KAIROS_BRIEF')) {
|
|
// Escape hatch: GB kill-switch while defaultView=chat was persisted
|
|
// can leave isBriefOnly stuck on, showing a blank filterForBriefTool
|
|
// view. Users will reach for ctrl+o — clear the stuck state first.
|
|
// Only needed in the prompt screen — transcript mode already ignores
|
|
// isBriefOnly (Messages.tsx filter is gated on !isTranscriptMode).
|
|
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
const { isBriefEnabled } =
|
|
require('@claude-code-best/builtin-tools/tools/BriefTool/BriefTool.js') as typeof import('@claude-code-best/builtin-tools/tools/BriefTool/BriefTool.js');
|
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
|
if (!isBriefEnabled() && isBriefOnlyState && screen !== 'transcript') {
|
|
setAppState(prev => {
|
|
if (!prev.isBriefOnly) return prev;
|
|
return { ...prev, isBriefOnly: false };
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
|
|
const isEnteringTranscript = screen !== 'transcript';
|
|
logEvent('tengu_toggle_transcript', {
|
|
is_entering: isEnteringTranscript,
|
|
show_all: showAllInTranscript,
|
|
message_count: messageCount,
|
|
});
|
|
setScreen(s => (s === 'transcript' ? 'prompt' : 'transcript'));
|
|
setShowAllInTranscript(false);
|
|
if (isEnteringTranscript && onEnterTranscript) {
|
|
onEnterTranscript();
|
|
}
|
|
if (!isEnteringTranscript && onExitTranscript) {
|
|
onExitTranscript();
|
|
}
|
|
}, [
|
|
screen,
|
|
setScreen,
|
|
isBriefOnlyState,
|
|
showAllInTranscript,
|
|
setShowAllInTranscript,
|
|
messageCount,
|
|
setAppState,
|
|
onEnterTranscript,
|
|
onExitTranscript,
|
|
]);
|
|
|
|
// Toggle showing all messages in transcript mode (ctrl+e)
|
|
const handleToggleShowAll = useCallback(() => {
|
|
logEvent('tengu_transcript_toggle_show_all', {
|
|
is_expanding: !showAllInTranscript,
|
|
message_count: messageCount,
|
|
});
|
|
setShowAllInTranscript(prev => !prev);
|
|
}, [showAllInTranscript, setShowAllInTranscript, messageCount]);
|
|
|
|
// Exit transcript mode (ctrl+c or escape)
|
|
const handleExitTranscript = useCallback(() => {
|
|
logEvent('tengu_transcript_exit', {
|
|
show_all: showAllInTranscript,
|
|
message_count: messageCount,
|
|
});
|
|
setScreen('prompt');
|
|
setShowAllInTranscript(false);
|
|
if (onExitTranscript) {
|
|
onExitTranscript();
|
|
}
|
|
}, [setScreen, showAllInTranscript, setShowAllInTranscript, messageCount, onExitTranscript]);
|
|
|
|
// Toggle brief-only view (ctrl+shift+b). Pure display filter toggle —
|
|
// does not touch opt-in state. Asymmetric gate (mirrors /brief): OFF
|
|
// transition always allowed so the same key that got you in gets you
|
|
// out even if the GB kill-switch fires mid-session.
|
|
const handleToggleBrief = useCallback(() => {
|
|
if (feature('KAIROS') || feature('KAIROS_BRIEF')) {
|
|
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
const { isBriefEnabled } =
|
|
require('@claude-code-best/builtin-tools/tools/BriefTool/BriefTool.js') as typeof import('@claude-code-best/builtin-tools/tools/BriefTool/BriefTool.js');
|
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
|
if (!isBriefEnabled() && !isBriefOnlyState) return;
|
|
const next = !isBriefOnlyState;
|
|
logEvent('tengu_brief_mode_toggled', {
|
|
enabled: next,
|
|
gated: false,
|
|
source: 'keybinding' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
|
|
});
|
|
setAppState(prev => {
|
|
if (prev.isBriefOnly === next) return prev;
|
|
return { ...prev, isBriefOnly: next };
|
|
});
|
|
}
|
|
}, [isBriefOnlyState, setAppState]);
|
|
|
|
// Register keybinding handlers
|
|
useKeybinding('app:toggleTodos', handleToggleTodos, {
|
|
context: 'Global',
|
|
});
|
|
useKeybinding('app:toggleTranscript', handleToggleTranscript, {
|
|
context: 'Global',
|
|
});
|
|
useKeybinding('app:toggleBrief', handleToggleBrief, {
|
|
context: 'Global',
|
|
isActive: feature('KAIROS') ? true : feature('KAIROS_BRIEF') ? true : false,
|
|
});
|
|
|
|
// Register teammate keybinding
|
|
useKeybinding(
|
|
'app:toggleTeammatePreview',
|
|
() => {
|
|
setAppState(prev => ({
|
|
...prev,
|
|
showTeammateMessagePreview: !prev.showTeammateMessagePreview,
|
|
}));
|
|
},
|
|
{
|
|
context: 'Global',
|
|
},
|
|
);
|
|
|
|
// Toggle built-in terminal panel (meta+j).
|
|
// toggle() blocks in spawnSync until the user detaches from tmux.
|
|
const handleToggleTerminal = useCallback(() => {
|
|
if (feature('TERMINAL_PANEL')) {
|
|
if (!getFeatureValue_CACHED_MAY_BE_STALE('tengu_terminal_panel', false)) {
|
|
return;
|
|
}
|
|
getTerminalPanel().toggle();
|
|
}
|
|
}, []);
|
|
useKeybinding('app:toggleTerminal', handleToggleTerminal, {
|
|
context: 'Global',
|
|
});
|
|
|
|
// Clear screen and force full redraw (ctrl+l). Recovery path when the
|
|
// terminal was cleared externally (macOS Cmd+K) and Ink's diff engine
|
|
// thinks unchanged cells don't need repainting.
|
|
const handleRedraw = useCallback(() => {
|
|
instances.get(process.stdout)?.forceRedraw();
|
|
}, []);
|
|
useKeybinding('app:redraw', handleRedraw, { context: 'Global' });
|
|
|
|
// Transcript-specific bindings (only active when in transcript mode)
|
|
const isInTranscript = screen === 'transcript';
|
|
useKeybinding('transcript:toggleShowAll', handleToggleShowAll, {
|
|
context: 'Transcript',
|
|
isActive: isInTranscript && !virtualScrollActive,
|
|
});
|
|
useKeybinding('transcript:exit', handleExitTranscript, {
|
|
context: 'Transcript',
|
|
// Bar-open is a mode (owns keystrokes). Navigating (highlights
|
|
// visible, n/N active, bar closed) is NOT — Esc exits transcript
|
|
// directly, same as less q. useSearchInput doesn't stopPropagation,
|
|
// so without this gate its onCancel AND this handler would both
|
|
// fire on one Esc (child registers first, fires first, bubbles).
|
|
isActive: isInTranscript && !searchBarOpen,
|
|
});
|
|
|
|
return null;
|
|
}
|