-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathGatewayApp.tsx
More file actions
5239 lines (4993 loc) · 203 KB
/
Copy pathGatewayApp.tsx
File metadata and controls
5239 lines (4993 loc) · 203 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 {
type CSSProperties,
type DragEvent,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { AppErrorBoundary } from "@/components/AppErrorBoundary";
import { CliIdentityUpdateHost } from "@/components/CliIdentityUpdateHost";
import type {
MentionComposerDraft,
MentionComposerHandle,
} from "@/components/chat/MentionComposer";
import { type NotifyItem, NotifyToast } from "@/components/chat/NotifyToast";
import { SharedHistoryManagerModal } from "@/components/chat/SharedHistoryManagerModal";
import { ToolApprovalBar } from "@/components/chat/ToolApprovalBar";
import { ChevronDown, PanelRightClose, PanelRightOpen, Terminal } from "@/components/icons";
import type {
GitCommitContextPayload,
GitFileContextPayload,
} from "@/components/project-tools/git-review";
import { RightDockPanel } from "@/components/project-tools/RightDockPanel";
import { Button } from "@/components/ui/button";
import { useConfirmDialog } from "@/components/ui/confirm-dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { LocaleContext, t as translate } from "@/i18n";
import { registerAskUserQuestionAnswerHandler } from "@/lib/chat/askUserQuestionBridge";
import type { ChatFileLink } from "@/lib/chat/chatFileLinks";
import type { ChatHistorySummary } from "@/lib/chat/chatHistory";
import { buildModelOptions } from "@/lib/chat/chatPageHelpers";
import type { HistoryMessageRef } from "@/lib/chat/conversationState";
import {
adoptHistoryWindowState,
evaluateHistoryWindowResponse,
type HistoryWindowState,
noteHistoryWindowTotal,
planHistoryWindowRequest,
readHistoryWindowCounts,
trimLeadingHeadlessEntries,
} from "@/lib/chat/historyWindow";
import type { CodeMentionReference } from "@/lib/chat/mentionReferences";
import { openChatFileLink } from "@/lib/chat/openChatFileLink";
import { isChatRuntimeProtocolIncompatible } from "@/lib/chat/runtimeCompatibility";
import { createActivityStore } from "@/lib/chat/stream/activityStore";
import {
type ChatCommandOutcome,
ChatCommandPipeline,
type PendingChatCommand,
} from "@/lib/chat/stream/chatCommandPipeline";
import {
type ChatCommandUpdate,
type ConversationActivityEvent,
type ConversationStreamEvent,
type ConversationSubscribeResult,
readEventRunId,
} from "@/lib/chat/stream/streamTypes";
import {
createTranscriptStoreRegistry,
useConversationChat,
} from "@/lib/chat/stream/useConversationChat";
import {
readToolApprovalDeadlineAt,
readToolApprovalPending,
readToolApprovalSummary,
} from "@/lib/chat/toolApprovalArgs";
import {
registerToolApprovalDecisionHandler,
submitToolApprovalDecision,
} from "@/lib/chat/toolApprovalBridge";
import type { PendingUploadedFile } from "@/lib/chat/uploadedFiles";
import { mergePendingUploadedFiles } from "@/lib/chat/uploadedFiles";
import {
buildOptimisticConversationTitle,
type ChatEntry,
resolveConversationBrowserTitle,
} from "@/lib/chatUi";
import type { GatewayChatCommandInput } from "@/lib/gatewaySocket";
import type {
AgentStatus,
ChatEvent,
ChatQueueItemSummary,
ChatQueueSnapshot,
HistoryDetail,
HistoryShareStatus,
} from "@/lib/gatewayTypes";
import { parseHistoryMessagesJsonAsync } from "@/lib/historyParser";
import { memoryDeleteProject } from "@/lib/memory/api";
import { toModelValue } from "@/lib/providers/llm";
import {
type ChatRuntimeControls,
DEFAULT_WORKSPACE_PROJECT_ID,
findProviderModelConfig,
getChatRuntimeReasoningLevelsForProvider,
getNextTheme,
getRightDockFileTreeState,
getRightDockProjectState,
getSshProjectHostIds,
isAgentDevMode,
isRightDockSingletonTabOpen,
isThinkingAlwaysOnForModel,
normalizeChatRuntimeControlsForProvider,
openRightDockSingletonTab,
parseSelectedModelJson,
type RightDockFileTreeStatePatch,
type RightDockProjectState,
removeRightDockProjectState,
resolveEffectiveTheme,
resolveWorkspaceProjects,
type SelectedModel,
setSelectedModel,
updateChatRuntimeControlsForProvider,
updateChatTranscriptWidth,
updateCustomSettings,
updateRightDockFileTreeState,
updateRightDockProjectState,
updateRightDockWidth,
updateSkills,
updateSshProjectHostIds,
updateSystem,
type WorkspaceProject,
workspaceProjectPathKey,
} from "@/lib/settings";
import { createUuid } from "@/lib/shared/id";
import { mergeAlwaysEnabledSkillNames } from "@/lib/skills";
import { terminalSessionBelongsToProject } from "@/lib/terminal/sessionStore";
import type { TerminalSession } from "@/lib/terminal/types";
import { createGatewayWorkspaceActivityClient } from "@/lib/workspace-activity/gatewayWorkspaceActivityClient";
import { ChatComposerBar, type ChatQueueTurnPreview } from "@/pages/chat/ChatComposerBar";
import { ChatHeader } from "@/pages/chat/ChatHeader";
import { queuedChatTurnHasContent } from "@/pages/chat/queue/chatTurnQueue";
import { useChatSkills } from "@/pages/chat/useChatSkills";
import { McpHubPage } from "@/pages/mcp-hub/McpHubPage";
import { SettingsPage } from "@/pages/SettingsPage";
import type { SectionId } from "@/pages/settings/types";
import { SkillsHubPage } from "@/pages/skills-hub/SkillsHubPage";
const LOCAL_DRAFT_PREFIX = "__local_draft__:";
function createLocalDraftConversationId() {
return `${LOCAL_DRAFT_PREFIX}${createUuid()}`;
}
function isLocalDraftConversationId(id: string) {
return id.trim().startsWith(LOCAL_DRAFT_PREFIX);
}
import {
type ChangedFilesActions,
ChangedFilesActionsProvider,
} from "@/components/chat/ChangedFilesCard";
import { HistoryShareModal } from "@/components/chat/HistoryShareModal";
import { GatewayTranscript, type GatewayTranscriptNavHandle } from "@/components/GatewayTranscript";
import type { GitReviewFocusRequest } from "@/components/project-tools/RightDockContext";
import { expandedPathsForFileTreePath } from "@/components/project-tools/rightDockModel";
import { buildFloorEntries } from "@/lib/chat-floor-nav/floorModel";
import { useScrollFollow } from "@/lib/chat-scroll/useScrollFollow";
import { parseHistoryShareToken } from "@/lib/historyShare";
import {
type ConversationOpenState,
createConversationOpenController,
} from "@/lib/sidebar/openController";
import { sortSidebarConversations } from "@/lib/sidebar/reconcile";
import { createSidebarStore } from "@/lib/sidebar/store";
import { useSidebarSelector } from "@/lib/sidebar/useSidebarSelector";
import {
createIdleSidebarBackend,
createWebSidebarBackend,
normalizeGatewayConversationSummary,
normalizeRunningConversationItems,
} from "@/lib/sidebar/webSidebarBackend";
import { findWorkspaceProject, mergeWorkspaceProjectsWithHistory } from "@/lib/workspaceProjects";
import { FloorNavRail } from "@/pages/chat/transcript/FloorNavRail";
import {
CHAT_TRANSCRIPT_WIDTH_CSS_VAR,
TranscriptWidthControls,
} from "@/pages/chat/transcript/TranscriptWidthControls";
import { WorkspaceCloneModal } from "@/pages/chat/WorkspaceCloneModal";
import {
type WorkspaceCloneTask,
WorkspaceCloneTaskOverlay,
} from "@/pages/chat/WorkspaceCloneTaskOverlay";
import { LoginPage } from "@/pages/LoginPage";
import { SettingsSyncLoading } from "@/pages/SettingsSyncLoading";
import { SharedHistoryPage } from "@/pages/SharedHistoryPage";
import { WorkdirPickerModal } from "@/pages/settings/WorkdirPickerModal";
import { AgentSelector } from "./AgentSelector";
import { buildTextFromComposerDraft, importPastedTextsAsFiles } from "./chatDraft";
import {
asErrorMessage,
buildGatewaySelectedModel,
buildGatewaySystemSettings,
isAbortError,
isChatEventTitleFinal,
readChatEventTitle,
readTunnelManagerToolChange,
resolveActiveModelSelection,
} from "./chatEventUtils";
import {
CHAT_RUNTIME_FOREGROUND_PREPARE_TIMEOUT_MS,
CHAT_RUNTIME_KEEP_WARM_INTERVAL_MS,
CHAT_RUNTIME_PREPARE_TIMEOUT_MS,
CHAT_RUNTIME_PREPARING_STATUS,
DEFAULT_BROWSER_TITLE,
HISTORY_DETAIL_INITIAL_MAX_MESSAGES,
HISTORY_DETAIL_LOAD_EARLIER_PAGE_MESSAGES,
HISTORY_LIST_PAGE_SIZE,
MAX_UPLOAD_FILES,
MCP_HUB_BROWSER_TITLE,
NEW_CONVERSATION_BROWSER_TITLE,
PROJECT_HISTORY_DELETE_PAGE_SIZE,
PROTECTED_DRAFT_CONVERSATION,
SHARED_HISTORY_BROWSER_TITLE,
SHARED_HISTORY_LIST_PAGE_SIZE,
SKILLS_HUB_BROWSER_TITLE,
} from "./constants";
import { FileDropOverlay } from "./FileDropOverlay";
import { HistorySwitchLoadingOverlay } from "./HistorySwitchLoadingOverlay";
import {
createWorkspaceProjectFromPath,
formatTranslation,
getDefaultWorkspaceProjectPath,
isMobileSidebarLayout,
resolveVisibleConversationId,
shouldOpenSidebarByDefault,
} from "./historyUtils";
import { useGatewayClients } from "./hooks/useGatewayClients";
import { useGatewaySession } from "./hooks/useGatewaySession";
import { useGatewaySettingsSync } from "./hooks/useGatewaySettingsSync";
import { usePendingUploads } from "./hooks/usePendingUploads";
import { useProjectToolsRuntime } from "./hooks/useProjectToolsRuntime";
import { GatewaySidebarContainer } from "./sidebar/GatewaySidebarContainer";
import {
type GatewaySidebarStatusFreshnessEvent,
INITIAL_GATEWAY_SIDEBAR_STATUS_FRESHNESS,
reduceGatewaySidebarStatusFreshness,
shouldDisableGatewaySidebarSections,
} from "./sidebar/gatewaySidebarAvailability";
import type { ModelProviderSource, OverlayState, SendChatFn, SendChatOptions } from "./types";
import { UserMenu } from "./UserMenu";
import { WorkspaceOverlayHost } from "./WorkspaceOverlayHost";
const STALE_HISTORY_RETRY_INITIAL_DELAY_MS = 1_000;
const STALE_HISTORY_RETRY_MAX_DELAY_MS = 30_000;
export default function GatewayApp() {
const historyShareToken = useMemo(() => parseHistoryShareToken(), []);
const {
token,
loginToken,
authSubmitting,
authError,
setLoginToken,
setAuthError,
login: handleLoginSubmit,
clearSession,
} = useGatewaySession(historyShareToken);
const { api, terminalClient, sftpClient, gitClient } = useGatewayClients(token);
const [workspaceCloneTasks, setWorkspaceCloneTasks] = useState<WorkspaceCloneTask[]>([]);
const dismissedWorkspaceCloneTaskIds = useRef(new Set<string>());
const [activeAgentId, setActiveAgentId] = useState(() => api?.getActiveAgent() ?? "");
const activeAgentIdRef = useRef(activeAgentId);
const activeAgentScope = activeAgentId || api?.getActiveAgent() || "";
const [status, setStatus] = useState<AgentStatus | null>(null);
const [statusError, setStatusError] = useState<string | null>(null);
// True only after an authenticated gateway connection has been established
// and then dropped; the initial connect never shows lost-connection UI.
const [gatewayConnectionLost, setGatewayConnectionLost] = useState(false);
// A cached Agent status is usable only after it has been observed on the
// currently authenticated browser-socket epoch.
const [sidebarAgentStatusFresh, setSidebarAgentStatusFresh] = useState(false);
const [conversationId, setConversationId] = useState("");
// 本地未持久化的会话模型切换(按会话 id 键);发消息随 selected_model
// 落库后由 history-sync 回声在清理 effect 中收敛删除。
const [conversationModelOverrides, setConversationModelOverrides] = useState<
ReadonlyMap<string, SelectedModel>
>(new Map());
const [chatError, setChatError] = useState<string | null>(null);
// Top-right toast stack for upload/attachment feedback — mirrors the GUI's
// NotifyToast usage so upload failures never render as conversation output.
const [notifyItems, setNotifyItems] = useState<NotifyItem[]>([]);
const notifyIdCounter = useRef(0);
const addNotify = useCallback((type: NotifyItem["type"], message: string) => {
const id = `notify-${++notifyIdCounter.current}`;
setNotifyItems((prev) => [...prev, { id, type, message }]);
}, []);
const dismissNotify = useCallback((id: string) => {
setNotifyItems((prev) => prev.filter((item) => item.id !== id));
}, []);
// Sidebar errors raised outside the sidebar store (project removal flow).
const [sidebarActionError, setSidebarActionError] = useState<string | null>(null);
const [queuedChatTurns, setQueuedChatTurns] = useState<ChatQueueItemSummary[]>([]);
const [, setChatQueueRevision] = useState(0);
const [selectedHistoryId, setSelectedHistoryId] = useState("");
const [selectedHistory, setSelectedHistory] = useState<HistoryDetail | null>(null);
// Two-phase conversation open (openController): "opening" gates the
// composer/transcript loading affordances; showOverlay drives the switch
// overlay (appears only after ~150ms of still-loading).
const [conversationOpenState, setConversationOpenState] = useState<ConversationOpenState>({
conversationId: "",
phase: "idle",
showOverlay: false,
errorCode: null,
});
// Explicit "load full history" request from the transcript header.
const [fullHistoryLoading, setFullHistoryLoading] = useState(false);
// Bumped whenever the command pipeline's pending set changes so busy state
// re-derives.
const [pendingCommandRevision, setPendingCommandRevision] = useState(0);
const [settingsOpen, setSettingsOpen] = useState(false);
const [projectPickerOpen, setProjectPickerOpen] = useState(false);
const [workspaceCreateModalOpen, setWorkspaceCreateModalOpen] = useState(false);
const [settingsSection, setSettingsSection] = useState<SectionId>("system");
const [settingsProviderId, setSettingsProviderId] = useState<string>();
const [overlay, setOverlay] = useState<OverlayState>("closed");
const { settings, setSettings, settingsSyncReady, settingsSyncError, settingsSaveState } =
useGatewaySettingsSync({ token, api, activeAgentId: activeAgentScope });
const effectiveTheme = resolveEffectiveTheme(settings.theme);
const isAgentMode = settings.system.executionMode !== "text";
const [activeWorkspaceProjectId, setActiveWorkspaceProjectId] = useState<string>(
() => settings.system.activeWorkspaceProjectId?.trim() || DEFAULT_WORKSPACE_PROJECT_ID,
);
const missingWorkspaceProjectPathKeys = useMemo(
() => new Set(settings.system.missingWorkspaceProjectPaths.map(workspaceProjectPathKey)),
[settings.system.missingWorkspaceProjectPaths],
);
const [sidebarOpen, setSidebarOpen] = useState(shouldOpenSidebarByDefault);
const [projectRenamingId, setProjectRenamingId] = useState<string | null>(null);
const [projectRenameDraft, setProjectRenameDraft] = useState("");
const [shareConversation, setShareConversation] = useState<ChatHistorySummary | null>(null);
const [shareStatus, setShareStatus] = useState<HistoryShareStatus | null>(null);
const [shareLoading, setShareLoading] = useState(false);
const [shareUpdating, setShareUpdating] = useState(false);
const [shareError, setShareError] = useState<string | null>(null);
const [sharedManagerOpen, setSharedManagerOpen] = useState(false);
const [sharedManagerStatuses, setSharedManagerStatuses] = useState<
Record<string, HistoryShareStatus | undefined>
>({});
const [sharedManagerLoadingIds, setSharedManagerLoadingIds] = useState<ReadonlySet<string>>(
() => new Set(),
);
const [sharedManagerUpdatingIds, setSharedManagerUpdatingIds] = useState<ReadonlySet<string>>(
() => new Set(),
);
const [sharedManagerErrors, setSharedManagerErrors] = useState<
Record<string, string | undefined>
>({});
const [sharedHistoryListError, setSharedHistoryListError] = useState<string | null>(null);
const [sharedHistoryItems, setSharedHistoryItems] = useState<ChatHistorySummary[]>([]);
const [userMenuOpen, setUserMenuOpen] = useState(false);
const [activeView, setActiveView] = useState<"chat" | "skills-hub" | "mcp-hub">("chat");
const [rightDockOpen, setRightDockOpen] = useState(false);
const { confirm: requestConfirmDialog, dialog: confirmDialog } = useConfirmDialog();
// Both elements arrive via callback refs → state so the scroll-follow hook
// re-binds on element identity change and can never keep listeners on a
// dead node.
const [transcriptScrollAreaRoot, setTranscriptScrollAreaRoot] = useState<HTMLDivElement | null>(
null,
);
const [transcriptViewport, setTranscriptViewport] = useState<HTMLDivElement | null>(null);
const transcriptStageRef = useRef<HTMLElement | null>(null);
const { handle: transcriptFollow, following: transcriptFollowing } = useScrollFollow({
viewport: transcriptViewport,
listenerRoot: transcriptScrollAreaRoot,
trackKeys: true,
});
// 楼层导航:当前楼层由转写区上报,跳转经 navRef 直达虚拟列表;粘底跟随
// 激活时程序化滚动会被立即拽回底部——跳转前先按「跳入历史」语义解除跟随。
const transcriptNavRef = useRef<GatewayTranscriptNavHandle | null>(null);
const [activeFloorKey, setActiveFloorKey] = useState<string | null>(null);
const handleFloorJump = useCallback(
(rowKey: string) => {
transcriptFollow.breakFollow();
transcriptNavRef.current?.scrollToRowKey(rowKey);
},
[transcriptFollow],
);
const composerRef = useRef<MentionComposerHandle | null>(null);
const composerDraftCacheRef = useRef<Map<string, MentionComposerDraft>>(new Map());
const composerDraftOwnerRef = useRef("");
const conversationIdRef = useRef(conversationId);
const selectedHistoryIdRef = useRef(selectedHistoryId);
const statusRef = useRef<AgentStatus | null>(status);
const queuedChatTurnsRef = useRef<ChatQueueItemSummary[]>([]);
const chatQueueConversationIdRef = useRef("");
const chatQueueRevisionRef = useRef(0);
const queuedChatEditSessionRef = useRef<{ itemId: string; revision: number } | null>(null);
const selectedHistoryRef = useRef(selectedHistory);
const sharedHistoryItemsRef = useRef<ChatHistorySummary[]>([]);
const sharedHistoryListRequestRef = useRef<{
generation: string;
promise: Promise<ChatHistorySummary[]>;
} | null>(null);
// Per-conversation runtime workdir (drafts have no persisted summary yet).
const conversationWorkdirsRef = useRef<Map<string, string>>(new Map());
// Lazy history windows: per conversation, the persisted-message edge the
// loaded transcript starts at (see lib/chat/historyWindow.ts). Entries are
// (re)established by every applied history fetch and dropped with the
// conversation's other per-id resources.
const historyWindowStatesRef = useRef<Map<string, HistoryWindowState>>(new Map());
const displayedConversationWorkdirRef = useRef("");
const pendingUploadContextRef = useRef<{
conversationId: string;
workdir: string;
executionMode: string;
} | null>(null);
const displayedConversationBusyRef = useRef(false);
const historyLoadSequenceRef = useRef(0);
const visibleConversationRevisionRef = useRef(0);
const previousDisplayedConversationIdRef = useRef("");
const pendingDisplayedConversationAutoBottomRef = useRef<string | null>(null);
const protectedConversationRef = useRef("");
const chatRuntimePreparePromiseRef = useRef<Promise<AgentStatus> | null>(null);
const submitInFlightRef = useRef(false);
// clientRequestId → draft conversation id, until the command binds.
const draftClientRequestsRef = useRef<Map<string, string>>(new Map());
const sendChatRef = useRef<SendChatFn | null>(null);
const isImportingPastedTextRef = useRef(false);
const resetProjectToolsRuntimeRef = useRef(() => undefined as void);
// --- Chat streaming infrastructure (Phase 4) -----------------------------
// Transcript stores (one per conversation), the global activity map, and
// the command pipeline replace the old live-store registry, running-id
// unions, and recovery machinery.
// Ref indirection: the registry memo is stable across token changes while
// the api client is not, and divergence resyncs must reach the live client.
const apiRef = useRef(api);
apiRef.current = api;
const transcriptStoreRegistry = useMemo(
() =>
createTranscriptStoreRegistry({
onDivergence: (divergedConversationId) =>
apiRef.current?.resyncConversation(divergedConversationId),
}),
[],
);
const activityStore = useMemo(() => createActivityStore(), []);
const pipelineOnBoundRef = useRef<
(update: ChatCommandUpdate, pending: PendingChatCommand) => void
>(() => undefined);
const pipelineOnQueuedInGuiRef = useRef<
(update: ChatCommandUpdate, pending: PendingChatCommand) => void
>(() => undefined);
const pipelineOnFailedRef = useRef<
(pending: PendingChatCommand, errorCode: string | null, message: string) => void
>(() => undefined);
const chatCommandPipeline = useMemo(
() =>
new ChatCommandPipeline({
getTranscriptStore: (targetConversationId) =>
transcriptStoreRegistry.get(targetConversationId),
onBound: (update, pending) => pipelineOnBoundRef.current(update, pending),
onQueuedInGui: (update, pending) => pipelineOnQueuedInGuiRef.current(update, pending),
onFailed: (pending, errorCode, message) =>
pipelineOnFailedRef.current(pending, errorCode, message),
onPendingChanged: () => setPendingCommandRevision((current) => current + 1),
}),
[transcriptStoreRegistry],
);
// --- Sidebar state layer --------------------------------------------------
// One external store owns the whole sidebar domain (list, workdirs, running
// set, per-row mutations); GatewayApp only creates it, feeds it the scope,
// and makes imperative peek/upsertLocal/removeLocal calls. All rendering
// subscriptions live in <GatewaySidebarContainer/>.
const getSidebarProtectedConversationIds = useCallback(() => {
// Authoritative reconciles keep only these ids when the server list omits
// them: in-flight commands, the protected (displayed) conversation, and
// running conversations. Never a blanket retain-all — that resurrects
// deletions made by other clients while this one was offline.
const ids = new Set<string>(chatCommandPipeline.pendingConversationIds());
const protectedId = protectedConversationRef.current.trim();
if (protectedId && protectedId !== PROTECTED_DRAFT_CONVERSATION) {
ids.add(protectedId);
}
for (const id of activityStore.getSnapshot().activities.keys()) {
ids.add(id);
}
return ids;
}, [activityStore, chatCommandPipeline]);
const getActivityKeepConversationIds = useCallback(
() => chatCommandPipeline.pendingConversationIds(),
[chatCommandPipeline],
);
// biome-ignore lint/correctness/useExhaustiveDependencies: Agent ID 是侧边栏 Store 的数据隔离边界。
const sidebarStore = useMemo(
() =>
createSidebarStore(
api
? createWebSidebarBackend({
api,
activityStore,
getProtectedConversationIds: getSidebarProtectedConversationIds,
getActivityKeepConversationIds,
})
: createIdleSidebarBackend(),
{ pageSize: HISTORY_LIST_PAGE_SIZE },
),
[
activeAgentScope,
activityStore,
api,
getActivityKeepConversationIds,
getSidebarProtectedConversationIds,
],
);
useEffect(() => {
if (!api) {
return;
}
sidebarStore.start();
return () => {
sidebarStore.stop();
};
}, [api, sidebarStore]);
// Narrow app-root subscriptions: workdirs (rare commits — project merge
// inputs) and the byId index (list commits only; never running/idle ticks).
const sidebarWorkdirs = useSidebarSelector(sidebarStore, (snapshot) => snapshot.workdirs);
const sidebarConversationsById = useSidebarSelector(sidebarStore, (snapshot) => snapshot.byId);
const workspaceProjects = useMemo(
() => mergeWorkspaceProjectsWithHistory(settings.system, sidebarWorkdirs),
[settings.system, sidebarWorkdirs],
);
const archivedWorkspaceProjectPathKeys = useMemo(
() => new Set(settings.system.archivedWorkspaceProjectPaths.map(workspaceProjectPathKey)),
[settings.system.archivedWorkspaceProjectPaths],
);
// Archived workspaces can never be active. Falling back to the full list
// only guards a transient synced state where everything is archived.
const selectableWorkspaceProjects = useMemo(() => {
const active = workspaceProjects.filter(
(project) => !archivedWorkspaceProjectPathKeys.has(workspaceProjectPathKey(project.path)),
);
return active.length > 0 ? active : workspaceProjects;
}, [archivedWorkspaceProjectPathKeys, workspaceProjects]);
const activeWorkspaceProject = useMemo(
() => findWorkspaceProject(selectableWorkspaceProjects, activeWorkspaceProjectId),
[activeWorkspaceProjectId, selectableWorkspaceProjects],
);
useEffect(() => {
if (activeWorkspaceProject?.id && activeWorkspaceProject.id !== activeWorkspaceProjectId) {
setActiveWorkspaceProjectId(activeWorkspaceProject.id);
}
}, [activeWorkspaceProject?.id, activeWorkspaceProjectId]);
const activeWorkspaceProjectPath = activeWorkspaceProject?.path.trim() ?? "";
// Scope derivation: agent mode with a project → that workdir; agent mode
// without a project → "none" (resolves to an empty list locally, no wire
// sentinel); text mode → unscoped.
useEffect(() => {
sidebarStore.setScope(
isAgentMode
? activeWorkspaceProjectPath
? { kind: "workdir", cwd: activeWorkspaceProjectPath }
: { kind: "none" }
: { kind: "unscoped" },
);
}, [activeWorkspaceProjectPath, isAgentMode, sidebarStore]);
// Conversation-open controller: the web end paints the conversation's whole
// established history window in the single open phase — messages above the
// window edge stay unfetched until the user pages up. Deps go through refs
// (assigned per render) so the controller instance stays stable.
const openInitialRef = useRef<(id: string) => Promise<"cache-hit" | "painted">>(() =>
Promise.resolve("painted"),
);
const openController = useMemo(
() =>
createConversationOpenController({
openInitial: (id) => openInitialRef.current(id),
onStateChange: setConversationOpenState,
}),
[],
);
const resolveActiveAgentID = useCallback(async () => {
const currentApi = apiRef.current;
if (!currentApi) {
throw new Error("Gateway 尚未连接。");
}
let agentID = currentApi.getActiveAgent().trim();
if (!agentID) {
await currentApi.listAgents();
agentID = currentApi.getActiveAgent().trim();
}
if (!agentID) {
throw new Error("没有可用的 Agent。");
}
return agentID;
}, []);
const {
pendingUploadedFiles,
isUploadingFiles,
isFileDropActive,
fileInputRef,
setUploadingFiles,
getPendingUploadsForConversation,
setPendingUploadsForConversation,
updatePendingUploadsForConversation,
moveConversationUploads,
clearPendingUploads,
handleImportReadableFiles,
handleFileDragEnter,
handleFileDragOver: handlePendingFileDragOver,
handleFileDragLeave,
handleFileDrop: handlePendingFileDrop,
} = usePendingUploads({
token,
resolveAgentID: resolveActiveAgentID,
historyShareToken,
settingsSyncReady,
settingsOpen,
activeView,
locale: settings.locale,
executionMode: settings.system.executionMode,
conversationId,
selectedHistoryId,
displayedConversationWorkdirRef,
composerRef,
addNotify,
});
const applyChatQueueSnapshot = useCallback((snapshot: ChatQueueSnapshot | null | undefined) => {
if (!snapshot) return;
const visibleConversationId = resolveVisibleConversationId(
selectedHistoryIdRef.current,
conversationIdRef.current,
);
if (snapshot.conversationId !== visibleConversationId) {
return;
}
const revision = Number(snapshot.revision ?? 0);
const isSameQueueConversation = snapshot.conversationId === chatQueueConversationIdRef.current;
if (isSameQueueConversation && revision < chatQueueRevisionRef.current) {
return;
}
chatQueueConversationIdRef.current = snapshot.conversationId;
chatQueueRevisionRef.current = revision;
queuedChatTurnsRef.current = snapshot.items.slice();
setChatQueueRevision(revision);
setQueuedChatTurns(snapshot.items.slice());
}, []);
useEffect(() => {
if (!api) return;
return api.subscribeChatQueue((snapshot) => {
applyChatQueueSnapshot(snapshot);
});
}, [api, applyChatQueueSnapshot]);
// AskUserQuestion 卡片的应答出口:经网关 chat_queue.tool_answer 送达桌面端
// 的工具挂起表;桌面端 resolve 后照常以 tool_result 事件流回本端。
useEffect(() => {
if (!api) {
registerAskUserQuestionAnswerHandler(null);
return;
}
registerAskUserQuestionAnswerHandler(async (toolCallId, answers) => {
const conversationIdValue = getDisplayedConversationId();
if (!conversationIdValue) {
return { ok: false, message: "No active conversation." };
}
try {
const response = await api.chatQueueToolAnswer(
conversationIdValue,
toolCallId,
JSON.stringify(answers),
);
return { ok: response.accepted, message: response.message || undefined };
} catch (error) {
return { ok: false, message: asErrorMessage(error, "Failed to submit the answer.") };
}
});
return () => registerAskUserQuestionAnswerHandler(null);
}, [api]);
// 工具审批卡片的决定出口:经网关 chat_queue.tool_approval 送达桌面端审批挂起表;
// 桌面端据此放行/拒绝该工具,结果照常以 tool_result 事件流回本端。
useEffect(() => {
if (!api) {
registerToolApprovalDecisionHandler(null);
return;
}
registerToolApprovalDecisionHandler(async (toolCallId, decision) => {
const conversationIdValue = getDisplayedConversationId();
if (!conversationIdValue) {
return { ok: false, message: "No active conversation." };
}
try {
const response = await api.chatQueueToolApproval(
conversationIdValue,
toolCallId,
JSON.stringify({ decision }),
);
return { ok: response.accepted, message: response.message || undefined };
} catch (error) {
return { ok: false, message: asErrorMessage(error, "Failed to submit the decision.") };
}
});
return () => registerToolApprovalDecisionHandler(null);
}, [api]);
function getVisibleComposerConversationId() {
return resolveVisibleConversationId(selectedHistoryIdRef.current, conversationIdRef.current);
}
function cacheVisibleComposerDraft(conversationId = composerDraftOwnerRef.current) {
const targetConversationId = conversationId.trim();
const composer = composerRef.current;
if (
!targetConversationId ||
composerDraftOwnerRef.current !== targetConversationId ||
!composer
) {
return;
}
const draft = composer.getDraft();
if (draft.isEmpty || !draft.text.trim()) {
composerDraftCacheRef.current.delete(targetConversationId);
return;
}
composerDraftCacheRef.current.set(targetConversationId, draft);
}
function prepareComposerForConversationChange() {
cacheVisibleComposerDraft();
composerDraftOwnerRef.current = "";
}
function restoreCachedComposerDraft(conversationId: string) {
const targetConversationId = conversationId.trim();
const composer = composerRef.current;
if (!targetConversationId || !composer) {
return;
}
const cachedDraft = composerDraftCacheRef.current.get(targetConversationId);
if (cachedDraft) {
composer.setDraft(cachedDraft);
} else {
composer.clear();
}
composerDraftOwnerRef.current = targetConversationId;
}
function clearCachedComposerDraft(conversationId = getVisibleComposerConversationId()) {
const targetConversationId = conversationId.trim();
if (!targetConversationId) {
return;
}
composerDraftCacheRef.current.delete(targetConversationId);
}
useEffect(() => {
conversationIdRef.current = conversationId;
}, [conversationId]);
useEffect(() => {
selectedHistoryIdRef.current = selectedHistoryId;
}, [selectedHistoryId]);
useEffect(() => {
statusRef.current = status;
}, [status]);
useEffect(() => {
selectedHistoryRef.current = selectedHistory;
}, [selectedHistory]);
function getDisplayedConversationId() {
return resolveVisibleConversationId(
selectedHistoryIdRef.current,
conversationIdRef.current,
).trim();
}
function isDisplayedConversation(targetConversationId: string) {
const conversationIdValue = targetConversationId.trim();
return conversationIdValue !== "" && getDisplayedConversationId() === conversationIdValue;
}
// Sent-prompt history for the composer's ↑/↓ recall. Read lazily from the
// displayed conversation's transcript snapshot at the moment recall starts,
// so transcript growth never re-renders the memoized composer bar.
const loadComposerHistoryPrompts = useCallback(() => {
const store = transcriptStoreRegistry.peek(getDisplayedConversationId());
if (!store) return [];
const prompts: string[] = [];
for (const row of store.getSnapshot().rows) {
if (row.kind === "user" && row.text.trim()) prompts.push(row.text);
}
return prompts;
}, [transcriptStoreRegistry]);
const applyLiveConversationTitle = useCallback(
(targetConversationId: string, nextTitle: string) => {
const conversationIdValue = targetConversationId.trim();
const title = nextTitle.trim();
if (!conversationIdValue || !title) {
return;
}
// Position-preserving local upsert: reuse the existing row's updatedAt
// so a live title never reorders the sidebar (the store's own position
// locks cover mutation confirmations).
const now = Date.now();
const existing = sidebarStore.peek(conversationIdValue);
sidebarStore.upsertLocal({
id: conversationIdValue,
title,
providerId: existing?.providerId ?? "",
model: existing?.model ?? "",
sessionId: existing?.sessionId,
cwd: existing?.cwd,
messageCount: existing?.messageCount ?? 1,
createdAt: existing?.createdAt ?? now,
updatedAt: existing?.updatedAt ?? now,
isPinned: existing?.isPinned,
pinnedAt: existing ? existing.pinnedAt : null,
isShared: existing?.isShared,
isPending: existing?.isPending,
});
},
[sidebarStore],
);
// Total entry count of a conversation's transcript store.
const getConversationTranscriptEntryCount = useCallback(
(targetConversationId: string) => {
const store = transcriptStoreRegistry.peek(targetConversationId.trim());
return store ? store.getSnapshot().entryCount : 0;
},
[transcriptStoreRegistry],
);
const isConversationBusy = useCallback(
(targetConversationId: string) => {
const conversationIdValue = targetConversationId.trim();
if (!conversationIdValue) {
return false;
}
return (
activityStore.isRunning(conversationIdValue) ||
chatCommandPipeline.hasPending(conversationIdValue) ||
transcriptStoreRegistry.peek(conversationIdValue)?.getSnapshot().activeRun != null
);
},
[activityStore, chatCommandPipeline, transcriptStoreRegistry],
);
// Keep an empty draft conversation's workdir following the active project.
useEffect(() => {
const nextWorkdir = activeWorkspaceProjectPath.trim();
if (!isAgentMode || !nextWorkdir) {
return;
}
const conversationIdValue = resolveVisibleConversationId(
selectedHistoryIdRef.current,
conversationIdRef.current,
).trim();
if (!conversationIdValue || !isLocalDraftConversationId(conversationIdValue)) {
return;
}
if (isConversationBusy(conversationIdValue)) {
return;
}
if (
getConversationTranscriptEntryCount(conversationIdValue) > 0 ||
getPendingUploadsForConversation(conversationIdValue).length > 0
) {
return;
}
conversationWorkdirsRef.current.set(conversationIdValue, nextWorkdir);
}, [
activeWorkspaceProjectPath,
getConversationTranscriptEntryCount,
getPendingUploadsForConversation,
isAgentMode,
isConversationBusy,
]);
// Quiet history refresh for the displayed conversation: fetch → parse →
// id-preserving merge into the transcript store (no flicker, no remount).
// Only runs while the conversation is idle; a run started mid-fetch aborts
// the merge so a stale snapshot can never truncate freshly folded entries.
//
// Fetches are EDGE-ANCHORED WINDOWS, not full hydrations: the request spans
// from the conversation's established window edge (historyWindow.ts) to the
// tail, so the per-turn refresh cost stays proportional to the loaded
// window instead of the conversation's lifetime size. `extendMessages`
// grows the window upward by a page (the transcript's "load earlier"
// affordance). A windowed response whose top edge slipped below the
// established one (concurrent append while the request was in flight) is
// refetched once with the corrected span and skipped if it slipped again —
// applying it could truncate the rendered region's top.
const refreshDisplayedConversationHistorySnapshot = useCallback(
async (
targetConversationId: string,
currentApi = api,
options?: { extendMessages?: number },
) => {
const conversationIdValue = targetConversationId.trim();
if (!currentApi || !conversationIdValue || isLocalDraftConversationId(conversationIdValue)) {
return;
}
const isStillDisplayedAndIdle = () =>
resolveVisibleConversationId(selectedHistoryIdRef.current, conversationIdRef.current) ===
conversationIdValue && !isConversationBusy(conversationIdValue);
if (!isStillDisplayedAndIdle()) {
return;
}
const extendMessages = options?.extendMessages;
const windowStates = historyWindowStatesRef.current;
let detail: HistoryDetail;
let entries: ChatEntry[];
try {
const planned = planHistoryWindowRequest(windowStates.get(conversationIdValue), {
initialWindowMessages: HISTORY_DETAIL_INITIAL_MAX_MESSAGES,
extendMessages,
});
detail = await currentApi.getHistory(
conversationIdValue,
planned === undefined ? undefined : { maxMessages: planned },
);
if (planned !== undefined && detail.has_more === true) {
const counts = readHistoryWindowCounts(detail);
if (!counts) {
// Producer reported a partial window without usable counts (a
// contradiction — both come from the same code path): fall back
// to a full fetch rather than risking a top truncation.
windowStates.delete(conversationIdValue);
detail = await currentApi.getHistory(conversationIdValue);
} else {
const verdict = evaluateHistoryWindowResponse({
previous: windowStates.get(conversationIdValue),
counts,
extendMessages,
});
if (verdict.action === "retry") {
detail = await currentApi.getHistory(conversationIdValue, {
maxMessages: verdict.retryMaxMessages,
});
const retryCounts = readHistoryWindowCounts(detail);
const retryVerdict =
retryCounts && detail.has_more === true
? evaluateHistoryWindowResponse({
previous: windowStates.get(conversationIdValue),
counts: retryCounts,
extendMessages,
})
: null;
if (detail.has_more === true) {
if (!retryVerdict || retryVerdict.action === "retry") {
// The edge slipped twice in a row: give up on this cycle;
// the refresh loops (busy→idle, upsert, stale-retry)
// converge on a later pass.
return;
}
windowStates.set(conversationIdValue, retryVerdict.nextState);
}
} else {
windowStates.set(conversationIdValue, verdict.nextState);
}
}
}
if (detail.has_more !== true) {
// Complete fetch: the window reaches message 0 and stays complete.
const counts = readHistoryWindowCounts(detail);
if (counts) {
windowStates.set(conversationIdValue, {
oldestOffset: 0,
lastTotal: counts.totalMessageCount,
});
} else {
windowStates.delete(conversationIdValue);
}
}
const parsed = await parseHistoryMessagesJsonAsync(detail.messages_json);
entries = detail.has_more === true ? trimLeadingHeadlessEntries(parsed) : parsed;
} catch {
return;
}
if (!isStillDisplayedAndIdle()) {
return;
}
const detailConversationId = detail.conversation_id.trim();
if (detailConversationId !== "" && detailConversationId !== conversationIdValue) {
return;
}