-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
1124 lines (1006 loc) · 39.8 KB
/
App.tsx
File metadata and controls
1124 lines (1006 loc) · 39.8 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 {
AlertCircle,
ArrowRight,
Bookmark,
Download,
History,
Loader2,
MessageCircle,
Moon,
MoreHorizontal,
PenTool,
Settings as SettingsIcon,
Share,
Sun,
Trash2,
} from 'lucide-react'
import React, { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'
const MarkdownRenderer = lazy(() => import('./components/MarkdownRenderer'))
import Dialog, { DialogState } from './components/Dialog'
import HistoryPanel from './components/HistoryPanel'
import QuotesView from './components/QuotesView'
import SettingsModal from './components/SettingsModal'
import SharedBanner from './components/SharedBanner'
import StartView from './components/StartView'
import ThreadList from './components/ThreadList'
import ThreadPanel from './components/ThreadPanel'
import Tooltip from './components/Tooltip'
import { useSession, createNewSession } from './hooks/useSession'
import { useDarkMode } from './hooks/useDarkMode'
import { useSettings } from './hooks/useSettings'
import { useQuotes } from './hooks/useQuotes'
import { useThreadManager } from './hooks/useThreadManager'
import { useTextSelection } from './hooks/useTextSelection'
import { useAiRequest } from './hooks/useAiRequest'
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts'
import { generateId } from './lib/id'
import {
removeThreadAnchor,
setThreadAnchorActive,
updateThreadAnchorId,
wrapCurrentSelectionWithThreadAnchor,
wrapFirstOccurrenceWithThreadAnchor,
} from './lib/threadAnchors'
import {
getHistory,
addToHistory,
removeFromHistory,
updateHistoryEntry,
getCurrentSessionId,
setCurrentSessionId,
extractTitle,
} from './services/sessionHistory'
import { generateSessionSummary } from './services/aiService'
import { Thread, ViewState, SourceMetadata, SessionMeta, Message, ThreadType } from './types'
const SESSION_ID_PATTERN = /^\/([a-zA-Z0-9_-]{10,})$/
function getSessionIdFromUrl(): string | null {
const path = window.location.pathname
const match = path.match(SESSION_ID_PATTERN)
return match ? match[1] : null
}
const App: React.FC = () => {
// URL is the single source of truth for session identity
const [sessionId, setSessionId] = useState<string | null>(() => getSessionIdFromUrl())
const session = useSession(sessionId, {
onSessionChange: setSessionId,
})
const [showSharedBanner, setShowSharedBanner] = useState(true)
// View state
const [viewState, setViewState] = useState<ViewState>(ViewState.START)
const [markdownContent, setMarkdownContent] = useState('')
const [sourceMetadata, setSourceMetadata] = useState<SourceMetadata | null>(null)
const [isSidebarOpen, setIsSidebarOpen] = useState(false)
const [generalInputValue, setGeneralInputValue] = useState('')
const [isCreatingSession, setIsCreatingSession] = useState(false)
const [showMoreMenu, setShowMoreMenu] = useState(false)
const [isHistoryOpen, setIsHistoryOpen] = useState(false)
const [dialog, setDialog] = useState<DialogState>({
isOpen: false,
type: 'alert',
title: '',
message: '',
})
const moreMenuRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const threadAnchorElsRef = useRef<Map<string, HTMLElement>>(new Map())
// Session history from localStorage (just metadata for display)
const [sessionHistory, setSessionHistory] = useState<SessionMeta[]>([])
// Extracted hooks
const { isDarkMode, toggleDarkMode } = useDarkMode()
const { settings, isSettingsOpen, openSettings, closeSettings, saveSettings } = useSettings()
const { quotes, addQuote, deleteQuote, setQuotes } = useQuotes()
const threadManager = useThreadManager()
const threadIdsKey = threadManager.threads.map(t => t.id).join('|')
const { selection, clearSelection } = useTextSelection(
contentRef,
viewState === ViewState.READING
)
const { isLoading: isAiLoading, sendRequest } = useAiRequest(settings, threadManager, session)
// Keyboard shortcuts
useKeyboardShortcuts({
onEscape: () => {
if (selection) {
clearSelection()
} else if (isSidebarOpen) {
setIsSidebarOpen(false)
}
},
onOpenSettings: openSettings,
})
// Reset any DOM thread anchors when the document changes
useEffect(() => {
threadAnchorElsRef.current.clear()
}, [markdownContent])
// Keep anchor "active" styling in sync with the open thread
useEffect(() => {
threadAnchorElsRef.current.forEach((el, id) => {
setThreadAnchorActive(el, id === threadManager.activeThreadId)
})
}, [threadManager.activeThreadId])
// Ensure existing threads have visible anchors in the document
useEffect(() => {
if (viewState !== ViewState.READING) return
const root = contentRef.current
if (!root) return
const currentThreadIds = new Set(threadManager.threads.map(t => t.id))
const idsToRemove: string[] = []
threadAnchorElsRef.current.forEach((_, id) => {
if (!currentThreadIds.has(id)) idsToRemove.push(id)
})
for (const id of idsToRemove) {
const el = threadAnchorElsRef.current.get(id)
if (el) removeThreadAnchor(el)
threadAnchorElsRef.current.delete(id)
}
let cancelled = false
const tryApplyAnchors = (attempt: number) => {
if (cancelled) return
if (!root.querySelector('.markdown-content')) {
if (attempt < 120) requestAnimationFrame(() => tryApplyAnchors(attempt + 1))
return
}
for (const thread of threadManager.threads) {
if (thread.context === 'Entire Document') continue
if (threadAnchorElsRef.current.has(thread.id)) continue
const el = wrapFirstOccurrenceWithThreadAnchor(root, thread.context, thread.id)
if (!el) continue
const labelPrefix = thread.type === 'comment' ? 'Open note' : 'Open thread'
el.title = `${labelPrefix}: ${thread.snippet}`
el.setAttribute('aria-label', `${labelPrefix}: ${thread.snippet}`)
setThreadAnchorActive(el, thread.id === threadManager.activeThreadId)
threadAnchorElsRef.current.set(thread.id, el)
}
}
requestAnimationFrame(() => tryApplyAnchors(0))
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [viewState, markdownContent, threadIdsKey])
// Load session history from localStorage on mount
useEffect(() => {
setSessionHistory(getHistory())
}, [])
// Load session from API when sessionId changes
useEffect(() => {
if (sessionId && session.session && !session.isLoading) {
const apiThreads: Thread[] = session.session.threads.map(t => ({
id: t.id,
type: (t.type as ThreadType) || 'discussion', // Default to discussion for backward compat
context: t.context,
snippet: t.snippet,
createdAt: t.createdAt,
messages: t.messages.map(m => ({
id: m.id,
// Migrate "model" → "assistant" for backwards compatibility
role: m.role === 'model' ? 'assistant' : m.role,
// Add parts array for backwards compatibility
parts: [{ type: 'text' as const, text: m.text }],
text: m.text,
timestamp: m.timestamp,
})),
}))
setMarkdownContent(session.session.markdownContent)
threadManager.setThreads(apiThreads)
setViewState(ViewState.READING)
// Add to history when session loads
if (sessionId) {
const entry: SessionMeta = {
id: sessionId,
title: extractTitle(session.session.markdownContent),
summary: null,
lastModified: Date.now(),
}
addToHistory(entry)
setSessionHistory(getHistory())
setCurrentSessionId(sessionId)
// Generate summary in background if needed
const existing = getHistory().find(h => h.id === sessionId)
if (!existing?.summary && (settings.apiKey || settings.provider === 'ollama')) {
generateSessionSummary(session.session.markdownContent, settings).then(summary => {
if (summary) {
updateHistoryEntry(sessionId, { summary })
setSessionHistory(getHistory())
}
})
}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session.session, session.isLoading, sessionId])
// Handle popstate (back/forward navigation)
useEffect(() => {
const handlePopState = () => {
const newSessionId = getSessionIdFromUrl()
setSessionId(newSessionId)
if (!newSessionId) {
setViewState(ViewState.START)
setMarkdownContent('')
threadManager.setThreads([])
setQuotes([])
}
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// On mount, check if we should restore last session
useEffect(() => {
if (sessionId) return // Already have a session from URL
const lastSessionId = getCurrentSessionId()
if (lastSessionId) {
// Navigate to last session
window.history.replaceState(null, '', `/${lastSessionId}`)
setSessionId(lastSessionId)
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// Close more menu when clicking outside
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (moreMenuRef.current && !moreMenuRef.current.contains(e.target as Node)) {
setShowMoreMenu(false)
}
}
if (showMoreMenu) {
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}
}, [showMoreMenu])
// Event handlers
const handleDocumentMouseDown = (e: React.MouseEvent) => {
const target = e.target as HTMLElement
if (
!target.closest('button') &&
!target.closest('input') &&
!target.closest('[data-thread-anchor]')
) {
clearSelection()
}
}
const openThreadFromAnchor = useCallback(
(threadId: string) => {
threadManager.setActiveThreadId(threadId)
setIsSidebarOpen(true)
},
[threadManager]
)
const handleThreadAnchorClick = useCallback(
(e: React.MouseEvent) => {
const target = e.target as HTMLElement
const el = target.closest<HTMLElement>('[data-thread-anchor]')
if (!el) return
const currentSelection = window.getSelection()
if (currentSelection && !currentSelection.isCollapsed) return
const threadId = el.getAttribute('data-thread-anchor')
if (!threadId) return
e.preventDefault()
e.stopPropagation()
openThreadFromAnchor(threadId)
},
[openThreadFromAnchor]
)
const handleThreadAnchorKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key !== 'Enter' && e.key !== ' ') return
const target = e.target as HTMLElement
const el = target.closest<HTMLElement>('[data-thread-anchor]')
if (!el) return
const threadId = el.getAttribute('data-thread-anchor')
if (!threadId) return
e.preventDefault()
e.stopPropagation()
openThreadFromAnchor(threadId)
},
[openThreadFromAnchor]
)
const handleExport = () => {
let exportText = markdownContent
// Separate threads by type
const comments = threadManager.threads.filter(t => t.type === 'comment')
const discussions = threadManager.threads.filter(t => t.type !== 'comment')
if (quotes.length > 0) {
exportText += '\n\n---\n\n# Saved Quotes\n\n'
quotes.forEach(q => {
exportText += `> "${q.text}"\n\n`
})
}
// Export personal comments
if (comments.length > 0) {
exportText += '\n\n---\n\n# Personal Notes\n\n'
exportText += '_Notes and commentary on the article_\n\n'
comments.forEach(c => {
exportText += `## ${c.snippet}\n\n`
if (c.context !== 'Entire Document') {
exportText += `> **Context**: ${c.context}\n\n`
}
c.messages.forEach(m => {
exportText += `${m.text}\n\n`
})
exportText += '---\n\n'
})
}
// Export AI discussions
if (discussions.length > 0) {
exportText += '\n\n---\n\n# AI Discussions\n\n'
discussions.forEach(t => {
exportText += `## Thread: ${t.snippet}\n`
exportText += `> **Context**: ${t.context}\n\n`
t.messages.forEach(m => {
exportText += `**${m.role === 'user' ? 'You' : 'AI'}**: ${m.text}\n\n`
})
exportText += '---\n\n'
})
}
const blob = new Blob([exportText], { type: 'text/markdown' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `threaded-export-${Date.now()}.md`
a.click()
URL.revokeObjectURL(url)
}
// New session: navigate to / and clear state
const handleNewSession = useCallback(() => {
window.history.pushState(null, '', '/')
setSessionId(null)
setCurrentSessionId(null)
setMarkdownContent('')
threadManager.setThreads([])
setQuotes([])
setSourceMetadata(null)
setViewState(ViewState.START)
}, [threadManager, setQuotes])
// Content ready: create via API, then navigate
const handleContentReady = useCallback(async (content: string, source?: SourceMetadata) => {
setIsCreatingSession(true)
try {
const result = await createNewSession(content)
if (result) {
window.history.pushState(null, '', `/${result.sessionId}`)
setSessionId(result.sessionId)
setSourceMetadata(source || null)
// useSession will load the session and add to history
}
} finally {
setIsCreatingSession(false)
}
}, [])
// Select from history: navigate to session URL
const handleSelectSession = useCallback((id: string) => {
window.history.pushState(null, '', `/${id}`)
setSessionId(id)
// useSession handles loading, which triggers the effect that sets view state
}, [])
// Delete session from history
const handleDeleteFromHistory = useCallback(
async (id: string) => {
// If it's the current session, also delete from API
if (id === sessionId && session.isOwner) {
await session.deleteSession()
}
removeFromHistory(id)
setSessionHistory(getHistory())
// If we deleted the current session, go to start
if (id === sessionId) {
handleNewSession()
}
},
[sessionId, session, handleNewSession]
)
// Share: copy link or create session first
const handleShare = async () => {
let shareSessionId = sessionId
if (!shareSessionId) {
if (!markdownContent.trim()) {
setDialog({
isOpen: true,
type: 'error',
title: 'Cannot Share',
message: 'No content to share. Please add some content first.',
})
return
}
setIsCreatingSession(true)
try {
const result = await createNewSession(markdownContent)
if (!result) {
setDialog({
isOpen: true,
type: 'error',
title: 'Share Failed',
message: 'Failed to create shareable link. Please try again.',
})
return
}
shareSessionId = result.sessionId
setSessionId(shareSessionId)
window.history.pushState(null, '', `/${shareSessionId}`)
} finally {
setIsCreatingSession(false)
}
}
const shareUrl = `${window.location.origin}/${shareSessionId}`
try {
await navigator.clipboard.writeText(shareUrl)
setDialog({
isOpen: true,
type: 'success',
title: 'Link Copied',
message: `Share URL copied to clipboard: ${shareUrl}`,
})
} catch {
prompt('Copy this link:', shareUrl)
}
}
// Delete current session (owner only)
const executeDeleteSession = useCallback(async () => {
if (!sessionId || !session.isOwner) return
const success = await session.deleteSession()
if (success) {
removeFromHistory(sessionId)
setSessionHistory(getHistory())
handleNewSession()
}
}, [sessionId, session, handleNewSession])
const handleDeleteSession = () => {
if (!sessionId || !session.isOwner) return
setDialog({
isOpen: true,
type: 'confirm',
title: 'Delete Session',
message: 'Are you sure you want to delete this session? This cannot be undone.',
onConfirm: executeDeleteSession,
})
}
const createThread = async (action: 'discuss' | 'summarize' | 'comment') => {
if (!selection) return
const newThreadId = Date.now().toString()
const snippet =
selection.text.length > 30 ? selection.text.substring(0, 30) + '...' : selection.text
// Determine thread type based on action
const threadType: ThreadType = action === 'comment' ? 'comment' : 'discussion'
const anchorEl = contentRef.current
? wrapCurrentSelectionWithThreadAnchor(contentRef.current, newThreadId)
: null
if (anchorEl) {
anchorEl.title = action === 'comment' ? `Open note: ${snippet}` : `Open thread: ${snippet}`
anchorEl.setAttribute(
'aria-label',
action === 'comment' ? `Open note: ${snippet}` : `Open thread: ${snippet}`
)
threadAnchorElsRef.current.set(newThreadId, anchorEl)
}
const newThread: Thread = {
id: newThreadId,
type: threadType,
context: selection.text,
messages: [],
createdAt: Date.now(),
snippet,
}
threadManager.addThread(newThread)
threadManager.setActiveThreadId(newThreadId)
setIsSidebarOpen(true)
clearSelection()
// Save to API
let apiThreadId = newThreadId
if (sessionId) {
const savedThreadId = await session.addThread(selection.text, snippet, threadType)
if (savedThreadId && savedThreadId !== newThreadId) {
threadManager.updateThreadId(newThreadId, savedThreadId)
apiThreadId = savedThreadId
const el = threadAnchorElsRef.current.get(newThreadId)
if (el) {
updateThreadAnchorId(el, savedThreadId)
threadAnchorElsRef.current.delete(newThreadId)
threadAnchorElsRef.current.set(savedThreadId, el)
}
}
}
// For comments, we're done - no AI involvement
if (action === 'comment') {
return
}
if (action === 'discuss') {
return
}
// For "summarize", add user message and stream AI response
const initialUserMessage = 'Please explain this section in simple terms.'
const initialUserMessageId = generateId()
const initialUserMsg: Message = {
id: initialUserMessageId,
role: 'user',
parts: [{ type: 'text', text: initialUserMessage }],
text: initialUserMessage,
timestamp: Date.now(),
}
threadManager.addMessageToThread(apiThreadId, initialUserMsg)
if (sessionId) {
const savedId = await session.addMessage(apiThreadId, 'user', initialUserMessage)
if (savedId && savedId !== initialUserMessageId) {
threadManager.replaceMessageId(apiThreadId, initialUserMessageId, savedId)
initialUserMsg.id = savedId
}
}
await sendRequest({
threadId: apiThreadId,
context: selection.text,
markdownContent,
messages: [initialUserMsg],
userMessage: initialUserMessage,
mode: 'explain',
})
}
const handleDeleteThread = async (threadId: string) => {
const el = threadAnchorElsRef.current.get(threadId)
if (el) {
removeThreadAnchor(el)
threadAnchorElsRef.current.delete(threadId)
}
threadManager.deleteThread(threadId)
// Delete from server if we have a session and are the owner
if (sessionId && session.isOwner) {
await session.deleteThread(threadId)
}
}
const handleCreateGeneralThread = async (e: React.FormEvent) => {
e.preventDefault()
if (!generalInputValue.trim()) return
const initialMessage = generalInputValue
setGeneralInputValue('')
const newThreadId = Date.now().toString()
const initialMessageId = generateId()
const initialUserMsg: Message = {
id: initialMessageId,
role: 'user',
parts: [{ type: 'text', text: initialMessage }],
text: initialMessage,
timestamp: Date.now(),
}
const newThread: Thread = {
id: newThreadId,
type: 'discussion', // General threads are always AI discussions
context: 'Entire Document',
messages: [initialUserMsg],
createdAt: Date.now(),
snippet: 'General Discussion',
}
threadManager.addThread(newThread)
threadManager.setActiveThreadId(newThreadId)
setIsSidebarOpen(true)
let apiThreadId = newThreadId
if (sessionId) {
const savedThreadId = await session.addThread('Entire Document', 'General Discussion')
if (savedThreadId && savedThreadId !== newThreadId) {
threadManager.updateThreadId(newThreadId, savedThreadId)
apiThreadId = savedThreadId
}
}
if (sessionId) {
const savedId = await session.addMessage(apiThreadId, 'user', initialMessage)
if (savedId && savedId !== initialMessageId) {
threadManager.replaceMessageId(apiThreadId, initialMessageId, savedId)
initialUserMsg.id = savedId
}
}
await sendRequest({
threadId: apiThreadId,
context: 'Entire Document',
markdownContent,
messages: [initialUserMsg],
userMessage: initialMessage,
mode: 'discuss',
})
}
const handleSendMessage = async (text: string) => {
if (!threadManager.activeThreadId || !threadManager.activeThread) return
const thread = threadManager.activeThread
const userMessageId = generateId()
const userMessage: Message = {
id: userMessageId,
role: 'user',
parts: [{ type: 'text', text }],
text,
timestamp: Date.now(),
}
threadManager.addMessageToThread(threadManager.activeThreadId, userMessage)
if (sessionId) {
const savedId = await session.addMessage(threadManager.activeThreadId, 'user', text)
if (savedId && savedId !== userMessageId) {
threadManager.replaceMessageId(threadManager.activeThreadId, userMessageId, savedId)
userMessage.id = savedId
}
}
// Skip AI for comment threads - they're personal notes without AI involvement
if (thread.type === 'comment') {
return
}
await sendRequest({
threadId: threadManager.activeThreadId,
context: thread.context,
markdownContent,
messages: [...thread.messages, userMessage],
userMessage: text,
mode: 'discuss',
})
}
const handleUpdateMessage = async (messageId: string, newText: string) => {
if (!threadManager.activeThreadId) return
const threadId = threadManager.activeThreadId
const thread = threadManager.activeThread
if (!thread) return
const msgIndex = thread.messages.findIndex(m => m.id === messageId)
if (msgIndex === -1) return
const isUserMessage = thread.messages[msgIndex].role === 'user'
const historyForAI = [
...thread.messages.slice(0, msgIndex),
{ ...thread.messages[msgIndex], text: newText },
]
threadManager.updateMessageToThread(threadId, messageId, newText)
const shouldTruncate = thread.type !== 'comment'
if (shouldTruncate) {
threadManager.truncateThreadAfter(threadId, messageId)
}
if (sessionId && session.isOwner) {
await session.updateMessage(threadId, messageId, newText)
if (shouldTruncate) {
await session.truncateThread(threadId, messageId)
}
}
// Only call AI for discussion threads, not comments
if (isUserMessage && thread.type !== 'comment') {
await sendRequest({
threadId,
context: thread.context,
markdownContent,
messages: historyForAI,
userMessage: newText,
mode: 'discuss',
})
}
}
const handleViewThreadList = () => {
threadManager.setActiveThreadId(null)
setIsSidebarOpen(true)
}
const handleSaveQuote = () => {
if (!selection) return
addQuote(selection.text)
clearSelection()
}
const handleRetry = async () => {
if (!threadManager.activeThreadId || !threadManager.activeThread) return
const currentThread = threadManager.activeThread
// No retry for comment threads - they have no AI responses
if (currentThread.type === 'comment') return
if (currentThread.messages.length < 2) return
const messages = currentThread.messages
const lastUserMessageIndex =
messages.length >= 2 && messages[messages.length - 1].role === 'assistant'
? messages.length - 2
: -1
if (lastUserMessageIndex < 0 || messages[lastUserMessageIndex].role !== 'user') return
const lastUserMessage = messages[lastUserMessageIndex].text
const lastUserMessageId = messages[lastUserMessageIndex].id
// Remove the last assistant message by truncating after the last user message
threadManager.truncateThreadAfter(threadManager.activeThreadId, lastUserMessageId)
// Truncate on server if owner
if (sessionId && session.isOwner) {
await session.truncateThread(threadManager.activeThreadId, lastUserMessageId)
}
// Generate new response
await sendRequest({
threadId: threadManager.activeThreadId,
context: currentThread.context,
markdownContent,
messages: messages.slice(0, lastUserMessageIndex + 1),
userMessage: lastUserMessage,
mode: 'discuss',
})
}
// --- Render ---
if (viewState === ViewState.QUOTES) {
return (
<QuotesView
quotes={quotes}
onBack={() => setViewState(ViewState.READING)}
onDeleteQuote={deleteQuote}
/>
)
}
if (viewState === ViewState.START) {
return (
<>
<HistoryPanel
sessions={sessionHistory}
currentSessionId={sessionId}
onSelectSession={handleSelectSession}
onDeleteSession={handleDeleteFromHistory}
onNewSession={handleNewSession}
isOpen={isHistoryOpen}
onToggle={() => setIsHistoryOpen(prev => !prev)}
/>
<StartView
onContentReady={handleContentReady}
settings={settings}
onSaveSettings={saveSettings}
isDarkMode={isDarkMode}
onToggleDarkMode={toggleDarkMode}
onToggleHistory={() => setIsHistoryOpen(prev => !prev)}
/>
</>
)
}
return (
<div className="flex flex-col h-screen overflow-hidden bg-white dark:bg-dark-base transition-colors duration-300">
{/* History Panel */}
<HistoryPanel
sessions={sessionHistory}
currentSessionId={sessionId}
onSelectSession={handleSelectSession}
onDeleteSession={handleDeleteFromHistory}
onNewSession={handleNewSession}
isOpen={isHistoryOpen}
onToggle={() => setIsHistoryOpen(prev => !prev)}
/>
{/* Shared Session Banner */}
{sessionId && !session.isOwner && showSharedBanner && (
<SharedBanner onDismiss={() => setShowSharedBanner(false)} />
)}
<div className="flex flex-1 overflow-hidden">
{/* Left Pane: Document View Container */}
<main
className={`flex-1 h-full relative flex flex-col transition-all duration-300 ease-in-out ${isSidebarOpen ? 'w-1/2' : 'w-full'}`}
onMouseDown={handleDocumentMouseDown}
>
{/* Scrollable Content Area */}
<div className="flex-1 overflow-y-auto w-full">
<div className="max-w-[720px] mx-auto px-8 py-16">
<header className="mb-8 flex items-center justify-between sticky top-0 z-10 py-3 bg-white/90 dark:bg-dark-base/90 backdrop-blur-sm -mx-4 px-4">
<div className="flex items-center gap-3">
<button
onClick={() => setIsHistoryOpen(prev => !prev)}
className="p-1.5 rounded-md text-slate-400 dark:text-zinc-500 hover:text-slate-600 dark:hover:text-zinc-300 hover:bg-slate-100 dark:hover:bg-dark-elevated transition-colors"
title="History"
>
<History size={18} />
</button>
<span className="text-slate-200 dark:text-zinc-700">|</span>
<button
onClick={handleNewSession}
className="flex items-center gap-1.5 text-sm text-slate-500 dark:text-zinc-400 hover:text-slate-700 dark:hover:text-zinc-200 transition-colors"
>
<PenTool size={15} />
<span>New</span>
</button>
{sourceMetadata && (
<>
<span className="text-slate-300 dark:text-zinc-600">·</span>
<span className="text-sm text-slate-400 dark:text-zinc-500 truncate max-w-[180px]">
{sourceMetadata.type === 'paste'
? 'Pasted'
: sourceMetadata.type === 'url'
? (() => {
try {
return new URL(sourceMetadata.name!).hostname
} catch {
return sourceMetadata.name
}
})()
: sourceMetadata.name}
</span>
</>
)}
{threadManager.threads.length > 0 && (
<button
onClick={handleViewThreadList}
className="text-sm text-slate-600 dark:text-zinc-300 hover:text-slate-900 dark:hover:text-zinc-100 px-2.5 py-1 rounded-full font-medium transition-colors hover:bg-slate-100 dark:hover:bg-dark-elevated"
>
{threadManager.threads.length} thread
{threadManager.threads.length !== 1 && 's'}
</button>
)}
</div>
<div className="flex items-center gap-1">
{quotes.length > 0 && (
<button
onClick={() => setViewState(ViewState.QUOTES)}
className="p-2 rounded-full hover:bg-slate-100 dark:hover:bg-dark-elevated text-amber-500 dark:text-amber-400 transition-colors"
title={`${quotes.length} saved quote${quotes.length !== 1 ? 's' : ''}`}
>
<Bookmark size={18} />
</button>
)}
<button
onClick={handleShare}
disabled={isCreatingSession}
className="p-2 rounded-full hover:bg-slate-100 dark:hover:bg-dark-elevated text-slate-500 dark:text-zinc-400 hover:text-slate-700 dark:hover:text-zinc-200 transition-colors disabled:opacity-50"
title="Share"
>
{isCreatingSession ? (
<Loader2 size={18} className="animate-spin" />
) : (
<Share size={18} />
)}
</button>
<button
onClick={toggleDarkMode}
className="p-2 rounded-full hover:bg-slate-100 dark:hover:bg-dark-elevated text-slate-500 dark:text-zinc-400 hover:text-slate-700 dark:hover:text-zinc-200 transition-colors"
title={isDarkMode ? 'Light mode' : 'Dark mode'}
>
{isDarkMode ? <Sun size={18} /> : <Moon size={18} />}
</button>
<div className="relative" ref={moreMenuRef}>
<button
onClick={() => setShowMoreMenu(!showMoreMenu)}
className="p-2 rounded-full hover:bg-slate-100 dark:hover:bg-dark-elevated text-slate-500 dark:text-zinc-400 hover:text-slate-700 dark:hover:text-zinc-200 transition-colors"
title="More options"
>
<MoreHorizontal size={18} />
</button>
{showMoreMenu && (
<div className="absolute right-0 top-full mt-1 w-48 bg-white dark:bg-dark-surface rounded-lg shadow-lg border border-slate-200 dark:border-dark-border py-1 z-50">
<button
onClick={() => {
handleExport()
setShowMoreMenu(false)
}}
className="w-full px-4 py-2 text-left text-sm text-slate-700 dark:text-zinc-300 hover:bg-slate-100 dark:hover:bg-dark-elevated flex items-center gap-3"
>
<Download size={16} />
Export
</button>
{quotes.length === 0 && (
<button
onClick={() => {
setViewState(ViewState.QUOTES)
setShowMoreMenu(false)
}}
className="w-full px-4 py-2 text-left text-sm text-slate-700 dark:text-zinc-300 hover:bg-slate-100 dark:hover:bg-dark-elevated flex items-center gap-3"
>
<Bookmark size={16} />
Saved quotes
</button>
)}
<button
onClick={() => {
openSettings()
setShowMoreMenu(false)
}}
className="w-full px-4 py-2 text-left text-sm text-slate-700 dark:text-zinc-300 hover:bg-slate-100 dark:hover:bg-dark-elevated flex items-center gap-3"
>
<SettingsIcon size={16} />
Settings
</button>
{sessionId && session.isOwner && (
<>
<div className="my-1 border-t border-slate-200 dark:border-dark-border" />
<button
onClick={() => {
handleDeleteSession()
setShowMoreMenu(false)
}}
className="w-full px-4 py-2 text-left text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center gap-3"
>
<Trash2 size={16} />
Delete
</button>
</>