forked from Piebald-AI/gemini-cli-desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
652 lines (597 loc) · 20.9 KB
/
App.tsx
File metadata and controls
652 lines (597 loc) · 20.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
import { useState, useRef, useCallback, useMemo, useEffect } from "react";
import {
Routes,
Route,
Outlet,
Navigate,
useLocation,
useNavigate,
} from "react-router-dom";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { api } from "./lib/api";
import { AppSidebar } from "./components/layout/AppSidebar";
import {
MessageInputBar,
MessageInputBarRef,
} from "./components/conversation/MessageInputBar";
import { AppHeader } from "./components/layout/AppHeader";
import { ConversationSearchDialog } from "./components/conversation/ConversationSearchDialog";
import { CustomTitleBar } from "./components/layout/CustomTitleBar";
import { DirectoryPanel } from "./components/common/DirectoryPanel";
import { SidebarInset } from "./components/ui/sidebar";
import { Toaster } from "./components/ui/sonner";
import { ConversationContext } from "./contexts/ConversationContext";
import {
BackendProvider,
useApiConfig,
useBackend,
} from "./contexts/BackendContext";
import { getBackendText } from "./utils/backendText";
import { HomeDashboard } from "./pages/HomeDashboard";
import ProjectsPage from "./pages/Projects";
import ProjectDetailPage from "./pages/ProjectDetail";
import { McpServersPage } from "./pages/McpServersPage";
// Hooks
import { useConversationManager } from "./hooks/useConversationManager";
import { useProcessManager } from "./hooks/useProcessManager";
import { useMessageHandler } from "./hooks/useMessageHandler";
import { useToolCallConfirmation } from "./hooks/useToolCallConfirmation";
import { useConversationEvents } from "./hooks/useConversationEvents";
import { useCliInstallation } from "./hooks/useCliInstallation";
import { useSessionProgress } from "./hooks/useSessionProgress";
import { useTauriMenu } from "./hooks/useTauriMenu";
import { CliIO, Conversation, Message } from "./types";
import "./index.css";
import { platform } from "@tauri-apps/plugin-os";
import { AboutDialog } from "./components/common/AboutDialog";
import { SettingsDialog } from "./components/common/SettingsDialog";
function RootLayoutContent() {
const { progress, startListeningForSession, seedProgress } =
useSessionProgress();
// Get current route to conditionally render MessageInputBar only on home page
const location = useLocation();
const navigate = useNavigate();
const isHomePage = location.pathname === "/";
const [selectedModel, setSelectedModel] =
useState<string>("gemini-2.5-flash");
const [cliIOLogs, setCliIOLogs] = useState<CliIO[]>([]);
const messagesContainerRef = useRef<HTMLDivElement>(null);
const [sidebarOpen, setSidebarOpen] = useState(true);
const [directoryPanelOpen, setDirectoryPanelOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [workingDirectory, setWorkingDirectory] = useState<string>(".");
const [isContinuingConversation, setIsContinuingConversation] =
useState(false);
const messageInputBarRef = useRef<MessageInputBarRef>(null);
const listenerCleanups = useRef(new Map<string, () => void>());
const pendingListenerSetup = useRef(new Set<string>());
// Global search dialog state (declared above)
// Get the current working directory (default fallback)
useEffect(() => {
const getCurrentWorkingDirectory = async () => {
console.log("🏠 [App] Initializing default working directory...");
try {
const cwd = await api.get_home_directory();
console.log("🏠 [App] Got home directory from API:", cwd);
setWorkingDirectory(cwd);
} catch (error) {
console.warn(
"🏠 [App] Failed to get working directory, using current directory:",
error
);
setWorkingDirectory(".");
}
};
getCurrentWorkingDirectory();
}, []);
// Use backend context instead of local state
const { apiConfig } = useApiConfig();
const { selectedBackend, state: backendState } = useBackend();
// Set document title based on selected backend
useEffect(() => {
const backendText = getBackendText(selectedBackend);
document.title = backendText.desktopName;
// Also update native window title on desktop platforms
if (!__WEB__) {
getCurrentWindow().setTitle(backendText.desktopName);
}
}, [selectedBackend]);
// Custom hooks for cleaner code
const isCliInstalled = useCliInstallation(selectedBackend);
const {
conversations,
activeConversation,
setActiveConversation,
updateConversation,
createNewConversation,
loadConversationFromHistory,
removeConversation,
} = useConversationManager();
const { processStatuses, fetchProcessStatuses, handleKillProcess } =
useProcessManager();
const conversationsWithStatus = useMemo(() => {
return conversations.map((conv) => {
const processStatus = processStatuses.find(
(status) =>
status.conversation_id === conv.id ||
status.conversation_id === conv.metadata?.timestamp
);
return {
...conv,
isActive: processStatus?.is_alive ?? false,
};
});
}, [conversations, processStatuses]);
const currentConversationWithStatus = useMemo(() => {
return conversationsWithStatus.find((c) => c.id === activeConversation);
}, [conversationsWithStatus, activeConversation]);
const currentConversation = useMemo(() => {
return currentConversationWithStatus
? ({
...currentConversationWithStatus,
isActive: undefined,
} as unknown as Conversation)
: undefined;
}, [currentConversationWithStatus]);
const {
confirmationRequests,
setConfirmationRequests,
handleConfirmToolCall,
} = useToolCallConfirmation({
activeConversation,
updateConversation,
});
// Get yolo mode status from backend config
const isYoloEnabled = backendState.selectedBackend === "gemini"
? backendState.configs.gemini.yolo
: backendState.selectedBackend === "qwen"
? backendState.configs.qwen.yolo
: false;
const { setupEventListenerForConversation } = useConversationEvents(
setCliIOLogs,
setConfirmationRequests,
updateConversation,
isYoloEnabled
);
const { input, handleInputChange, handleSendMessage } = useMessageHandler({
activeConversation,
conversations: conversationsWithStatus,
selectedModel,
isCliInstalled,
updateConversation,
createNewConversation,
setActiveConversation,
setupEventListenerForConversation,
fetchProcessStatuses,
});
// Update working directory when active conversation changes
useEffect(() => {
if (currentConversationWithStatus?.workingDirectory) {
setWorkingDirectory(currentConversationWithStatus.workingDirectory);
}
}, [currentConversationWithStatus]);
// Open Settings dialog when a global event is dispatched
useEffect(() => {
const handler = () => setIsSettingsOpen(true);
// Type guard for addEventListener/removeEventListener signature without using any
type WindowEventHandler = (this: Window, ev: Event) => unknown;
window.addEventListener(
"app:open-settings",
handler as unknown as WindowEventHandler
);
return () =>
window.removeEventListener(
"app:open-settings",
handler as unknown as WindowEventHandler
);
}, []);
// Open Search dialog when a global event is dispatched
useEffect(() => {
const handler = () => setSearchOpen(true);
// Type guard to satisfy TS without any
type WindowEventHandler = (this: Window, ev: Event) => unknown;
window.addEventListener(
"app:open-search",
handler as unknown as WindowEventHandler
);
return () =>
window.removeEventListener(
"app:open-search",
handler as unknown as WindowEventHandler
);
}, []);
// Progress listener started in startNewConversation
useEffect(() => {
const setup = async () => {
const activeConversations = new Set(
conversationsWithStatus.map((c) => c.id)
);
// Cleanup listeners for deleted conversations
for (const id of listenerCleanups.current.keys()) {
if (!activeConversations.has(id)) {
const cleanup = listenerCleanups.current.get(id);
if (cleanup) {
cleanup();
}
listenerCleanups.current.delete(id);
}
}
// Add listeners for new conversations
for (const conversation of conversationsWithStatus) {
if (
!listenerCleanups.current.has(conversation.id) &&
!pendingListenerSetup.current.has(conversation.id)
) {
// Mark as pending to prevent duplicate setup
pendingListenerSetup.current.add(conversation.id);
try {
const cleanup = await setupEventListenerForConversation(
conversation.id
);
listenerCleanups.current.set(conversation.id, cleanup);
} finally {
// Remove from pending set regardless of success/failure
pendingListenerSetup.current.delete(conversation.id);
}
}
}
};
setup();
}, [conversationsWithStatus, setupEventListenerForConversation]);
const handleModelChange = useCallback((model: string) => {
setSelectedModel(model);
}, []);
const startNewConversation = useCallback(
async (
title: string,
workingDirectory?: string,
initialMessages: Message[] = [],
conversationId?: string
): Promise<string> => {
const convId = conversationId || Date.now().toString();
createNewConversation(
convId,
title,
initialMessages,
false,
workingDirectory
);
setActiveConversation(convId);
if (workingDirectory) {
// Start listening for progress before starting the session
await startListeningForSession(convId);
console.log(
"🔄 [APP] Started listening for session progress: ",
convId
);
console.log("Debug - apiConfig:", apiConfig);
console.log("Debug - selectedBackend:", selectedBackend);
let backendConfig;
let geminiAuth;
// For Qwen backend, pass full backend_config
// For Gemini backend, pass geminiAuth with the appropriate configuration
if (selectedBackend === "qwen") {
// Always ensure backend_config is set for Qwen to trigger qwen CLI
backendConfig = {
// Tauri auto-converts to backend_config
api_key: apiConfig?.api_key || "", // Empty string if OAuth
base_url: apiConfig?.base_url || "https://openrouter.ai/api/v1",
model: apiConfig?.model || selectedModel,
};
} else if (selectedBackend === "gemini") {
const geminiConfig = backendState.configs.gemini;
geminiAuth = {
// Tauri auto-converts to gemini_auth
method: geminiConfig.authMethod,
api_key:
geminiConfig.authMethod === "gemini-api-key"
? geminiConfig.apiKey
: undefined,
vertex_project:
geminiConfig.authMethod === "vertex-ai"
? geminiConfig.vertexProject
: undefined,
vertex_location:
geminiConfig.authMethod === "vertex-ai"
? geminiConfig.vertexLocation
: undefined,
};
}
// Optimistically seed initial progress so the UI shows immediately
try {
const backendName = getBackendText(selectedBackend).name;
seedProgress({
message: `Starting ${backendName} session initialization`,
progress_percent: 5,
details: workingDirectory
? `Working directory: ${workingDirectory}`
: undefined,
});
} catch (e) {
console.warn("⚠️ [APP] Failed to seed initial progress", e);
}
// IMPORTANT: Attach conversation event listeners BEFORE starting the session
// to avoid losing early streaming chunks (race observed in web mode).
try {
if (
!listenerCleanups.current.has(convId) &&
!pendingListenerSetup.current.has(convId)
) {
// Mark as pending to prevent duplicate setup
pendingListenerSetup.current.add(convId);
try {
const cleanup = await setupEventListenerForConversation(convId);
listenerCleanups.current.set(convId, cleanup);
console.log(
"👂 [APP] Pre-attached conversation listeners before start_session:",
convId
);
} finally {
// Remove from pending set regardless of success/failure
pendingListenerSetup.current.delete(convId);
}
}
} catch (e) {
console.error(
"❌ [APP] Failed to pre-attach conversation listeners:",
e
);
}
await api.start_session({
sessionId: convId,
workingDirectory,
model: selectedModel,
backendConfig,
geminiAuth,
});
}
return convId;
},
[
selectedModel,
selectedBackend,
apiConfig,
backendState.configs.gemini,
createNewConversation,
setActiveConversation,
startListeningForSession,
setupEventListenerForConversation,
seedProgress,
]
);
const toggleDirectoryPanel = useCallback(() => {
setDirectoryPanelOpen((prev) => !prev);
}, []);
// Auto-close directory panel when active conversation ends
useEffect(() => {
if (!activeConversation && directoryPanelOpen) {
setDirectoryPanelOpen(false);
}
}, [activeConversation, directoryPanelOpen]);
const handleContinueConversation = useCallback(
async (conversationToContinue: Conversation) => {
if (!conversationToContinue || isContinuingConversation) return;
setIsContinuingConversation(true);
try {
const newTitle = `(Continued) ${conversationToContinue.title}`;
await startNewConversation(
newTitle,
conversationToContinue.workingDirectory,
conversationToContinue.messages
);
} finally {
setIsContinuingConversation(false);
}
},
[startNewConversation, isContinuingConversation]
);
// Handle mention insertion from DirectoryPanel
const handleMentionInsert = useCallback((mention: string) => {
if (messageInputBarRef.current) {
messageInputBarRef.current.insertMention(mention);
// Close the dropdown after inserting the mention
messageInputBarRef.current.closeDropdown();
}
}, []);
// Handle conversation selection from sidebar
const handleConversationSelect = useCallback(
(conversationId: string) => {
setActiveConversation(conversationId);
// Navigate to home page to show the conversation
if (location.pathname !== "/") {
navigate("/");
}
},
[navigate, location.pathname, setActiveConversation]
);
// Conversation context with progress
const contextValue = useMemo(
() => ({
conversations,
activeConversation,
currentConversation,
input,
isCliInstalled,
messagesContainerRef,
cliIOLogs,
handleInputChange,
handleSendMessage,
selectedModel,
startNewConversation,
loadConversationFromHistory,
handleConfirmToolCall,
confirmationRequests,
removeConversation,
progress,
}),
[
conversations,
activeConversation,
currentConversation,
input,
isCliInstalled,
messagesContainerRef,
cliIOLogs,
handleInputChange,
handleSendMessage,
selectedModel,
startNewConversation,
loadConversationFromHistory,
handleConfirmToolCall,
confirmationRequests,
removeConversation,
progress,
]
);
return (
<ConversationContext.Provider value={contextValue}>
<AppSidebar
conversations={conversationsWithStatus}
activeConversation={activeConversation}
processStatuses={processStatuses}
onConversationSelect={handleConversationSelect}
onKillProcess={handleKillProcess}
onRemoveConversation={removeConversation}
onModelChange={handleModelChange}
open={sidebarOpen}
onOpenChange={setSidebarOpen}
onOpenSearch={() => setSearchOpen(true)}
>
<SidebarInset>
{/* Grid layout: header spans all columns; content + optional right panel */}
<div
className="grid h-full"
style={{
gridTemplateRows: "auto 1fr",
gridTemplateColumns:
directoryPanelOpen && activeConversation ? "1fr 20rem" : "1fr",
}}
>
{/* Header */}
<div className="row-start-1 col-span-full">
<AppHeader
onDirectoryPanelToggle={toggleDirectoryPanel}
isDirectoryPanelOpen={directoryPanelOpen}
hasActiveConversation={!!activeConversation}
onReturnToDashboard={() => setActiveConversation(null)}
onOpenSettings={() => setIsSettingsOpen(true)}
/>
</div>
{/* Main content column */}
<div className="row-start-2 col-start-1 flex flex-col min-w-0 min-h-0">
<Outlet context={{ workingDirectory }} />
{currentConversationWithStatus && isHomePage && (
<>
{console.log(
"📝 [App] Rendering MessageInputBar with workingDirectory:",
workingDirectory
)}
<MessageInputBar
ref={messageInputBarRef}
input={input}
isCliInstalled={isCliInstalled}
cliIOLogs={cliIOLogs}
handleInputChange={handleInputChange}
handleSendMessage={handleSendMessage}
workingDirectory={workingDirectory}
isConversationActive={
currentConversationWithStatus.isActive
}
onContinueConversation={() =>
handleContinueConversation(currentConversationWithStatus)
}
isContinuingConversation={isContinuingConversation}
isNew={currentConversationWithStatus.isNew}
isStreaming={currentConversationWithStatus.isStreaming}
/>
</>
)}
</div>
{/* Right directory panel */}
{directoryPanelOpen && activeConversation && (
<div className="row-start-2 col-start-2 border-l min-h-0">
<DirectoryPanel
workingDirectory={workingDirectory}
onDirectoryChange={(path) => {
console.log("📁 [App] Directory changed to:", path);
}}
onMentionInsert={handleMentionInsert}
className="w-[20rem] h-full"
/>
</div>
)}
</div>
</SidebarInset>
</AppSidebar>
{/* Global Search Dialog */}
<ConversationSearchDialog
open={searchOpen}
onOpenChange={setSearchOpen}
onConversationSelect={(id) => setActiveConversation(id)}
fullScreen
/>
{/* Settings Dialog */}
<SettingsDialog
open={isSettingsOpen}
onOpenChange={setIsSettingsOpen}
onModelChange={handleModelChange}
/>
</ConversationContext.Provider>
);
}
function RootLayoutInner() {
// Set up Tauri menu for non-Windows desktop platforms
const { isAboutDialogOpen, setIsAboutDialogOpen } = useTauriMenu();
// Add OS-specific class to body for styling
useEffect(() => {
const setOsClass = async () => {
if (!__WEB__) {
const p = await platform();
document.body.classList.add(`os-${p}`);
} else {
document.body.classList.add("os-web");
}
};
setOsClass();
}, []);
return (
<div className="h-screen w-full">
<CustomTitleBar />
<div className="size-full">
<RootLayoutContent />
</div>
{/* About Dialog for non-Windows platforms using Tauri menu */}
{!__WEB__ && platform() !== "windows" && (
<AboutDialog
open={isAboutDialogOpen}
onOpenChange={setIsAboutDialogOpen}
/>
)}
</div>
);
}
function RootLayout() {
return (
<BackendProvider>
<RootLayoutInner />
</BackendProvider>
);
}
function App() {
return (
<>
<Routes>
<Route element={<RootLayout />}>
<Route index element={<HomeDashboard />} />
<Route path="projects" element={<ProjectsPage />} />
<Route path="projects/:id" element={<ProjectDetailPage />} />
<Route path="mcp" element={<McpServersPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Routes>
<Toaster richColors />
</>
);
}
export default App;