forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromptInput.tsx
More file actions
2339 lines (2213 loc) · 347 KB
/
Copy pathPromptInput.tsx
File metadata and controls
2339 lines (2213 loc) · 347 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
import { feature } from 'bun:bundle';
import chalk from 'chalk';
import * as path from 'path';
import * as React from 'react';
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { useNotifications } from 'src/context/notifications.js';
import { useCommandQueue } from 'src/hooks/useCommandQueue.js';
import { type IDEAtMentioned, useIdeAtMentioned } from 'src/hooks/useIdeAtMentioned.js';
import { type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, logEvent } from 'src/services/analytics/index.js';
import { type AppState, useAppState, useAppStateStore, useSetAppState } from 'src/state/AppState.js';
import type { FooterItem } from 'src/state/AppStateStore.js';
import { getCwd } from 'src/utils/cwd.js';
import { isQueuedCommandEditable, popAllEditable } from 'src/utils/messageQueueManager.js';
import stripAnsi from 'strip-ansi';
import { companionReservedColumns } from '../../buddy/CompanionSprite.js';
import { findBuddyTriggerPositions, useBuddyNotification } from '../../buddy/useBuddyNotification.js';
import { FastModePicker } from '../../commands/fast/fast.js';
import { isUltrareviewEnabled } from '../../commands/review/ultrareviewEnabled.js';
import { getNativeCSIuTerminalDisplayName } from '../../commands/terminalSetup/terminalSetup.js';
import { type Command, hasCommand } from '../../commands.js';
import { useIsModalOverlayActive } from '../../context/overlayContext.js';
import { useSetPromptOverlayDialog } from '../../context/promptOverlayContext.js';
import { formatImageRef, formatPastedTextRef, getPastedTextRefNumLines, parseReferences } from '../../history.js';
import type { VerificationStatus } from '../../hooks/useApiKeyVerification.js';
import { type HistoryMode, useArrowKeyHistory } from '../../hooks/useArrowKeyHistory.js';
import { useDoublePress } from '../../hooks/useDoublePress.js';
import { useHistorySearch } from '../../hooks/useHistorySearch.js';
import type { IDESelection } from '../../hooks/useIdeSelection.js';
import { useInputBuffer } from '../../hooks/useInputBuffer.js';
import { useMainLoopModel } from '../../hooks/useMainLoopModel.js';
import { usePromptSuggestion } from '../../hooks/usePromptSuggestion.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import { useTypeahead } from '../../hooks/useTypeahead.js';
import type { BorderTextOptions } from '../../ink/render-border.js';
import { stringWidth } from '../../ink/stringWidth.js';
import { Box, type ClickEvent, type Key, Text, useInput } from '../../ink.js';
import { useOptionalKeybindingContext } from '../../keybindings/KeybindingContext.js';
import { getShortcutDisplay } from '../../keybindings/shortcutFormat.js';
import { useKeybinding, useKeybindings } from '../../keybindings/useKeybinding.js';
import type { MCPServerConnection } from '../../services/mcp/types.js';
import { abortPromptSuggestion, logSuggestionSuppressed } from '../../services/PromptSuggestion/promptSuggestion.js';
import { type ActiveSpeculationState, abortSpeculation } from '../../services/PromptSuggestion/speculation.js';
import { getActiveAgentForInput, getViewedTeammateTask } from '../../state/selectors.js';
import { enterTeammateView, exitTeammateView, stopOrDismissAgent } from '../../state/teammateViewHelpers.js';
import type { ToolPermissionContext } from '../../Tool.js';
import { getRunningTeammatesSorted } from '../../tasks/InProcessTeammateTask/InProcessTeammateTask.js';
import type { InProcessTeammateTaskState } from '../../tasks/InProcessTeammateTask/types.js';
import { isPanelAgentTask, type LocalAgentTaskState } from '../../tasks/LocalAgentTask/LocalAgentTask.js';
import { isBackgroundTask } from '../../tasks/types.js';
import { AGENT_COLOR_TO_THEME_COLOR, AGENT_COLORS, type AgentColorName } from '../../tools/AgentTool/agentColorManager.js';
import type { AgentDefinition } from '../../tools/AgentTool/loadAgentsDir.js';
import type { Message } from '../../types/message.js';
import type { PermissionMode } from '../../types/permissions.js';
import type { BaseTextInputProps, PromptInputMode, VimMode } from '../../types/textInputTypes.js';
import { isAgentSwarmsEnabled } from '../../utils/agentSwarmsEnabled.js';
import { count } from '../../utils/array.js';
import type { AutoUpdaterResult } from '../../utils/autoUpdater.js';
import { Cursor } from '../../utils/Cursor.js';
import { getGlobalConfig, type PastedContent, saveGlobalConfig } from '../../utils/config.js';
import { logForDebugging } from '../../utils/debug.js';
import { parseDirectMemberMessage, sendDirectMemberMessage } from '../../utils/directMemberMessage.js';
import type { EffortLevel } from '../../utils/effort.js';
import { env } from '../../utils/env.js';
import { errorMessage } from '../../utils/errors.js';
import { isBilledAsExtraUsage } from '../../utils/extraUsage.js';
import { getFastModeUnavailableReason, isFastModeAvailable, isFastModeCooldown, isFastModeEnabled, isFastModeSupportedByModel } from '../../utils/fastMode.js';
import { isFullscreenEnvEnabled } from '../../utils/fullscreen.js';
import type { PromptInputHelpers } from '../../utils/handlePromptSubmit.js';
import { getImageFromClipboard, PASTE_THRESHOLD } from '../../utils/imagePaste.js';
import type { ImageDimensions } from '../../utils/imageResizer.js';
import { cacheImagePath, storeImage } from '../../utils/imageStore.js';
import { isMacosOptionChar, MACOS_OPTION_SPECIAL_CHARS } from '../../utils/keyboardShortcuts.js';
import { logError } from '../../utils/log.js';
import { isOpus1mMergeEnabled, modelDisplayString } from '../../utils/model/model.js';
import { setAutoModeActive } from '../../utils/permissions/autoModeState.js';
import { cyclePermissionMode, getNextPermissionMode } from '../../utils/permissions/getNextPermissionMode.js';
import { transitionPermissionMode } from '../../utils/permissions/permissionSetup.js';
import { getPlatform } from '../../utils/platform.js';
import type { ProcessUserInputContext } from '../../utils/processUserInput/processUserInput.js';
import { editPromptInEditor } from '../../utils/promptEditor.js';
import { hasAutoModeOptIn } from '../../utils/settings/settings.js';
import { findBtwTriggerPositions } from '../../utils/sideQuestion.js';
import { findSlashCommandPositions } from '../../utils/suggestions/commandSuggestions.js';
import { findSlackChannelPositions, getKnownChannelsVersion, hasSlackMcpServer, subscribeKnownChannels } from '../../utils/suggestions/slackChannelSuggestions.js';
import { isInProcessEnabled } from '../../utils/swarm/backends/registry.js';
import { syncTeammateMode } from '../../utils/swarm/teamHelpers.js';
import type { TeamSummary } from '../../utils/teamDiscovery.js';
import { getTeammateColor } from '../../utils/teammate.js';
import { isInProcessTeammate } from '../../utils/teammateContext.js';
import { writeToMailbox } from '../../utils/teammateMailbox.js';
import type { TextHighlight } from '../../utils/textHighlighting.js';
import type { Theme } from '../../utils/theme.js';
import { findThinkingTriggerPositions, getRainbowColor, isUltrathinkEnabled } from '../../utils/thinking.js';
import { findTokenBudgetPositions } from '../../utils/tokenBudget.js';
import { findUltraplanTriggerPositions, findUltrareviewTriggerPositions } from '../../utils/ultraplan/keyword.js';
import { AutoModeOptInDialog } from '../AutoModeOptInDialog.js';
import { BridgeDialog } from '../BridgeDialog.js';
import { ConfigurableShortcutHint } from '../ConfigurableShortcutHint.js';
import { getVisibleAgentTasks, useCoordinatorTaskCount } from '../CoordinatorAgentStatus.js';
import { getEffortNotificationText } from '../EffortIndicator.js';
import { getFastIconString } from '../FastIcon.js';
import { GlobalSearchDialog } from '../GlobalSearchDialog.js';
import { HistorySearchDialog } from '../HistorySearchDialog.js';
import { ModelPicker } from '../ModelPicker.js';
import { QuickOpenDialog } from '../QuickOpenDialog.js';
import TextInput from '../TextInput.js';
import { ThinkingToggle } from '../ThinkingToggle.js';
import { BackgroundTasksDialog } from '../tasks/BackgroundTasksDialog.js';
import { shouldHideTasksFooter } from '../tasks/taskStatusUtils.js';
import { TeamsDialog } from '../teams/TeamsDialog.js';
import VimTextInput from '../VimTextInput.js';
import { getModeFromInput, getValueFromInput } from './inputModes.js';
import { FOOTER_TEMPORARY_STATUS_TIMEOUT, Notifications } from './Notifications.js';
import PromptInputFooter from './PromptInputFooter.js';
import type { SuggestionItem } from './PromptInputFooterSuggestions.js';
import { PromptInputModeIndicator } from './PromptInputModeIndicator.js';
import { PromptInputQueuedCommands } from './PromptInputQueuedCommands.js';
import { PromptInputStashNotice } from './PromptInputStashNotice.js';
import { useMaybeTruncateInput } from './useMaybeTruncateInput.js';
import { usePromptInputPlaceholder } from './usePromptInputPlaceholder.js';
import { useShowFastIconHint } from './useShowFastIconHint.js';
import { useSwarmBanner } from './useSwarmBanner.js';
import { isNonSpacePrintable, isVimModeEnabled } from './utils.js';
type Props = {
debug: boolean;
ideSelection: IDESelection | undefined;
toolPermissionContext: ToolPermissionContext;
setToolPermissionContext: (ctx: ToolPermissionContext) => void;
apiKeyStatus: VerificationStatus;
commands: Command[];
agents: AgentDefinition[];
isLoading: boolean;
verbose: boolean;
messages: Message[];
onAutoUpdaterResult: (result: AutoUpdaterResult) => void;
autoUpdaterResult: AutoUpdaterResult | null;
input: string;
onInputChange: (value: string) => void;
mode: PromptInputMode;
onModeChange: (mode: PromptInputMode) => void;
stashedPrompt: {
text: string;
cursorOffset: number;
pastedContents: Record<number, PastedContent>;
} | undefined;
setStashedPrompt: (value: {
text: string;
cursorOffset: number;
pastedContents: Record<number, PastedContent>;
} | undefined) => void;
submitCount: number;
onShowMessageSelector: () => void;
/** Fullscreen message actions: shift+↑ enters cursor. */
onMessageActionsEnter?: () => void;
mcpClients: MCPServerConnection[];
pastedContents: Record<number, PastedContent>;
setPastedContents: React.Dispatch<React.SetStateAction<Record<number, PastedContent>>>;
vimMode: VimMode;
setVimMode: (mode: VimMode) => void;
showBashesDialog: string | boolean;
setShowBashesDialog: (show: string | boolean) => void;
onExit: () => void;
getToolUseContext: (messages: Message[], newMessages: Message[], abortController: AbortController, mainLoopModel: string) => ProcessUserInputContext;
onSubmit: (input: string, helpers: PromptInputHelpers, speculationAccept?: {
state: ActiveSpeculationState;
speculationSessionTimeSavedMs: number;
setAppState: (f: (prev: AppState) => AppState) => void;
}, options?: {
fromKeybinding?: boolean;
}) => Promise<void>;
onAgentSubmit?: (input: string, task: InProcessTeammateTaskState | LocalAgentTaskState, helpers: PromptInputHelpers) => Promise<void>;
isSearchingHistory: boolean;
setIsSearchingHistory: (isSearching: boolean) => void;
onDismissSideQuestion?: () => void;
isSideQuestionVisible?: boolean;
helpOpen: boolean;
setHelpOpen: React.Dispatch<React.SetStateAction<boolean>>;
hasSuppressedDialogs?: boolean;
isLocalJSXCommandActive?: boolean;
insertTextRef?: React.MutableRefObject<{
insert: (text: string) => void;
setInputWithCursor: (value: string, cursor: number) => void;
cursorOffset: number;
} | null>;
voiceInterimRange?: {
start: number;
end: number;
} | null;
};
// Bottom slot has maxHeight="50%"; reserve lines for footer, border, status.
const PROMPT_FOOTER_LINES = 5;
const MIN_INPUT_VIEWPORT_LINES = 3;
function PromptInput({
debug,
ideSelection,
toolPermissionContext,
setToolPermissionContext,
apiKeyStatus,
commands,
agents,
isLoading,
verbose,
messages,
onAutoUpdaterResult,
autoUpdaterResult,
input,
onInputChange,
mode,
onModeChange,
stashedPrompt,
setStashedPrompt,
submitCount,
onShowMessageSelector,
onMessageActionsEnter,
mcpClients,
pastedContents,
setPastedContents,
vimMode,
setVimMode,
showBashesDialog,
setShowBashesDialog,
onExit,
getToolUseContext,
onSubmit: onSubmitProp,
onAgentSubmit,
isSearchingHistory,
setIsSearchingHistory,
onDismissSideQuestion,
isSideQuestionVisible,
helpOpen,
setHelpOpen,
hasSuppressedDialogs,
isLocalJSXCommandActive = false,
insertTextRef,
voiceInterimRange
}: Props): React.ReactNode {
const mainLoopModel = useMainLoopModel();
// A local-jsx command (e.g., /mcp while agent is running) renders a full-
// screen dialog on top of PromptInput via the immediate-command path with
// shouldHidePromptInput: false. Those dialogs don't register in the overlay
// system, so treat them as a modal overlay here to stop navigation keys from
// leaking into TextInput/footer handlers and stacking a second dialog.
const isModalOverlayActive = useIsModalOverlayActive() || isLocalJSXCommandActive;
const [isAutoUpdating, setIsAutoUpdating] = useState(false);
const [exitMessage, setExitMessage] = useState<{
show: boolean;
key?: string;
}>({
show: false
});
const [cursorOffset, setCursorOffset] = useState<number>(input.length);
// Track the last input value set via internal handlers so we can detect
// external input changes (e.g. speech-to-text injection) and move cursor to end.
const lastInternalInputRef = React.useRef(input);
if (input !== lastInternalInputRef.current) {
// Input changed externally (not through any internal handler) — move cursor to end
setCursorOffset(input.length);
lastInternalInputRef.current = input;
}
// Wrap onInputChange to track internal changes before they trigger re-render
const trackAndSetInput = React.useCallback((value: string) => {
lastInternalInputRef.current = value;
onInputChange(value);
}, [onInputChange]);
// Expose an insertText function so callers (e.g. STT) can splice text at the
// current cursor position instead of replacing the entire input.
if (insertTextRef) {
insertTextRef.current = {
cursorOffset,
insert: (text: string) => {
const needsSpace = cursorOffset === input.length && input.length > 0 && !/\s$/.test(input);
const insertText = needsSpace ? ' ' + text : text;
const newValue = input.slice(0, cursorOffset) + insertText + input.slice(cursorOffset);
lastInternalInputRef.current = newValue;
onInputChange(newValue);
setCursorOffset(cursorOffset + insertText.length);
},
setInputWithCursor: (value: string, cursor: number) => {
lastInternalInputRef.current = value;
onInputChange(value);
setCursorOffset(cursor);
}
};
}
const store = useAppStateStore();
const setAppState = useSetAppState();
const tasks = useAppState(s => s.tasks);
const replBridgeConnected = useAppState(s => s.replBridgeConnected);
const replBridgeExplicit = useAppState(s => s.replBridgeExplicit);
const replBridgeReconnecting = useAppState(s => s.replBridgeReconnecting);
// Must match BridgeStatusIndicator's render condition (PromptInputFooter.tsx) —
// the pill returns null for implicit-and-not-reconnecting, so nav must too,
// otherwise bridge becomes an invisible selection stop.
const bridgeFooterVisible = replBridgeConnected && (replBridgeExplicit || replBridgeReconnecting);
// Tmux pill (ant-only) — visible when there's an active tungsten session
const hasTungstenSession = useAppState(s => "external" === 'ant' && s.tungstenActiveSession !== undefined);
const tmuxFooterVisible = "external" === 'ant' && hasTungstenSession;
// WebBrowser pill — visible when a browser is open
const bagelFooterVisible = useAppState(s => false);
const teamContext = useAppState(s => s.teamContext);
const queuedCommands = useCommandQueue();
const promptSuggestionState = useAppState(s => s.promptSuggestion);
const speculation = useAppState(s => s.speculation);
const speculationSessionTimeSavedMs = useAppState(s => s.speculationSessionTimeSavedMs);
const viewingAgentTaskId = useAppState(s => s.viewingAgentTaskId);
const viewSelectionMode = useAppState(s => s.viewSelectionMode);
const showSpinnerTree = useAppState(s => s.expandedView) === 'teammates';
const {
companion: _companion,
companionMuted
} = feature('BUDDY') ? getGlobalConfig() : {
companion: undefined,
companionMuted: undefined
};
const companionFooterVisible = !!_companion && !companionMuted;
// Brief mode: BriefSpinner/BriefIdleStatus own the 2-row footprint above
// the input. Dropping marginTop here lets the spinner sit flush against
// the input bar. viewingAgentTaskId mirrors the gate on both (Spinner.tsx,
// REPL.tsx) — teammate view falls back to SpinnerWithVerbInner which has
// its own marginTop, so the gap stays even without ours.
const briefOwnsGap = feature('KAIROS') || feature('KAIROS_BRIEF') ?
// biome-ignore lint/correctness/useHookAtTopLevel: feature() is a compile-time constant
useAppState(s => s.isBriefOnly) && !viewingAgentTaskId : false;
const mainLoopModel_ = useAppState(s => s.mainLoopModel);
const mainLoopModelForSession = useAppState(s => s.mainLoopModelForSession);
const thinkingEnabled = useAppState(s => s.thinkingEnabled);
const isFastMode = useAppState(s => isFastModeEnabled() ? s.fastMode : false);
const effortValue = useAppState(s => s.effortValue);
const viewedTeammate = getViewedTeammateTask(store.getState());
const viewingAgentName = viewedTeammate?.identity.agentName;
// identity.color is typed as `string | undefined` (not AgentColorName) because
// teammate identity comes from file-based config. Validate before casting to
// ensure we only use valid color names (falls back to cyan if invalid).
const viewingAgentColor = viewedTeammate?.identity.color && AGENT_COLORS.includes(viewedTeammate.identity.color as AgentColorName) ? viewedTeammate.identity.color as AgentColorName : undefined;
// In-process teammates sorted alphabetically for footer team selector
const inProcessTeammates = useMemo(() => getRunningTeammatesSorted(tasks), [tasks]);
// Team mode: all background tasks are in-process teammates
const isTeammateMode = inProcessTeammates.length > 0 || viewedTeammate !== undefined;
// When viewing a teammate, show their permission mode in the footer instead of the leader's
const effectiveToolPermissionContext = useMemo((): ToolPermissionContext => {
if (viewedTeammate) {
return {
...toolPermissionContext,
mode: viewedTeammate.permissionMode
};
}
return toolPermissionContext;
}, [viewedTeammate, toolPermissionContext]);
const {
historyQuery,
setHistoryQuery,
historyMatch,
historyFailedMatch
} = useHistorySearch(entry => {
setPastedContents(entry.pastedContents);
void onSubmit(entry.display);
}, input, trackAndSetInput, setCursorOffset, cursorOffset, onModeChange, mode, isSearchingHistory, setIsSearchingHistory, setPastedContents, pastedContents);
// Counter for paste IDs (shared between images and text).
// Compute initial value once from existing messages (for --continue/--resume).
// useRef(fn()) evaluates fn() on every render and discards the result after
// mount — getInitialPasteId walks all messages + regex-scans text blocks,
// so guard with a lazy-init pattern to run it exactly once.
const nextPasteIdRef = useRef(-1);
if (nextPasteIdRef.current === -1) {
nextPasteIdRef.current = getInitialPasteId(messages);
}
// Armed by onImagePaste; if the very next keystroke is a non-space
// printable, inputFilter prepends a space before it. Any other input
// (arrow, escape, backspace, paste, space) disarms without inserting.
const pendingSpaceAfterPillRef = useRef(false);
const [showTeamsDialog, setShowTeamsDialog] = useState(false);
const [showBridgeDialog, setShowBridgeDialog] = useState(false);
const [teammateFooterIndex, setTeammateFooterIndex] = useState(0);
// -1 sentinel: tasks pill is selected but no specific agent row is selected yet.
// First ↓ selects the pill, second ↓ moves to row 0. Prevents double-select
// of pill + row when both bg tasks (pill) and forked agents (rows) are visible.
const coordinatorTaskIndex = useAppState(s => s.coordinatorTaskIndex);
const setCoordinatorTaskIndex = useCallback((v: number | ((prev: number) => number)) => setAppState(prev => {
const next = typeof v === 'function' ? v(prev.coordinatorTaskIndex) : v;
if (next === prev.coordinatorTaskIndex) return prev;
return {
...prev,
coordinatorTaskIndex: next
};
}), [setAppState]);
const coordinatorTaskCount = useCoordinatorTaskCount();
// The pill (BackgroundTaskStatus) only renders when non-local_agent bg tasks
// exist. When only local_agent tasks are running (coordinator/fork mode), the
// pill is absent, so the -1 sentinel would leave nothing visually selected.
// In that case, skip -1 and treat 0 as the minimum selectable index.
const hasBgTaskPill = useMemo(() => Object.values(tasks).some(t => isBackgroundTask(t) && !("external" === 'ant' && isPanelAgentTask(t))), [tasks]);
const minCoordinatorIndex = hasBgTaskPill ? -1 : 0;
// Clamp index when tasks complete and the list shrinks beneath the cursor
useEffect(() => {
if (coordinatorTaskIndex >= coordinatorTaskCount) {
setCoordinatorTaskIndex(Math.max(minCoordinatorIndex, coordinatorTaskCount - 1));
} else if (coordinatorTaskIndex < minCoordinatorIndex) {
setCoordinatorTaskIndex(minCoordinatorIndex);
}
}, [coordinatorTaskCount, coordinatorTaskIndex, minCoordinatorIndex]);
const [isPasting, setIsPasting] = useState(false);
const [isExternalEditorActive, setIsExternalEditorActive] = useState(false);
const [showModelPicker, setShowModelPicker] = useState(false);
const [showQuickOpen, setShowQuickOpen] = useState(false);
const [showGlobalSearch, setShowGlobalSearch] = useState(false);
const [showHistoryPicker, setShowHistoryPicker] = useState(false);
const [showFastModePicker, setShowFastModePicker] = useState(false);
const [showThinkingToggle, setShowThinkingToggle] = useState(false);
const [showAutoModeOptIn, setShowAutoModeOptIn] = useState(false);
const [previousModeBeforeAuto, setPreviousModeBeforeAuto] = useState<PermissionMode | null>(null);
const autoModeOptInTimeoutRef = useRef<NodeJS.Timeout | null>(null);
// Check if cursor is on the first line of input
const isCursorOnFirstLine = useMemo(() => {
const firstNewlineIndex = input.indexOf('\n');
if (firstNewlineIndex === -1) {
return true; // No newlines, cursor is always on first line
}
return cursorOffset <= firstNewlineIndex;
}, [input, cursorOffset]);
const isCursorOnLastLine = useMemo(() => {
const lastNewlineIndex = input.lastIndexOf('\n');
if (lastNewlineIndex === -1) {
return true; // No newlines, cursor is always on last line
}
return cursorOffset > lastNewlineIndex;
}, [input, cursorOffset]);
// Derive team info from teamContext (no filesystem I/O needed)
// A session can only lead one team at a time
const cachedTeams: TeamSummary[] = useMemo(() => {
if (!isAgentSwarmsEnabled()) return [];
// In-process mode uses Shift+Down/Up navigation instead of footer menu
if (isInProcessEnabled()) return [];
if (!teamContext) {
return [];
}
const teammateCount = count(Object.values(teamContext.teammates), t => t.name !== 'team-lead');
return [{
name: teamContext.teamName,
memberCount: teammateCount,
runningCount: 0,
idleCount: 0
}];
}, [teamContext]);
// ─── Footer pill navigation ─────────────────────────────────────────────
// Which pills render below the input box. Order here IS the nav order
// (down/right = forward, up/left = back). Selection lives in AppState so
// pills rendered outside PromptInput (CompanionSprite) can read focus.
const runningTaskCount = useMemo(() => count(Object.values(tasks), t => t.status === 'running'), [tasks]);
// Panel shows retained-completed agents too (getVisibleAgentTasks), so the
// pill must stay navigable whenever the panel has rows — not just when
// something is running.
const tasksFooterVisible = (runningTaskCount > 0 || "external" === 'ant' && coordinatorTaskCount > 0) && !shouldHideTasksFooter(tasks, showSpinnerTree);
const teamsFooterVisible = cachedTeams.length > 0;
const footerItems = useMemo(() => [tasksFooterVisible && 'tasks', tmuxFooterVisible && 'tmux', bagelFooterVisible && 'bagel', teamsFooterVisible && 'teams', bridgeFooterVisible && 'bridge', companionFooterVisible && 'companion'].filter(Boolean) as FooterItem[], [tasksFooterVisible, tmuxFooterVisible, bagelFooterVisible, teamsFooterVisible, bridgeFooterVisible, companionFooterVisible]);
// Effective selection: null if the selected pill stopped rendering (bridge
// disconnected, task finished). The derivation makes the UI correct
// immediately; the useEffect below clears the raw state so it doesn't
// resurrect when the same pill reappears (new task starts → focus stolen).
const rawFooterSelection = useAppState(s => s.footerSelection);
const footerItemSelected = rawFooterSelection && footerItems.includes(rawFooterSelection) ? rawFooterSelection : null;
useEffect(() => {
if (rawFooterSelection && !footerItemSelected) {
setAppState(prev => prev.footerSelection === null ? prev : {
...prev,
footerSelection: null
});
}
}, [rawFooterSelection, footerItemSelected, setAppState]);
const tasksSelected = footerItemSelected === 'tasks';
const tmuxSelected = footerItemSelected === 'tmux';
const bagelSelected = footerItemSelected === 'bagel';
const teamsSelected = footerItemSelected === 'teams';
const bridgeSelected = footerItemSelected === 'bridge';
function selectFooterItem(item: FooterItem | null): void {
setAppState(prev => prev.footerSelection === item ? prev : {
...prev,
footerSelection: item
});
if (item === 'tasks') {
setTeammateFooterIndex(0);
setCoordinatorTaskIndex(minCoordinatorIndex);
}
}
// delta: +1 = down/right, -1 = up/left. Returns true if nav happened
// (including deselecting at the start), false if at a boundary.
function navigateFooter(delta: 1 | -1, exitAtStart = false): boolean {
const idx = footerItemSelected ? footerItems.indexOf(footerItemSelected) : -1;
const next = footerItems[idx + delta];
if (next) {
selectFooterItem(next);
return true;
}
if (delta < 0 && exitAtStart) {
selectFooterItem(null);
return true;
}
return false;
}
// Prompt suggestion hook - reads suggestions generated by forked agent in query loop
const {
suggestion: promptSuggestion,
markAccepted,
logOutcomeAtSubmission,
markShown
} = usePromptSuggestion({
inputValue: input,
isAssistantResponding: isLoading
});
const displayedValue = useMemo(() => isSearchingHistory && historyMatch ? getValueFromInput(typeof historyMatch === 'string' ? historyMatch : historyMatch.display) : input, [isSearchingHistory, historyMatch, input]);
const thinkTriggers = useMemo(() => findThinkingTriggerPositions(displayedValue), [displayedValue]);
const ultraplanSessionUrl = useAppState(s => s.ultraplanSessionUrl);
const ultraplanLaunching = useAppState(s => s.ultraplanLaunching);
const ultraplanTriggers = useMemo(() => feature('ULTRAPLAN') && !ultraplanSessionUrl && !ultraplanLaunching ? findUltraplanTriggerPositions(displayedValue) : [], [displayedValue, ultraplanSessionUrl, ultraplanLaunching]);
const ultrareviewTriggers = useMemo(() => isUltrareviewEnabled() ? findUltrareviewTriggerPositions(displayedValue) : [], [displayedValue]);
const btwTriggers = useMemo(() => findBtwTriggerPositions(displayedValue), [displayedValue]);
const buddyTriggers = useMemo(() => findBuddyTriggerPositions(displayedValue), [displayedValue]);
const slashCommandTriggers = useMemo(() => {
const positions = findSlashCommandPositions(displayedValue);
// Only highlight valid commands
return positions.filter(pos => {
const commandName = displayedValue.slice(pos.start + 1, pos.end); // +1 to skip "/"
return hasCommand(commandName, commands);
});
}, [displayedValue, commands]);
const tokenBudgetTriggers = useMemo(() => feature('TOKEN_BUDGET') ? findTokenBudgetPositions(displayedValue) : [], [displayedValue]);
const knownChannelsVersion = useSyncExternalStore(subscribeKnownChannels, getKnownChannelsVersion);
const slackChannelTriggers = useMemo(() => hasSlackMcpServer(store.getState().mcp.clients) ? findSlackChannelPositions(displayedValue) : [],
// eslint-disable-next-line react-hooks/exhaustive-deps -- store is a stable ref
[displayedValue, knownChannelsVersion]);
// Find @name mentions and highlight with team member's color
const memberMentionHighlights = useMemo((): Array<{
start: number;
end: number;
themeColor: keyof Theme;
}> => {
if (!isAgentSwarmsEnabled()) return [];
if (!teamContext?.teammates) return [];
const highlights: Array<{
start: number;
end: number;
themeColor: keyof Theme;
}> = [];
const members = teamContext.teammates;
if (!members) return highlights;
// Find all @name patterns in the input
const regex = /(^|\s)@([\w-]+)/g;
const memberValues = Object.values(members);
let match;
while ((match = regex.exec(displayedValue)) !== null) {
const leadingSpace = match[1] ?? '';
const nameStart = match.index + leadingSpace.length;
const fullMatch = match[0].trimStart();
const name = match[2];
// Check if this name matches a team member
const member = memberValues.find(t => t.name === name);
if (member?.color) {
const themeColor = AGENT_COLOR_TO_THEME_COLOR[member.color as AgentColorName];
if (themeColor) {
highlights.push({
start: nameStart,
end: nameStart + fullMatch.length,
themeColor
});
}
}
}
return highlights;
}, [displayedValue, teamContext]);
const imageRefPositions = useMemo(() => parseReferences(displayedValue).filter(r => r.match.startsWith('[Image')).map(r => ({
start: r.index,
end: r.index + r.match.length
})), [displayedValue]);
// chip.start is the "selected" state: the inverted chip IS the cursor.
// chip.end stays a normal position so you can park the cursor right after
// `]` like any other character.
const cursorAtImageChip = imageRefPositions.some(r => r.start === cursorOffset);
// up/down movement or a fullscreen click can land the cursor strictly
// inside a chip; snap to the nearer boundary so it's never editable
// char-by-char.
useEffect(() => {
const inside = imageRefPositions.find(r => cursorOffset > r.start && cursorOffset < r.end);
if (inside) {
const mid = (inside.start + inside.end) / 2;
setCursorOffset(cursorOffset < mid ? inside.start : inside.end);
}
}, [cursorOffset, imageRefPositions, setCursorOffset]);
const combinedHighlights = useMemo((): TextHighlight[] => {
const highlights: TextHighlight[] = [];
// Invert the [Image #N] chip when the cursor is at chip.start (the
// "selected" state) so backspace-to-delete is visually obvious.
for (const ref of imageRefPositions) {
if (cursorOffset === ref.start) {
highlights.push({
start: ref.start,
end: ref.end,
color: undefined,
inverse: true,
priority: 8
});
}
}
if (isSearchingHistory && historyMatch && !historyFailedMatch) {
highlights.push({
start: cursorOffset,
end: cursorOffset + historyQuery.length,
color: 'warning',
priority: 20
});
}
// Add "btw" highlighting (solid yellow)
for (const trigger of btwTriggers) {
highlights.push({
start: trigger.start,
end: trigger.end,
color: 'warning',
priority: 15
});
}
// Add /command highlighting (blue)
for (const trigger of slashCommandTriggers) {
highlights.push({
start: trigger.start,
end: trigger.end,
color: 'suggestion',
priority: 5
});
}
// Add token budget highlighting (blue)
for (const trigger of tokenBudgetTriggers) {
highlights.push({
start: trigger.start,
end: trigger.end,
color: 'suggestion',
priority: 5
});
}
for (const trigger of slackChannelTriggers) {
highlights.push({
start: trigger.start,
end: trigger.end,
color: 'suggestion',
priority: 5
});
}
// Add @name highlighting with team member's color
for (const mention of memberMentionHighlights) {
highlights.push({
start: mention.start,
end: mention.end,
color: mention.themeColor,
priority: 5
});
}
// Dim interim voice dictation text
if (voiceInterimRange) {
highlights.push({
start: voiceInterimRange.start,
end: voiceInterimRange.end,
color: undefined,
dimColor: true,
priority: 1
});
}
// Rainbow highlighting for ultrathink keyword (per-character cycling colors)
if (isUltrathinkEnabled()) {
for (const trigger of thinkTriggers) {
for (let i = trigger.start; i < trigger.end; i++) {
highlights.push({
start: i,
end: i + 1,
color: getRainbowColor(i - trigger.start),
shimmerColor: getRainbowColor(i - trigger.start, true),
priority: 10
});
}
}
}
// Same rainbow treatment for the ultraplan keyword
if (feature('ULTRAPLAN')) {
for (const trigger of ultraplanTriggers) {
for (let i = trigger.start; i < trigger.end; i++) {
highlights.push({
start: i,
end: i + 1,
color: getRainbowColor(i - trigger.start),
shimmerColor: getRainbowColor(i - trigger.start, true),
priority: 10
});
}
}
}
// Same rainbow treatment for the ultrareview keyword
for (const trigger of ultrareviewTriggers) {
for (let i = trigger.start; i < trigger.end; i++) {
highlights.push({
start: i,
end: i + 1,
color: getRainbowColor(i - trigger.start),
shimmerColor: getRainbowColor(i - trigger.start, true),
priority: 10
});
}
}
// Rainbow for /buddy
for (const trigger of buddyTriggers) {
for (let i = trigger.start; i < trigger.end; i++) {
highlights.push({
start: i,
end: i + 1,
color: getRainbowColor(i - trigger.start),
shimmerColor: getRainbowColor(i - trigger.start, true),
priority: 10
});
}
}
return highlights;
}, [isSearchingHistory, historyQuery, historyMatch, historyFailedMatch, cursorOffset, btwTriggers, imageRefPositions, memberMentionHighlights, slashCommandTriggers, tokenBudgetTriggers, slackChannelTriggers, displayedValue, voiceInterimRange, thinkTriggers, ultraplanTriggers, ultrareviewTriggers, buddyTriggers]);
const {
addNotification,
removeNotification
} = useNotifications();
// Show ultrathink notification
useEffect(() => {
if (thinkTriggers.length && isUltrathinkEnabled()) {
addNotification({
key: 'ultrathink-active',
text: 'Effort set to high for this turn',
priority: 'immediate',
timeoutMs: 5000
});
} else {
removeNotification('ultrathink-active');
}
}, [addNotification, removeNotification, thinkTriggers.length]);
useEffect(() => {
if (feature('ULTRAPLAN') && ultraplanTriggers.length) {
addNotification({
key: 'ultraplan-active',
text: 'This prompt will launch an ultraplan session in Claude Code on the web',
priority: 'immediate',
timeoutMs: 5000
});
} else {
removeNotification('ultraplan-active');
}
}, [addNotification, removeNotification, ultraplanTriggers.length]);
useEffect(() => {
if (isUltrareviewEnabled() && ultrareviewTriggers.length) {
addNotification({
key: 'ultrareview-active',
text: 'Run /ultrareview after Claude finishes to review these changes in the cloud',
priority: 'immediate',
timeoutMs: 5000
});
}
}, [addNotification, ultrareviewTriggers.length]);
// Track input length for stash hint
const prevInputLengthRef = useRef(input.length);
const peakInputLengthRef = useRef(input.length);
// Dismiss stash hint when user makes any input change
const dismissStashHint = useCallback(() => {
removeNotification('stash-hint');
}, [removeNotification]);
// Show stash hint when user gradually clears substantial input
useEffect(() => {
const prevLength = prevInputLengthRef.current;
const peakLength = peakInputLengthRef.current;
const currentLength = input.length;
prevInputLengthRef.current = currentLength;
// Update peak when input grows
if (currentLength > peakLength) {
peakInputLengthRef.current = currentLength;
return;
}
// Reset state when input is empty
if (currentLength === 0) {
peakInputLengthRef.current = 0;
return;
}
// Detect gradual clear: peak was high, current is low, but this wasn't a single big jump
// (rapid clears like esc-esc go from 20+ to 0 in one step)
const clearedSubstantialInput = peakLength >= 20 && currentLength <= 5;
const wasRapidClear = prevLength >= 20 && currentLength <= 5;
if (clearedSubstantialInput && !wasRapidClear) {
const config = getGlobalConfig();
if (!config.hasUsedStash) {
addNotification({
key: 'stash-hint',
jsx: <Text dimColor>
Tip:{' '}
<ConfigurableShortcutHint action="chat:stash" context="Chat" fallback="ctrl+s" description="stash" />
</Text>,
priority: 'immediate',
timeoutMs: FOOTER_TEMPORARY_STATUS_TIMEOUT
});
}
peakInputLengthRef.current = currentLength;
}
}, [input.length, addNotification]);
// Initialize input buffer for undo functionality
const {
pushToBuffer,
undo,
canUndo,
clearBuffer
} = useInputBuffer({
maxBufferSize: 50,
debounceMs: 1000
});
useMaybeTruncateInput({
input,
pastedContents,
onInputChange: trackAndSetInput,
setCursorOffset,
setPastedContents
});
const defaultPlaceholder = usePromptInputPlaceholder({
input,
submitCount,
viewingAgentName
});
const onChange = useCallback((value: string) => {
if (value === '?') {
logEvent('tengu_help_toggled', {});
setHelpOpen(v => !v);
return;
}
setHelpOpen(false);
// Dismiss stash hint when user makes any input change
dismissStashHint();
// Cancel any pending prompt suggestion and speculation when user types
abortPromptSuggestion();
abortSpeculation(setAppState);
// Check if this is a single character insertion at the start
const isSingleCharInsertion = value.length === input.length + 1;
const insertedAtStart = cursorOffset === 0;
const mode = getModeFromInput(value);
if (insertedAtStart && mode !== 'prompt') {
if (isSingleCharInsertion) {
onModeChange(mode);
return;
}
// Multi-char insertion into empty input (e.g. tab-accepting "! gcloud auth login")
if (input.length === 0) {
onModeChange(mode);
const valueWithoutMode = getValueFromInput(value).replaceAll('\t', ' ');
pushToBuffer(input, cursorOffset, pastedContents);
trackAndSetInput(valueWithoutMode);
setCursorOffset(valueWithoutMode.length);
return;
}
}
const processedValue = value.replaceAll('\t', ' ');
// Push current state to buffer before making changes
if (input !== processedValue) {
pushToBuffer(input, cursorOffset, pastedContents);
}
// Deselect footer items when user types
setAppState(prev => prev.footerSelection === null ? prev : {
...prev,
footerSelection: null
});
trackAndSetInput(processedValue);
}, [trackAndSetInput, onModeChange, input, cursorOffset, pushToBuffer, pastedContents, dismissStashHint, setAppState]);
const {
resetHistory,
onHistoryUp,
onHistoryDown,
dismissSearchHint,
historyIndex
} = useArrowKeyHistory((value: string, historyMode: HistoryMode, pastedContents: Record<number, PastedContent>) => {
onChange(value);
onModeChange(historyMode);
setPastedContents(pastedContents);
}, input, pastedContents, setCursorOffset, mode);
// Dismiss search hint when user starts searching
useEffect(() => {
if (isSearchingHistory) {
dismissSearchHint();
}
}, [isSearchingHistory, dismissSearchHint]);
// Only use history navigation when there are 0 or 1 slash command suggestions.
// Footer nav is NOT here — when a pill is selected, TextInput focus=false so
// these never fire. The Footer keybinding context handles ↑/↓ instead.
function handleHistoryUp() {
if (suggestions.length > 1) {
return;
}
// Only navigate history when cursor is on the first line.
// In multiline inputs, up arrow should move the cursor (handled by TextInput)
// and only trigger history when at the top of the input.
if (!isCursorOnFirstLine) {
return;
}
// If there's an editable queued command, move it to the input for editing when UP is pressed
const hasEditableCommand = queuedCommands.some(isQueuedCommandEditable);
if (hasEditableCommand) {
void popAllCommandsFromQueue();
return;
}
onHistoryUp();
}
function handleHistoryDown() {
if (suggestions.length > 1) {
return;
}
// Only navigate history/footer when cursor is on the last line.
// In multiline inputs, down arrow should move the cursor (handled by TextInput)
// and only trigger navigation when at the bottom of the input.
if (!isCursorOnLastLine) {
return;
}
// At bottom of history → enter footer at first visible pill
if (onHistoryDown() && footerItems.length > 0) {
const first = footerItems[0]!;
selectFooterItem(first);
if (first === 'tasks' && !getGlobalConfig().hasSeenTasksHint) {
saveGlobalConfig(c => c.hasSeenTasksHint ? c : {
...c,
hasSeenTasksHint: true
});
}
}
}
// Create a suggestions state directly - we'll sync it with useTypeahead later
const [suggestionsState, setSuggestionsStateRaw] = useState<{
suggestions: SuggestionItem[];
selectedSuggestion: number;
commandArgumentHint?: string;
}>({
suggestions: [],
selectedSuggestion: -1,
commandArgumentHint: undefined
});
// Setter for suggestions state
const setSuggestionsState = useCallback((updater: typeof suggestionsState | ((prev: typeof suggestionsState) => typeof suggestionsState)) => {
setSuggestionsStateRaw(prev => typeof updater === 'function' ? updater(prev) : updater);
}, []);
const onSubmit = useCallback(async (inputParam: string, isSubmittingSlashCommand = false) => {
inputParam = inputParam.trimEnd();
// Don't submit if a footer indicator is being opened. Read fresh from
// store — footer:openSelected calls selectFooterItem(null) then onSubmit
// in the same tick, and the closure value hasn't updated yet. Apply the
// same "still visible?" derivation as footerItemSelected so a stale
// selection (pill disappeared) doesn't swallow Enter.
const state = store.getState();
if (state.footerSelection && footerItems.includes(state.footerSelection)) {
return;
}
// Enter in selection modes confirms selection (useBackgroundTaskNavigation).
// BaseTextInput's useInput registers before that hook (child effects fire first),
// so without this guard Enter would double-fire and auto-submit the suggestion.
if (state.viewSelectionMode === 'selecting-agent') {