forked from QwenLM/qwen-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppContainer.tsx
More file actions
3255 lines (3032 loc) · 111 KB
/
AppContainer.tsx
File metadata and controls
3255 lines (3032 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
useMemo,
useState,
useCallback,
useEffect,
useRef,
useLayoutEffect,
type Dispatch,
type SetStateAction,
} from 'react';
import { type DOMElement, measureElement } from 'ink';
import { App } from './App.js';
import { AppContext } from './contexts/AppContext.js';
import { UIStateContext, type UIState } from './contexts/UIStateContext.js';
import {
UIActionsContext,
type UIActions,
} from './contexts/UIActionsContext.js';
import { ConfigContext } from './contexts/ConfigContext.js';
import {
type HistoryItem,
ToolCallStatus,
type HistoryItemWithoutId,
} from './types.js';
import { MessageType, StreamingState } from './types.js';
import {
type EditorType,
type Config,
type IdeInfo,
type IdeContext,
IdeClient,
ideContextStore,
createDebugLogger,
getErrorMessage,
getAllGeminiMdFilenames,
ShellExecutionService,
Storage,
SessionEndReason,
generatePromptSuggestion,
logPromptSuggestion,
PromptSuggestionEvent,
logSpeculation,
SpeculationEvent,
startSpeculation,
acceptSpeculation,
abortSpeculation,
type SpeculationState,
IDLE_SPECULATION,
ApprovalMode,
ConditionalRulesRegistry,
MCPDiscoveryState,
ToolConfirmationOutcome,
type WaitingToolCall,
ToolNames,
} from '@qwen-code/qwen-code-core';
import { buildResumedHistoryItems } from './utils/resumeHistoryUtils.js';
import { loadLowlight } from './utils/lowlightLoader.js';
import { restoreGoalFromHistory } from './utils/restoreGoal.js';
import {
getStickyTodos,
getStickyTodoMaxVisibleItems,
getStickyTodosLayoutKey,
getStickyTodosRenderKey,
} from './utils/todoSnapshot.js';
import type { TodoItem } from './components/TodoDisplay.js';
import { loadHierarchicalGeminiMemory } from '../config/config.js';
import {
profileCheckpoint,
finalizeStartupProfile,
} from '../utils/startupProfiler.js';
import { appEvents } from '../utils/events.js';
import process from 'node:process';
/**
* Window in which mcp-client-update events are coalesced before the cli calls
* `setTools()`. Matches Claude Code's `MCP_BATCH_FLUSH_MS` (16 ≈ one 60Hz
* frame). Smaller windows would refresh the model tool list more often
* without user benefit; larger windows would let multiple servers settle
* before the model sees them. 16ms is the sweet spot validated by Claude's
* production deployment (see design.md § 8.3 + § 3.2 Round 2).
*/
const MCP_BATCH_FLUSH_MS = 16;
/**
* Maximum time we keep the startup profile open waiting for MCP discovery to
* settle. Slightly longer than the default 30s per-server discovery timeout
* so a server that times out can still log its `outcome: failed` event into
* the profile. After this cap the profile file is written regardless.
*/
const STARTUP_PROFILE_FINALIZE_CAP_MS = 35_000;
import { useHistory } from './hooks/useHistoryManager.js';
import { useMemoryMonitor } from './hooks/useMemoryMonitor.js';
import { useThemeCommand } from './hooks/useThemeCommand.js';
import { useFeedbackDialog } from './hooks/useFeedbackDialog.js';
import { useAuthCommand } from './auth/useAuth.js';
import { useEditorSettings } from './hooks/useEditorSettings.js';
import { useSettingsCommand } from './hooks/useSettingsCommand.js';
import { useModelCommand } from './hooks/useModelCommand.js';
import { useManageModelsCommand } from './hooks/useManageModelsCommand.js';
import { useArenaCommand } from './hooks/useArenaCommand.js';
import { useApprovalModeCommand } from './hooks/useApprovalModeCommand.js';
import { useBranchCommand } from './hooks/useBranchCommand.js';
import { useResumeCommand } from './hooks/useResumeCommand.js';
import { useDeleteCommand } from './hooks/useDeleteCommand.js';
import { useSlashCommandProcessor } from './hooks/slashCommandProcessor.js';
import { useDoublePress } from './hooks/useDoublePress.js';
import {
computeApiTruncationIndex,
isRealUserTurn,
} from './utils/historyMapping.js';
import { useVimMode } from './contexts/VimModeContext.js';
import { CompactModeProvider } from './contexts/CompactModeContext.js';
import { useTerminalSize } from './hooks/useTerminalSize.js';
import { calculatePromptWidths } from './components/InputPrompt.js';
import { useStdin, useStdout } from 'ink';
import ansiEscapes from 'ansi-escapes';
import * as fs from 'node:fs';
import { basename } from 'node:path';
import { computeWindowTitle } from '../utils/windowTitle.js';
import { clearScreen } from '../utils/stdioHelpers.js';
import { useTextBuffer } from './components/shared/text-buffer.js';
import { useLogger } from './hooks/useLogger.js';
import {
useGeminiStream,
type CancelSubmitInfo,
} from './hooks/useGeminiStream.js';
import type { TrackedExecutingToolCall } from './hooks/useReactToolScheduler.js';
import { useVim } from './hooks/vim.js';
import { isBtwCommand, isSlashCommand } from './utils/commandUtils.js';
import { type LoadedSettings, SettingScope } from '../config/settings.js';
import { type InitializationResult } from '../core/initializer.js';
import { useFocus } from './hooks/useFocus.js';
import { useAwaySummary } from './hooks/useAwaySummary.js';
import { useBracketedPaste } from './hooks/useBracketedPaste.js';
import { useKeypress, type Key } from './hooks/useKeypress.js';
import { keyMatchers, Command } from './keyMatchers.js';
import { useLoadingIndicator } from './hooks/useLoadingIndicator.js';
import { useTerminalProgress } from './hooks/useTerminalProgress.js';
import { useFolderTrust } from './hooks/useFolderTrust.js';
import { useIdeTrustListener } from './hooks/useIdeTrustListener.js';
import { type IdeIntegrationNudgeResult } from './IdeIntegrationNudge.js';
import { type CommandMigrationNudgeResult } from './CommandFormatMigrationNudge.js';
import { useCommandMigration } from './hooks/useCommandMigration.js';
import { migrateTomlCommands } from '../services/command-migration-tool.js';
import { type UpdateObject } from './utils/updateCheck.js';
import { setUpdateHandler } from '../utils/handleAutoUpdate.js';
import { registerCleanup, runExitCleanup } from '../utils/cleanup.js';
import { useMessageQueue } from './hooks/useMessageQueue.js';
import { useAutoAcceptIndicator } from './hooks/useAutoAcceptIndicator.js';
import { useSessionStats } from './contexts/SessionContext.js';
import { useGitBranchName } from './hooks/useGitBranchName.js';
import {
useExtensionUpdates,
useConfirmUpdateRequests,
useSettingInputRequests,
usePluginChoiceRequests,
} from './hooks/useExtensionUpdates.js';
import { useProviderUpdates } from './hooks/useProviderUpdates.js';
import { ShellFocusContext } from './contexts/ShellFocusContext.js';
import {
RenderModeProvider,
type RenderMode,
} from './contexts/RenderModeContext.js';
import { TerminalOutputProvider } from './contexts/TerminalOutputContext.js';
import { useAgentViewState } from './contexts/AgentViewContext.js';
import {
useBackgroundTaskViewState,
useBackgroundTaskViewActions,
} from './contexts/BackgroundTaskViewContext.js';
import { t } from '../i18n/index.js';
import { useWelcomeBack } from './hooks/useWelcomeBack.js';
import { useDialogClose } from './hooks/useDialogClose.js';
import { useInitializationAuthError } from './hooks/useInitializationAuthError.js';
import { useSubagentCreateDialog } from './hooks/useSubagentCreateDialog.js';
import { useAgentsManagerDialog } from './hooks/useAgentsManagerDialog.js';
import { useExtensionsManagerDialog } from './hooks/useExtensionsManagerDialog.js';
import { useMcpDialog } from './hooks/useMcpDialog.js';
import { useHooksDialog } from './hooks/useHooksDialog.js';
import { useMemoryDialog } from './hooks/useMemoryDialog.js';
import { useAttentionNotifications } from './hooks/useAttentionNotifications.js';
import { buildTerminalNotification } from './hooks/useTerminalNotification.js';
import { useContextualTips } from './hooks/useContextualTips.js';
import { getTipHistory } from '../services/tips/index.js';
import { useRemoteInput } from '../remoteInput/RemoteInputContext.js';
import { useDualOutput } from '../dualOutput/DualOutputContext.js';
import {
requestConsentInteractive,
requestConsentOrFail,
} from '../commands/extensions/consent.js';
import { compactToggleHasVisualEffect } from './utils/mergeCompactToolGroups.js';
import {
findLastUserItemIndex,
isSyntheticHistoryItem,
itemsAfterAreOnlySynthetic,
} from './utils/historyUtils.js';
const CTRL_EXIT_PROMPT_DURATION_MS = 1000;
const debugLogger = createDebugLogger('APP_CONTAINER');
export function isRenderModeToggleKey(key: Key): boolean {
return (
keyMatchers[Command.TOGGLE_RENDER_MODE](key) ||
(key.name === 'm' && key.meta && !key.ctrl && !key.paste)
);
}
export function getNextRenderMode(current: RenderMode): RenderMode {
return current === 'render' ? 'raw' : 'render';
}
export function handleRenderModeToggleKey(
key: Key,
setRenderMode: Dispatch<SetStateAction<RenderMode>>,
): boolean {
if (!isRenderModeToggleKey(key)) {
return false;
}
setRenderMode(getNextRenderMode);
return true;
}
function isToolExecuting(pendingHistoryItems: HistoryItemWithoutId[]) {
return pendingHistoryItems.some((item) => {
if (item && item.type === 'tool_group') {
return item.tools.some(
(tool) => ToolCallStatus.Executing === tool.status,
);
}
return false;
});
}
function useStableStickyTodos(todos: TodoItem[] | null): TodoItem[] | null {
const renderKey = getStickyTodosRenderKey(todos);
const stableTodosRef = useRef<{
renderKey: string;
todos: TodoItem[] | null;
} | null>(null);
if (stableTodosRef.current?.renderKey !== renderKey) {
stableTodosRef.current = { renderKey, todos };
}
return stableTodosRef.current.todos;
}
// Exported for tests. Given a newest-first list of messages, return a list
// with duplicates removed, keeping the first (newest) occurrence of each.
export function dedupeNewestFirst(messages: readonly string[]): string[] {
const seen = new Set<string>();
const result: string[] = [];
for (const msg of messages) {
if (!seen.has(msg)) {
seen.add(msg);
result.push(msg);
}
}
return result;
}
interface AppContainerProps {
config: Config;
settings: LoadedSettings;
startupWarnings?: string[];
version: string;
initializationResult: InitializationResult;
}
/**
* The fraction of the terminal width to allocate to the shell.
* This provides horizontal padding.
*/
const SHELL_WIDTH_FRACTION = 0.89;
/**
* The number of lines to subtract from the available terminal height
* for the shell. This provides vertical padding and space for other UI elements.
*/
const SHELL_HEIGHT_PADDING = 10;
export const AppContainer = (props: AppContainerProps) => {
const { settings, config, initializationResult } = props;
const historyManager = useHistory();
// `useHistory()` returns a fresh memoized object whenever `history` changes,
// so depending on `historyManager` directly inside event-handler callbacks
// would rebuild them on every message. Mirror history into a ref so
// handlers can read the latest snapshot at call time without reactive deps.
const historyRef = useRef(historyManager.history);
historyRef.current = historyManager.history;
useMemoryMonitor(historyManager);
const [debugMessage, setDebugMessage] = useState<string>('');
const [quittingMessages, setQuittingMessages] = useState<
HistoryItem[] | null
>(null);
const [themeError, setThemeError] = useState<string | null>(
initializationResult.themeError,
);
const [isProcessing, setIsProcessing] = useState<boolean>(false);
const [embeddedShellFocused, setEmbeddedShellFocused] = useState(false);
const [geminiMdFileCount, setGeminiMdFileCount] = useState<number>(
initializationResult.geminiMdFileCount,
);
const [shellModeActive, setShellModeActive] = useState(false);
const [modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError] =
useState<boolean>(false);
const [historyRemountKey, setHistoryRemountKey] = useState(0);
const [updateInfo, setUpdateInfo] = useState<UpdateObject | null>(null);
const [isTrustedFolder, setIsTrustedFolder] = useState<boolean | undefined>(
config.isTrustedFolder(),
);
const extensionManager = config.getExtensionManager();
const { addConfirmUpdateExtensionRequest, confirmUpdateExtensionRequests } =
useConfirmUpdateRequests();
const { addSettingInputRequest, settingInputRequests } =
useSettingInputRequests();
const { addPluginChoiceRequest, pluginChoiceRequests } =
usePluginChoiceRequests();
extensionManager.setRequestConsent(
requestConsentOrFail.bind(null, (description) =>
requestConsentInteractive(description, addConfirmUpdateExtensionRequest),
),
);
extensionManager.setRequestChoicePlugin(
(marketplace) =>
new Promise<string>((resolve, reject) => {
addPluginChoiceRequest({
marketplaceName: marketplace.name,
plugins: marketplace.plugins.map((p) => ({
name: p.name,
description: p.description,
})),
onSelect: (pluginName) => {
resolve(pluginName);
},
onCancel: () => {
reject(new Error('Plugin selection cancelled'));
},
});
}),
);
extensionManager.setRequestSetting(
(setting) =>
new Promise<string>((resolve, reject) => {
addSettingInputRequest({
settingName: setting.name,
settingDescription: setting.description,
sensitive: setting.sensitive ?? false,
onSubmit: (value) => {
resolve(value);
},
onCancel: () => {
reject(new Error('Setting input cancelled'));
},
});
}),
);
const {
extensionsUpdateState,
extensionsUpdateStateInternal,
dispatchExtensionStateUpdate,
} = useExtensionUpdates(
extensionManager,
historyManager.addItem,
config.getWorkingDir(),
);
const { providerUpdateRequest, dismissProviderUpdate } = useProviderUpdates(
settings,
config,
historyManager.addItem,
);
const [isTrustDialogOpen, setTrustDialogOpen] = useState(false);
const openTrustDialog = useCallback(() => setTrustDialogOpen(true), []);
const closeTrustDialog = useCallback(() => setTrustDialogOpen(false), []);
const [isPermissionsDialogOpen, setPermissionsDialogOpen] = useState(false);
const openPermissionsDialog = useCallback(
() => setPermissionsDialogOpen(true),
[],
);
const closePermissionsDialog = useCallback(
() => setPermissionsDialogOpen(false),
[],
);
const [currentModel, setCurrentModel] = useState(() => config.getModel());
const [isConfigInitialized, setConfigInitialized] = useState(false);
const [userMessages, setUserMessages] = useState<string[]>([]);
// Terminal and layout hooks
const { columns: terminalWidth, rows: terminalHeight } = useTerminalSize();
const { stdin, setRawMode } = useStdin();
const { stdout } = useStdout();
// Raw write function for terminal escape sequences.
// Uses process.stdout directly instead of Ink's useStdout() because
// standard Ink v6.2.3 proxies stdout writes through its rendering
// pipeline, which can corrupt binary escape sequences (OSC, DCS).
const writeRaw = useCallback((data: string) => {
process.stdout.write(data);
}, []);
// Terminal notification helpers (constructed directly, not via context)
const terminal = useMemo(
() => buildTerminalNotification(writeRaw),
[writeRaw],
);
// Additional hooks moved from App.tsx
const { stats: sessionStats, startNewSession } = useSessionStats();
const logger = useLogger(config.storage, sessionStats.sessionId);
const branchName = useGitBranchName(config.getTargetDir());
// Layout measurements
const mainControlsRef = useRef<DOMElement>(null);
const originalTitleRef = useRef(
computeWindowTitle(basename(config.getTargetDir())),
);
const lastTitleRef = useRef<string | null>(null);
const staticExtraHeight = 3;
// Prefetch the lowlight chunk on mount so the dynamic import is already
// in flight before the first code block needs colorizing. Without this
// kick-off, code blocks committed to ink's append-only <Static> region
// before the import resolves stay plain text for the rest of the session
// — Static can only be re-rendered via `refreshStatic`, which is not
// wired to lowlight load completion. Common reachable paths: short
// `--prompt -p` runs that finalize quickly, Ctrl+C-cancelled first turns,
// and the first-paint history replay on `--resume`. Firing the load
// from mount keeps the startup parse-cost win (V8 still parses off the
// critical path) while restoring the "first paint sees a loaded
// instance" guarantee. Errors are silently swallowed; CodeColorizer
// already falls back to plain text on miss.
useEffect(() => {
void loadLowlight().catch((err) => {
// The loader caches rejection with a cooldown (see
// `LOWLIGHT_RETRY_COOLDOWN_MS` / `lowlightLastFailureAt` in
// `lowlightLoader.ts`). This useEffect runs once on mount, so this
// catch fires at most once per session regardless. Log to the debug
// channel so a degraded syntax-highlight state (corrupted install,
// missing chunk) leaves a breadcrumb without spamming the user's
// TTY — `CodeColorizer` already falls back to plain text.
debugLogger.warn(
`Failed to load lowlight chunk; code blocks will render as plain text: ${err instanceof Error ? err.message : String(err)}`,
);
});
}, []);
// Initialize config (runs once on mount)
useEffect(() => {
(async () => {
// Note: the program will not work if this fails so let errors be
// handled by the global catch.
profileCheckpoint('config_initialize_start');
await config.initialize();
profileCheckpoint('config_initialize_end');
setConfigInitialized(true);
profileCheckpoint('input_enabled');
// Profile finalize is intentionally NOT here. With PR-A's background
// MCP discovery, MCP-related events (`mcp_server_ready:*`,
// `mcp_first_tool_registered`, `mcp_all_servers_settled`,
// `gemini_tools_updated`) arrive AFTER `input_enabled`. The dedicated
// `useEffect` below (gated by `configInitialized`) defers finalize
// until MCP discovery settles or the 35s hard cap elapses — that way
// the profile captures the full MCP timeline without holding back
// the user-facing TTI.
const resumedSessionData = config.getResumedSessionData();
if (resumedSessionData) {
const historyItems = buildResumedHistoryItems(
resumedSessionData,
config,
);
historyManager.loadHistory(historyItems);
// Re-arm any `/goal` that was active when the prior session ended.
try {
restoreGoalFromHistory(historyItems, config, historyManager.addItem);
} catch {
// Restore is best-effort — never block resume on it.
}
const recovered = await config.loadPausedBackgroundAgents(
config.getSessionId(),
);
if (recovered.length > 0) {
historyManager.addItem(
{
type: MessageType.INFO,
text: config
.getBackgroundAgentResumeService()
.buildRecoveredBackgroundAgentsNotice(recovered.length),
},
Date.now(),
);
}
// Restore session name tag from custom title
const title = config
.getSessionService()
.getSessionTitle(config.getSessionId());
if (title) {
setSessionName(title);
}
}
})();
// Register SessionEnd cleanup for process exit
registerCleanup(async () => {
try {
await config
.getHookSystem()
?.fireSessionEndEvent(SessionEndReason.PromptInputExit);
debugLogger.debug('SessionEnd event completed successfully!!!');
} catch (err) {
debugLogger.error(`SessionEnd hook failed: ${err}`);
}
});
registerCleanup(async () => {
const ideClient = await IdeClient.getInstance();
await ideClient.disconnect();
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [config]);
/**
* PR-A wiring: progressive MCP availability.
*
* This effect does two coupled things, both gated on `configInitialized`:
*
* 1. **16ms batch-flush of `setTools()`**: as each MCP server completes
* discover, `McpClientManager` emits `mcp-client-update`. We coalesce
* these into at most one `GeminiClient.setTools()` call per ~16ms
* window. With three MCP servers settling within a few ms of each
* other, the model sees one consolidated tool refresh instead of
* three back-to-back; with a server stream over 1s, the model sees
* each batch with at most one frame of lag (this is the gap the
* baseline measured at 6235 ms in three-mixed-mcp before PR-A).
*
* 2. **Deferred startup-profile finalize**: in PR-A's default mode
* MCP discovery runs in the background, so MCP-related profiler
* events arrive AFTER `input_enabled`. The profile file is held open
* until either the manager's discovery state reaches `COMPLETED`
* (all servers ready or failed) or `STARTUP_PROFILE_FINALIZE_CAP_MS`
* elapses (so a hung server doesn't keep the profile open forever).
*
* In legacy blocking mode (`QWEN_CODE_LEGACY_MCP_BLOCKING=1`) MCP
* discovery already completed inside `config.initialize()`, so this
* effect observes `MCPDiscoveryState.COMPLETED` immediately and finalizes
* without waiting.
*/
useEffect(() => {
if (!isConfigInitialized) return undefined;
const geminiClient = config.getGeminiClient();
if (!geminiClient) return undefined;
const manager = config.getToolRegistry().getMcpClientManager();
let flushTimer: NodeJS.Timeout | null = null;
let finalized = false;
const finalizeOnce = () => {
if (finalized) return;
finalized = true;
finalizeStartupProfile(config.getSessionId());
};
// Runs the pending batched setTools() immediately and clears the timer.
// Returns a promise that resolves when setTools() finishes so callers
// can sequence subsequent work after `gemini_tools_updated` is
// recorded into the startup profile.
const flushNow = (): Promise<void> => {
if (flushTimer !== null) {
clearTimeout(flushTimer);
flushTimer = null;
}
// GeminiClient.setTools() has no try/catch around warmAll() /
// getFunctionDeclarations() / getChat().setTools(). A silent
// discard here would make production tool-registration regressions
// invisible, so route the error through debugLogger.
return geminiClient.setTools().catch((err) => {
debugLogger.error(
`setTools() batch-flush failed: ${err instanceof Error ? err.message : String(err)}`,
);
});
};
const scheduleFlush = () => {
if (flushTimer !== null) return;
flushTimer = setTimeout(() => {
flushTimer = null;
void flushNow();
}, MCP_BATCH_FLUSH_MS);
};
// Match the non-interactive entry points (`gemini.tsx`, `session.ts`,
// `acpAgent.ts`) which warn to stderr when MCP discovery completes with
// failed servers. The interactive path can't use stderr (it would
// collide with Ink's rendered output), so we route through
// `debugLogger.warn` so it shows up under `QWEN_CODE_DEBUG=1` and in
// the debug log file — matching the channel `setTools()` errors above
// use. The MCP status footer pill already surfaces failures
// continuously in the UI; this log is the actionable-on-debug record
// wenshao asked for in round 7.
let failureSurfaced = false;
const surfaceFailuresOnce = () => {
if (failureSurfaced) return;
failureSurfaced = true;
const failedNames =
typeof config.getFailedMcpServerNames === 'function'
? config.getFailedMcpServerNames()
: [];
if (failedNames.length > 0) {
debugLogger.warn(
`MCP server(s) failed to start: ${failedNames.join(', ')}. ` +
`Continuing with built-in tools and any servers that did connect.`,
);
}
};
const onMcpUpdate = () => {
if (manager.getDiscoveryState() === MCPDiscoveryState.COMPLETED) {
// Discovery has settled. Flush the pending setTools() NOW (rather
// than waiting for the 16ms batch timer) and only finalize after
// it runs — `setTools()` emits the `gemini_tools_updated` event,
// and finalizing before it fires would drop that event because
// the module-level `finalized` guard suppresses every subsequent
// record. That dropped event is what `gemini_tools_lag` is
// derived from in the profile summary.
surfaceFailuresOnce();
void flushNow().finally(finalizeOnce);
} else {
scheduleFlush();
}
};
// Legacy / no-MCP path: discovery already finished synchronously
// inside config.initialize(), so finalize immediately and only keep
// the flush listener around for late refreshes (e.g. SkillTool's
// post-construction refreshSkills triggering setTools).
if (manager.getDiscoveryState() === MCPDiscoveryState.COMPLETED) {
surfaceFailuresOnce();
finalizeOnce();
}
appEvents.on('mcp-client-update', onMcpUpdate);
const finalizeCap = setTimeout(
finalizeOnce,
STARTUP_PROFILE_FINALIZE_CAP_MS,
);
return () => {
appEvents.off('mcp-client-update', onMcpUpdate);
if (flushTimer !== null) clearTimeout(flushTimer);
clearTimeout(finalizeCap);
};
}, [isConfigInitialized, config]);
// Track idle state via ref so the update handler can defer notifications
// while the model is streaming, without triggering re-renders.
// Note: isIdleRef.current is assigned after streamingState becomes available
// (see the assignment below useGeminiStream).
const isIdleRef = useRef(true);
const updateHandlerRef = useRef<{
cleanup: () => void;
flush: () => void;
} | null>(null);
useEffect(() => {
const handler = setUpdateHandler(
historyManager.addItem,
setUpdateInfo,
isIdleRef,
);
updateHandlerRef.current = handler;
return () => handler?.cleanup();
}, [historyManager.addItem]);
// Derive widths for InputPrompt using shared helper
const { inputWidth, suggestionsWidth } = useMemo(() => {
const { inputWidth, suggestionsWidth } =
calculatePromptWidths(terminalWidth);
return { inputWidth, suggestionsWidth };
}, [terminalWidth]);
// Uniform width for bordered box components: accounts for margins and caps at 100
const mainAreaWidth = Math.min(terminalWidth - 4, 100);
const staticAreaMaxItemHeight = Math.max(terminalHeight * 4, 100);
const isValidPath = useCallback((filePath: string): boolean => {
try {
return fs.existsSync(filePath) && fs.statSync(filePath).isFile();
} catch (_e) {
return false;
}
}, []);
const buffer = useTextBuffer({
initialText: '',
viewport: { height: 10, width: inputWidth },
stdin,
setRawMode,
isValidPath,
shellModeActive,
});
useEffect(() => {
const fetchUserMessages = async () => {
const pastMessagesRaw = (await logger?.getPreviousUserMessages()) || [];
const currentSessionUserMessages = historyManager.history
.filter(
(item): item is HistoryItem & { type: 'user'; text: string } =>
item.type === 'user' &&
typeof item.text === 'string' &&
item.text.trim() !== '',
)
.map((item) => item.text)
.reverse();
// Current-session messages are already newest-first; combining with past
// messages gives a newest-first list. dedupeNewestFirst keeps the first
// (newest) occurrence so resubmitting an old prompt promotes it to
// "most recent" rather than leaving a stale copy at an older position.
const combinedMessages = [
...currentSessionUserMessages,
...pastMessagesRaw,
];
setUserMessages(dedupeNewestFirst(combinedMessages).reverse());
};
fetchUserMessages();
}, [historyManager.history, logger]);
const remountStaticHistory = useCallback(() => {
setHistoryRemountKey((prev) => prev + 1);
}, []);
const refreshStatic = useCallback(() => {
stdout.write(ansiEscapes.clearTerminal);
remountStaticHistory();
}, [remountStaticHistory, stdout]);
// Targeted repaint for resize events: move cursor to top-left and erase
// downward instead of a full clearTerminal, avoiding the full-screen
// flash. Ink's <Static> region is append-only, so when terminal width
// changes (tmux split, fullscreen toggle, font size change) we must
// explicitly re-emit the static history at the new width — otherwise
// header content stays at the old width and visibly tears.
const repaintStaticViewport = useCallback(() => {
stdout.write(`${ansiEscapes.cursorTo(0, 0)}${ansiEscapes.eraseDown}`);
remountStaticHistory();
}, [remountStaticHistory, stdout]);
// Track previous terminal width across renders so we only repaint when
// the width actually changes. Initialized to the current width to avoid
// a spurious repaint on first mount.
const previousTerminalWidthRef = useRef(terminalWidth);
// Keep the static header in sync with model changes without polling.
// Ink's <Static> output is append-only, so model changes must explicitly
// clear and remount the static region to redraw the banner at the top.
//
// Two requirements pull in opposite directions:
// (a) refreshStatic() must NOT be called from inside a setState updater,
// because React.StrictMode double-invokes updaters in dev and we'd
// fire two clearTerminal writes per model swap.
// (b) setHistoryRemountKey (inside refreshStatic) and setCurrentModel
// MUST land in the SAME commit. MainContent's <Static> key is
// `${historyRemountKey}-${currentModel}` and its render-phase
// progressive-replay reset (lastRemountKey !== historyRemountKey)
// only fires when historyRemountKey changes. If currentModel
// changes first in its own render, Static remounts with the OLD
// remount key and the unreset (full-length) replayCount — i.e.
// a full-history Static render that bypasses progressive replay
// (the issue #3899 freeze regression). See PR #4119 review.
//
// Fix: side-effect lives in the event handler (NOT the updater); a ref
// guard de-dupes same-model notifications. React batches the
// setHistoryRemountKey (via refreshStatic) and setCurrentModel calls in
// this event handler into a single commit, so the render-phase reset
// and the Static remount happen together — no full-history flash.
const lastNotifiedModelRef = useRef(currentModel);
useEffect(() => {
const unsubscribe = config.onModelChange((model) => {
if (lastNotifiedModelRef.current === model) {
return;
}
lastNotifiedModelRef.current = model;
refreshStatic();
setCurrentModel(model);
});
return unsubscribe;
}, [config, refreshStatic]);
const {
isThemeDialogOpen,
openThemeDialog,
handleThemeSelect,
handleThemeHighlight,
} = useThemeCommand(
settings,
setThemeError,
historyManager.addItem,
initializationResult.themeError,
);
const {
isApprovalModeDialogOpen,
openApprovalModeDialog,
handleApprovalModeSelect,
} = useApprovalModeCommand(settings, config);
const auth = useAuthCommand(
settings,
config,
historyManager.addItem,
refreshStatic,
);
const { state: authState, actions: authActions } = auth;
const { onAuthError, openAuthDialog, handleAuthSelect } = authActions;
const { isAuthDialogOpen, isAuthenticating, pendingAuthType } = authState;
useInitializationAuthError(initializationResult.authError, onAuthError);
// Sync user tier from config when authentication changes
// TODO: Implement getUserTier() method on Config if needed
// useEffect(() => {
// if (authState === AuthState.Authenticated) {
// setUserTier(config.getUserTier());
// }
// }, [config, authState]);
// Check for enforced auth type mismatch
useEffect(() => {
// Check for initialization error first
const currentAuthType = config.getModelsConfig().getCurrentAuthType();
if (
settings.merged.security?.auth?.enforcedType &&
currentAuthType &&
settings.merged.security?.auth.enforcedType !== currentAuthType
) {
onAuthError(
t(
'Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.',
{
enforcedType: String(settings.merged.security?.auth.enforcedType),
currentType: String(currentAuthType),
},
),
);
}
}, [settings.merged.security?.auth?.enforcedType, config, onAuthError]);
const [editorError, setEditorError] = useState<string | null>(null);
const {
isEditorDialogOpen,
openEditorDialog,
handleEditorSelect,
exitEditorDialog,
} = useEditorSettings(settings, setEditorError, historyManager.addItem);
const { isSettingsDialogOpen, openSettingsDialog, closeSettingsDialog } =
useSettingsCommand();
const { isMemoryDialogOpen, openMemoryDialog, closeMemoryDialog } =
useMemoryDialog();
const {
isModelDialogOpen,
isFastModelMode,
openModelDialog,
closeModelDialog,
} = useModelCommand();
const {
isManageModelsDialogOpen,
openManageModelsDialog,
closeManageModelsDialog,
} = useManageModelsCommand();
const { activeArenaDialog, openArenaDialog, closeArenaDialog } =
useArenaCommand();
// Session name state (set via /rename, restored on /resume)
const [sessionName, setSessionName] = useState<string | null>(null);
const {
isResumeDialogOpen,
resumeMatchedSessions,
openResumeDialog,
closeResumeDialog,
handleResume,
} = useResumeCommand({
config,
historyManager,
startNewSession,
setSessionName,
remount: refreshStatic,
});
const { handleBranch } = useBranchCommand({
config,
historyManager,
startNewSession,
setSessionName,
remount: refreshStatic,
});
const {
isDeleteDialogOpen,
openDeleteDialog,
closeDeleteDialog,
handleDelete,
handleDeleteMany,
} = useDeleteCommand({
config,
addItem: historyManager.addItem,
});
const [isHelpDialogOpen, setHelpDialogOpen] = useState(false);
const [activeHelpTab, setHelpTab] = useState<
'general' | 'commands' | 'custom-commands'
>('general');
const openHelpDialog = useCallback(() => setHelpDialogOpen(true), []);
const closeHelpDialog = useCallback(() => setHelpDialogOpen(false), []);
const { toggleVimEnabled } = useVimMode();
const {
isSubagentCreateDialogOpen,
openSubagentCreateDialog,
closeSubagentCreateDialog,
} = useSubagentCreateDialog();
const {
isAgentsManagerDialogOpen,
openAgentsManagerDialog,
closeAgentsManagerDialog,
} = useAgentsManagerDialog();
const {
isExtensionsManagerDialogOpen,
openExtensionsManagerDialog,
closeExtensionsManagerDialog,
} = useExtensionsManagerDialog();
const { isMcpDialogOpen, openMcpDialog, closeMcpDialog } = useMcpDialog();
const { isHooksDialogOpen, openHooksDialog, closeHooksDialog } =
useHooksDialog();
// Ref bridge: the guarded openRewindSelector callback is defined later
// (after useDoublePress), but slashCommandActions needs it now. The ref
// lets the useMemo capture a stable function pointer whose implementation
// is swapped in once the real callback exists.
const openRewindSelectorRef = useRef<() => void>(() => {});
const slashCommandActions = useMemo(
() => ({
openAuthDialog,
openThemeDialog,
openEditorDialog,
openMemoryDialog,
openSettingsDialog,
openModelDialog,
openManageModelsDialog,
openTrustDialog,
openArenaDialog,
openPermissionsDialog,
openApprovalModeDialog,
quit: (messages: HistoryItem[]) => {
setQuittingMessages(messages);
setTimeout(async () => {
await runExitCleanup();
process.exit(0);
}, 100);
},
setDebugMessage,
dispatchExtensionStateUpdate,
addConfirmUpdateExtensionRequest,
openSubagentCreateDialog,
openAgentsManagerDialog,
openExtensionsManagerDialog,
openMcpDialog,
openHooksDialog,
openResumeDialog,
openRewindSelector: () => openRewindSelectorRef.current(),
handleResume,
handleBranch,
openDeleteDialog,
openHelpDialog,