-
Notifications
You must be signed in to change notification settings - Fork 498
Expand file tree
/
Copy pathApp.svelte
More file actions
708 lines (648 loc) · 20.3 KB
/
Copy pathApp.svelte
File metadata and controls
708 lines (648 loc) · 20.3 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
<script lang="ts">
import { onMount, untrack } from "svelte";
import AppHeader from "./lib/components/layout/AppHeader.svelte";
import ThreeColumnLayout from "./lib/components/layout/ThreeColumnLayout.svelte";
import SessionBreadcrumb from "./lib/components/layout/SessionBreadcrumb.svelte";
import StatusBar from "./lib/components/layout/StatusBar.svelte";
import SessionList from "./lib/components/sidebar/SessionList.svelte";
import MessageList from "./lib/components/content/MessageList.svelte";
import SessionVitals from "./lib/components/content/SessionVitals.svelte";
import { sessionActivity } from "./lib/stores/sessionActivity.svelte.js";
import { sessionTiming } from "./lib/stores/sessionTiming.svelte.js";
import CommandPalette from "./lib/components/command-palette/CommandPalette.svelte";
import AboutModal from "./lib/components/modals/AboutModal.svelte";
import ShortcutsModal from "./lib/components/modals/ShortcutsModal.svelte";
import PublishModal from "./lib/components/modals/PublishModal.svelte";
import ResyncModal from "./lib/components/modals/ResyncModal.svelte";
import UpdateModal from "./lib/components/modals/UpdateModal.svelte";
import ConfirmDeleteModal from "./lib/components/modals/ConfirmDeleteModal.svelte";
import PerfDebugPanel from "./lib/components/debug/PerfDebugPanel.svelte";
import AnalyticsPage from "./lib/components/analytics/AnalyticsPage.svelte";
import UsagePage from "./lib/components/usage/UsagePage.svelte";
import ActivityPage from "./lib/components/activity/ActivityPage.svelte";
import TrendsPage from "./lib/components/trends/TrendsPage.svelte";
import InsightsPage from "./lib/components/insights/InsightsPage.svelte";
import PinnedPage from "./lib/components/pinned/PinnedPage.svelte";
import TrashPage from "./lib/components/trash/TrashPage.svelte";
import SettingsPage from "./lib/components/settings/SettingsPage.svelte";
import { sessions, filtersToParams } from "./lib/stores/sessions.svelte.js";
import { messages } from "./lib/stores/messages.svelte.js";
import { sync } from "./lib/stores/sync.svelte.js";
import { ui } from "./lib/stores/ui.svelte.js";
import { router } from "./lib/stores/router.svelte.js";
import { starred } from "./lib/stores/starred.svelte.js";
import { pins } from "./lib/stores/pins.svelte.js";
import { settings } from "./lib/stores/settings.svelte.js";
import { yokedDates } from "./lib/stores/yokedDates.svelte.js";
import { setAuthToken, getAuthToken, setServerUrl, getBase } from "./lib/api/runtime.js";
import { setupVisibilityHealthCheck } from "./lib/utils/health.js";
import { registerShortcuts } from "./lib/utils/keyboard.js";
import { shouldAutoSwitchTranscriptModeToNormal } from "./lib/utils/transcript-mode.js";
import {
filterParamsEqual,
hasFilterParams,
sessionDateIntentCleared,
sessionRouteParamsForDetailExit,
sessionRouteParamsForFilters,
} from "./lib/stores/sessionRouteParams.js";
let globalAuthToken: string = $state("");
function handleGlobalAuth() {
const token = globalAuthToken.trim();
if (!token) return;
setAuthToken(token);
// Full reload ensures all stores (settings, sessions, starred,
// sync, pins, etc.) reinitialize with the new credentials.
window.location.reload();
}
import type { DisplayItem } from "./lib/utils/display-items.js";
import {
parseContent,
enrichSegments,
} from "./lib/utils/content-parser.js";
let messageListRef:
| {
scrollToOrdinal: (o: number) => void;
getDisplayItems: () => DisplayItem[];
getNormalDisplayItems: () => DisplayItem[];
}
| undefined = $state(undefined);
// Load active session's messages when selection changes.
// Only track activeSessionId — untrack the rest to prevent
// reactive loops from messages.loading / messages.messages.
$effect(() => {
const id = sessions.activeSessionId;
untrack(() => {
// Preserve selection when a pending scroll is queued
// for this specific session (e.g. search result
// navigation sets session + ordinal before this effect
// fires). Clear if the pending scroll targets a
// different session or there is no pending scroll.
const pendingMatchesSession =
ui.pendingScrollOrdinal !== null &&
(ui.pendingScrollSession === null ||
ui.pendingScrollSession === id);
if (!pendingMatchesSession) {
ui.clearSelection();
ui.pendingScrollOrdinal = null;
ui.pendingScrollSession = null;
}
if (id) {
if (ui.isMobileViewport) {
ui.closeSidebar();
}
messages.loadSession(id);
sessions.loadChildSessions(id);
sessionTiming.load(id);
sync.watchSession(
id,
() => {
messages.reload();
sessions.refreshActiveSession();
sessions.loadChildSessions(id);
if (ui.vitalsOpen) {
sessionActivity.reload(id);
} else {
sessionActivity.invalidate();
}
},
(t) => {
sessionTiming.applyEvent(t);
},
);
pins.loadForSession(id);
} else {
sessionActivity.clear();
sessionTiming.reset();
messages.clear();
sessions.childSessions = new Map();
sync.unwatchSession();
pins.clearSession();
}
});
});
// Scroll to pending ordinal once messages finish loading.
// If the target message is hidden specifically because thinking
// is disabled, auto-enable thinking so the message becomes visible.
// Messages hidden by other block filters (tool/code/user/assistant)
// are left alone — auto-changing unrelated filters is unexpected.
$effect(() => {
const ordinal = ui.pendingScrollOrdinal;
const loading = messages.loading;
const thinkingVisible = ui.isBlockVisible("thinking");
untrack(() => {
if (ordinal === null || loading || !messageListRef) return;
const items = messageListRef.getDisplayItems();
const normalItems =
messageListRef.getNormalDisplayItems();
const found = items.some((item) =>
item.ordinals.includes(ordinal),
);
if (!found) {
if (
shouldAutoSwitchTranscriptModeToNormal(
ui.transcriptMode,
ordinal,
items,
normalItems,
)
) {
ui.setTranscriptMode("normal");
return; // effect re-runs with normal transcript mode
}
// Only auto-enable thinking if the ordinal is loaded
// but filtered out *specifically* due to hidden thinking.
// If it's outside the loaded window, don't change filters.
// Auto-enable thinking filter when navigating to a message
// that contains a thinking block.
const msg = messages.messages.find(
(m) => m.ordinal === ordinal,
);
if (msg && !thinkingVisible) {
const segs = enrichSegments(
parseContent(
msg.content,
msg.has_tool_use,
msg.id,
msg.content_length,
),
msg.tool_calls,
);
const hasThinkingSegment = segs.some(
(s) => s.type === "thinking",
);
if (hasThinkingSegment) {
ui.setBlockVisible("thinking", true);
return; // effect re-runs with thinking visible
}
}
}
messageListRef.scrollToOrdinal(ordinal);
// Ensure highlight is set (the session-change effect
// may have cleared it before this effect ran).
ui.selectedOrdinal = ordinal;
ui.pendingScrollOrdinal = null;
ui.pendingScrollSession = null;
});
});
function navigateMessage(delta: number) {
const items = messageListRef?.getDisplayItems();
if (!items || items.length === 0) return;
const sorted = ui.sortNewestFirst
? [...items].reverse()
: items;
const selected = ui.selectedOrdinal;
if (selected === null) {
const first = sorted[0]!;
navigateToMessageOrdinal(first.ordinals[0]!);
return;
}
const curIdx = sorted.findIndex((item) =>
item.ordinals.includes(selected),
);
const nextIdx = Math.max(
0,
Math.min(sorted.length - 1, curIdx + delta),
);
if (nextIdx === curIdx) return;
const next = sorted[nextIdx]!;
navigateToMessageOrdinal(next.ordinals[0]!);
}
function navigateToMessageOrdinal(ordinal: number) {
if (ui.followLatest) {
ui.setFollowLatest(false);
}
ui.selectOrdinal(ordinal);
messageListRef?.scrollToOrdinal(ordinal);
}
function clearYokeForClearedSessionDates(
nextParams: Record<string, string>,
): void {
if (sessionDateIntentCleared(router.params, nextParams)) {
yokedDates.clear();
}
}
let lastDetailFilterParamsSignature: string | null = $state(null);
// React to route changes: reload sessions and apply URL params.
// Only apply URL deep-link params (initFromParams) when the URL
// actually contains filter keys — a bare /sessions preserves the
// current store state (restored from localStorage).
// Only track route and params — NOT sessionId.
$effect(() => {
const route = router.route;
const params = router.params;
untrack(() => {
const sid = router.sessionId;
if (!sid && route === "sessions" && hasFilterParams(params)) {
sessions.initFromParams(params);
}
if (route === "sessions") {
sessions.load();
}
sessions.loadProjects();
sessions.loadAgents();
});
});
// Deep-link: select session from URL and handle ?msg param.
$effect(() => {
const sid = router.sessionId;
const msgParam = router.params["msg"] ?? null;
untrack(() => {
if (sid) {
if (sid !== sessions.activeSessionId) {
sessions.navigateToSession(sid);
}
if (msgParam) {
if (msgParam === "last") {
ui.pendingScrollOrdinal = -1;
ui.pendingScrollSession = sid;
} else {
const ordinal = parseInt(msgParam, 10);
if (Number.isFinite(ordinal)) {
ui.scrollToOrdinal(ordinal, sid);
}
}
}
} else if (router.route === "sessions") {
if (sessions.activeSessionId !== null) {
sessions.deselectSession();
}
}
});
});
// Resolve msg=last once messages are loaded.
$effect(() => {
const pending = ui.pendingScrollOrdinal;
const loading = messages.loading;
const msgs = messages.messages;
untrack(() => {
if (pending !== -1 || loading || msgs.length === 0) return;
const target = ui.pendingScrollSession;
if (target !== null && target !== messages.sessionId) return;
const lastOrdinal = msgs[msgs.length - 1]!.ordinal;
ui.scrollToOrdinal(lastOrdinal, target ?? undefined);
});
});
// Sync active session to URL.
$effect(() => {
const activeId = sessions.activeSessionId;
const currentUrlSessionId = router.sessionId;
const filterParams = filtersToParams(sessions.filters);
const filterParamsSignature = JSON.stringify(filterParams);
untrack(() => {
if (router.route !== "sessions") {
lastDetailFilterParamsSignature = null;
return;
}
if (activeId) {
const nextParams = sessionRouteParamsForFilters(
filterParams,
router.params,
);
if (activeId === currentUrlSessionId) {
if (
lastDetailFilterParamsSignature !== null &&
lastDetailFilterParamsSignature !== filterParamsSignature &&
!filterParamsEqual(router.params, nextParams)
) {
clearYokeForClearedSessionDates(nextParams);
router.replaceParams(nextParams);
}
lastDetailFilterParamsSignature = filterParamsSignature;
return;
}
clearYokeForClearedSessionDates(nextParams);
router.navigateToSession(activeId, nextParams);
lastDetailFilterParamsSignature = filterParamsSignature;
} else {
if (currentUrlSessionId === null) {
lastDetailFilterParamsSignature = null;
return;
}
const filterChangedOnDetail =
lastDetailFilterParamsSignature !== null &&
lastDetailFilterParamsSignature !== filterParamsSignature;
const nextParams = filterChangedOnDetail
? sessionRouteParamsForFilters(
filterParams,
router.params,
)
: sessionRouteParamsForDetailExit(
filterParams,
router.params,
);
clearYokeForClearedSessionDates(nextParams);
router.navigateFromSession(nextParams);
lastDetailFilterParamsSignature = null;
}
});
});
// URL write-back: keep query string in sync with filter state
// when on /sessions with no session selected, so users can
// share/bookmark the view and the URL reflects what's shown.
// Tracks route so a tab switch back to /sessions also syncs
// the URL with localStorage-restored filters.
$effect(() => {
const route = router.route;
const newParams = sessionRouteParamsForFilters(
filtersToParams(sessions.filters),
router.params,
);
untrack(() => {
if (route !== "sessions") return;
if (router.sessionId) return;
if (filterParamsEqual(router.params, newParams)) return;
clearYokeForClearedSessionDates(newParams);
router.replaceParams(newParams);
});
});
function showAbout() {
if (ui.activeModal === "resync" && sync.syncing) return;
ui.activeModal = "about";
}
onMount(() => {
globalAuthToken = getAuthToken();
settings.load();
starred.load();
sync.loadStatus();
sync.loadStats();
sync.loadVersion();
sync.checkForUpdate();
sync.startPolling();
const healthCleanup = setupVisibilityHealthCheck(getBase, {
onBackendDegraded: () => sync.markBackendDegraded(),
});
window.addEventListener("show-about", showAbout);
const cleanup = registerShortcuts({ navigateMessage });
return () => {
healthCleanup();
cleanup();
window.removeEventListener("show-about", showAbout);
sync.stopPolling();
sync.unwatchSession();
};
});
</script>
{#if settings.needsAuth && router.route !== "settings"}
<div class="auth-overlay">
<div class="auth-card">
<h2 class="auth-card-title">Authentication Required</h2>
<p class="auth-card-desc">
This server requires an auth token to access. Enter the token
shown on the server's console or settings page.
</p>
<div class="auth-card-field">
<input
class="auth-card-input"
type="password"
placeholder="Paste auth token"
bind:value={globalAuthToken}
onkeydown={(e) => { if (e.key === "Enter") handleGlobalAuth(); }}
/>
<button
class="auth-card-btn"
disabled={!globalAuthToken.trim()}
onclick={handleGlobalAuth}
>
Authenticate
</button>
</div>
<button
class="auth-card-disconnect"
onclick={() => {
setAuthToken("");
setServerUrl("");
settings.needsAuth = false;
settings.load();
}}
>
Disconnect and reset
</button>
</div>
</div>
{:else}
<AppHeader />
{#if router.route === "usage"}
<div class="page-scroll">
<UsagePage />
</div>
{:else if router.route === "activity"}
<div class="page-scroll">
<ActivityPage />
</div>
{:else if router.route === "trends"}
<div class="page-scroll">
<TrendsPage />
</div>
{:else if router.route === "insights"}
<div class="page-scroll">
<InsightsPage />
</div>
{:else if router.route === "pinned"}
<div class="page-scroll">
<PinnedPage />
</div>
{:else if router.route === "trash"}
<div class="page-scroll">
<TrashPage />
</div>
{:else if router.route === "settings"}
<div class="page-scroll">
<SettingsPage />
</div>
{:else}
<ThreeColumnLayout>
{#snippet sidebar()}
<SessionList />
{/snippet}
{#snippet content()}
{#if sessions.activeSessionId}
{@const session = sessions.activeSession}
<SessionBreadcrumb
session={session}
onBack={() => sessions.deselectSession()}
/>
<MessageList bind:this={messageListRef} />
{:else}
<AnalyticsPage />
{/if}
{/snippet}
{#snippet vitals()}
{#if sessions.activeSessionId}
<SessionVitals sessionId={sessions.activeSessionId} />
{/if}
{/snippet}
</ThreeColumnLayout>
{/if}
<StatusBar />
<PerfDebugPanel />
{#if ui.activeModal === "about"}
<AboutModal />
{/if}
{#if ui.activeModal === "commandPalette"}
<CommandPalette />
{/if}
{#if ui.activeModal === "shortcuts"}
<ShortcutsModal />
{/if}
{#if ui.activeModal === "publish"}
<PublishModal />
{/if}
{#if ui.activeModal === "resync"}
<ResyncModal />
{/if}
{#if ui.activeModal === "update"}
<UpdateModal />
{/if}
{#if ui.activeModal === "confirmDelete"}
<ConfirmDeleteModal />
{/if}
{/if}
{#if sessions.recentlyDeleted.length > 0}
<div class="undo-toast">
<span>Session deleted</span>
<button
class="undo-btn"
onclick={async (e) => {
const btn = e.currentTarget;
if (btn.disabled) return;
const last = sessions.recentlyDeleted[sessions.recentlyDeleted.length - 1];
if (!last) return;
btn.disabled = true;
try {
await sessions.restoreSession(last.id);
} catch {
// restore failed — toast will remain
} finally {
btn.disabled = false;
}
}}
>
Undo
</button>
</div>
{/if}
<style>
.page-scroll {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.undo-toast {
position: fixed;
bottom: 40px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 12px;
background: var(--bg-surface);
border: 1px solid var(--border-default);
border-radius: 8px;
padding: 10px 18px;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.3);
z-index: 10000;
font-size: 13px;
color: var(--text-primary);
animation: slide-up 0.2s ease-out;
}
@keyframes slide-up {
from {
opacity: 0;
transform: translateX(-50%) translateY(10px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
.undo-btn {
background: none;
border: none;
color: var(--accent-blue);
font-size: 13px;
font-weight: 600;
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
}
.undo-btn:hover {
background: color-mix(in srgb, var(--accent-blue) 12%, transparent);
}
.auth-overlay {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background: var(--bg-default);
}
.auth-card {
text-align: center;
max-width: 420px;
padding: 32px 24px;
background: var(--bg-surface);
border: 1px solid var(--border-default);
border-radius: 12px;
box-shadow: var(--shadow-lg);
}
.auth-card-title {
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
margin: 0 0 8px;
}
.auth-card-desc {
font-size: 13px;
color: var(--text-muted);
margin: 0 0 20px;
}
.auth-card-field {
display: flex;
gap: 8px;
}
.auth-card-input {
flex: 1;
height: 34px;
padding: 0 12px;
border-radius: 6px;
font-size: 13px;
font-family: var(--font-mono, monospace);
color: var(--text-primary);
background: var(--bg-inset);
border: 1px solid var(--border-muted);
}
.auth-card-input:focus {
outline: none;
border-color: var(--accent-blue);
}
.auth-card-btn {
height: 34px;
padding: 0 16px;
border-radius: 6px;
font-size: 13px;
font-weight: 500;
color: white;
background: var(--accent-blue);
border: none;
cursor: pointer;
white-space: nowrap;
}
.auth-card-btn:disabled {
opacity: 0.6;
cursor: default;
}
.auth-card-btn:hover:not(:disabled) {
opacity: 0.9;
}
.auth-card-disconnect {
margin-top: 12px;
background: none;
border: none;
color: var(--text-muted);
font-size: 12px;
cursor: pointer;
text-decoration: underline;
}
.auth-card-disconnect:hover {
color: var(--text-secondary);
}
</style>