summaryrefslogtreecommitdiffhomepage
path: root/packages/frontend/src/lib/components/ChatPanel.svelte
blob: ee1b8efb63a5913ae34307d79a37126521c35bf0 (plain)
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
<script lang="ts">
import { tick, untrack } from "svelte";
import { tabStore } from "../tabs.svelte.js";
import ChatMessageComponent from "./ChatMessage.svelte";

let messagesEl: HTMLDivElement | undefined;
let userScrolledUp = $state(false);
let isAutoScrolling = false;
let isLoadingMore = $state(false);

const renderGroups = $derived(tabStore.activeTab?.renderGroups ?? []);
const activeTabId = $derived(tabStore.activeTab?.id);
// Compaction placeholder state for the active tab. `compactingSource` is set on
// a transient placeholder tab while a conversation is being compacted;
// `compactionError` is set if it failed.
const compactingSource = $derived(tabStore.activeTab?.compactingSource ?? null);
const compactionError = $derived(tabStore.activeTab?.compactionError ?? null);

// Stable, turn-scoped render keys. A bubble's identity is `${turnId}:${role}:${n}`
// (n = its index among same-(turn,role) messages) rather than the underlying
// row/client id, so when the live turn reconciles into sealed chunk rows the
// bubble keeps its identity and does NOT remount (no flash). Falls back to the
// message id for anything without a turnId (e.g. optimistic/queued messages
// before turn-start, standalone system notices).
const keyedMessages = $derived.by(() => {
	const counts = new Map<string, number>();
	return renderGroups.map((m) => {
		if (!m.turnId) return { m, key: m.id };
		const base = `${m.turnId}:${m.role}`;
		const n = counts.get(base) ?? 0;
		counts.set(base, n + 1);
		return { m, key: `${base}:${n}` };
	});
});

function isNearBottom(el: HTMLElement): boolean {
	return el.scrollHeight - el.scrollTop - el.clientHeight < 64;
}

function scrollToBottom(animate = false) {
	if (!messagesEl) return;
	messagesEl.scrollTo({
		top: messagesEl.scrollHeight,
		behavior: animate ? "smooth" : "instant",
	});
}

async function onNearTop() {
	if (isLoadingMore) return;
	const tab = tabStore.activeTab;
	if (!tab) return;
	// Nothing older to load if we're already at the very first message, or if
	// we already hold every message the backend has for this tab.
	if (tab.oldestLoadedSeq !== null && tab.oldestLoadedSeq <= 0) return;

	isLoadingMore = true;
	const prevScrollHeight = messagesEl?.scrollHeight ?? 0;
	const prevScrollTop = messagesEl?.scrollTop ?? 0;
	try {
		await tabStore.loadOlderChunks(tab.id);
		// Wait for Svelte to flush the prepended messages into the DOM.
		// Reading `scrollHeight` synchronously after the await would observe
		// the OLD layout (reactive updates are batched), so the scroll
		// correction would be computed against a stale height and the
		// viewport would jump. `tick()` resolves once the DOM reflects the
		// new message list.
		await tick();
		if (messagesEl) {
			const newScrollHeight = messagesEl.scrollHeight;
			const delta = newScrollHeight - prevScrollHeight;
			// Only adjust when content was actually prepended above the
			// viewport. If nothing was added (all duplicates / nothing older),
			// `delta` is 0 and we leave the user where they are instead of
			// snapping to the top.
			if (delta > 0) {
				messagesEl.scrollTop = prevScrollTop + delta;
			}
		}
	} finally {
		isLoadingMore = false;
	}
}

function handleScroll() {
	if (!messagesEl || isAutoScrolling) return;
	const wasScrolledUp = userScrolledUp;
	userScrolledUp = !isNearBottom(messagesEl);
	if (activeTabId) tabStore.setScrolledUp(activeTabId, userScrolledUp);
	// User just scrolled back to the bottom manually — safe to evict now.
	if (wasScrolledUp && !userScrolledUp && activeTabId) {
		tabStore.evictChunks(activeTabId);
	}
	// Near the top — pull in older history.
	if (userScrolledUp && messagesEl.scrollTop < 200) {
		void onNearTop();
	}
}

function resumeAutoScroll() {
	userScrolledUp = false;
	isAutoScrolling = true;
	if (activeTabId) {
		tabStore.setScrolledUp(activeTabId, false);
		tabStore.evictChunks(activeTabId);
	}
	scrollToBottom(true);
}

$effect(() => {
	const count = renderGroups.length;
	void count;
	if (messagesEl) {
		untrack(() => {
			if (!userScrolledUp) scrollToBottom(false);
		});
	}
});

$effect(() => {
	const prevTabId = activeTabId;
	// Reset scroll state when switching tabs
	userScrolledUp = false;
	isAutoScrolling = false;
	return () => {
		if (prevTabId) {
			tabStore.setScrolledUp(prevTabId, false);
		}
	};
});
</script>

<div class="flex flex-col h-full">
	<!-- Messages -->
	<div class="relative flex-1 min-h-0">
		<div
			bind:this={messagesEl}
			class="h-full overflow-y-auto p-4"
			onscroll={handleScroll}
			onscrollend={() => {
				isAutoScrolling = false;
			}}
		>
			{#if isLoadingMore}
				<div class="text-center text-xs text-base-content/40 py-2">Loading earlier messages...</div>
			{/if}
			{#if compactingSource || compactionError}
				<div class="flex flex-col items-center justify-center h-full gap-4 px-6 text-center">
					{#if compactionError}
						<div class="text-2xl font-semibold text-error">Compaction failed</div>
						<div class="text-base text-base-content/70 max-w-md">{compactionError}</div>
						<div class="text-sm text-base-content/50">Close this tab to dismiss — your conversation was not changed.</div>
					{:else}
						<span class="loading loading-spinner loading-lg text-primary"></span>
						<div class="text-2xl font-semibold text-base-content">Please wait, compacting conversation…</div>
						<div class="text-sm text-base-content/50">You can cancel by closing this tab.</div>
					{/if}
				</div>
			{:else if renderGroups.length === 0}
				<div class="flex items-center justify-center h-full text-base-content/40 text-sm">
					Send a message to start a conversation
				</div>
			{/if}
			{#if !compactingSource && !compactionError}
				{#each keyedMessages as { m, key } (key)}
					<ChatMessageComponent message={m} tabId={activeTabId} />
				{/each}
			{/if}
		</div>

		<!-- Scroll-to-bottom button -->
		<button
			type="button"
			class="absolute bottom-0 left-1/2 -translate-x-1/2 mb-4 btn btn-sm px-8 rounded-lg shadow-lg transition-opacity duration-200 {userScrolledUp ? 'opacity-100' : 'opacity-0 pointer-events-none'}"
			onclick={resumeAutoScroll}
			aria-label="Scroll to bottom"
			tabindex={userScrolledUp ? 0 : -1}
		>
			&#x25BC;
		</button>
	</div>
</div>