forked from tinyhumansai/openhuman
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConversations.tsx
More file actions
1791 lines (1699 loc) · 77.9 KB
/
Copy pathConversations.tsx
File metadata and controls
1791 lines (1699 loc) · 77.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
import { convertFileSrc } from '@tauri-apps/api/core';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { type ChatSendError, chatSendError } from '../chat/chatSendError';
import { checkPromptInjection, promptGuardMessage } from '../chat/promptInjectionGuard';
import TokenUsagePill from '../components/chat/TokenUsagePill';
import { ConfirmationModal } from '../components/intelligence/ConfirmationModal';
import PillTabBar from '../components/PillTabBar';
import UpsellBanner from '../components/upsell/UpsellBanner';
import { dismissBanner, shouldShowBanner } from '../components/upsell/upsellDismissState';
import UsageLimitModal from '../components/upsell/UsageLimitModal';
import MicCloudComposer from '../features/human/MicCloudComposer';
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// import { ONBOARDING_WELCOME_THREAD_LABEL } from '../constants/onboardingChat';
import { useStickToBottom } from '../hooks/useStickToBottom';
import { useUsageState } from '../hooks/useUsageState';
import { trackEvent } from '../services/analytics';
// [#1123] getCoreStateSnapshot and isWelcomeLocked commented out — welcome-agent onboarding replaced by Joyride walkthrough
// import { getCoreStateSnapshot, isWelcomeLocked } from '../lib/coreState/store';
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// import { useCoreState } from '../providers/CoreStateProvider';
import { chatCancel, chatSend, useRustChat } from '../services/chatService';
import { store } from '../store';
import {
beginInferenceTurn,
clearRuntimeForThread,
fetchAndHydrateTurnState,
setToolTimelineForThread,
} from '../store/chatRuntimeSlice';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { selectSocketStatus } from '../store/socketSelectors';
import {
addMessageLocal,
createNewThread,
deleteThread,
loadThreadMessages,
loadThreads,
persistReaction,
setActiveThread,
setSelectedThread,
} from '../store/threadSlice';
import type { ConfirmationModal as ConfirmationModalType } from '../types/intelligence';
import type { ThreadMessage } from '../types/thread';
import { splitAgentMessageIntoBubbles } from '../utils/agentMessageBubbles';
import { BILLING_DASHBOARD_URL } from '../utils/links';
import { openUrl } from '../utils/openUrl';
import {
isTauri,
notifyOverlaySttState,
openhumanAutocompleteAccept,
openhumanAutocompleteCurrent,
openhumanVoiceStatus,
openhumanVoiceTranscribeBytes,
openhumanVoiceTts,
} from '../utils/tauriCommands';
import { formatTimelineEntry } from '../utils/toolTimelineFormatting';
import { AgentMessageBubble, BubbleMarkdown } from './conversations/components/AgentMessageBubble';
import { CitationChips, type MessageCitation } from './conversations/components/CitationChips';
import { LimitPill } from './conversations/components/LimitPill';
import { ToolTimelineBlock } from './conversations/components/ToolTimelineBlock';
import {
evaluateComposerSend,
getComposerBlockedSendFeedback,
handleComposerSlashCommand,
} from './conversations/composerSendDecision';
import {
type AgentBubblePosition,
buildAcceptedInlineCompletion,
formatRelativeTime,
formatResetTime,
getInlineCompletionSuffix,
} from './conversations/utils/format';
// Chat uses the reasoning model; `agentic-v1` is reserved for sub-agents
// that execute tool calls, not the primary user-facing conversation.
const CHAT_MODEL_ID = 'reasoning-v1';
/** Maximum trailing characters rendered in the live-streaming assistant
* preview bubble. The full response is revealed via `addInferenceResponse`
* on `chat_done` — this is purely a ticker-tape affordance to signal
* progress without jumping the scroll position as tokens arrive. */
const STREAMING_PREVIEW_CHARS = 120;
type InputMode = 'text' | 'voice';
type ReplyMode = 'text' | 'voice';
const AUTOCOMPLETE_POLL_DEBOUNCE_MS = 320;
const AUTOCOMPLETE_MIN_CONTEXT_CHARS = 3;
interface ConversationsProps {
/**
* `page` (default) renders the centered max-w-2xl card layout used as
* a top-level route at /conversations. `sidebar` drops the centering
* and width cap so the panel can be embedded as a right rail inside
* another page (e.g. /accounts).
*/
variant?: 'page' | 'sidebar';
/**
* Composer mode. `text` (default) uses the textarea + send button.
* `mic-cloud` swaps the entire composer for a single mic button that
* captures audio via `MediaRecorder`, transcribes it through the cloud
* STT proxy, then routes the transcript through the same send path.
* Used by the mascot tab so the only interaction is voice.
*/
composer?: 'text' | 'mic-cloud';
}
export function isComposerInteractionBlocked(args: {
activeThreadId: string | null;
welcomePending: boolean;
rustChat: boolean;
}): boolean {
return !args.rustChat || Boolean(args.activeThreadId) || args.welcomePending;
}
/**
* Normalise the value thrown out of `dispatch(loadThreads()).unwrap()` into a
* displayable string. `createAsyncThunk` re-throws Redux's `SerializedError`
* (a plain object, not an `Error` instance) when the thunk rejects — which is
* why the original Sentry report (OPENHUMAN-REACT-X) showed up as
* "Non-Error promise rejection captured with value: …" rather than a stack.
* Exported so the mount-effect's `.catch` stays a one-liner and the message
* shape can be unit-tested without mounting the full page.
*/
export function formatThreadLoadError(err: unknown): string {
if (err instanceof Error) return err.message;
if (err && typeof err === 'object' && 'message' in err) {
const message = (err as { message?: unknown }).message;
if (typeof message === 'string') return message;
}
return String(err);
}
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// function WelcomeThinkingTypewriter() {
// const text = 'Your agent is thinking...';
// const [visibleChars, setVisibleChars] = useState(0);
//
// useEffect(() => {
// const isComplete = visibleChars >= text.length;
// const delayMs = isComplete ? 950 : 42;
// const timeoutId = window.setTimeout(() => {
// setVisibleChars(current => (current >= text.length ? 0 : current + 1));
// }, delayMs);
//
// return () => window.clearTimeout(timeoutId);
// }, [text.length, visibleChars]);
//
// return (
// <p className="flex items-center text-sm text-stone-600 font-mono tracking-tight">
// <span>{text.slice(0, visibleChars)}</span>
// <span
// aria-hidden="true"
// className="ml-0.5 inline-block h-4 w-px bg-stone-400 animate-pulse"
// />
// </p>
// );
// }
const Conversations = ({ variant = 'page', composer = 'text' }: ConversationsProps = {}) => {
const dispatch = useAppDispatch();
const navigate = useNavigate();
const {
threads,
selectedThreadId,
messages,
isLoadingMessages,
messagesError,
activeThreadId,
// [#1123] welcomeThreadId commented out — welcome-agent onboarding replaced by Joyride walkthrough
// welcomeThreadId,
} = useAppSelector(state => state.thread);
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// const { snapshot } = useCoreState();
// const welcomeLocked = isWelcomeLocked(snapshot);
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// While the proactive welcome agent is running and hasn't published its
// first message yet, hide the composer (and a few other non-message
// chrome bits) so the user just sees the "Your agent is thinking..."
// loader. Flips off the moment the first agent message arrives.
// const welcomePending =
// !!welcomeThreadId && selectedThreadId === welcomeThreadId && messages.length === 0;
// const chatOnboardingCompleted = snapshot.chatOnboardingCompleted;
// const previousChatOnboardingCompletedRef = useRef<boolean | null>(null);
// Guard against the mount-time `loadThreads()` promise resolving AFTER
// the welcome-lock unlock transition creates a fresh thread. Without
// this, the stale `.then(...)` would re-select the old welcome thread
// and clobber the auto-created one (#883 CodeRabbit feedback).
// const skipInitialThreadSelectionRef = useRef(false);
const [showSidebar, setShowSidebar] = useState(true);
const [inputValue, setInputValue] = useState('');
const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);
const [inputMode, setInputMode] = useState<InputMode>('text');
const [replyMode, setReplyMode] = useState<ReplyMode>('text');
const [isRecording, setIsRecording] = useState(false);
const [isTranscribing, setIsTranscribing] = useState(false);
const [voiceStatus, setVoiceStatus] = useState<string | null>(null);
const [isPlayingReply, setIsPlayingReply] = useState(false);
const [selectedLabel, setSelectedLabel] = useState<string>('all');
const [inlineSuggestionValue, setInlineSuggestionValue] = useState('');
const [sendError, setSendError] = useState<ChatSendError | null>(null);
const [sendAdvisory, setSendAdvisory] = useState<string | null>(null);
const socketStatus = useAppSelector(selectSocketStatus);
const toolTimelineByThread = useAppSelector(state => state.chatRuntime.toolTimelineByThread);
const inferenceStatusByThread = useAppSelector(
state => state.chatRuntime.inferenceStatusByThread
);
const streamingAssistantByThread = useAppSelector(
state => state.chatRuntime.streamingAssistantByThread
);
const inferenceTurnLifecycleByThread = useAppSelector(
state => state.chatRuntime.inferenceTurnLifecycleByThread
);
const rustChat = useRustChat();
const [reactionPickerMsgId, setReactionPickerMsgId] = useState<string | null>(null);
const {
teamUsage,
isLoading: isLoadingBudget,
isAtLimit,
isBudgetExhausted,
isRateLimited,
isNearLimit,
isFreeTier,
shouldShowBudgetCompletedMessage,
usagePct10h,
usagePct7d,
currentTier,
} = useUsageState();
const [showLimitModal, setShowLimitModal] = useState(false);
const [deleteModal, setDeleteModal] = useState<ConfirmationModalType>({
isOpen: false,
title: '',
message: '',
onConfirm: () => {},
onCancel: () => {},
});
const textInputRef = useRef<HTMLTextAreaElement>(null);
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const mediaStreamRef = useRef<MediaStream | null>(null);
const audioChunksRef = useRef<Blob[]>([]);
const replyAudioRef = useRef<HTMLAudioElement | null>(null);
const lastSpokenMessageIdRef = useRef<string | null>(null);
const autocompleteDebounceRef = useRef<number | null>(null);
const autocompleteRequestSeqRef = useRef(0);
const sendingTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Thread id whose send started the current silence timer. Tracked separately
// from `selectedThreadId` so switching threads mid-turn doesn't move the
// timer's reference point.
const sendingThreadIdRef = useRef<string | null>(null);
const getAudioExtension = (mimeType: string): string => {
const lower = mimeType.toLowerCase();
if (lower.includes('webm')) return 'webm';
if (lower.includes('ogg')) return 'ogg';
if (lower.includes('wav')) return 'wav';
if (lower.includes('mp4') || lower.includes('mpeg') || lower.includes('aac')) return 'm4a';
return 'webm';
};
const canUseMicrophoneApi =
typeof navigator !== 'undefined' &&
typeof navigator.mediaDevices !== 'undefined' &&
typeof navigator.mediaDevices.getUserMedia === 'function';
const handleCreateNewThread = async () => {
const thread = await dispatch(createNewThread()).unwrap();
dispatch(setSelectedThread(thread.id));
void dispatch(loadThreadMessages(thread.id));
};
useEffect(() => {
let cancelled = false;
void dispatch(loadThreads())
.unwrap()
.then(data => {
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// if (cancelled || skipInitialThreadSelectionRef.current) return;
if (cancelled) return;
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// Always prefer the welcome thread during lockdown regardless of
// whether the server list is empty or not. Without this guard the
// stale `.then` could select a pre-existing thread from a prior
// session and pull the user out of the welcome conversation.
// const snapForSelect = getCoreStateSnapshot().snapshot;
// const threadStateForSelect = store.getState().thread;
// if (isWelcomeLocked(snapForSelect) && threadStateForSelect.welcomeThreadId) {
// dispatch(setSelectedThread(threadStateForSelect.welcomeThreadId));
// void dispatch(loadThreadMessages(threadStateForSelect.welcomeThreadId));
// return;
// }
const threadStateForSelect = store.getState().thread;
if (data.threads.length > 0) {
// Prefer the thread the user was last viewing (persisted across
// reloads via redux-persist on the `thread` slice). Only fall
// through to "most recent" if that thread no longer exists
// server-side (deleted, purged, or different user).
const persistedId = threadStateForSelect.selectedThreadId;
const resumeId =
persistedId && data.threads.some(t => t.id === persistedId)
? persistedId
: data.threads[0].id;
dispatch(setSelectedThread(resumeId));
void dispatch(loadThreadMessages(resumeId));
} else {
void handleCreateNewThread();
}
})
.catch(err => {
if (cancelled) return;
console.warn('[conversations] loadThreads failed on mount:', formatThreadLoadError(err));
});
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch]);
useEffect(() => {
if (selectedThreadId) {
void dispatch(loadThreadMessages(selectedThreadId));
void dispatch(fetchAndHydrateTurnState(selectedThreadId));
}
}, [selectedThreadId, dispatch]);
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// Welcome lockdown unlock (#883) — when `chatOnboardingCompleted`
// transitions from `false` → `true` (the welcome agent just called
// `complete_onboarding(action: "complete")`), open a fresh thread so
// the user starts their first "real" conversation with the orchestrator
// instead of continuing the welcome thread. Ref-tracked one-shot so
// the 2s snapshot poll cannot re-fire this.
// useEffect(() => {
// const prev = previousChatOnboardingCompletedRef.current;
// previousChatOnboardingCompletedRef.current = chatOnboardingCompleted;
// if (prev === false && chatOnboardingCompleted === true) {
// // Signal the mount-time `loadThreads()` promise to bail if it is
// // still pending — otherwise its stale resolution would overwrite
// // our freshly created thread selection.
// skipInitialThreadSelectionRef.current = true;
// console.debug('[welcome-lock] chat onboarding completed — opening new thread');
// void handleCreateNewThread();
// }
// // handleCreateNewThread is stable for the component lifetime (only
// // uses `dispatch`); the ref guards against duplicate fires.
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [chatOnboardingCompleted]);
const location = useLocation();
const { containerRef: messagesContainerRef, endRef: messagesEndRef } = useStickToBottom(
messages,
selectedThreadId,
location.pathname
);
useEffect(() => {
const onDictationInsert = (event: Event) => {
const customEvent = event as CustomEvent<{ text?: string }>;
const text = customEvent.detail?.text?.trim();
if (!text) return;
customEvent.preventDefault();
setInputMode('text');
setInputValue(prev => {
const base = prev.trim();
if (!base) return text;
return `${base}${base.endsWith(' ') ? '' : ' '}${text}`;
});
window.requestAnimationFrame(() => {
textInputRef.current?.focus();
});
};
window.addEventListener('dictation://insert-text', onDictationInsert as EventListener);
return () =>
window.removeEventListener('dictation://insert-text', onDictationInsert as EventListener);
}, []);
useEffect(() => {
if (sendError && inputValue.length > 0) {
setSendError(null);
}
if (sendAdvisory && inputValue.length > 0) {
setSendAdvisory(null);
}
}, [inputValue, sendAdvisory, sendError]);
const armSilenceTimer = (threadId: string) => {
if (sendingTimeoutRef.current) clearTimeout(sendingTimeoutRef.current);
sendingThreadIdRef.current = threadId;
sendingTimeoutRef.current = setTimeout(() => {
console.warn('[chat] silence timeout: no inference signal for 120s');
setSendError(
chatSendError(
'safety_timeout',
'No response from the agent after 2 minutes. Try again or check your connection.'
)
);
dispatch(clearRuntimeForThread({ threadId }));
dispatch(setActiveThread(null));
sendingTimeoutRef.current = null;
sendingThreadIdRef.current = null;
}, 120_000);
};
// Rearm the silence timer on every inference signal for the sending
// thread. Tool / iteration / subagent events bump `inferenceStatusByThread`;
// pure-text streams (no tools) only bump `streamingAssistantByThread`, so
// both must be watched — otherwise a long text stream would trip the
// safety timer mid-reply. When the status is cleared (chat_done /
// chat_error), drop the timer — the completion handlers own UI cleanup.
useEffect(() => {
const threadId = sendingThreadIdRef.current;
if (!threadId || !sendingTimeoutRef.current) return;
const status = inferenceStatusByThread[threadId];
if (status === undefined) {
clearTimeout(sendingTimeoutRef.current);
sendingTimeoutRef.current = null;
sendingThreadIdRef.current = null;
return;
}
armSilenceTimer(threadId);
// armSilenceTimer is stable (refs + dispatch); depending on the
// selector references is enough to rearm on every progress event.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [inferenceStatusByThread, streamingAssistantByThread]);
useEffect(() => {
if (
!isTauri() ||
!rustChat ||
inputMode !== 'text' ||
Boolean(activeThreadId) ||
inputValue.trim().length < AUTOCOMPLETE_MIN_CONTEXT_CHARS
) {
setInlineSuggestionValue('');
return;
}
if (autocompleteDebounceRef.current !== null) {
window.clearTimeout(autocompleteDebounceRef.current);
}
autocompleteDebounceRef.current = window.setTimeout(() => {
const requestSeq = autocompleteRequestSeqRef.current + 1;
autocompleteRequestSeqRef.current = requestSeq;
void openhumanAutocompleteCurrent({ context: inputValue })
.then(response => {
if (autocompleteRequestSeqRef.current !== requestSeq) return;
setInlineSuggestionValue(response.result.suggestion?.value ?? '');
})
.catch(() => {
if (autocompleteRequestSeqRef.current !== requestSeq) return;
setInlineSuggestionValue('');
});
}, AUTOCOMPLETE_POLL_DEBOUNCE_MS);
return () => {
if (autocompleteDebounceRef.current !== null) {
window.clearTimeout(autocompleteDebounceRef.current);
autocompleteDebounceRef.current = null;
}
};
}, [activeThreadId, inputValue, inputMode, rustChat]);
useEffect(() => {
return () => {
mediaRecorderRef.current?.stop();
mediaStreamRef.current?.getTracks().forEach(track => track.stop());
replyAudioRef.current?.pause();
replyAudioRef.current = null;
};
}, []);
useEffect(() => {
if (inputMode === 'text' && isRecording) {
mediaRecorderRef.current?.stop();
}
}, [inputMode, isRecording]);
useEffect(() => {
if (inputMode === 'voice') {
setReplyMode('voice');
} else if (replyMode === 'voice') {
setReplyMode('text');
}
}, [inputMode, replyMode]);
// Proactively check voice binary availability when switching to voice mode
useEffect(() => {
if (inputMode !== 'voice' || !rustChat) return;
let cancelled = false;
void (async () => {
try {
const status = await openhumanVoiceStatus();
if (cancelled) return;
if (!status.stt_available) {
setVoiceStatus(
'Voice input needs a speech model to work. Go to Settings > Local AI Models to set it up.'
);
} else {
setVoiceStatus('Ready — tap "Start Talking" to record.');
}
} catch {
if (!cancelled) {
setVoiceStatus('Could not check voice availability.');
}
}
})();
return () => {
cancelled = true;
};
}, [inputMode, rustChat]);
const handleSlashCommand = (command: string): boolean => {
const decision = handleComposerSlashCommand(command, false);
if (decision.kind === 'not_handled') return false;
setInputValue('');
void handleCreateNewThread();
return true;
};
const handleSendMessage = async (text?: string) => {
const normalized = text ?? inputValue;
const trimmedInput = normalized.trim();
if (handleSlashCommand(trimmedInput)) return;
const sendDecision = evaluateComposerSend({
rawText: normalized,
selectedThreadId,
composerInteractionBlocked,
isAtLimit,
socketStatus,
});
const trimmed = sendDecision.trimmedText;
if (
sendDecision.blockReason === 'empty_input' ||
sendDecision.blockReason === 'missing_thread' ||
sendDecision.blockReason === 'composer_blocked'
) {
return;
}
const promptGuard = checkPromptInjection(trimmed);
if (promptGuard.verdict === 'review' || promptGuard.verdict === 'block') {
setSendAdvisory(promptGuardMessage(promptGuard));
} else {
setSendAdvisory(null);
}
if (!sendDecision.shouldSend) {
const blockedFeedback = getComposerBlockedSendFeedback(sendDecision.blockReason);
if (blockedFeedback?.showLimitModal) {
setShowLimitModal(true);
}
if (blockedFeedback) {
setSendError(chatSendError(blockedFeedback.error.code, blockedFeedback.error.message));
}
return;
}
const sendingThreadId = selectedThreadId;
if (!sendingThreadId) return;
const userMessage: ThreadMessage = {
id: `msg_${globalThis.crypto.randomUUID()}`,
content: trimmed,
type: 'text',
extraMetadata: {},
sender: 'user',
createdAt: new Date().toISOString(),
};
try {
await dispatch(addMessageLocal({ threadId: sendingThreadId, message: userMessage })).unwrap();
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
setSendError(chatSendError('cloud_send_failed', msg));
return;
}
setInputValue('');
setSendError(null);
// Silence timer: fires only if 600s pass without ANY inference progress
// (tool call, tool result, iteration start, subagent event, text delta).
// The effect below rearms this timer whenever `inferenceStatusByThread`
// changes for `sendingThreadId`, so long-running agent turns stay alive
// as long as the backend is emitting signals. A truly hung server still
// fails fast.
armSilenceTimer(sendingThreadId);
dispatch(setToolTimelineForThread({ threadId: sendingThreadId, entries: [] }));
dispatch(beginInferenceTurn({ threadId: sendingThreadId }));
dispatch(setActiveThread(sendingThreadId));
// ── Cloud socket path ─────────────────────────────────────────────────────
// Always route primary chat through the cloud backend via socket.
// Local model (Ollama) is used only for supplementary features
// (auto-react, autocomplete, etc.) — never as a primary chat path.
try {
await chatSend({ threadId: sendingThreadId, message: trimmed, model: CHAT_MODEL_ID });
trackEvent('chat_message_sent');
// Active-thread reset happens in the global ChatRuntimeProvider events.
} catch (err) {
// Chat loop errors are emitted via socket events; this catch handles emit-level failures.
if (sendingTimeoutRef.current) {
clearTimeout(sendingTimeoutRef.current);
sendingTimeoutRef.current = null;
}
sendingThreadIdRef.current = null;
const msg = err instanceof Error ? err.message : String(err);
if (
msg.toLowerCase().includes('blocked by a security policy') ||
msg.toLowerCase().includes('flagged for security review')
) {
const code = msg.toLowerCase().includes('flagged for security review')
? 'prompt_review'
: 'prompt_blocked';
setSendError(chatSendError(code, msg));
} else {
setSendError(chatSendError('cloud_send_failed', msg));
}
dispatch(clearRuntimeForThread({ threadId: sendingThreadId }));
dispatch(setActiveThread(null));
}
};
const transcribeAndSendAudio = async (mimeType: string) => {
setIsRecording(false);
mediaRecorderRef.current = null;
mediaStreamRef.current?.getTracks().forEach(track => track.stop());
mediaStreamRef.current = null;
const chunks = audioChunksRef.current;
audioChunksRef.current = [];
if (chunks.length === 0) {
notifyOverlaySttState('cancelled');
setVoiceStatus('No audio captured. Try again.');
return;
}
setIsTranscribing(true);
setVoiceStatus('Transcribing with Whisper…');
try {
const blob = new Blob(chunks, { type: mimeType || 'audio/webm' });
const audioBytes = Array.from(new Uint8Array(await blob.arrayBuffer()));
const extension = getAudioExtension(mimeType || blob.type);
// Build conversation context from recent messages for LLM cleanup.
const recentMessages = messages.slice(-10);
const context =
recentMessages.length > 0
? recentMessages.map(m => `${m.sender}: ${m.content}`).join('\n')
: undefined;
const result = await openhumanVoiceTranscribeBytes(audioBytes, extension, context);
const transcript = result.text.trim();
if (!transcript) {
notifyOverlaySttState('cancelled');
setVoiceStatus('No speech detected. Try again.');
return;
}
notifyOverlaySttState('transcription_done', transcript);
setVoiceStatus(`Heard: ${transcript}`);
await handleSendMessage(transcript);
} catch (err) {
notifyOverlaySttState('error');
const message = err instanceof Error ? err.message : String(err);
const isSetupIssue =
message.includes('whisper') ||
message.includes('binary not found') ||
message.includes('STT model');
setSendError(
chatSendError(
isSetupIssue ? 'stt_not_ready' : 'voice_transcription',
isSetupIssue
? 'Voice input needs a speech model. Go to Settings to download one.'
: `Voice transcription failed: ${message}`
)
);
setVoiceStatus(null);
} finally {
setIsTranscribing(false);
}
};
const handleVoiceRecordToggle = async () => {
if (!rustChat || Boolean(activeThreadId) || isTranscribing) return;
if (!canUseMicrophoneApi) {
setSendError(
chatSendError(
'microphone_unavailable',
'Microphone capture is unavailable in this runtime. Use Text mode, or run the desktop app bundle with microphone permissions enabled.'
)
);
return;
}
if (isRecording) {
mediaRecorderRef.current?.stop();
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaStreamRef.current = stream;
const preferredTypes = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/ogg',
'audio/mp4',
];
const supportedType = preferredTypes.find(type => MediaRecorder.isTypeSupported(type));
const recorder = supportedType
? new MediaRecorder(stream, { mimeType: supportedType })
: new MediaRecorder(stream);
audioChunksRef.current = [];
recorder.ondataavailable = event => {
if (event.data.size > 0) {
audioChunksRef.current.push(event.data);
}
};
recorder.onerror = () => {
notifyOverlaySttState('error');
setIsRecording(false);
mediaStreamRef.current?.getTracks().forEach(track => track.stop());
mediaStreamRef.current = null;
setSendError(chatSendError('microphone_recording', 'Microphone recording failed.'));
};
recorder.onstop = () => {
void transcribeAndSendAudio(recorder.mimeType);
};
mediaRecorderRef.current = recorder;
setVoiceStatus('Listening… click Stop to send.');
setSendError(null);
setIsRecording(true);
recorder.start();
notifyOverlaySttState('recording_started');
} catch (err) {
notifyOverlaySttState('error');
const message = err instanceof Error ? err.message : String(err);
setSendError(chatSendError('microphone_access', `Microphone access failed: ${message}`));
setVoiceStatus(null);
}
};
useEffect(() => {
const latestAgentMessage = [...messages].reverse().find(m => m.sender === 'agent');
if (!latestAgentMessage) return;
if (replyMode === 'text') {
lastSpokenMessageIdRef.current = latestAgentMessage.id;
replyAudioRef.current?.pause();
replyAudioRef.current = null;
setIsPlayingReply(false);
return;
}
if (!rustChat || latestAgentMessage.id === lastSpokenMessageIdRef.current) return;
lastSpokenMessageIdRef.current = latestAgentMessage.id;
let cancelled = false;
setIsPlayingReply(true);
void (async () => {
try {
const ttsResult = await openhumanVoiceTts(latestAgentMessage.content);
if (cancelled) return;
const audioSrc = convertFileSrc(ttsResult.output_path);
const audio = new window.Audio(audioSrc);
replyAudioRef.current?.pause();
replyAudioRef.current = audio;
await audio.play();
} catch {
if (!cancelled) {
setSendError(chatSendError('voice_playback', 'Failed to play voice reply.'));
}
} finally {
if (!cancelled) {
setIsPlayingReply(false);
}
}
})();
return () => {
cancelled = true;
};
}, [messages, replyMode, rustChat]);
const handleInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
const inlineSuffix = getInlineCompletionSuffix(inputValue, inlineSuggestionValue);
const textarea = e.currentTarget;
const caretAtEnd =
textarea.selectionStart === inputValue.length && textarea.selectionEnd === inputValue.length;
const tryAcceptInlineSuggestion = () => {
const nextValue = buildAcceptedInlineCompletion(inputValue, inlineSuffix);
if (!nextValue || nextValue === inputValue) return false;
setInputValue(nextValue);
setInlineSuggestionValue('');
if (isTauri()) {
void openhumanAutocompleteAccept({ suggestion: nextValue, skip_apply: true }).catch(() => {
// Keep local UX smooth even if accept RPC fails.
});
}
return true;
};
if (
e.key === 'Tab' &&
!e.shiftKey &&
!e.altKey &&
!e.ctrlKey &&
!e.metaKey &&
inlineSuffix.length > 0 &&
caretAtEnd
) {
e.preventDefault();
tryAcceptInlineSuggestion();
return;
}
if (e.key === 'ArrowRight' && inlineSuffix.length > 0 && caretAtEnd) {
e.preventDefault();
tryAcceptInlineSuggestion();
return;
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
void handleSendMessage();
}
};
const handleCopyMessage = async (messageId: string, content: string) => {
try {
await navigator.clipboard.writeText(content);
setCopiedMessageId(messageId);
setTimeout(() => setCopiedMessageId(null), 1500);
} catch {
// Clipboard API not available — silently fail
}
};
const selectedThreadToolTimeline = selectedThreadId
? (toolTimelineByThread[selectedThreadId] ?? [])
: [];
const visibleMessages = messages.filter(msg => !msg.extraMetadata?.hidden);
const hasVisibleMessages = visibleMessages.length > 0;
const latestVisibleMessage = visibleMessages[visibleMessages.length - 1] ?? null;
const latestVisibleAgentMessage = [...visibleMessages]
.reverse()
.find(msg => msg.sender === 'agent');
const activeSubagentTimelineEntry = selectedThreadToolTimeline.find(
entry => entry.status === 'running' && entry.name.startsWith('subagent:')
);
const activeToolTimelineEntry = [...selectedThreadToolTimeline]
.reverse()
.find(entry => entry.status === 'running' && !entry.name.startsWith('subagent:'));
const selectedInferenceStatus = selectedThreadId
? (inferenceStatusByThread[selectedThreadId] ?? null)
: null;
const selectedStreamingAssistant = selectedThreadId
? (streamingAssistantByThread[selectedThreadId] ?? null)
: null;
const inlineCompletionSuffix = getInlineCompletionSuffix(inputValue, inlineSuggestionValue);
// Blocks all composer interaction while a turn is in-flight, the
// proactive welcome opener is pending, or Rust chat is unavailable.
// isSending: the *selected* thread is in-flight (drives selected-thread UI only).
// [#1123] welcomePending removed — welcome-agent onboarding replaced by Joyride walkthrough
const composerInteractionBlocked = isComposerInteractionBlocked({
activeThreadId,
welcomePending: false,
rustChat,
});
// Auto-focus the composer when a thread becomes selected and the composer
// isn't blocked. Without this, navigating into a thread from elsewhere in
// the app (e.g. acting on a subconscious reflection in the Intelligence
// tab — `IntelligenceSubconsciousTab.handleNavigateToReflectionThread`
// dispatches `setSelectedThread` then routes to `/chat`) leaves focus on
// the unmounted source button, falling back to `document.body`. The
// textarea is rendered and enabled but ignores keystrokes until the user
// clicks into it. Skip when there is no thread, when the composer is
// disabled, when in voice mode, and when the user has focus on another
// input/textarea/contenteditable (don't steal focus from a settings pane
// the user just clicked into).
useEffect(() => {
if (!selectedThreadId) return;
if (composerInteractionBlocked) return;
if (inputMode !== 'text') return;
const ta = textInputRef.current;
if (!ta) return;
const active = document.activeElement;
if (
active &&
active !== document.body &&
active !== ta &&
(active.tagName === 'INPUT' ||
active.tagName === 'TEXTAREA' ||
active.getAttribute('contenteditable') === 'true')
) {
return;
}
// rAF — wait for the textarea to be in the layout tree (selectedThread
// changes can arrive a tick before the panel mounts on first navigation).
const id = window.requestAnimationFrame(() => {
textInputRef.current?.focus();
});
return () => window.cancelAnimationFrame(id);
}, [selectedThreadId, composerInteractionBlocked, inputMode]);
const isSending = Boolean(
selectedThreadId &&
(inferenceTurnLifecycleByThread[selectedThreadId] === 'started' ||
inferenceTurnLifecycleByThread[selectedThreadId] === 'streaming')
);
const shouldRenderTimelineBeforeLatestAgentMessage =
selectedThreadToolTimeline.length > 0 && !isSending && Boolean(latestVisibleAgentMessage);
const filteredThreads = useMemo(() => {
const base = threads.filter(t => {
if (selectedLabel === 'all') return true;
return t.labels?.includes(selectedLabel);
});
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// if (!welcomeLocked) return base;
// // During welcome lockdown only the onboarding welcome thread should
// // appear — not stray blank threads from races or proactive:* handling.
// if (welcomeThreadId) {
// return base.filter(t => t.id === welcomeThreadId);
// }
// // Fallback: welcomeThreadId not yet set but the server already returned the
// // thread (e.g. hot-reload). Keep only onboarding-labelled threads so the
// // welcome thread is visible rather than hidden behind the empty-state message.
// return base.filter(t => (t.labels ?? []).includes(ONBOARDING_WELCOME_THREAD_LABEL));
return base;
}, [threads, selectedLabel]);
const sortedThreads = useMemo(() => {
return [...filteredThreads].sort(
(a, b) => new Date(b.lastMessageAt).getTime() - new Date(a.lastMessageAt).getTime()
);
}, [filteredThreads]);
const allLabels = useMemo(() => {
return Array.from(new Set(threads.flatMap(t => t.labels ?? []))).sort();
}, [threads]);
// Fixed tab set so categories don't disappear when empty and the active
// filter state remains unambiguous regardless of what threads exist.
const labelTabs = [
{ label: 'All', value: 'all' },
{ label: 'Work', value: 'work' },
{ label: 'Briefing', value: 'briefing' },
{ label: 'Notification', value: 'notification' },
];
// Reset stale selectedLabel when the last thread carrying that label is deleted.
useEffect(() => {
if (selectedLabel !== 'all' && !allLabels.includes(selectedLabel)) {
setSelectedLabel('all');
}
}, [allLabels, selectedLabel]);
const isSidebar = variant === 'sidebar';
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// During welcome lockdown keep the sidebar forced open so the user always
// sees the single onboarding thread entry and cannot accidentally close the
// panel via the toggle (leaving themselves with no thread list).
// const effectiveShowSidebar = welcomeLocked ? true : showSidebar;
const effectiveShowSidebar = showSidebar;
// Stable title resolver used by both the sidebar thread list and the header.
// [#1123] welcome-lock title override removed — Joyride walkthrough replaced welcome-agent
const resolveThreadDisplayTitle = (threadId: string | null): string => {
if (!threadId) return 'Select a thread';
const t = threads.find(thr => thr.id === threadId);
// [#1123] Commented out — welcome-agent onboarding replaced by Joyride walkthrough
// if (
// welcomeLocked &&
// t?.id === welcomeThreadId &&
// (t?.labels ?? []).includes(ONBOARDING_WELCOME_THREAD_LABEL)
// ) {
// return 'Onboarding';
// }
return t?.title ?? 'Select a thread';
};