File size: 24,390 Bytes
212c959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useDeferredValue, useEffect, useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import clsx from 'clsx'
import { AnimatePresence } from 'framer-motion'
import { Copy, Download, Link2, Sparkles, X } from 'lucide-react'
import ChatArea from './components/Chat/ChatArea'
import Composer from './components/Composer/Composer'
import Sidebar from './components/Sidebar/Sidebar'
import AuthDialog from './components/UI/AuthDialogPanel'
import AppHeader from './components/UI/AppHeader'
import Button from './components/UI/Button'
import ConfirmDialog from './components/UI/ConfirmDialog'
import FeedbackDialog from './components/UI/FeedbackDialog'
import Modal from './components/UI/Modal'
import ModelDialog from './components/UI/ModelDialog'
import Toaster from './components/UI/Toaster'
import WorkspacePanel from './components/UI/WorkspacePanel'
import { useAuth } from './hooks/useAuth'
import { useChat } from './hooks/useChat'
import { useInstallPrompt } from './hooks/useInstallPrompt'
import { decodeSharePayload, useAppStore } from './store/useAppStore'
import { api } from './utils/api'

function isSmallViewport() {
  return typeof window !== 'undefined' && window.innerWidth < 1024
}

function clearShareHash() {
  if (typeof window === 'undefined' || !window.location.hash.startsWith('#share=')) return
  window.history.replaceState({}, '', window.location.pathname + window.location.search)
}

function buildRenamePayload(sessionId, title) {
  return sessionId ? { session_id: sessionId, title } : { title, isDraft: true }
}

function getEnabledProviderIds(registry = {}) {
  return Object.entries(registry)
    .filter(([, providerEntry]) => providerEntry?.enabled !== false)
    .map(([providerId]) => providerId)
}

function getPreferredModelId(providerId, providerEntry, defaultProvider, defaultModel) {
  if (!providerEntry?.models?.length) {
    return defaultModel
  }
  if (providerId === defaultProvider && providerEntry.models.some((entry) => entry.id === defaultModel)) {
    return defaultModel
  }
  return providerEntry.models[0]?.id || defaultModel
}

function getInstallSteps(platform, instructions) {
  if (platform === 'ios') {
    return [
      'Open OwnGPT in Safari on your iPhone or iPad.',
      'Tap the Share button in the browser toolbar.',
      'Choose Add to Home Screen, then confirm Install.',
    ]
  }

  if (platform === 'android') {
    return [
      'Open the browser menu in Chrome or Edge.',
      'Choose Install app or Add to Home screen.',
      'Confirm the install prompt to keep OwnGPT on your device.',
    ]
  }

  return [
    'Open the browser menu near the address bar.',
    'Choose Install OwnGPT, Install app, or Create shortcut.',
    'Launch the installed app for a cleaner desktop workspace.',
  ]
}

export default function AppShell() {
  const {
    token,
    user,
    isAuthenticated,
    authMode,
    isAuthDialogOpen,
    openAuth,
    closeAuth,
    login,
    register,
    loginPending,
    registerPending,
    logout,
    loginWithGoogle,
    requireAuth,
  } = useAuth()

  const theme = useAppStore((state) => state.theme)
  const themePreference = useAppStore((state) => state.themePreference)
  const setThemePreference = useAppStore((state) => state.setThemePreference)
  const syncSystemTheme = useAppStore((state) => state.syncSystemTheme)
  const sidebarOpen = useAppStore((state) => state.sidebarOpen)
  const setSidebarOpen = useAppStore((state) => state.setSidebarOpen)
  const toggleSidebar = useAppStore((state) => state.toggleSidebar)
  const currentSessionId = useAppStore((state) => state.currentSessionId)
  const currentSessionTitle = useAppStore((state) => state.currentSessionTitle)
  const composerText = useAppStore((state) => state.composerText)
  const setComposerText = useAppStore((state) => state.setComposerText)
  const attachments = useAppStore((state) => state.attachments)
  const removeAttachment = useAppStore((state) => state.removeAttachment)
  const mode = useAppStore((state) => state.mode)
  const setMode = useAppStore((state) => state.setMode)
  const provider = useAppStore((state) => state.provider)
  const model = useAppStore((state) => state.model)
  const setProviderModel = useAppStore((state) => state.setProviderModel)
  const sessionSearch = useAppStore((state) => state.sessionSearch)
  const setSessionSearch = useAppStore((state) => state.setSessionSearch)
  const sidePanel = useAppStore((state) => state.sidePanel)
  const setSidePanel = useAppStore((state) => state.setSidePanel)
  const selectedFile = useAppStore((state) => state.selectedFile)
  const clearSelectedFile = useAppStore((state) => state.clearSelectedFile)
  const sharedConversation = useAppStore((state) => state.sharedConversation)
  const setSharedConversation = useAppStore((state) => state.setSharedConversation)
  const clearSharedConversation = useAppStore((state) => state.clearSharedConversation)
  const startNewChat = useAppStore((state) => state.startNewChat)
  const renameCurrentSession = useAppStore((state) => state.renameCurrentSession)
  const activeModal = useAppStore((state) => state.activeModal)
  const modalPayload = useAppStore((state) => state.modalPayload)
  const openModal = useAppStore((state) => state.openModal)
  const closeModal = useAppStore((state) => state.closeModal)
  const addToast = useAppStore((state) => state.addToast)

  const deferredSearch = useDeferredValue(sessionSearch)
  const [renameDraft, setRenameDraft] = useState('')
  const [editDraft, setEditDraft] = useState('')

  const {
    messages,
    isLoadingHistory,
    isStreaming,
    currentMode,
    uploadFiles,
    sendMessage,
    selectSession,
    renameSession,
    deleteSession,
    submitFeedback,
    feedbackPending,
    askAboutFile,
    branchFromUserMessage,
    regenerateFromAssistant,
    exportChatAsMarkdown,
    exportChatAsPdf,
    shareConversation,
    toggleSpeech,
    speakingMessageId,
  } = useChat({ token, user })

  const { install, installState, platform, manualInstructions } = useInstallPrompt()
  const previewFile = useAppStore.getState().previewFile

  const modelsQuery = useQuery({
    queryKey: ['models'],
    queryFn: () => api.get('/models'),
    staleTime: 300_000,
  })

  const healthQuery = useQuery({
    queryKey: ['healthz-ready'],
    queryFn: () => api.get('/healthz/ready'),
    staleTime: 15_000,
    retry: 0,
    refetchInterval: 30_000,
  })

  const sessionsQuery = useQuery({
    queryKey: ['sessions', token || 'guest', deferredSearch],
    queryFn: () =>
      api.get(
        deferredSearch?.trim()
          ? `/search?query=${encodeURIComponent(deferredSearch.trim())}`
          : '/search',
        { token },
      ),
    enabled: isAuthenticated,
    placeholderData: (previous) => previous,
    staleTime: 15_000,
  })

  const insightsQuery = useQuery({
    queryKey: ['workspace-insights', token || 'guest'],
    queryFn: () => api.get('/insights/workspace', { token }),
    enabled: isAuthenticated,
    staleTime: 30_000,
    refetchInterval: 60_000,
  })

  const registry = modelsQuery.data?.providers || {}
  const sessions = sessionsQuery.data?.sessions || []

  useEffect(() => {
    const nextRegistry = modelsQuery.data?.providers
    if (!nextRegistry) return

    const defaultProvider = modelsQuery.data.default_provider
    const defaultModel = modelsQuery.data.default_model
    const enabledProviderIds = getEnabledProviderIds(nextRegistry)
    const resolvedProvider =
      nextRegistry[provider] && nextRegistry[provider].enabled !== false
        ? provider
        : enabledProviderIds[0] || defaultProvider
    const providerEntry = nextRegistry[resolvedProvider]
    const preferredModel = getPreferredModelId(
      resolvedProvider,
      providerEntry,
      defaultProvider,
      defaultModel,
    )

    if (!providerEntry) {
      setProviderModel(defaultProvider, defaultModel)
      return
    }

    const modelExists = providerEntry.models.some((entry) => entry.id === model)
    if (resolvedProvider !== provider || !modelExists) {
      setProviderModel(resolvedProvider, modelExists ? model : preferredModel)
    }
  }, [model, modelsQuery.data, provider, setProviderModel])

  useEffect(() => {
    if (activeModal === 'renameSession') {
      setRenameDraft(modalPayload?.title || '')
    }
    if (activeModal === 'editMessage') {
      setEditDraft(modalPayload?.content || '')
    }
  }, [activeModal, modalPayload])

  useEffect(() => {
    if (typeof window === 'undefined') return undefined

    const syncSharedConversation = () => {
      const payload = decodeSharePayload(window.location.hash)
      if (payload?.messages?.length) {
        setSharedConversation(payload)
        setSidePanel('analytics')
      } else if (window.location.hash.startsWith('#share=')) {
        clearSharedConversation()
      }
    }

    syncSharedConversation()
    window.addEventListener('hashchange', syncSharedConversation)
    return () => window.removeEventListener('hashchange', syncSharedConversation)
  }, [clearSharedConversation, setSharedConversation, setSidePanel])

  useEffect(() => {
    if (typeof window === 'undefined') return undefined
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleThemeChange = () => syncSystemTheme()
    mediaQuery.addEventListener?.('change', handleThemeChange)
    return () => mediaQuery.removeEventListener?.('change', handleThemeChange)
  }, [syncSystemTheme])

  const stats = useMemo(
    () => ({
      sessionCount: sessions.length,
      messageCount: messages.length,
      attachmentCount: attachments.length,
      modeLabel: currentMode.label,
      modeDescription: currentMode.description,
      totalSessions: insightsQuery.data?.total_sessions || 0,
      totalMessages: insightsQuery.data?.total_messages || 0,
      totalAttachments: insightsQuery.data?.total_attachments || 0,
      activeDays: insightsQuery.data?.active_days || 0,
      averageMessagesPerSession: insightsQuery.data?.average_messages_per_session || 0,
    }),
    [
      attachments.length,
      currentMode.description,
      currentMode.label,
      insightsQuery.data?.active_days,
      insightsQuery.data?.average_messages_per_session,
      insightsQuery.data?.total_attachments,
      insightsQuery.data?.total_messages,
      insightsQuery.data?.total_sessions,
      messages.length,
      sessions.length,
    ],
  )

  const pendingAuth = loginPending || registerPending

  const handleNewChat = () => {
    clearShareHash()
    clearSharedConversation()
    startNewChat()
    if (isSmallViewport()) {
      setSidebarOpen(false)
    }
  }

  const handleSelectSession = (session) => {
    clearShareHash()
    clearSharedConversation()
    selectSession(session)
    if (isSmallViewport()) {
      setSidebarOpen(false)
    }
  }

  const handleDeleteSessionRequest = (session) => {
    if (!session?.session_id) return
    openModal('deleteSession', {
      session_id: session.session_id,
      title: session.title || 'this chat',
    })
  }

  const handleSubmitMessage = async (text) => {
    await sendMessage({ text })
  }

  const handleCopyMessage = async (message) => {
    try {
      await navigator.clipboard.writeText(message.content || '')
      addToast({
        title: 'Message copied',
        description: 'The response is now in your clipboard.',
        variant: 'success',
      })
    } catch (error) {
      addToast({
        title: 'Copy failed',
        description: error.message || 'Clipboard access is unavailable.',
        variant: 'danger',
      })
    }
  }

  const handleOpenFeedback = () => {
    requireAuth(() => openModal('feedback'))
  }

  const handleShareConversation = async () => {
    if (!messages.length) {
      addToast({
        title: 'Nothing to share yet',
        description: 'Start a conversation first, then generate a shareable link.',
        variant: 'info',
      })
      return
    }
    await shareConversation()
  }

  const handleRenameSubmit = async () => {
    const title = renameDraft.trim()
    if (!title) return

    if (modalPayload?.session_id) {
      await renameSession({ sessionId: modalPayload.session_id, title })
    } else {
      renameCurrentSession(title)
    }
    closeModal()
  }

  const handleDeleteSubmit = async () => {
    if (!modalPayload?.session_id) return
    await deleteSession(modalPayload.session_id)
    closeModal()
  }

  const handleEditSubmit = async () => {
    const text = editDraft.trim()
    if (!text || !modalPayload) return
    await branchFromUserMessage(modalPayload, text)
    closeModal()
  }

  const handleClosePanel = () => {
    if (sidePanel === 'file') {
      clearSelectedFile()
      return
    }
    setSidePanel(null)
  }

  const handleInstallApp = async () => {
    const result = await install()

    if (result.status === 'accepted') {
      addToast({
        title: 'Install started',
        description: 'Confirm the browser prompt to finish installing OwnGPT.',
        variant: 'success',
      })
      return
    }

    if (result.status === 'dismissed') {
      addToast({
        title: 'Install dismissed',
        description: 'You can install OwnGPT anytime from the header button.',
        variant: 'info',
      })
      return
    }

    if (result.status === 'installed') {
      addToast({
        title: 'Already installed',
        description: 'OwnGPT is already available as an app on this device.',
        variant: 'info',
      })
      return
    }

    openModal('installHelp', result)
  }

  const activeProviderLabel = registry[provider]?.label || provider
  const appTitle = sharedConversation ? sharedConversation.title || 'Shared Conversation' : currentSessionTitle
  const runtimeStatus = healthQuery.data || {
    status: healthQuery.isError ? 'degraded' : 'checking',
    version: 'unknown',
    checks: {
      mongo: healthQuery.isError ? 'unreachable' : 'checking',
      vector_memory: 'unknown',
    },
    enabled_providers: getEnabledProviderIds(registry),
  }

  return (
    <div
      className={clsx(
        'relative flex h-screen overflow-hidden bg-background text-foreground transition-[padding] duration-300',
        sidebarOpen ? 'lg:pl-[288px]' : 'lg:pl-0',
      )}
    >
      <div className="pointer-events-none absolute inset-0 -z-10 overflow-hidden">
        <div className="app-background absolute inset-0" />
      </div>

      <Sidebar
        open={sidebarOpen}
        sessions={sessions}
        loading={sessionsQuery.isLoading && !sessions.length}
        currentSessionId={currentSessionId}
        searchValue={sessionSearch}
        onSearchChange={setSessionSearch}
        onSelectSession={handleSelectSession}
        onDeleteSession={handleDeleteSessionRequest}
        onNewSession={handleNewChat}
        onClose={() => setSidebarOpen(false)}
        stats={stats}
        insights={insightsQuery.data}
      />

      <div className="flex min-w-0 flex-1 flex-col">
        <AppHeader
          title={appTitle}
          theme={theme}
          themePreference={themePreference}
          currentSessionId={currentSessionId}
          canRenameSession={Boolean(user && !sharedConversation)}
          hasMessages={Boolean(messages.length)}
          onToggleSidebar={toggleSidebar}
          onThemePreferenceChange={setThemePreference}
          onNewChat={handleNewChat}
          onRenameSession={() =>
            openModal('renameSession', buildRenamePayload(currentSessionId, currentSessionTitle))
          }
          onDeleteSession={() =>
            currentSessionId
              ? openModal('deleteSession', {
                  session_id: currentSessionId,
                  title: currentSessionTitle,
                })
              : null
          }
          onShare={handleShareConversation}
          onExportMarkdown={exportChatAsMarkdown}
          onExportPdf={exportChatAsPdf}
          onToggleAnalytics={() => setSidePanel(sidePanel === 'analytics' ? null : 'analytics')}
          onFeedback={handleOpenFeedback}
          user={user}
          onLogin={() => openAuth('login')}
          onLogout={logout}
        />

        {sharedConversation ? (
          <div className="border-b border-border bg-background px-4 py-3 sm:px-6">
            <div className="mx-auto flex max-w-3xl flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
              <div className="flex items-center gap-2 text-sm font-medium text-foreground">
                <Link2 className="h-4 w-4 text-muted-foreground" />
                Shared conversation
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <Button variant="secondary" onClick={handleNewChat}>
                  <Copy className="h-4 w-4" />
                  New chat
                </Button>
                <Button
                  variant="ghost"
                  onClick={() => {
                    clearShareHash()
                    clearSharedConversation()
                  }}
                >
                  <X className="h-4 w-4" />
                  Dismiss
                </Button>
              </div>
            </div>
          </div>
        ) : null}

        <div className="flex min-h-0 flex-1">
          <div className="flex min-w-0 flex-1 flex-col">
            <ChatArea
              messages={messages}
              loading={isLoadingHistory}
              user={user}
              onCopyMessage={handleCopyMessage}
              onRegenerate={regenerateFromAssistant}
              onEdit={(message) => openModal('editMessage', message)}
              onSpeak={toggleSpeech}
              onPreviewFile={previewFile}
              speakingMessageId={speakingMessageId}
            />

            <Composer
              text={composerText}
              onTextChange={setComposerText}
              attachments={attachments}
              onRemoveAttachment={removeAttachment}
              onUpload={uploadFiles}
              onSend={handleSubmitMessage}
              onAskAboutFile={askAboutFile}
              onPreviewFile={previewFile}
              mode={mode}
              onModeChange={setMode}
              provider={activeProviderLabel}
              model={model}
              onOpenModels={() => openModal('model')}
              disabled={!isAuthenticated}
              streaming={isStreaming}
              onRequireAuth={() => openAuth('login')}
            />
          </div>

          <AnimatePresence initial={false}>
            <WorkspacePanel
              sidePanel={sidePanel}
              selectedFile={selectedFile}
              stats={stats}
              insights={insightsQuery.data}
              isAuthenticated={isAuthenticated}
              runtimeStatus={runtimeStatus}
              activeProvider={activeProviderLabel}
              activeModel={model}
              onClose={handleClosePanel}
              onPreviewAnalytics={() => setSidePanel('analytics')}
              onAskAboutFile={askAboutFile}
            />
          </AnimatePresence>
        </div>
      </div>

      <AuthDialog
        open={isAuthDialogOpen}
        mode={authMode || 'login'}
        onModeChange={openAuth}
        onClose={closeAuth}
        onLogin={login}
        onRegister={register}
        onGoogleLogin={loginWithGoogle}
        pending={pendingAuth}
      />

      <FeedbackDialog
        open={activeModal === 'feedback'}
        onOpenChange={(next) => {
          if (!next) closeModal()
        }}
        onSubmit={submitFeedback}
        pending={feedbackPending}
      />

      <ModelDialog
        open={activeModal === 'model'}
        onOpenChange={(next) => {
          if (!next) closeModal()
        }}
        registry={registry}
        currentProvider={provider}
        currentModel={model}
        onSelect={setProviderModel}
      />

      <ConfirmDialog
        open={activeModal === 'deleteSession'}
        onOpenChange={(next) => {
          if (!next) closeModal()
        }}
        title="Delete conversation?"
        description={
          modalPayload?.title
            ? `This will permanently remove "${modalPayload.title}" and its saved messages.`
            : 'This will permanently remove the selected conversation and its saved messages.'
        }
        onConfirm={handleDeleteSubmit}
        confirmLabel="Delete"
        destructive
      />

      <Modal
        open={activeModal === 'renameSession'}
        onOpenChange={(next) => {
          if (!next) closeModal()
        }}
        size="sm"
        title="Rename conversation"
        footer={
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={closeModal}>
              Cancel
            </Button>
            <Button variant="primary" onClick={handleRenameSubmit} disabled={!renameDraft.trim()}>
              Save title
            </Button>
          </div>
        }
      >
        <label className="block space-y-2">
          <span className="text-sm font-medium text-foreground">Conversation title</span>
          <div className="field rounded-lg px-4 py-3">
            <input
              value={renameDraft}
              onChange={(event) => setRenameDraft(event.target.value)}
              placeholder="Product launch planning"
              className="w-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground"
            />
          </div>
        </label>
      </Modal>

      <Modal
        open={activeModal === 'editMessage'}
        onOpenChange={(next) => {
          if (!next) closeModal()
        }}
        size="md"
        title="Edit user prompt"
        footer={
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={closeModal}>
              Cancel
            </Button>
            <Button variant="primary" onClick={handleEditSubmit} disabled={!editDraft.trim()}>
              <Sparkles className="h-4 w-4" />
              Run new branch
            </Button>
          </div>
        }
      >
        <label className="block space-y-2">
          <span className="text-sm font-medium text-foreground">Prompt</span>
          <div className="field rounded-lg px-4 py-3">
            <textarea
              value={editDraft}
              onChange={(event) => setEditDraft(event.target.value)}
              className="min-h-[220px] w-full bg-transparent text-sm leading-7 text-foreground outline-none placeholder:text-muted-foreground"
              placeholder="Refine the original message and branch from it..."
            />
          </div>
        </label>
      </Modal>

      <Modal
        open={activeModal === 'installHelp'}
        onOpenChange={(next) => {
          if (!next) closeModal()
        }}
        size="sm"
        title="Install OwnGPT"
        footer={
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={closeModal}>
              Close
            </Button>
            <Button variant="primary" onClick={closeModal}>
              <Download className="h-4 w-4" />
              I understand
            </Button>
          </div>
        }
      >
        <div className="space-y-4">
          <div className="surface-soft p-4">
            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
              Recommended steps
            </p>
            <div className="mt-3 space-y-3 text-sm leading-6 text-foreground">
              {getInstallSteps(modalPayload?.platform || platform, modalPayload?.instructions || manualInstructions).map((step, index) => (
                <div key={step} className="flex items-start gap-3">
                  <span className="mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-lg bg-accent/10 text-xs font-semibold text-accent">
                    {index + 1}
                  </span>
                  <span>{step}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="rounded-lg border border-border bg-background px-4 py-4 text-sm leading-6 text-muted-foreground">
            {modalPayload?.instructions || manualInstructions}
          </div>
        </div>
      </Modal>

      <Toaster />
    </div>
  )
}