forked from vybestack/llxprt-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppContainer.tsx
More file actions
2464 lines (2183 loc) · 71.9 KB
/
AppContainer.tsx
File metadata and controls
2464 lines (2183 loc) · 71.9 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 Vybestack LLC
* SPDX-License-Identifier: Apache-2.0
*/
import React, {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useState,
useRef,
} from 'react';
import { type DOMElement, measureElement, useStdin, useStdout } from 'ink';
import {
StreamingState,
MessageType,
ToolCallStatus,
type HistoryItemWithoutId,
type HistoryItem,
type IndividualToolCallDisplay,
} from './types.js';
import { useTerminalSize } from './hooks/useTerminalSize.js';
import { useResponsive } from './hooks/useResponsive.js';
import { useGeminiStream } from './hooks/useGeminiStream.js';
import { useLoadingIndicator } from './hooks/useLoadingIndicator.js';
import { useThemeCommand } from './hooks/useThemeCommand.js';
import { useAuthCommand } from './hooks/useAuthCommand.js';
import { useFolderTrust } from './hooks/useFolderTrust.js';
import { useWelcomeOnboarding } from './hooks/useWelcomeOnboarding.js';
import { useIdeTrustListener } from './hooks/useIdeTrustListener.js';
import { useEditorSettings } from './hooks/useEditorSettings.js';
import { useSlashCommandProcessor } from './hooks/slashCommandProcessor.js';
import { useAutoAcceptIndicator } from './hooks/useAutoAcceptIndicator.js';
import { useConsoleMessages } from './hooks/useConsoleMessages.js';
import { useExtensionAutoUpdate } from './hooks/useExtensionAutoUpdate.js';
import { useExtensionUpdates } from './hooks/useExtensionUpdates.js';
import { isMouseEventsActive, setMouseEventsActive } from './utils/mouse.js';
import { loadHierarchicalLlxprtMemory } from '../config/config.js';
import {
DEFAULT_HISTORY_MAX_BYTES,
DEFAULT_HISTORY_MAX_ITEMS,
} from '../constants/historyLimits.js';
import { LoadedSettings, SettingScope } from '../config/settings.js';
import { ConsolePatcher } from './utils/ConsolePatcher.js';
import { registerCleanup } from '../utils/cleanup.js';
import { useHistory } from './hooks/useHistoryManager.js';
import { useInputHistoryStore } from './hooks/useInputHistoryStore.js';
import { useMemoryMonitor } from './hooks/useMemoryMonitor.js';
import {
useTodoPausePreserver,
TodoPausePreserver,
} from './hooks/useTodoPausePreserver.js';
import process from 'node:process';
import {
getErrorMessage,
type Config,
getAllLlxprtMdFilenames,
isEditorAvailable,
EditorType,
type IdeContext,
ideContext,
type IModel,
// type IdeInfo, // TODO: Fix IDE integration
getSettingsService,
DebugLogger,
uiTelemetryService,
SessionPersistenceService,
type PersistedSession,
type IContent,
type ToolCallBlock,
type ToolResponseBlock,
} from '@vybestack/llxprt-code-core';
import { IdeIntegrationNudgeResult } from './IdeIntegrationNudge.js';
import { validateAuthMethod } from '../config/auth.js';
import { useLogger } from './hooks/useLogger.js';
import { useSessionStats } from './contexts/SessionContext.js';
import { useGitBranchName } from './hooks/useGitBranchName.js';
import { useFocus } from './hooks/useFocus.js';
import { useBracketedPaste } from './hooks/useBracketedPaste.js';
import { useTextBuffer } from './components/shared/text-buffer.js';
import { SubagentView } from './components/SubagentManagement/types.js';
import { useVimMode } from './contexts/VimModeContext.js';
import { useVim } from './hooks/vim.js';
import { useKeypress, Key } from './hooks/useKeypress.js';
import { keyMatchers, Command } from './keyMatchers.js';
import * as fs from 'fs';
import { type AppState, type AppAction } from './reducers/appReducer.js';
import { UpdateObject } from './utils/updateCheck.js';
import ansiEscapes from 'ansi-escapes';
import { useSettingsCommand } from './hooks/useSettingsCommand.js';
import { setUpdateHandler } from '../utils/handleAutoUpdate.js';
import { appEvents, AppEvent } from '../utils/events.js';
import { useRuntimeApi } from './contexts/RuntimeContext.js';
import { submitOAuthCode } from './oauth-submission.js';
import { useProviderModelDialog } from './hooks/useProviderModelDialog.js';
import { useProviderDialog } from './hooks/useProviderDialog.js';
import { useLoadProfileDialog } from './hooks/useLoadProfileDialog.js';
import { useCreateProfileDialog } from './hooks/useCreateProfileDialog.js';
import { useProfileManagement } from './hooks/useProfileManagement.js';
import { useToolsDialog } from './hooks/useToolsDialog.js';
import {
shouldUpdateTokenMetrics,
toTokenMetricsSnapshot,
type TokenMetricsSnapshot,
} from './utils/tokenMetricsTracker.js';
import { useStaticHistoryRefresh } from './hooks/useStaticHistoryRefresh.js';
import { useTodoContext } from './contexts/TodoContext.js';
import { useWorkspaceMigration } from './hooks/useWorkspaceMigration.js';
import { useFlickerDetector } from './hooks/useFlickerDetector.js';
import { useMouseSelection } from './hooks/useMouseSelection.js';
import { isWorkspaceTrusted } from '../config/trustedFolders.js';
import { globalOAuthUI } from '../auth/global-oauth-ui.js';
import { UIStateProvider, type UIState } from './contexts/UIStateContext.js';
import {
UIActionsProvider,
type UIActions,
} from './contexts/UIActionsContext.js';
import { DefaultAppLayout } from './layouts/DefaultAppLayout.js';
import {
disableBracketedPaste,
enableBracketedPaste,
} from './utils/bracketedPaste.js';
import { enableSupportedProtocol } from './utils/kittyProtocolDetector.js';
import {
ENABLE_FOCUS_TRACKING,
DISABLE_FOCUS_TRACKING,
SHOW_CURSOR,
} from './utils/terminalSequences.js';
import { calculateMainAreaWidth } from './utils/ui-sizing.js';
const CTRL_EXIT_PROMPT_DURATION_MS = 1000;
const QUEUE_ERROR_DISPLAY_DURATION_MS = 3000;
const debug = new DebugLogger('llxprt:ui:appcontainer');
const selectionLogger = new DebugLogger('llxprt:ui:selection');
interface AppContainerProps {
config: Config;
settings: LoadedSettings;
startupWarnings?: string[];
version: string;
appState: AppState;
appDispatch: React.Dispatch<AppAction>;
restoredSession?: PersistedSession;
}
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;
});
}
// Valid history item types for session restore validation (must be module-level for stable reference)
const VALID_HISTORY_TYPES = new Set([
'user',
'gemini',
'gemini_content',
'oauth_url',
'info',
'error',
'warning',
'about',
'help',
'stats',
'model_stats',
'tool_stats',
'cache_stats',
'lb_stats',
'quit',
'tool_group',
'user_shell',
'compression',
'extensions_list',
'tools_list',
'mcp_status',
'chat_list',
]);
export const AppContainer = (props: AppContainerProps) => {
debug.log('AppContainer architecture active (v2)');
const {
config,
settings,
startupWarnings = [],
appState,
appDispatch,
restoredSession,
} = props;
const runtime = useRuntimeApi();
const isFocused = useFocus();
const { isNarrow } = useResponsive();
useBracketedPaste();
const [updateInfo, setUpdateInfo] = useState<UpdateObject | null>(null);
const { stdout } = useStdout();
const { stdin, setRawMode } = useStdin();
const nightly = props.version.includes('nightly'); // TODO: Use for nightly-specific features
const historyLimits = useMemo(
() => ({
maxItems:
typeof settings.merged.ui?.historyMaxItems === 'number'
? settings.merged.ui.historyMaxItems
: DEFAULT_HISTORY_MAX_ITEMS,
maxBytes:
typeof settings.merged.ui?.historyMaxBytes === 'number'
? settings.merged.ui.historyMaxBytes
: DEFAULT_HISTORY_MAX_BYTES,
}),
[settings.merged.ui?.historyMaxItems, settings.merged.ui?.historyMaxBytes],
);
const { history, addItem, clearItems, loadHistory } =
useHistory(historyLimits);
useMemoryMonitor({ addItem });
const { updateTodos } = useTodoContext();
const todoPauseController = useMemo(() => new TodoPausePreserver(), []);
const registerTodoPause = useCallback(() => {
todoPauseController.registerTodoPause();
}, [todoPauseController]);
const [idePromptAnswered, setIdePromptAnswered] = useState(false);
const currentIDE = config.getIdeClient()?.getCurrentIde();
useEffect(() => {
const ideClient = config.getIdeClient();
if (ideClient) {
registerCleanup(() => ideClient.disconnect());
}
}, [config]);
const shouldShowIdePrompt =
currentIDE &&
!config.getIdeMode() &&
!settings.merged.hasSeenIdeIntegrationNudge &&
!idePromptAnswered;
useEffect(() => {
const cleanup = setUpdateHandler(addItem, setUpdateInfo);
// Attach addItem to OAuth providers for displaying auth URLs
if (addItem) {
const oauthManager = runtime.getCliOAuthManager();
if (oauthManager) {
const providersMap = (
oauthManager as unknown as { providers?: Map<string, unknown> }
).providers;
if (providersMap instanceof Map) {
for (const provider of providersMap.values()) {
const candidate = provider as {
setAddItem?: (callback: typeof addItem) => void;
};
candidate.setAddItem?.(addItem);
}
}
}
}
return cleanup;
}, [addItem, runtime]);
// Set global OAuth addItem callback for all OAuth flows
useEffect(() => {
(global as Record<string, unknown>).__oauth_add_item = addItem;
globalOAuthUI.setAddItem(addItem);
return () => {
delete (global as Record<string, unknown>).__oauth_add_item;
globalOAuthUI.clearAddItem();
};
}, [addItem]);
const {
consoleMessages,
handleNewMessage,
clearConsoleMessages: clearConsoleMessagesState,
} = useConsoleMessages();
useExtensionAutoUpdate({
settings,
onConsoleMessage: handleNewMessage,
});
useEffect(() => {
const consolePatcher = new ConsolePatcher({
onNewMessage: handleNewMessage,
debugMode: config.getDebugMode(),
});
consolePatcher.patch();
registerCleanup(consolePatcher.cleanup);
}, [handleNewMessage, config]);
const { stats: sessionStats, updateHistoryTokenCount } = useSessionStats();
const historyTokenCleanupRef = useRef<(() => void) | null>(null);
const lastHistoryServiceRef = useRef<unknown>(null);
const lastPublishedHistoryTokensRef = useRef<number | null>(null);
const tokenLogger = useMemo(
() => new DebugLogger('llxprt:ui:tokentracking'),
[],
);
// Set up history token count listener
useEffect(() => {
let intervalCleared = false;
// Poll continuously to detect when the history service changes (e.g., after compression)
const checkInterval = setInterval(() => {
if (intervalCleared) return;
const geminiClient = config.getGeminiClient();
// Check if chat is initialized first
if (geminiClient?.hasChatInitialized?.()) {
const historyService = geminiClient.getHistoryService?.();
if (!historyService && lastHistoryServiceRef.current === null) {
tokenLogger.debug(() => 'No history service available yet');
} else if (historyService) {
// Always get the current token count even if not a new instance
const currentTokens = historyService.getTotalTokens();
if (
currentTokens > 0 &&
currentTokens !== lastPublishedHistoryTokensRef.current
) {
lastPublishedHistoryTokensRef.current = currentTokens;
updateHistoryTokenCount(currentTokens);
}
}
// Check if we have a new history service instance (happens after compression)
if (
historyService &&
historyService !== lastHistoryServiceRef.current
) {
tokenLogger.debug(
() => 'Found new history service, setting up listener',
);
// Clean up old listener if it exists
if (historyTokenCleanupRef.current) {
historyTokenCleanupRef.current();
historyTokenCleanupRef.current = null;
}
// Store reference to current history service
lastHistoryServiceRef.current = historyService;
const handleTokensUpdated = (event: { totalTokens: number }) => {
tokenLogger.debug(
() =>
`Received tokensUpdated event: totalTokens=${event.totalTokens}`,
);
if (event.totalTokens !== lastPublishedHistoryTokensRef.current) {
lastPublishedHistoryTokensRef.current = event.totalTokens;
updateHistoryTokenCount(event.totalTokens);
}
};
historyService.on('tokensUpdated', handleTokensUpdated);
// Initialize with current token count
const currentTokens = historyService.getTotalTokens();
tokenLogger.debug(() => `Initial token count: ${currentTokens}`);
lastPublishedHistoryTokensRef.current = currentTokens;
updateHistoryTokenCount(currentTokens);
// Store cleanup function for later
historyTokenCleanupRef.current = () => {
historyService.off('tokensUpdated', handleTokensUpdated);
};
}
}
}, 100); // Check every 100ms
return () => {
clearInterval(checkInterval);
intervalCleared = true;
// Clean up the event listener if it was set up
if (historyTokenCleanupRef.current) {
historyTokenCleanupRef.current();
historyTokenCleanupRef.current = null;
}
lastHistoryServiceRef.current = null;
lastPublishedHistoryTokensRef.current = null;
};
}, [config, updateHistoryTokenCount, tokenLogger]);
// Convert IContent[] to UI HistoryItem[] for display
const convertToUIHistory = useCallback(
(history: IContent[]): HistoryItem[] => {
const items: HistoryItem[] = [];
let id = 1;
// First pass: collect all tool responses by callId for lookup
const toolResponseMap = new Map<string, ToolResponseBlock>();
for (const content of history) {
if (content.speaker === 'tool') {
const responseBlocks = content.blocks.filter(
(b): b is ToolResponseBlock => b.type === 'tool_response',
);
for (const resp of responseBlocks) {
toolResponseMap.set(resp.callId, resp);
}
}
}
for (const content of history) {
// Extract text blocks
const textBlocks = content.blocks.filter(
(b): b is { type: 'text'; text: string } => b.type === 'text',
);
const text = textBlocks.map((b) => b.text).join('\n');
// Extract tool call blocks for AI
const toolCallBlocks = content.blocks.filter(
(b): b is ToolCallBlock => b.type === 'tool_call',
);
if (content.speaker === 'human' && text) {
items.push({
id: id++,
type: 'user',
text,
} as HistoryItem);
} else if (content.speaker === 'ai') {
// Add text response if present
if (text) {
items.push({
id: id++,
type: 'gemini',
text,
model: content.metadata?.model,
} as HistoryItem);
}
// Add tool calls as proper tool_group items
if (toolCallBlocks.length > 0) {
const tools: IndividualToolCallDisplay[] = toolCallBlocks.map(
(tc) => {
const response = toolResponseMap.get(tc.id);
// Format result display from tool response
let resultDisplay: string | undefined;
if (response) {
if (response.error) {
resultDisplay = `Error: ${response.error}`;
} else if (response.result !== undefined) {
// Convert result to string for display
const result = response.result as Record<string, unknown>;
if (typeof result === 'string') {
resultDisplay = result;
} else if (result && typeof result === 'object') {
// Handle common result formats
if (
'output' in result &&
typeof result.output === 'string'
) {
resultDisplay = result.output;
} else {
resultDisplay = JSON.stringify(result, null, 2);
}
}
}
}
return {
callId: tc.id,
name: tc.name,
description: tc.description || '',
resultDisplay,
status: response
? ToolCallStatus.Success
: ToolCallStatus.Pending,
confirmationDetails: undefined,
};
},
);
items.push({
id: id++,
type: 'tool_group',
agentId: 'primary',
tools,
} as HistoryItem);
}
}
// Skip tool speaker entries - already processed via map
}
return items;
},
[],
);
// Session restoration for --continue functionality
// Split into two parts: UI restoration (immediate) and core history (when available)
const sessionRestoredRef = useRef(false);
const coreHistoryRestoredRef = useRef(false);
/**
* Validates that an item matches the HistoryItem schema.
* Uses duck typing for flexibility with minor schema changes.
*/
const isValidHistoryItem = useCallback(
(item: unknown): item is HistoryItem => {
if (typeof item !== 'object' || item === null) {
return false;
}
const obj = item as Record<string, unknown>;
// Required fields
if (typeof obj.id !== 'number') return false;
if (typeof obj.type !== 'string') return false;
// Check if type is valid (allow unknown types from newer versions)
if (!VALID_HISTORY_TYPES.has(obj.type)) {
debug.warn(`Unknown history item type: ${obj.type}`);
// Allow unknown types to pass - might be from newer version
}
// Type-specific validation
switch (obj.type) {
case 'user':
case 'gemini':
case 'gemini_content':
case 'info':
case 'warning':
case 'error':
case 'user_shell':
// Text types should have text (but might be empty)
return typeof obj.text === 'string' || obj.text === undefined;
case 'tool_group':
// Tool groups must have tools array
if (!Array.isArray(obj.tools)) return false;
return obj.tools.every(
(tool) =>
typeof tool === 'object' &&
tool !== null &&
typeof (tool as Record<string, unknown>).callId === 'string' &&
typeof (tool as Record<string, unknown>).name === 'string',
);
default:
// For other types, just having id and type is enough
return true;
}
},
[],
);
/**
* Validates all items in a history array.
* Returns valid items, filters invalid ones.
*/
const validateUIHistory = useCallback(
(items: unknown[]): { valid: HistoryItem[]; invalidCount: number } => {
const valid: HistoryItem[] = [];
let invalidCount = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (isValidHistoryItem(item)) {
valid.push(item);
} else {
debug.warn(`Invalid history item at index ${i}:`, item);
invalidCount++;
}
}
return { valid, invalidCount };
},
[isValidHistoryItem],
);
// Part 1: Restore UI history immediately on mount
useEffect(() => {
if (!restoredSession || sessionRestoredRef.current) {
return;
}
sessionRestoredRef.current = true;
try {
// Use saved UI history if available (preserves exact display), otherwise convert from core history
let uiHistoryItems: HistoryItem[];
let usedFallback = false;
let invalidCount = 0;
if (
restoredSession.uiHistory &&
Array.isArray(restoredSession.uiHistory)
) {
// Validate UI history items before loading
const validation = validateUIHistory(restoredSession.uiHistory);
invalidCount = validation.invalidCount;
if (invalidCount > 0) {
debug.warn(`${invalidCount} invalid UI history items found`);
if (validation.valid.length === 0) {
// All items invalid - fall back to conversion
debug.warn('All UI history invalid, falling back to conversion');
uiHistoryItems = convertToUIHistory(restoredSession.history);
usedFallback = true;
} else {
// Some items valid - use them
uiHistoryItems = validation.valid;
}
} else {
uiHistoryItems = validation.valid;
}
if (!usedFallback) {
debug.log(`Using saved UI history (${uiHistoryItems.length} items)`);
}
} else {
uiHistoryItems = convertToUIHistory(restoredSession.history);
usedFallback = true;
debug.log(
`Converted core history to UI (${uiHistoryItems.length} items)`,
);
}
loadHistory(uiHistoryItems);
debug.log(
`Restored ${restoredSession.history.length} messages (${uiHistoryItems.length} UI items) for display`,
);
// Add info message about restoration
const sessionTime = new Date(
restoredSession.updatedAt || restoredSession.createdAt,
).toLocaleString();
const source = usedFallback
? 'converted from core'
: 'restored from UI cache';
addItem(
{
type: 'info',
text: `Session restored (${uiHistoryItems.length} messages ${source} from ${sessionTime})`,
},
Date.now(),
);
// Warn if some items were corrupted
if (invalidCount > 0 && !usedFallback) {
addItem(
{
type: 'warning',
text: `${invalidCount} corrupted message(s) could not be displayed.`,
},
Date.now(),
);
}
} catch (err) {
debug.error('Failed to restore UI history:', err);
addItem(
{
type: 'warning',
text: 'Failed to restore previous session display.',
},
Date.now(),
);
}
}, [
restoredSession,
convertToUIHistory,
loadHistory,
addItem,
validateUIHistory,
]);
// Part 2: Restore core history when historyService becomes available (for AI context)
useEffect(() => {
if (!restoredSession || coreHistoryRestoredRef.current) {
return;
}
const TIMEOUT_MS = 30000; // 30 second timeout
const timeout = setTimeout(() => {
clearInterval(checkInterval);
debug.warn(
'Timed out waiting for history service to restore core history',
);
addItem(
{
type: 'warning',
text: 'Could not restore AI context - history service unavailable.',
},
Date.now(),
);
}, TIMEOUT_MS);
const checkInterval = setInterval(() => {
const geminiClient = config.getGeminiClient();
const historyService = geminiClient?.getHistoryService?.();
if (!historyService) {
return;
}
clearInterval(checkInterval);
clearTimeout(timeout);
coreHistoryRestoredRef.current = true;
try {
historyService.validateAndFix();
historyService.addAll(restoredSession.history);
debug.log(
`Restored ${restoredSession.history.length} items to core history for AI context`,
);
} catch (err) {
debug.error('Failed to restore core history:', err);
// Notify user that AI context is missing - this is critical!
addItem(
{
type: 'warning',
text: 'Previous session display restored, but AI context could not be loaded. The AI will not remember the previous conversation.',
},
Date.now(),
);
}
}, 100);
return () => {
clearInterval(checkInterval);
clearTimeout(timeout);
};
}, [restoredSession, config, addItem]);
const [_staticNeedsRefresh, setStaticNeedsRefresh] = useState(false);
const [staticKey, setStaticKey] = useState(0);
const externalEditorStateRef = useRef<{
paused: boolean;
rawModeManaged: boolean;
} | null>(null);
const keypressRefreshRef = useRef<() => void>(() => {});
const useAlternateBuffer =
settings.merged.ui?.useAlternateBuffer === true &&
!config.getScreenReader();
const restoreTerminalStateAfterEditor = useCallback(() => {
const editorState = externalEditorStateRef.current;
if (!stdin) {
return;
}
const readStream = stdin as NodeJS.ReadStream;
if (editorState?.paused && typeof readStream.resume === 'function') {
readStream.resume();
}
if (editorState?.rawModeManaged && setRawMode) {
try {
setRawMode(true);
} catch (error) {
console.error('Failed to re-enable raw mode:', error);
}
}
if (keypressRefreshRef.current) {
keypressRefreshRef.current();
debug.debug(
() => 'Keypress refresh requested after external editor closed',
);
}
externalEditorStateRef.current = null;
}, [setRawMode, stdin]);
const refreshStatic = useCallback(() => {
if (useAlternateBuffer) {
restoreTerminalStateAfterEditor();
enableBracketedPaste();
enableSupportedProtocol();
stdout.write(ENABLE_FOCUS_TRACKING);
stdout.write(SHOW_CURSOR);
return;
}
stdout.write(ansiEscapes.clearTerminal);
setStaticKey((prev) => prev + 1);
restoreTerminalStateAfterEditor();
// Re-send terminal control sequences
enableBracketedPaste();
enableSupportedProtocol();
stdout.write(ENABLE_FOCUS_TRACKING);
stdout.write(SHOW_CURSOR);
}, [
restoreTerminalStateAfterEditor,
setStaticKey,
stdout,
useAlternateBuffer,
]);
const handleExternalEditorOpen = useCallback(() => {
if (!stdin) {
return;
}
const readStream = stdin as NodeJS.ReadStream;
externalEditorStateRef.current = {
paused: false,
rawModeManaged: false,
};
if (typeof readStream.pause === 'function') {
readStream.pause();
externalEditorStateRef.current.paused = true;
}
if (setRawMode) {
try {
setRawMode(false);
externalEditorStateRef.current.rawModeManaged = true;
} catch (error) {
console.error('Failed to disable raw mode:', error);
}
}
disableBracketedPaste();
stdout.write(DISABLE_FOCUS_TRACKING);
stdout.write(SHOW_CURSOR);
}, [setRawMode, stdin, stdout]);
useStaticHistoryRefresh(history, refreshStatic);
const [llxprtMdFileCount, setLlxprtMdFileCount] = useState<number>(0);
const [debugMessage, setDebugMessage] = useState<string>('');
const [themeError, _setThemeError] = useState<string | null>(null);
const [authError, setAuthError] = useState<string | null>(null);
const [editorError, _setEditorError] = useState<string | null>(null);
const [footerHeight, setFooterHeight] = useState<number>(0);
// Token metrics state for live updates
const [tokenMetrics, setTokenMetrics] = useState({
tokensPerMinute: 0,
throttleWaitTimeMs: 0,
sessionTokenTotal: 0,
});
const tokenMetricsSnapshotRef = useRef<TokenMetricsSnapshot | null>(null);
const [_corgiMode, setCorgiMode] = useState(false);
const [_isTrustedFolderState, _setIsTrustedFolder] = useState(
isWorkspaceTrusted(settings.merged),
);
const [currentModel, setCurrentModel] = useState(config.getModel());
const [shellModeActive, setShellModeActive] = useState(false);
const [showErrorDetails, setShowErrorDetails] = useState<boolean>(false);
const [showToolDescriptions, setShowToolDescriptions] =
useState<boolean>(false);
const [showDebugProfiler, setShowDebugProfiler] = useState(false);
const [renderMarkdown, setRenderMarkdown] = useState<boolean>(true);
const [isTodoPanelCollapsed, setIsTodoPanelCollapsed] = useState(false);
const [ctrlCPressedOnce, setCtrlCPressedOnce] = useState(false);
const [quittingMessages, setQuittingMessages] = useState<
HistoryItem[] | null
>(null);
const ctrlCTimerRef = useRef<NodeJS.Timeout | null>(null);
const [ctrlDPressedOnce, setCtrlDPressedOnce] = useState(false);
const ctrlDTimerRef = useRef<NodeJS.Timeout | null>(null);
const [constrainHeight, setConstrainHeight] = useState<boolean>(true);
const [showPrivacyNotice, setShowPrivacyNotice] = useState<boolean>(false);
const [ideContextState, setIdeContextState] = useState<
IdeContext | undefined
>();
const [showEscapePrompt, setShowEscapePrompt] = useState(false);
const [showIdeRestartPrompt, setShowIdeRestartPrompt] = useState(false);
const [isProcessing, setIsProcessing] = useState<boolean>(false);
const [providerModels, setProviderModels] = useState<IModel[]>([]);
const [isPermissionsDialogOpen, setIsPermissionsDialogOpen] = useState(false);
const openPermissionsDialog = useCallback(() => {
setIsPermissionsDialogOpen(true);
}, []);
const closePermissionsDialog = useCallback(() => {
setIsPermissionsDialogOpen(false);
}, []);
const [isLoggingDialogOpen, setIsLoggingDialogOpen] = useState(false);
const [loggingDialogData, setLoggingDialogData] = useState<{
entries: unknown[];
}>({ entries: [] });
// Subagent dialog state
const [isSubagentDialogOpen, setIsSubagentDialogOpen] = useState(false);
const [subagentDialogInitialView, setSubagentDialogInitialView] = useState<
SubagentView | undefined
>(undefined);
const [subagentDialogInitialName, setSubagentDialogInitialName] = useState<
string | undefined
>(undefined);
// Queue error message state (for preventing slash/shell commands from being queued)
const [queueErrorMessage, setQueueErrorMessage] = useState<string | null>(
null,
);
const openLoggingDialog = useCallback((data?: { entries: unknown[] }) => {
setLoggingDialogData(data || { entries: [] });
setIsLoggingDialogOpen(true);
}, []);
const closeLoggingDialog = useCallback(() => {
setIsLoggingDialogOpen(false);
}, []);
const openSubagentDialog = useCallback(
(initialView?: SubagentView, initialName?: string) => {
setSubagentDialogInitialView(initialView);
setSubagentDialogInitialName(initialName);
setIsSubagentDialogOpen(true);
},
[],
);
const closeSubagentDialog = useCallback(() => {
setIsSubagentDialogOpen(false);
setSubagentDialogInitialView(undefined);
setSubagentDialogInitialName(undefined);
}, []);
const {
showWorkspaceMigrationDialog,
workspaceGeminiCLIExtensions,
onWorkspaceMigrationDialogOpen,
onWorkspaceMigrationDialogClose,
} = useWorkspaceMigration(settings);
const extensions = config.getExtensions();
const {
extensionsUpdateState,
dispatchExtensionStateUpdate,
confirmUpdateExtensionRequests,
addConfirmUpdateExtensionRequest,
} = useExtensionUpdates(extensions, addItem, config.getWorkingDir());
useEffect(() => {
const unsubscribe = ideContext.subscribeToIdeContext(setIdeContextState);
// Set the initial value
setIdeContextState(ideContext.getIdeContext());
return unsubscribe;
}, []);
// Update currentModel when settings change - get it from the SAME place as diagnostics
useEffect(() => {
const updateModel = async () => {
const settingsService = getSettingsService();
// Try to get from SettingsService first (same as diagnostics does)
if (settingsService && settingsService.getDiagnosticsData) {
try {
const diagnosticsData = await settingsService.getDiagnosticsData();
if (diagnosticsData && diagnosticsData.model) {
setCurrentModel(diagnosticsData.model);
return;
}
} catch (_error) {
// Fall through to config
}
}
// Otherwise use config (which is what diagnostics falls back to)
setCurrentModel(config.getModel());
};
// Update immediately
updateModel();
// Also listen for any changes if SettingsService is available
const settingsService = getSettingsService();
if (settingsService) {
settingsService.on('settings-changed', updateModel);
return () => {
settingsService.off('settings-changed', updateModel);
};
}
return undefined;
}, [config]);
useEffect(() => {
const openDebugConsole = () => {
setShowErrorDetails(true);
setConstrainHeight(false); // Make sure the user sees the full message.
};
appEvents.on(AppEvent.OpenDebugConsole, openDebugConsole);
const logErrorHandler = (errorMessage: unknown) => {
handleNewMessage({
type: 'error',
content: String(errorMessage),
count: 1,
});
};