fix(svelte): replace $effect with onMount for side effects

$effect runs during SSR and re-runs on every reactive dependency change,
causing polling loops and URL reads to fire at the wrong time. onMount
runs once on the client after first render, which is the correct lifecycle
for polling, URL param reads, and async data loads.

- IndexingProgress: polling loop now starts on mount, not on reactive trigger
- search/+page.svelte: URL param init moved to onMount; use window.location
  directly instead of the page store to avoid reactive re-runs
- settings/+page.svelte: config load and local provider probe moved to onMount

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Giancarmine Salucci
2026-03-25 14:30:04 +01:00
parent 215cadf070
commit a63de39473
3 changed files with 224 additions and 203 deletions

View File

@@ -1,12 +1,12 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte';
import type { IndexingJob } from '$lib/types'; import type { IndexingJob } from '$lib/types';
let { jobId }: { jobId: string } = $props(); let { jobId }: { jobId: string } = $props();
let job = $state<IndexingJob | null>(null); let job = $state<IndexingJob | null>(null);
$effect(() => { onMount(() => {
// Reset and restart polling whenever jobId changes.
job = null; job = null;
let stopped = false; let stopped = false;
@@ -23,13 +23,13 @@
} }
} }
poll(); void poll();
const interval = setInterval(() => { const interval = setInterval(() => {
if (job?.status === 'done' || job?.status === 'failed') { if (job?.status === 'done' || job?.status === 'failed') {
clearInterval(interval); clearInterval(interval);
return; return;
} }
poll(); void poll();
}, 2000); }, 2000);
return () => { return () => {

View File

@@ -1,11 +1,11 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { page } from '$app/state';
import LibraryResult from '$lib/components/search/LibraryResult.svelte'; import LibraryResult from '$lib/components/search/LibraryResult.svelte';
import SnippetCard from '$lib/components/search/SnippetCard.svelte'; import SnippetCard from '$lib/components/search/SnippetCard.svelte';
import SearchInput from '$lib/components/search/SearchInput.svelte'; import SearchInput from '$lib/components/search/SearchInput.svelte';
import { copyToClipboard } from '$lib/utils/copy-to-clipboard'; import { copyToClipboard } from '$lib/utils/copy-to-clipboard';
import type { LibrarySearchJsonResult, SnippetJson } from '$lib/server/api/formatters'; import type { LibrarySearchJsonResult, SnippetJson } from '$lib/server/api/formatters';
import { onMount } from 'svelte';
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// State // State
@@ -38,9 +38,9 @@
// Initialise from URL params on mount // Initialise from URL params on mount
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
$effect(() => { onMount(() => {
const libParam = page.url.searchParams.get('lib'); const libParam = new URL(window.location.href).searchParams.get('lib');
const qParam = page.url.searchParams.get('q'); const qParam = new URL(window.location.href).searchParams.get('q');
if (libParam) { if (libParam) {
selectedLibraryId = libParam; selectedLibraryId = libParam;
@@ -50,7 +50,7 @@
query = qParam; query = qParam;
} }
if (libParam && qParam) { if (libParam && qParam) {
searchDocs(); void searchDocs(false);
} }
}); });
@@ -81,7 +81,7 @@
} }
} }
async function searchDocs() { async function searchDocs(syncUrl = true) {
if (!selectedLibraryId || !query.trim()) return; if (!selectedLibraryId || !query.trim()) return;
loadingSnippets = true; loadingSnippets = true;
snippetError = null; snippetError = null;
@@ -89,10 +89,11 @@
totalTokens = 0; totalTokens = 0;
try { try {
const url = new URL('/api/v1/context', window.location.origin); const params = new URLSearchParams({
url.searchParams.set('libraryId', selectedLibraryId); libraryId: selectedLibraryId,
url.searchParams.set('query', query); query
const res = await fetch(url); });
const res = await fetch(`/api/v1/context?${params.toString()}`);
if (!res.ok) { if (!res.ok) {
const data = await res.json(); const data = await res.json();
throw new Error(data.error ?? `Request failed (${res.status})`); throw new Error(data.error ?? `Request failed (${res.status})`);
@@ -101,11 +102,12 @@
snippets = data.snippets ?? []; snippets = data.snippets ?? [];
totalTokens = data.totalTokens ?? 0; totalTokens = data.totalTokens ?? 0;
// Sync URL state. if (syncUrl) {
goto( goto(
`/search?lib=${encodeURIComponent(selectedLibraryId)}&q=${encodeURIComponent(query)}`, `/search?lib=${encodeURIComponent(selectedLibraryId)}&q=${encodeURIComponent(query)}`,
{ replaceState: true, keepFocus: true } { replaceState: true, keepFocus: true }
); );
}
} catch (e) { } catch (e) {
snippetError = (e as Error).message; snippetError = (e as Error).message;
} finally { } finally {

View File

@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte';
import StatBadge from '$lib/components/StatBadge.svelte'; import StatBadge from '$lib/components/StatBadge.svelte';
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -43,15 +44,16 @@
let saving = $state(false); let saving = $state(false);
let saveStatus = $state<'idle' | 'ok' | 'error'>('idle'); let saveStatus = $state<'idle' | 'ok' | 'error'>('idle');
let saveError = $state<string | null>(null); let saveError = $state<string | null>(null);
let saveStatusTimer: ReturnType<typeof setTimeout> | null = null;
let localAvailable = $state<boolean | null>(null); let localAvailable = $state<boolean | null>(null);
let loading = $state(true); let loading = $state(true);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Load current config + probe local provider on mount (Svelte 5 $effect) // Load current config + probe local provider on mount
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
$effect(() => { onMount(() => {
let cancelled = false; let cancelled = false;
(async () => { (async () => {
@@ -75,12 +77,11 @@
// Probe whether the local provider is available // Probe whether the local provider is available
try { try {
const res = await fetch('/api/v1/settings/embedding/test', { const res = await fetch('/api/v1/settings/embedding/test');
method: 'POST', if (!cancelled && res.ok) {
headers: { 'Content-Type': 'application/json' }, const data = await res.json();
body: JSON.stringify({ provider: 'local' }) localAvailable = data.available ?? false;
}); }
if (!cancelled) localAvailable = res.ok;
} catch { } catch {
if (!cancelled) localAvailable = false; if (!cancelled) localAvailable = false;
} }
@@ -88,19 +89,10 @@
return () => { return () => {
cancelled = true; cancelled = true;
if (saveStatusTimer) clearTimeout(saveStatusTimer);
}; };
}); });
// Auto-dismiss save success banner after 3 seconds
$effect(() => {
if (saveStatus === 'ok') {
const timer = setTimeout(() => {
saveStatus = 'idle';
}, 3000);
return () => clearTimeout(timer);
}
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Actions // Actions
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -151,6 +143,11 @@
}); });
if (res.ok) { if (res.ok) {
saveStatus = 'ok'; saveStatus = 'ok';
if (saveStatusTimer) clearTimeout(saveStatusTimer);
saveStatusTimer = setTimeout(() => {
saveStatus = 'idle';
saveStatusTimer = null;
}, 3000);
} else { } else {
const data = await res.json(); const data = await res.json();
saveStatus = 'error'; saveStatus = 'error';
@@ -163,6 +160,11 @@
saving = false; saving = false;
} }
} }
function handleSubmit(event: SubmitEvent) {
event.preventDefault();
void save();
}
</script> </script>
<svelte:head> <svelte:head>
@@ -184,182 +186,199 @@
{#if loading} {#if loading}
<p class="text-sm text-gray-400">Loading current configuration…</p> <p class="text-sm text-gray-400">Loading current configuration…</p>
{:else} {:else}
<!-- Provider selector --> <form class="space-y-4" onsubmit={handleSubmit}>
<div class="mb-4 flex gap-2"> <!-- Provider selector -->
{#each ['none', 'openai', 'local'] as p} <div class="mb-4 flex gap-2">
<button {#each ['none', 'openai', 'local'] as p}
onclick={() => {
provider = p as 'none' | 'openai' | 'local';
testStatus = 'idle';
testError = null;
}}
class={[
'rounded-lg px-4 py-2 text-sm',
provider === p
? 'bg-blue-600 text-white'
: 'border border-gray-200 text-gray-700 hover:bg-gray-50'
].join(' ')}
>
{p === 'none' ? 'None (FTS5 only)' : p === 'openai' ? 'OpenAI-compatible' : 'Local Model'}
</button>
{/each}
</div>
<!-- None warning -->
{#if provider === 'none'}
<div class="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-700">
Search will use keyword matching only. Results may be less relevant for complex questions.
</div>
{/if}
<!-- OpenAI-compatible form -->
{#if provider === 'openai'}
<div class="space-y-3">
<!-- Preset buttons -->
<div class="flex flex-wrap gap-2">
{#each PROVIDER_PRESETS as preset}
<button
onclick={() => applyPreset(preset)}
class="rounded border border-gray-200 px-2.5 py-1 text-xs text-gray-600 hover:bg-gray-50"
>
{preset.name}
</button>
{/each}
</div>
<label class="block">
<span class="text-sm font-medium text-gray-700">Base URL</span>
<input
type="text"
bind:value={baseUrl}
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<label class="block">
<span class="text-sm font-medium text-gray-700">API Key</span>
<input
type="password"
bind:value={apiKey}
placeholder="sk-…"
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<label class="block">
<span class="text-sm font-medium text-gray-700">Model</span>
<input
type="text"
bind:value={model}
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<label class="block">
<span class="text-sm font-medium text-gray-700">Dimensions (optional override)</span>
<input
type="number"
bind:value={dimensions}
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<!-- Test connection row -->
<div class="flex items-center gap-3">
<button <button
onclick={testConnection} type="button"
disabled={testStatus === 'testing'} onclick={() => {
class="rounded-lg border border-gray-300 px-3 py-1.5 text-sm hover:bg-gray-50 disabled:opacity-50" provider = p as 'none' | 'openai' | 'local';
testStatus = 'idle';
testError = null;
}}
class={[
'rounded-lg px-4 py-2 text-sm',
provider === p
? 'bg-blue-600 text-white'
: 'border border-gray-200 text-gray-700 hover:bg-gray-50'
].join(' ')}
> >
{testStatus === 'testing' ? 'Testing…' : 'Test Connection'} {p === 'none' ? 'None (FTS5 only)' : p === 'openai' ? 'OpenAI-compatible' : 'Local Model'}
</button> </button>
{/each}
</div>
{#if testStatus === 'ok'} <!-- None warning -->
<span class="text-sm text-green-600"> {#if provider === 'none'}
Connection successful <div class="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-700">
{#if testDimensions}{testDimensions} dimensions{/if} Search will use keyword matching only. Results may be less relevant for complex questions.
</span> </div>
{:else if testStatus === 'error'} {/if}
<span class="text-sm text-red-600">
{testError} <!-- OpenAI-compatible form -->
</span> {#if provider === 'openai'}
<div class="space-y-3">
<!-- Preset buttons -->
<div class="flex flex-wrap gap-2">
{#each PROVIDER_PRESETS as preset}
<button
type="button"
onclick={() => applyPreset(preset)}
class="rounded border border-gray-200 px-2.5 py-1 text-xs text-gray-600 hover:bg-gray-50"
>
{preset.name}
</button>
{/each}
</div>
<label class="block" for="embedding-base-url">
<span class="text-sm font-medium text-gray-700">Base URL</span>
<input
id="embedding-base-url"
name="baseUrl"
type="text"
autocomplete="url"
bind:value={baseUrl}
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<label class="block" for="embedding-api-key">
<span class="text-sm font-medium text-gray-700">API Key</span>
<input
id="embedding-api-key"
name="apiKey"
type="password"
autocomplete="off"
bind:value={apiKey}
placeholder="sk-…"
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<label class="block" for="embedding-model">
<span class="text-sm font-medium text-gray-700">Model</span>
<input
id="embedding-model"
name="model"
type="text"
autocomplete="off"
bind:value={model}
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<label class="block" for="embedding-dimensions">
<span class="text-sm font-medium text-gray-700">Dimensions (optional override)</span>
<input
id="embedding-dimensions"
name="dimensions"
type="number"
inputmode="numeric"
bind:value={dimensions}
class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
/>
</label>
<!-- Test connection row -->
<div class="flex items-center gap-3">
<button
type="button"
onclick={testConnection}
disabled={testStatus === 'testing'}
class="rounded-lg border border-gray-300 px-3 py-1.5 text-sm hover:bg-gray-50 disabled:opacity-50"
>
{testStatus === 'testing' ? 'Testing…' : 'Test Connection'}
</button>
{#if testStatus === 'ok'}
<span class="text-sm text-green-600">
Connection successful
{#if testDimensions}{testDimensions} dimensions{/if}
</span>
{:else if testStatus === 'error'}
<span class="text-sm text-red-600">
{testError}
</span>
{/if}
</div>
</div>
{/if}
<!-- Local model section -->
{#if provider === 'local'}
<div class="rounded-lg border border-gray-200 bg-gray-50 p-4 text-sm">
<p class="font-medium text-gray-800">Local ONNX model via @xenova/transformers</p>
<p class="mt-1 text-gray-500">Model: Xenova/all-MiniLM-L6-v2 · 384 dimensions</p>
{#if localAvailable === null}
<p class="mt-2 text-gray-400">Checking availability…</p>
{:else if localAvailable}
<p class="mt-2 text-green-600">@xenova/transformers is installed and ready.</p>
{:else}
<p class="mt-2 text-amber-700">
@xenova/transformers is not installed. Run
<code class="rounded bg-amber-100 px-1 py-0.5 font-mono text-xs"
>npm install @xenova/transformers</code
>
to enable local embeddings.
</p>
{/if} {/if}
</div> </div>
</div> {/if}
{/if}
<!-- Local model section --> <!-- Save feedback banners -->
{#if provider === 'local'} {#if saveStatus === 'ok'}
<div class="rounded-lg border border-gray-200 bg-gray-50 p-4 text-sm"> <div
<p class="font-medium text-gray-800">Local ONNX model via @xenova/transformers</p> class="mt-4 flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm font-medium text-green-700"
<p class="mt-1 text-gray-500">Model: Xenova/all-MiniLM-L6-v2 · 384 dimensions</p>
{#if localAvailable === null}
<p class="mt-2 text-gray-400">Checking availability…</p>
{:else if localAvailable}
<p class="mt-2 text-green-600">@xenova/transformers is installed and ready.</p>
{:else}
<p class="mt-2 text-amber-700">
@xenova/transformers is not installed. Run
<code class="rounded bg-amber-100 px-1 py-0.5 font-mono text-xs"
>npm install @xenova/transformers</code
>
to enable local embeddings.
</p>
{/if}
</div>
{/if}
<!-- Save feedback banners -->
{#if saveStatus === 'ok'}
<div
class="mt-4 flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm font-medium text-green-700"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4 shrink-0"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
> >
<path <svg
fill-rule="evenodd" xmlns="http://www.w3.org/2000/svg"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" class="h-4 w-4 shrink-0"
clip-rule="evenodd" viewBox="0 0 20 20"
/> fill="currentColor"
</svg> aria-hidden="true"
Settings saved successfully. >
</div> <path
{:else if saveStatus === 'error'} fill-rule="evenodd"
<div d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
class="mt-4 flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm font-medium text-red-700" clip-rule="evenodd"
> />
<svg </svg>
xmlns="http://www.w3.org/2000/svg" Settings saved successfully.
class="h-4 w-4 shrink-0" </div>
viewBox="0 0 20 20" {:else if saveStatus === 'error'}
fill="currentColor" <div
aria-hidden="true" class="mt-4 flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm font-medium text-red-700"
> >
<path <svg
fill-rule="evenodd" xmlns="http://www.w3.org/2000/svg"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" class="h-4 w-4 shrink-0"
clip-rule="evenodd" viewBox="0 0 20 20"
/> fill="currentColor"
</svg> aria-hidden="true"
{saveError} >
</div> <path
{/if} fill-rule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
clip-rule="evenodd"
/>
</svg>
{saveError}
</div>
{/if}
<!-- Save row --> <!-- Save row -->
<div class="mt-4 flex items-center justify-end"> <div class="mt-4 flex items-center justify-end">
<button <button
onclick={save} type="submit"
disabled={saving} disabled={saving}
class="rounded-lg bg-blue-600 px-4 py-2 text-sm text-white hover:bg-blue-700 disabled:opacity-50" class="rounded-lg bg-blue-600 px-4 py-2 text-sm text-white hover:bg-blue-700 disabled:opacity-50"
> >
{saving ? 'Saving…' : 'Save Settings'} {saving ? 'Saving…' : 'Save Settings'}
</button> </button>
</div> </div>
</form>
{/if} {/if}
</div> </div>