mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-17 13:55:50 +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
291 lines
11 KiB
TypeScript
291 lines
11 KiB
TypeScript
import { feature } from 'bun:bundle';
|
|
import * as React from 'react';
|
|
import { type ReactNode, useEffect, useMemo, useState } from 'react';
|
|
import { type Notification, useNotifications } from 'src/context/notifications.js';
|
|
import { logEvent } from 'src/services/analytics/index.js';
|
|
import { useAppState } from 'src/state/AppState.js';
|
|
import { useVoiceState } from '../../context/voice.js';
|
|
import type { VerificationStatus } from '../../hooks/useApiKeyVerification.js';
|
|
import { useIdeConnectionStatus } from '../../hooks/useIdeConnectionStatus.js';
|
|
import type { IDESelection } from '../../hooks/useIdeSelection.js';
|
|
import { useMainLoopModel } from '../../hooks/useMainLoopModel.js';
|
|
import { useVoiceEnabled } from '../../hooks/useVoiceEnabled.js';
|
|
import { Box, Text } from '@anthropic/ink';
|
|
import { useClaudeAiLimits } from '../../services/claudeAiLimitsHook.js';
|
|
import { calculateTokenWarningState } from '../../services/compact/autoCompact.js';
|
|
import type { MCPServerConnection } from '../../services/mcp/types.js';
|
|
import type { Message } from '../../types/message.js';
|
|
import { getApiKeyHelperElapsedMs, getConfiguredApiKeyHelper, getSubscriptionType } from '../../utils/auth.js';
|
|
import type { AutoUpdaterResult } from '../../utils/autoUpdater.js';
|
|
import { getExternalEditor } from '../../utils/editor.js';
|
|
import { isEnvTruthy } from '../../utils/envUtils.js';
|
|
import { formatDuration } from '../../utils/format.js';
|
|
import { setEnvHookNotifier } from '../../utils/hooks/fileChangedWatcher.js';
|
|
import { toIDEDisplayName } from '../../utils/ide.js';
|
|
import { getMessagesAfterCompactBoundary } from '../../utils/messages.js';
|
|
import { tokenCountFromLastAPIResponse } from '../../utils/tokens.js';
|
|
import { ConfigurableShortcutHint } from '../ConfigurableShortcutHint.js';
|
|
import { IdeStatusIndicator } from '../IdeStatusIndicator.js';
|
|
import { MemoryUsageIndicator } from '../MemoryUsageIndicator.js';
|
|
import { SentryErrorBoundary } from '../SentryErrorBoundary.js';
|
|
import { TokenWarning } from '../TokenWarning.js';
|
|
import { SandboxPromptFooterHint } from './SandboxPromptFooterHint.js';
|
|
|
|
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
const VoiceIndicator: typeof import('./VoiceIndicator.js').VoiceIndicator = feature('VOICE_MODE')
|
|
? require('./VoiceIndicator.js').VoiceIndicator
|
|
: () => null;
|
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
|
|
|
export const FOOTER_TEMPORARY_STATUS_TIMEOUT = 5000;
|
|
|
|
type Props = {
|
|
apiKeyStatus: VerificationStatus;
|
|
autoUpdaterResult: AutoUpdaterResult | null;
|
|
isAutoUpdating: boolean;
|
|
debug: boolean;
|
|
verbose: boolean;
|
|
messages: Message[];
|
|
onAutoUpdaterResult: (result: AutoUpdaterResult) => void;
|
|
onChangeIsUpdating: (isUpdating: boolean) => void;
|
|
ideSelection: IDESelection | undefined;
|
|
mcpClients?: MCPServerConnection[];
|
|
isInputWrapped?: boolean;
|
|
isNarrow?: boolean;
|
|
};
|
|
|
|
export function Notifications({
|
|
apiKeyStatus,
|
|
autoUpdaterResult: _autoUpdaterResult,
|
|
debug,
|
|
isAutoUpdating: _isAutoUpdating,
|
|
verbose,
|
|
messages,
|
|
onAutoUpdaterResult: _onAutoUpdaterResult,
|
|
onChangeIsUpdating: _onChangeIsUpdating,
|
|
ideSelection,
|
|
mcpClients,
|
|
isInputWrapped = false,
|
|
isNarrow = false,
|
|
}: Props): ReactNode {
|
|
const tokenUsage = useMemo(() => {
|
|
const messagesForTokenCount = getMessagesAfterCompactBoundary(messages);
|
|
return tokenCountFromLastAPIResponse(messagesForTokenCount);
|
|
}, [messages]);
|
|
|
|
// AppState-sourced model — same source as API requests. getMainLoopModel()
|
|
// re-reads settings.json on every call, so another session's /model write
|
|
// would leak into this session's display (anthropics/claude-code#37596).
|
|
const mainLoopModel = useMainLoopModel();
|
|
const isShowingCompactMessage = calculateTokenWarningState(tokenUsage, mainLoopModel).isAboveWarningThreshold;
|
|
const { status: ideStatus } = useIdeConnectionStatus(mcpClients);
|
|
const notifications = useAppState(s => s.notifications);
|
|
const { addNotification, removeNotification } = useNotifications();
|
|
const claudeAiLimits = useClaudeAiLimits();
|
|
|
|
// Register env hook notifier for CwdChanged/FileChanged feedback
|
|
useEffect(() => {
|
|
setEnvHookNotifier((text, isError) => {
|
|
addNotification({
|
|
key: 'env-hook',
|
|
text,
|
|
color: isError ? 'error' : undefined,
|
|
priority: isError ? 'medium' : 'low',
|
|
timeoutMs: isError ? 8000 : 5000,
|
|
});
|
|
});
|
|
return () => setEnvHookNotifier(null);
|
|
}, [addNotification]);
|
|
|
|
// Check if we should show the IDE selection indicator
|
|
const shouldShowIdeSelection =
|
|
ideStatus === 'connected' && (ideSelection?.filePath || (ideSelection?.text && ideSelection.lineCount > 0));
|
|
|
|
// Check if we're in overage mode for UI indicators
|
|
const isInOverageMode = claudeAiLimits.isUsingOverage;
|
|
const subscriptionType = getSubscriptionType();
|
|
const isTeamOrEnterprise = subscriptionType === 'team' || subscriptionType === 'enterprise';
|
|
|
|
// Check if the external editor hint should be shown
|
|
const editor = getExternalEditor();
|
|
const shouldShowExternalEditorHint =
|
|
isInputWrapped &&
|
|
!isShowingCompactMessage &&
|
|
apiKeyStatus !== 'invalid' &&
|
|
apiKeyStatus !== 'missing' &&
|
|
editor !== undefined;
|
|
|
|
// Show external editor hint as notification when input is wrapped
|
|
useEffect(() => {
|
|
if (shouldShowExternalEditorHint && editor) {
|
|
logEvent('tengu_external_editor_hint_shown', {});
|
|
addNotification({
|
|
key: 'external-editor-hint',
|
|
jsx: (
|
|
<Text dimColor>
|
|
<ConfigurableShortcutHint
|
|
action="chat:externalEditor"
|
|
context="Chat"
|
|
fallback="ctrl+g"
|
|
description={`edit in ${toIDEDisplayName(editor)}`}
|
|
/>
|
|
</Text>
|
|
),
|
|
priority: 'immediate',
|
|
timeoutMs: 5000,
|
|
});
|
|
} else {
|
|
removeNotification('external-editor-hint');
|
|
}
|
|
}, [shouldShowExternalEditorHint, editor, addNotification, removeNotification]);
|
|
|
|
return (
|
|
<SentryErrorBoundary>
|
|
<Box flexDirection="column" alignItems={isNarrow ? 'flex-start' : 'flex-end'} flexShrink={0} overflowX="hidden">
|
|
<NotificationContent
|
|
ideSelection={ideSelection}
|
|
mcpClients={mcpClients}
|
|
notifications={notifications}
|
|
isInOverageMode={isInOverageMode ?? false}
|
|
isTeamOrEnterprise={isTeamOrEnterprise}
|
|
apiKeyStatus={apiKeyStatus}
|
|
debug={debug}
|
|
verbose={verbose}
|
|
tokenUsage={tokenUsage}
|
|
mainLoopModel={mainLoopModel}
|
|
/>
|
|
</Box>
|
|
</SentryErrorBoundary>
|
|
);
|
|
}
|
|
|
|
function NotificationContent({
|
|
ideSelection,
|
|
mcpClients,
|
|
notifications,
|
|
isInOverageMode,
|
|
isTeamOrEnterprise,
|
|
apiKeyStatus,
|
|
debug,
|
|
verbose,
|
|
tokenUsage,
|
|
mainLoopModel,
|
|
}: {
|
|
ideSelection: IDESelection | undefined;
|
|
mcpClients?: MCPServerConnection[];
|
|
notifications: {
|
|
current: Notification | null;
|
|
queue: Notification[];
|
|
};
|
|
isInOverageMode: boolean;
|
|
isTeamOrEnterprise: boolean;
|
|
apiKeyStatus: VerificationStatus;
|
|
debug: boolean;
|
|
verbose: boolean;
|
|
tokenUsage: number;
|
|
mainLoopModel: string;
|
|
}): ReactNode {
|
|
// Poll apiKeyHelper inflight state to show slow-helper notice.
|
|
// Gated on configuration — most users never set apiKeyHelper, so the
|
|
// effect is a no-op for them (no interval allocated).
|
|
const [apiKeyHelperSlow, setApiKeyHelperSlow] = useState<string | null>(null);
|
|
useEffect(() => {
|
|
if (!getConfiguredApiKeyHelper()) return;
|
|
const interval = setInterval(
|
|
(setSlow: React.Dispatch<React.SetStateAction<string | null>>) => {
|
|
const ms = getApiKeyHelperElapsedMs();
|
|
const next = ms >= 10_000 ? formatDuration(ms) : null;
|
|
setSlow(prev => (next === prev ? prev : next));
|
|
},
|
|
1000,
|
|
setApiKeyHelperSlow,
|
|
);
|
|
return () => clearInterval(interval);
|
|
}, []);
|
|
|
|
// Voice state (VOICE_MODE builds only, runtime-gated by GrowthBook)
|
|
const voiceStateRaw = useVoiceState(s => s.voiceState);
|
|
const voiceState = feature('VOICE_MODE') ? voiceStateRaw : ('idle' as const);
|
|
const voiceEnabledRaw = useVoiceEnabled();
|
|
const voiceEnabled = feature('VOICE_MODE') ? voiceEnabledRaw : false;
|
|
const voiceErrorRaw = useVoiceState(s => s.voiceError);
|
|
const voiceError = feature('VOICE_MODE') ? voiceErrorRaw : null;
|
|
const isBriefOnlyState = useAppState(s => s.isBriefOnly);
|
|
const isBriefOnly = feature('KAIROS') || feature('KAIROS_BRIEF') ? isBriefOnlyState : false;
|
|
|
|
// When voice is actively recording or processing, replace all
|
|
// notifications with just the voice indicator.
|
|
if (feature('VOICE_MODE') && voiceEnabled && (voiceState === 'recording' || voiceState === 'processing')) {
|
|
return <VoiceIndicator voiceState={voiceState} />;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<IdeStatusIndicator ideSelection={ideSelection} mcpClients={mcpClients} />
|
|
{notifications.current &&
|
|
('jsx' in notifications.current ? (
|
|
<Text wrap="truncate" key={notifications.current.key}>
|
|
{notifications.current.jsx}
|
|
</Text>
|
|
) : (
|
|
<Text color={notifications.current.color} dimColor={!notifications.current.color} wrap="truncate">
|
|
{notifications.current.text}
|
|
</Text>
|
|
))}
|
|
{isInOverageMode && !isTeamOrEnterprise && (
|
|
<Box>
|
|
<Text dimColor wrap="truncate">
|
|
Now using extra usage
|
|
</Text>
|
|
</Box>
|
|
)}
|
|
{apiKeyHelperSlow && (
|
|
<Box>
|
|
<Text color="warning" wrap="truncate">
|
|
apiKeyHelper is taking a while{' '}
|
|
</Text>
|
|
<Text dimColor wrap="truncate">
|
|
({apiKeyHelperSlow})
|
|
</Text>
|
|
</Box>
|
|
)}
|
|
{(apiKeyStatus === 'invalid' || apiKeyStatus === 'missing') && (
|
|
<Box>
|
|
<Text color="error" wrap="truncate">
|
|
{isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)
|
|
? 'Authentication error · Try again'
|
|
: 'Not logged in · Run /login'}
|
|
</Text>
|
|
</Box>
|
|
)}
|
|
{debug && (
|
|
<Box>
|
|
<Text color="warning" wrap="truncate">
|
|
Debug mode
|
|
</Text>
|
|
</Box>
|
|
)}
|
|
{apiKeyStatus !== 'invalid' && apiKeyStatus !== 'missing' && verbose && (
|
|
<Box>
|
|
<Text dimColor wrap="truncate">
|
|
{tokenUsage} tokens
|
|
</Text>
|
|
</Box>
|
|
)}
|
|
{!isBriefOnly && <TokenWarning tokenUsage={tokenUsage} model={mainLoopModel} />}
|
|
{feature('VOICE_MODE')
|
|
? voiceEnabled &&
|
|
voiceError && (
|
|
<Box>
|
|
<Text color="error" wrap="truncate">
|
|
{voiceError}
|
|
</Text>
|
|
</Box>
|
|
)
|
|
: null}
|
|
<MemoryUsageIndicator />
|
|
<SandboxPromptFooterHint />
|
|
</>
|
|
);
|
|
}
|