Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

Add provider tests and fix Ollama web search

nash_subedc8c67ecfa
diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsx
index 3e661b8f..b5ec72eb 100644
--- a/src/components/review/review-view.tsx
+++ b/src/components/review/review-view.tsx
@@ -36,6 +36,7 @@ export function ReviewView() {
const handleResolve = useCallback(async (id: string, action: string) => {
const pp = project ? normalizePath(project.path) : ""
+ const item = items.find((i) => i.id === id)
// Deep Research — must be checked FIRST before any fuzzy matching
if (action === "__deep_research__" && project) {
const searchConfig = useWikiStore.getState().searchApiConfig
@@ -43,7 +44,6 @@ export function ReviewView() {
window.alert("Web Search not configured. Go to Settings → Web Search to configure a provider first.")
return
}
- const item = items.find((i) => i.id === id)
if (item) {
const llmConfig = useWikiStore.getState().llmConfig
// Use pre-generated search queries if available, otherwise fall back to title
@@ -106,25 +106,29 @@ export function ReviewView() {
console.error("Failed to save to wiki from review:", err)
resolveItem(id, "Save failed")
}
- } else if (action.startsWith("open:") && project) {
- // Open a page for editing
- const page = action.slice(5)
- const candidates = [
- `${pp}/wiki/${page}`,
- `${pp}/wiki/${page}.md`,
- ]
+ } else if ((action.startsWith("open:") || actionLooksLikeOpen(action)) && project) {
+ // Open a page in the right-side preview without resolving the
+ // review item. Viewing is not the same as accepting / fixing it.
+ const page = action.startsWith("open:")
+ ? action.slice(5)
+ : item?.affectedPages?.[0] ?? item?.sourcePath ?? ""
+ if (!page) return
+ const normalizedPage = normalizePath(page)
+ const candidates = normalizedPage.startsWith(pp)
+ ? [normalizedPage]
+ : normalizedPage.startsWith("wiki/") || normalizedPage.startsWith("raw/")
+ ? [`${pp}/${normalizedPage}`, `${pp}/${normalizedPage}.md`]
+ : [`${pp}/wiki/${normalizedPage}`, `${pp}/wiki/${normalizedPage}.md`]
for (const path of candidates) {
try {
const content = await readFile(path)
useWikiStore.getState().setSelectedFile(path)
useWikiStore.getState().setFileContent(content)
- useWikiStore.getState().setActiveView("wiki")
- break
+ return
} catch {
// try next
}
}
- resolveItem(id, action)
} else if (action.startsWith("delete:") && project) {
// Delete a file
const filePath = action.slice(7)
@@ -142,13 +146,11 @@ export function ReviewView() {
const searchConfig = useWikiStore.getState().searchApiConfig
if (!hasConfiguredSearchProvider(searchConfig)) {
// No search API — fall through to create a page instead
- const item = items.find((i) => i.id === id)
if (item) {
handleResolve(id, "__create_page__:" + action)
}
return
}
- const item = items.find((i) => i.id === id)
if (item) {
const llmConfig = useWikiStore.getState().llmConfig
const topic = action.replace(/^research\s*/i, "").trim() || item.description.split("\n")[0]
@@ -168,7 +170,6 @@ export function ReviewView() {
const realAction = action.startsWith("__create_page__:")
? action.slice("__create_page__:".length)
: action
- const item = items.find((i) => i.id === id)
if (item) {
try {
const title = item.title.replace(/^(Create|Save|Add)[:\s]*/i, "").trim() || "Untitled"
@@ -369,6 +370,20 @@ function actionLooksLikeResearch(action: string): boolean {
)
}
+function actionLooksLikeOpen(action: string): boolean {
+ const lower = action.trim().toLowerCase()
+ return (
+ lower === "open" ||
+ lower === "view" ||
+ lower === "open page" ||
+ lower === "view page" ||
+ lower === "打开" ||
+ lower === "查看" ||
+ lower === "打开页面" ||
+ lower === "查看页面"
+ )
+}
+
/** Detect if an action is a dismissal (no-op) or should create a page */
function actionIsDismissal(action: string): boolean {
const lower = action.toLowerCase()
diff --git a/src/components/settings/sections/embedding-section.tsx b/src/components/settings/sections/embedding-section.tsx
index 2b521cd9..09d060e2 100644
--- a/src/components/settings/sections/embedding-section.tsx
+++ b/src/components/settings/sections/embedding-section.tsx
@@ -4,6 +4,7 @@ import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useWikiStore } from "@/stores/wiki-store"
+import type { EmbeddingConfig } from "@/stores/wiki-store"
import {
dropLegacyVectorTable,
embedAllPages,
@@ -11,6 +12,7 @@ import {
getLastEmbeddingError,
legacyVectorRowCount,
} from "@/lib/embedding"
+import { testEmbeddingConnection, testEmbeddingFunction, type ProviderTestResult } from "@/lib/connection-tests"
import type { SettingsDraft, DraftSetter } from "../settings-types"
interface Props {
@@ -23,6 +25,11 @@ type ReindexState =
| { kind: "running"; done: number; total: number }
| { kind: "done"; count: number }
+type TestState =
+ | { kind: "idle" }
+ | { kind: "running"; label: string }
+ | { kind: "done"; result: ProviderTestResult }
+
function parsePositiveInteger(value: string): number | undefined {
const trimmed = value.trim()
if (trimmed === "") return undefined
@@ -40,6 +47,7 @@ export function EmbeddingSection({ draft, setDraft }: Props) {
const [legacyCount, setLegacyCount] = useState<number>(0)
const [lastError, setLastError] = useState<string | null>(null)
const [reindex, setReindex] = useState<ReindexState>({ kind: "idle" })
+ const [testState, setTestState] = useState<TestState>({ kind: "idle" })
const [legacyDropped, setLegacyDropped] = useState(false)
const refreshStats = useCallback(async () => {
@@ -78,6 +86,30 @@ export function EmbeddingSection({ draft, setDraft }: Props) {
setLegacyDropped(true)
}, [project])
+ const draftEmbeddingConfig: EmbeddingConfig = {
+ enabled: draft.embeddingEnabled,
+ endpoint: draft.embeddingEndpoint,
+ apiKey: draft.embeddingApiKey,
+ model: draft.embeddingModel,
+ outputDimensionality: draft.embeddingOutputDimensionality,
+ maxChunkChars: draft.embeddingMaxChunkChars,
+ overlapChunkChars: draft.embeddingOverlapChunkChars,
+ }
+
+ async function runEmbeddingTest(kind: "connection" | "function") {
+ setTestState({
+ kind: "running",
+ label: kind === "connection"
+ ? t("settings.sections.embedding.testingConnection")
+ : t("settings.sections.embedding.testingFunction"),
+ })
+ const result = kind === "connection"
+ ? await testEmbeddingConnection(draftEmbeddingConfig)
+ : await testEmbeddingFunction(draftEmbeddingConfig)
+ setTestState({ kind: "done", result })
+ setLastError(getLastEmbeddingError())
+ }
+
const showLegacyMigration =
legacyCount > 0 && (chunkCount === null || chunkCount === 0)
@@ -210,6 +242,49 @@ export function EmbeddingSection({ draft, setDraft }: Props) {
</div>
</div>
+ <div className="space-y-3 rounded-md border p-3">
+ <div>
+ <div className="text-sm font-medium">
+ {t("settings.sections.embedding.providerTests")}
+ </div>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("settings.sections.embedding.providerTestsHint")}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void runEmbeddingTest("connection")}
+ disabled={testState.kind === "running"}
+ >
+ {t("settings.sections.embedding.testConnection")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void runEmbeddingTest("function")}
+ disabled={testState.kind === "running"}
+ >
+ {t("settings.sections.embedding.testFunction")}
+ </Button>
+ </div>
+ {testState.kind === "running" && (
+ <p className="text-xs text-muted-foreground">{testState.label}</p>
+ )}
+ {testState.kind === "done" && (
+ <div
+ className={`rounded-md border px-3 py-2 text-xs ${
+ testState.result.ok
+ ? "border-emerald-500/40 bg-emerald-500/5 text-emerald-700 dark:text-emerald-400"
+ : "border-destructive/40 bg-destructive/5 text-destructive"
+ }`}
+ >
+ {testState.result.message}
+ </div>
+ )}
+ </div>
+
{showLegacyMigration && (
<div className="space-y-2 rounded-md border border-destructive/40 bg-destructive/5 p-3">
<div className="text-sm font-medium text-destructive">
diff --git a/src/components/settings/sections/llm-provider-section.tsx b/src/components/settings/sections/llm-provider-section.tsx
index a5337659..44544a63 100644
--- a/src/components/settings/sections/llm-provider-section.tsx
+++ b/src/components/settings/sections/llm-provider-section.tsx
@@ -10,6 +10,7 @@ import { ContextSizeSelector } from "../context-size-selector"
import { resolveConfig } from "../preset-resolver"
import { normalizeEndpoint } from "@/lib/endpoint-normalizer"
import { AZURE_OPENAI_API_VERSION } from "@/lib/azure-openai"
+import { testLlmConnection, testLlmFunction, type ProviderTestResult } from "@/lib/connection-tests"
export function LlmProviderSection() {
const { t } = useTranslation()
@@ -102,6 +103,11 @@ interface PresetRowProps {
onChange: (patch: ProviderOverride) => void
}
+type ProviderTestState =
+ | { kind: "idle" }
+ | { kind: "running"; label: string }
+ | { kind: "done"; result: ProviderTestResult }
+
function PresetRow({
preset,
override,
@@ -121,6 +127,7 @@ function PresetRow({
const azureApiVersion = ov.azureApiVersion ?? preset.azureApiVersion ?? AZURE_OPENAI_API_VERSION
const context = ov.maxContextSize ?? preset.suggestedContextSize ?? 131072
const reasoning = ov.reasoning ?? { mode: "auto" as const }
+ const [testState, setTestState] = useState<ProviderTestState>({ kind: "idle" })
const hasConfig = !!apiKey || !!ov.baseUrl || !!ov.model || !!ov.azureApiVersion
// Local CLI providers authenticate via their own existing login state
// (inherited by the spawned subprocess), so no API key field is shown.
@@ -130,6 +137,24 @@ function PresetRow({
preset.provider !== "claude-code" &&
preset.provider !== "codex-cli"
+ const resolvedConfig = useMemo(
+ () => resolveConfig(preset, ov, useWikiStore.getState().llmConfig),
+ [apiKey, apiMode, azureApiVersion, baseUrl, context, model, preset, reasoning, ov],
+ )
+
+ async function runProviderTest(kind: "connection" | "function") {
+ setTestState({
+ kind: "running",
+ label: kind === "connection"
+ ? t("settings.sections.llm.testingConnection")
+ : t("settings.sections.llm.testingFunction"),
+ })
+ const result = kind === "connection"
+ ? await testLlmConnection(resolvedConfig)
+ : await testLlmFunction(resolvedConfig)
+ setTestState({ kind: "done", result })
+ }
+
return (
<div
className={`rounded-lg border transition-colors ${
@@ -310,6 +335,49 @@ function PresetRow({
value={reasoning}
onChange={(reasoning) => onChange({ reasoning })}
/>
+
+ <div className="space-y-2 rounded-md border p-3">
+ <div>
+ <div className="text-sm font-medium">
+ {t("settings.sections.llm.providerTests")}
+ </div>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("settings.sections.llm.providerTestsHint")}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => void runProviderTest("connection")}
+ disabled={testState.kind === "running"}
+ className="rounded-md border px-3 py-1.5 text-xs hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {t("settings.sections.llm.testConnection")}
+ </button>
+ <button
+ type="button"
+ onClick={() => void runProviderTest("function")}
+ disabled={testState.kind === "running"}
+ className="rounded-md border px-3 py-1.5 text-xs hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {t("settings.sections.llm.testFunction")}
+ </button>
+ </div>
+ {testState.kind === "running" && (
+ <p className="text-xs text-muted-foreground">{testState.label}</p>
+ )}
+ {testState.kind === "done" && (
+ <div
+ className={`rounded-md border px-3 py-2 text-xs ${
+ testState.result.ok
+ ? "border-emerald-500/40 bg-emerald-500/5 text-emerald-700 dark:text-emerald-400"
+ : "border-destructive/40 bg-destructive/5 text-destructive"
+ }`}
+ >
+ {testState.result.message}
+ </div>
+ )}
+ </div>
</div>
)}
</div>
diff --git a/src/components/settings/sections/web-search-section.tsx b/src/components/settings/sections/web-search-section.tsx
index a8c123c0..53f8f8cf 100644
--- a/src/components/settings/sections/web-search-section.tsx
+++ b/src/components/settings/sections/web-search-section.tsx
@@ -9,16 +9,19 @@ import {
type SearchProvider,
type SearchProviderOverride,
} from "@/stores/wiki-store"
-import { SEARXNG_CATEGORY_OPTIONS, SERPAPI_ENGINE_OPTIONS, resolveSearchConfig } from "@/lib/web-search"
+import {
+ SEARXNG_CATEGORY_OPTIONS,
+ SERPAPI_ENGINE_OPTIONS,
+ resolveSearchConfig,
+} from "@/lib/web-search"
const SEARCH_PROVIDERS = [
{
id: "ollama",
- label: "Ollama (Local)",
- hint: "Free web search via your local Ollama instance — no API key required",
- urlPlaceholder: "http://localhost:11434",
- needsApiKey: false,
- isLocal: true,
+ label: "Ollama",
+ hint: "Ollama Web Search API",
+ keyPlaceholder: "Enter your Ollama API key (ollama.com)",
+ needsApiKey: true,
},
{
id: "tavily",
@@ -90,8 +93,6 @@ export function WebSearchSection() {
const isActive = resolvedConfig.provider === provider.id
const hasConfig = provider.id === "searxng"
? !!override?.searXngUrl
- : provider.id === "ollama"
- ? !!override?.ollamaUrl
: !!override?.apiKey
const isExpanded = !!expanded[provider.id]
return (
@@ -159,20 +160,7 @@ export function WebSearchSection() {
{isExpanded && (
<div className="space-y-4 border-t bg-background/50 px-4 py-3">
- {"isLocal" in provider && provider.isLocal ? (
- // Ollama: URL field without API key
- <div className="space-y-2">
- <Label>{t("settings.sections.webSearch.instanceUrl")}</Label>
- <Input
- value={override?.ollamaUrl ?? resolvedConfig.ollamaUrl ?? "http://localhost:11434"}
- onChange={(e) => updateProvider("ollama", { ollamaUrl: e.target.value })}
- placeholder={provider.urlPlaceholder}
- />
- <p className="text-xs text-muted-foreground">
- {t("settings.sections.webSearch.ollamaHint")}
- </p>
- </div>
- ) : provider.needsApiKey ? (
+ {provider.needsApiKey ? (
<div className="space-y-2">
<Label>{t("settings.apiKey")}</Label>
<Input
@@ -181,6 +169,11 @@ export function WebSearchSection() {
onChange={(e) => updateProvider(provider.id, { apiKey: e.target.value })}
placeholder={provider.keyPlaceholder}
/>
+ {provider.id === "ollama" && (
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.webSearch.ollamaHint")}
+ </p>
+ )}
</div>
) : (
<div className="space-y-2">
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 1832324b..8ea36a08 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -217,6 +217,12 @@
"customModelBadge": "Custom: {{model}}",
"endpointPreviewWillUse": "Will resolve to",
"endpointPreviewAutoApply": "(applied automatically when you leave the input)",
+ "providerTests": "Provider tests",
+ "providerTestsHint": "Connection test verifies the endpoint can respond. Functional test asks the model to follow a tiny instruction.",
+ "testConnection": "Test connection",
+ "testFunction": "Test function",
+ "testingConnection": "Testing connection…",
+ "testingFunction": "Testing function…",
"reasoning": {
"title": "Reasoning / thinking",
"auto": "Auto",
@@ -247,6 +253,12 @@
"maxChunkCharsHint": "Target size of each chunk. Lower this (e.g. 500) when your endpoint's context is small (llama.cpp n_ctx=512, mxbai-embed-large, etc.).",
"overlapChunkChars": "Overlap (characters)",
"overlapChunkCharsHint": "Characters of overlap between adjacent chunks so ideas aren't severed at boundaries.",
+ "providerTests": "Provider tests",
+ "providerTestsHint": "Connection test sends one short embedding request. Functional test verifies stable finite vectors and reports the returned dimension.",
+ "testConnection": "Test connection",
+ "testFunction": "Test function",
+ "testingConnection": "Testing embedding connection…",
+ "testingFunction": "Testing embedding function…",
"statsHeading": "Index status",
"chunkCount": "{{count}} chunks indexed",
"lastErrorHeading": "Last embedding error",
@@ -295,7 +307,7 @@
"activeBadge": "Active",
"savedBadge": "Saved",
"instanceUrl": "Instance URL",
- "ollamaHint": "Uses your local Ollama's built-in web search. Make sure Ollama is running and a web-search-capable model is available.",
+ "ollamaHint": "Uses the official Ollama Web Search API (`https://ollama.com/api/web_search`). An Ollama API key is required.",
"searxngJsonHint": "The instance must allow JSON search responses (`format=json`).",
"searchCategories": "Search categories",
"searxngCategoriesHint": "Categories are sent as the SearXNG `categories` parameter.",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index d4170b0a..b78cadcf 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -217,6 +217,12 @@
"customModelBadge": "自定义:{{model}}",
"endpointPreviewWillUse": "将使用",
"endpointPreviewAutoApply": "(离开输入框时自动套用)",
+ "providerTests": "Provider 测试",
+ "providerTestsHint": "连接测试用于确认 endpoint 能正常响应;功能测试会让模型执行一个极小指令。",
+ "testConnection": "测试连接",
+ "testFunction": "测试功能",
+ "testingConnection": "正在测试连接…",
+ "testingFunction": "正在测试功能…",
"reasoning": {
"title": "Reasoning / thinking",
"auto": "自动",
@@ -247,6 +253,12 @@
"maxChunkCharsHint": "单个 chunk 的目标长度。endpoint 上下文较小时(llama.cpp n_ctx=512、mxbai-embed-large 等)调低(如 500)。",
"overlapChunkChars": "重叠字符数",
"overlapChunkCharsHint": "相邻 chunk 之间的重叠字符数,避免语义在边界被切断。",
+ "providerTests": "Provider 测试",
+ "providerTestsHint": "连接测试会发送一次短 embedding 请求;功能测试会验证返回的是稳定、有限的向量,并显示维度。",
+ "testConnection": "测试连接",
+ "testFunction": "测试功能",
+ "testingConnection": "正在测试 embedding 连接…",
+ "testingFunction": "正在测试 embedding 功能…",
"statsHeading": "索引状态",
"chunkCount": "已索引 {{count}} 个 chunk",
"lastErrorHeading": "上次 embedding 错误",
@@ -295,7 +307,7 @@
"activeBadge": "活跃",
"savedBadge": "已保存",
"instanceUrl": "实例 URL",
- "ollamaHint": "使用本地 Ollama 内置的网页搜索功能。请确保 Ollama 正在运行,并且有支持网页搜索的模型可用。",
+ "ollamaHint": "使用官方 Ollama Web Search API(`https://ollama.com/api/web_search`),需要填写 Ollama API Key。",
"searxngJsonHint": "实例必须允许 JSON 搜索响应(`format=json`)。",
"searchCategories": "搜索分类",
"searxngCategoriesHint": "分类会作为 SearXNG 的 `categories` 参数发送。",
diff --git a/src/lib/connection-tests.test.ts b/src/lib/connection-tests.test.ts
new file mode 100644
index 00000000..ddbee03b
--- /dev/null
+++ b/src/lib/connection-tests.test.ts
@@ -0,0 +1,98 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { EmbeddingConfig, LlmConfig } from "@/stores/wiki-store"
+import {
+ testEmbeddingConnection,
+ testEmbeddingFunction,
+ testLlmConnection,
+ testLlmFunction,
+} from "./connection-tests"
+import { fetchEmbedding, getLastEmbeddingError } from "@/lib/embedding"
+import { streamChat } from "@/lib/llm-client"
+
+vi.mock("@/lib/embedding", () => ({
+ fetchEmbedding: vi.fn(),
+ getLastEmbeddingError: vi.fn(),
+}))
+
+vi.mock("@/lib/llm-client", () => ({
+ streamChat: vi.fn(),
+}))
+
+const fetchEmbeddingMock = vi.mocked(fetchEmbedding)
+const getLastEmbeddingErrorMock = vi.mocked(getLastEmbeddingError)
+const streamChatMock = vi.mocked(streamChat)
+
+const embeddingConfig: EmbeddingConfig = {
+ enabled: true,
+ endpoint: "http://localhost:1234/v1/embeddings",
+ apiKey: "",
+ model: "text-embedding-test",
+}
+
+const llmConfig: LlmConfig = {
+ provider: "custom",
+ apiKey: "",
+ model: "test-model",
+ ollamaUrl: "http://localhost:11434",
+ customEndpoint: "http://localhost:1234/v1",
+ maxContextSize: 4096,
+ apiMode: "chat_completions",
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ getLastEmbeddingErrorMock.mockReturnValue(null)
+})
+
+describe("provider connection tests", () => {
+ it("reports embedding connection dimensions", async () => {
+ fetchEmbeddingMock.mockResolvedValueOnce([0.1, 0.2, 0.3])
+
+ const result = await testEmbeddingConnection(embeddingConfig)
+
+ expect(result.ok).toBe(true)
+ expect(result.message).toContain("3 dimensions")
+ expect(fetchEmbeddingMock).toHaveBeenCalledWith(expect.any(String), embeddingConfig, 0)
+ })
+
+ it("fails embedding functional test when dimensions are unstable", async () => {
+ fetchEmbeddingMock
+ .mockResolvedValueOnce([0.1, 0.2])
+ .mockResolvedValueOnce([0.1, 0.2, 0.3])
+
+ const result = await testEmbeddingFunction(embeddingConfig)
+
+ expect(result.ok).toBe(false)
+ expect(result.message).toContain("dimension changed")
+ })
+
+ it("passes LLM connection when any content is streamed", async () => {
+ streamChatMock.mockImplementationOnce(async (_cfg, _messages, callbacks) => {
+ callbacks.onToken("OK")
+ callbacks.onDone()
+ })
+
+ const result = await testLlmConnection(llmConfig)
+
+ expect(result.ok).toBe(true)
+ expect(result.message).toContain("Response: OK")
+ })
+
+ it("validates LLM functional output token", async () => {
+ streamChatMock.mockImplementationOnce(async (_cfg, _messages, callbacks) => {
+ callbacks.onToken("LLM_WIKI_TEST_OK")
+ callbacks.onDone()
+ })
+
+ const result = await testLlmFunction(llmConfig)
+
+ expect(result.ok).toBe(true)
+ expect(streamChatMock).toHaveBeenCalledWith(
+ llmConfig,
+ expect.any(Array),
+ expect.any(Object),
+ undefined,
+ { max_tokens: 32, reasoning: { mode: "off" } },
+ )
+ })
+})
diff --git a/src/lib/connection-tests.ts b/src/lib/connection-tests.ts
new file mode 100644
index 00000000..21e49614
--- /dev/null
+++ b/src/lib/connection-tests.ts
@@ -0,0 +1,122 @@
+import type { EmbeddingConfig, LlmConfig } from "@/stores/wiki-store"
+import { fetchEmbedding, getLastEmbeddingError } from "@/lib/embedding"
+import { streamChat } from "@/lib/llm-client"
+
+export interface ProviderTestResult {
+ ok: boolean
+ message: string
+}
+
+export async function testEmbeddingConnection(cfg: EmbeddingConfig): Promise<ProviderTestResult> {
+ if (!cfg.endpoint.trim()) {
+ return { ok: false, message: "Embedding endpoint is empty." }
+ }
+ if (!cfg.model.trim()) {
+ return { ok: false, message: "Embedding model is empty." }
+ }
+
+ const started = performance.now()
+ const vector = await fetchEmbedding("LLM Wiki embedding connection test.", cfg, 0)
+ if (!vector) {
+ return {
+ ok: false,
+ message: getLastEmbeddingError() ?? "Embedding endpoint returned no vector.",
+ }
+ }
+
+ return {
+ ok: true,
+ message: `Connected. Returned ${vector.length} dimensions in ${Math.round(performance.now() - started)} ms.`,
+ }
+}
+
+export async function testEmbeddingFunction(cfg: EmbeddingConfig): Promise<ProviderTestResult> {
+ const first = await fetchEmbedding("LLM Wiki functional embedding test: apple banana graph.", cfg, 0)
+ const second = await fetchEmbedding("LLM Wiki functional embedding test: apple banana graph.", cfg, 0)
+ if (!first || !second) {
+ return {
+ ok: false,
+ message: getLastEmbeddingError() ?? "Embedding endpoint did not return vectors.",
+ }
+ }
+ if (first.length !== second.length) {
+ return {
+ ok: false,
+ message: `Embedding dimension changed between calls (${first.length} vs ${second.length}).`,
+ }
+ }
+ if (first.length === 0 || first.some((v) => !Number.isFinite(v)) || second.some((v) => !Number.isFinite(v))) {
+ return { ok: false, message: "Embedding endpoint returned an empty or non-finite vector." }
+ }
+
+ const norm = Math.sqrt(first.reduce((sum, v) => sum + v * v, 0))
+ if (!Number.isFinite(norm) || norm <= 0) {
+ return { ok: false, message: "Embedding vector norm is zero or invalid." }
+ }
+
+ return {
+ ok: true,
+ message: `Functional test passed. Stable ${first.length}-dimension finite vectors returned.`,
+ }
+}
+
+export async function testLlmConnection(cfg: LlmConfig): Promise<ProviderTestResult> {
+ const started = performance.now()
+ let content = ""
+ let errorMessage: string | null = null
+
+ await streamChat(
+ cfg,
+ [
+ { role: "system", content: "You are a connection checker. Reply briefly." },
+ { role: "user", content: "Reply with one short word." },
+ ],
+ {
+ onToken: (token) => { content += token },
+ onDone: () => {},
+ onError: (err) => { errorMessage = err.message },
+ },
+ undefined,
+ { max_tokens: 32, reasoning: { mode: "off" } },
+ )
+
+ if (errorMessage) return { ok: false, message: errorMessage }
+ if (!content.trim()) return { ok: false, message: "Model connected but returned empty content." }
+ return {
+ ok: true,
+ message: `Connected in ${Math.round(performance.now() - started)} ms. Response: ${content.trim().slice(0, 80)}`,
+ }
+}
+
+export async function testLlmFunction(cfg: LlmConfig): Promise<ProviderTestResult> {
+ let content = ""
+ let errorMessage: string | null = null
+
+ await streamChat(
+ cfg,
+ [
+ {
+ role: "system",
+ content: "You are a deterministic API test. Do not explain. Output only the requested token.",
+ },
+ { role: "user", content: "Output exactly this token and nothing else: LLM_WIKI_TEST_OK" },
+ ],
+ {
+ onToken: (token) => { content += token },
+ onDone: () => {},
+ onError: (err) => { errorMessage = err.message },
+ },
+ undefined,
+ { max_tokens: 32, reasoning: { mode: "off" } },
+ )
+
+ if (errorMessage) return { ok: false, message: errorMessage }
+ const trimmed = content.trim()
+ if (!trimmed.includes("LLM_WIKI_TEST_OK")) {
+ return {
+ ok: false,
+ message: `Model responded, but did not follow the functional test prompt. Response: ${trimmed.slice(0, 120) || "(empty)"}`,
+ }
+ }
+ return { ok: true, message: "Functional test passed. The model returned the expected token." }
+}
diff --git a/src/lib/web-search.test.ts b/src/lib/web-search.test.ts
index 3b21ff2f..70d9889a 100644
--- a/src/lib/web-search.test.ts
+++ b/src/lib/web-search.test.ts
@@ -175,4 +175,77 @@ describe("webSearch", () => {
serpApiEngine: "google",
})).toBe(true)
})
+
+ it("requires an API key for the Ollama Web Search API", async () => {
+ await expect(webSearch(
+ "official ollama",
+ {
+ provider: "ollama",
+ apiKey: "",
+ providerConfigs: {
+ ollama: { ollamaUrl: "https://ollama.com" },
+ },
+ },
+ 5,
+ )).rejects.toThrow("requires an Ollama API key")
+
+ expect(hasConfiguredSearchProvider({
+ provider: "ollama",
+ apiKey: "",
+ providerConfigs: {
+ ollama: { ollamaUrl: "https://ollama.com" },
+ },
+ })).toBe(false)
+ })
+
+ it("calls the Ollama Web Search API with Bearer auth", async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({
+ results: [
+ { title: "Official", url: "https://ollama.example/search", content: "Cloud result" },
+ ],
+ }))
+
+ const out = await webSearch(
+ "official ollama",
+ {
+ provider: "ollama",
+ apiKey: "",
+ providerConfigs: {
+ ollama: { apiKey: "ollama-key" },
+ },
+ },
+ 1,
+ )
+ const [url, init] = fetchMock.mock.calls[0]
+
+ expect(url).toBe("https://ollama.com/api/web_search")
+ expect((init?.headers as Record<string, string>).Authorization).toBe("Bearer ollama-key")
+ expect(JSON.parse(String(init?.body))).toEqual({ query: "official ollama", max_results: 1 })
+ expect(out).toEqual([
+ { title: "Official", url: "https://ollama.example/search", snippet: "Cloud result", source: "ollama.example" },
+ ])
+ expect(hasConfiguredSearchProvider({
+ provider: "ollama",
+ apiKey: "",
+ providerConfigs: {
+ ollama: { apiKey: "ollama-key" },
+ },
+ })).toBe(true)
+ })
+
+ it("surfaces Ollama authentication guidance for 401 responses", async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, { status: 401 }))
+
+ await expect(webSearch(
+ "official ollama",
+ {
+ provider: "ollama",
+ apiKey: "",
+ providerConfigs: {
+ ollama: { apiKey: "bad-key" },
+ },
+ },
+ 5,
+ )).rejects.toThrow("Check your Ollama API key")
+ })
})
diff --git a/src/lib/web-search.ts b/src/lib/web-search.ts
index 93ec0f05..678560fe 100644
--- a/src/lib/web-search.ts
+++ b/src/lib/web-search.ts
@@ -77,7 +77,7 @@ export function resolveSearchConfig(config: SearchApiConfig): SearchApiConfig {
serpApiEngine: config.serpApiEngine ?? providerConfigs.serpapi?.serpApiEngine ?? "google",
searXngUrl: config.searXngUrl ?? providerConfigs.searxng?.searXngUrl ?? "",
searXngCategories: config.searXngCategories ?? providerConfigs.searxng?.searXngCategories ?? ["general"],
- ollamaUrl: config.ollamaUrl ?? providerConfigs.ollama?.ollamaUrl ?? "http://localhost:11434",
+ ollamaUrl: config.ollamaUrl ?? providerConfigs.ollama?.ollamaUrl ?? "https://ollama.com",
providerConfigs,
}
}
@@ -90,7 +90,7 @@ export function resolveSearchConfig(config: SearchApiConfig): SearchApiConfig {
serpApiEngine: activeOverride?.serpApiEngine ?? config.serpApiEngine ?? "google",
searXngUrl: activeOverride?.searXngUrl ?? config.searXngUrl ?? "",
searXngCategories: activeOverride?.searXngCategories ?? config.searXngCategories ?? ["general"],
- ollamaUrl: activeOverride?.ollamaUrl ?? config.ollamaUrl ?? "http://localhost:11434",
+ ollamaUrl: activeOverride?.ollamaUrl ?? config.ollamaUrl ?? "https://ollama.com",
providerConfigs,
}
}
@@ -102,7 +102,7 @@ export function hasConfiguredSearchProvider(config: SearchApiConfig): boolean {
return Boolean(resolved.searXngUrl?.trim())
}
if (resolved.provider === "ollama") {
- return true // Ollama uses default localhost URL if not configured
+ return Boolean(resolved.apiKey?.trim())
}
return Boolean(resolved.apiKey?.trim())
}
@@ -122,6 +122,9 @@ export async function webSearch(
if (resolved.provider === "searxng" && !resolved.searXngUrl?.trim()) {
throw new Error("Web search not configured. Add a SearXNG instance URL in Settings.")
}
+ if (resolved.provider === "ollama" && !resolved.apiKey?.trim()) {
+ throw new Error("Ollama Web Search API requires an Ollama API key. Add one in Settings.")
+ }
switch (resolved.provider) {
case "tavily":
@@ -131,7 +134,7 @@ export async function webSearch(
case "searxng":
return searXngSearch(query, resolved.searXngUrl ?? "", maxResults, resolved.searXngCategories ?? ["general"])
case "ollama":
- return ollamaSearch(query, resolved.ollamaUrl ?? "http://localhost:11434", maxResults)
+ return ollamaSearch(query, resolved.apiKey ?? "", maxResults)
default:
throw new Error(`Unknown search provider: ${resolved.provider}`)
}
@@ -367,18 +370,28 @@ interface OllamaSearchResponse {
async function ollamaSearch(
query: string,
- ollamaUrl: string,
+ apiKey: string,
maxResults: number,
): Promise<WebSearchResult[]> {
- const baseUrl = ollamaUrl.replace(/\/+$/, "")
- const searchUrl = `${baseUrl}/api/experimental/web_search`
+ const trimmedApiKey = apiKey.trim()
+ if (!trimmedApiKey) {
+ throw new Error("Ollama Web Search API requires an Ollama API key. Add one in Settings.")
+ }
+
+ const headers: Record<string, string> = {
+ Accept: "application/json",
+ "Content-Type": "application/json",
+ }
+ if (trimmedApiKey) {
+ headers.Authorization = `Bearer ${trimmedApiKey}`
+ }
const httpFetch = await getHttpFetch()
let response: Response
try {
- response = await httpFetch(searchUrl, {
+ response = await httpFetch("https://ollama.com/api/web_search", {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers,
body: JSON.stringify({
query,
max_results: maxResults,
@@ -387,7 +400,7 @@ async function ollamaSearch(
} catch (err) {
if (isFetchNetworkError(err)) {
throw new Error(
- `Network error reaching Ollama at ${baseUrl}. Make sure Ollama is running and web search is enabled.`,
+ "Network error reaching the Ollama Web Search API. Check your connectivity and whether the Ollama API key is still valid.",
)
}
throw err
@@ -396,7 +409,7 @@ async function ollamaSearch(
if (!response.ok) {
if (response.status === 401) {
throw new Error(
- "Ollama requires authentication. Run `ollama signin` in your terminal to authenticate.",
+ "Ollama Web Search API authentication failed. Check your Ollama API key.",
)
}
const errorText = await response.text().catch(() => "Unknown error")