diff --git a/README.md b/README.md index d25e70dd..acbdcc74 100644 --- a/README.md +++ b/README.md @@ -270,10 +270,12 @@ If you have chatted for a while and still see the message, check that auto-captu ### Web UI -Open `http://127.0.0.1:4747` to browse the memory–prompt timeline, inspect captures, and manage the user profile. The UI has five views: **Project memories** (`/project-memories`), **User profile** (`/user-profile`), **Skill library** (`/skill-library`), **Markdown vault** (`/markdown-vault`) and **Stats** (`/stats`). Change the port with `webServerPort`, or set `webServerEnabled: false` to run without the web UI. If you bind the server beyond loopback, see [Web UI HTTP Basic Auth](#web-ui-http-basic-auth). +Open `http://127.0.0.1:4747` to browse the memory–prompt timeline, inspect captures, and manage the user profile. The UI has six views: **Project memories** (`/project-memories`), **User profile** (`/user-profile`), **Skill library** (`/skill-library`), **Markdown vault** (`/markdown-vault`), **Stats** (`/stats`) and **Model** (`/model-settings`). Change the port with `webServerPort`, or set `webServerEnabled: false` to run without the web UI. If you bind the server beyond loopback, see [Web UI HTTP Basic Auth](#web-ui-http-basic-auth). The timeline shows each memory and prompt once. If several capture prompts refer to one memory, its current prompt is paired with it when available on the page; earlier prompts remain visible as separate entries. +The tag-migration dialog picks the provider/model used for tagging. Because tag migration has no live session, `opencodeModel: "inherit"` cannot be used there, so the dialog lists OpenCode's connected providers and models, lets you choose one, and writes `opencodeProvider` / `opencodeModel` back to the config file that supplied them (global or project). The running plugin reloads the config in place, so no restart is needed. + ## Usage Examples ```typescript diff --git a/src/config.ts b/src/config.ts index d0996081..cbbf4815 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1680,11 +1680,15 @@ export function hasAutoCaptureProviderConfig(config: RuntimeConfig = CONFIG): bo return getAutoCaptureProviderStatus(config).ready; } -export function initConfig(directory: string): void { - const projectPaths = [ +function projectConfigPaths(directory: string): string[] { + return [ join(directory, ".opencode", "opencode-mem.jsonc"), join(directory, ".opencode", "opencode-mem.json"), ]; +} + +export function initConfig(directory: string): void { + const projectPaths = projectConfigPaths(directory); const globalConfig = loadConfigFromPaths(CONFIG_FILES); const projectConfig = loadConfigFromPaths(projectPaths); assertProjectRemoteProviderConfigIsSafe(projectConfig); @@ -1698,3 +1702,23 @@ export function initConfig(directory: string): void { export function isConfigured(): boolean { return true; } + +/** + * Config file that owns a model override written from the web UI: a project + * config that already sets opencodeProvider/opencodeModel wins (that is where + * the running value comes from), then the first existing global file, then a + * new global .jsonc. + */ +export function resolveModelConfigPath(projectDirectory?: string): string { + if (projectDirectory) { + for (const path of projectConfigPaths(projectDirectory)) { + if (!existsSync(path)) continue; + const config = loadConfigFromPaths([path]); + if (config.opencodeProvider || config.opencodeModel) return path; + } + } + for (const path of CONFIG_FILES) { + if (existsSync(path)) return path; + } + return CONFIG_FILES[0] ?? join(CONFIG_DIR, "opencode-mem.jsonc"); +} diff --git a/src/index.ts b/src/index.ts index 2dc657d5..e224aabb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,7 @@ import { CaptureEvidenceRecorder } from "./services/capture-evidence.js"; import { performUserProfileLearning } from "./services/user-memory-learning.js"; import { userPromptManager } from "./services/user-prompt/user-prompt-manager.js"; import { startWebServer, WebServer } from "./services/web-server.js"; +import type { ProviderDirectoryEntry } from "./services/api-handlers.js"; import { ensureTursoReady } from "./services/turso/ready.js"; import { tursoConnectionManager } from "./services/turso/connection-manager.js"; import { retainPluginTurso } from "./services/turso/plugin-refs.js"; @@ -422,8 +423,18 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => { try { const providerResult = await ctx.client.provider.list(); if (providerResult.data?.connected) { - const { setConnectedProviders } = await loadOpencodeProvider(); + const { setConnectedProviders, setProviderCatalog } = await loadOpencodeProvider(); setConnectedProviders(providerResult.data.connected); + setProviderCatalog( + (providerResult.data.all ?? []).map((provider) => ({ + id: provider.id, + name: provider.name ?? provider.id, + models: Object.values(provider.models ?? {}).map((model) => ({ + id: model.id, + name: model.name ?? model.id, + })), + })) + ); log("opencode providers connected", { list: providerResult.data.connected, configured: CONFIG.opencodeProvider || "(not set)", @@ -438,6 +449,37 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => { } }; + // Fresh provider directory for the web UI: the module-level snapshot can be + // empty when the host registers providers after the last event refresh. The + // V2 host passes its native catalog, because its client only knows which + // provider ids are connected. + // Reload through this module's config instance: a dynamic import inside the + // web handlers can resolve to a second copy of config.js under bundling. + const reloadConfig = () => initConfig(directory); + const loadProviderDirectory = + (ctx as { providerDirectory?: () => Promise }).providerDirectory ?? + (async (): Promise => { + const providerResult = await ctx.client.provider.list(); + const data = (providerResult.data ?? {}) as { + all?: Array<{ + id: string; + name?: string; + models?: Record; + }>; + connected?: string[]; + }; + const connected = data.connected ?? []; + return (data.all ?? []).map((provider) => ({ + id: provider.id, + name: provider.name ?? provider.id, + connected: connected.includes(provider.id), + models: Object.values(provider.models ?? {}).map((model) => ({ + id: model.id, + name: model.name ?? model.id, + })), + })); + }); + // Coalesce refresh triggers into one in-flight pass plus trailing drain. // Event handlers and ensureProviderConnected (gate miss) share this path so // concurrent list() calls collapse; callers can await the same promise. @@ -529,6 +571,9 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => { enabled: CONFIG.webServerEnabled, auth: webAuth, apiToken: CONFIG.webServerApiToken, + projectDirectory: directory, + loadProviderDirectory, + reloadConfig, }) .then((server) => { webServer = server; diff --git a/src/services/ai/opencode-provider.ts b/src/services/ai/opencode-provider.ts index 49712ce5..bc67cfd3 100644 --- a/src/services/ai/opencode-provider.ts +++ b/src/services/ai/opencode-provider.ts @@ -132,6 +132,23 @@ export function setConnectedProviders(providers: string[]): void { _connectedProviders = new Set(providers); } +/** Provider directory snapshot (id, display name, models) for config UIs. */ +export type ProviderCatalogEntry = { + id: string; + name: string; + models: Array<{ id: string; name: string }>; +}; + +let _providerCatalog: ProviderCatalogEntry[] = []; + +export function setProviderCatalog(providers: ProviderCatalogEntry[]): void { + _providerCatalog = providers; +} + +export function getProviderCatalog(): ProviderCatalogEntry[] { + return _providerCatalog; +} + export function isProviderConnected(providerName: string): boolean { return _connectedProviders.has(providerName); } diff --git a/src/services/api-handlers.ts b/src/services/api-handlers.ts index 1e4ef7f8..46508c12 100644 --- a/src/services/api-handlers.ts +++ b/src/services/api-handlers.ts @@ -7,6 +7,7 @@ import { formatTagsForEmbedding } from "./turso/vector-utils.js"; import { extractScopeFromContainerTag, tryExtractScopeFromContainerTag } from "./memory-scope.js"; import { log } from "./logger.js"; import { CONFIG } from "../config.js"; +import { MODEL_ID_PATTERN, writeModelOverride, type ModelOverride } from "./model-config-writer.js"; import type { MemoryType } from "../types/index.js"; import { userPromptManager } from "./user-prompt/user-prompt-manager.js"; import type { UserProfileData } from "./user-profile/types.js"; @@ -1708,6 +1709,124 @@ export async function handleGetTagMigrationProgress(): Promise; + }>; +} + +export type ProviderDirectoryEntry = { + id: string; + name: string; + connected: boolean; + models: Array<{ id: string; name: string }>; +}; + +export async function handleGetTagMigrationModel( + loadDirectory?: () => Promise +): Promise> { + const status: TagMigrationModelStatus = { + configured: isOpencodeTagMigrationConfigured(), + providerID: CONFIG.opencodeProvider ?? null, + modelID: CONFIG.opencodeModel ?? null, + }; + + try { + const { loadOpencodeProvider } = await import("./ai/opencode-provider-loader.js"); + const { getProviderCatalog, isProviderConnected } = await loadOpencodeProvider(); + let catalog: ProviderDirectoryEntry[] = getProviderCatalog().map((provider) => ({ + id: provider.id, + name: provider.name, + connected: isProviderConnected(provider.id), + models: provider.models, + })); + // The snapshot is empty when the host has not refreshed it in this module + // instance yet; ask the host directly in that case. + if (catalog.length === 0 && loadDirectory) { + catalog = await loadDirectory(); + } + if (catalog.length === 0) { + return { + success: true, + data: { + ...status, + available: false, + reason: "provider directory not loaded", + providers: [], + }, + }; + } + return { + success: true, + data: { ...status, available: true, providers: catalog }, + }; + } catch (error) { + return { success: false, error: String(error) }; + } +} + +export async function handleSetTagMigrationModel( + body: unknown, + projectDirectory?: string, + reloadConfig?: () => void +): Promise< + ApiResponse<{ + writtenTo: string; + providerID: string; + modelID: string; + requiresReload: boolean; + }> +> { + const input = (body ?? {}) as Partial; + const providerID = typeof input.providerID === "string" ? input.providerID.trim() : ""; + const modelID = typeof input.modelID === "string" ? input.modelID.trim() : ""; + if (!MODEL_ID_PATTERN.test(providerID) || !MODEL_ID_PATTERN.test(modelID)) { + return { + success: false, + error: "providerID and modelID must be non-empty provider/model identifiers", + }; + } + + try { + // Loaded lazily so config mocks in the test suite keep working. + const { initConfig, resolveModelConfigPath } = await import("../config.js"); + const writtenTo = resolveModelConfigPath(projectDirectory); + writeModelOverride(writtenTo, { providerID, modelID }); + + // Reload so the running process picks the new values up without a restart. + // The plugin's own reload wins: under bundling the lazily imported config + // module is a second copy, and reloading it would change nothing here. + let requiresReload = true; + if (reloadConfig) { + reloadConfig(); + } else if (projectDirectory) { + initConfig(projectDirectory); + } + if (reloadConfig || projectDirectory) { + requiresReload = CONFIG.opencodeProvider !== providerID || CONFIG.opencodeModel !== modelID; + } + + log("tag-migration model override saved", { writtenTo, providerID, modelID, requiresReload }); + return { success: true, data: { writtenTo, providerID, modelID, requiresReload } }; + } catch (error) { + log("tag-migration model override failed", { error: String(error) }); + return { success: false, error: String(error) }; + } +} + type TagMigrationChannel = "opencode" | "external"; function isOpencodeTagMigrationConfigured(): boolean { diff --git a/src/services/model-config-writer.ts b/src/services/model-config-writer.ts new file mode 100644 index 00000000..6a610717 --- /dev/null +++ b/src/services/model-config-writer.ts @@ -0,0 +1,142 @@ +import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { stripJsoncComments } from "./jsonc.js"; + +export type ModelOverride = { + providerID: string; + modelID: string; +}; + +/** Provider/model ids as the host reports them; slashes appear in ids like "auto/glm-5.3-flash". */ +export const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9._/-]*$/; + +const KEYS = [ + ["providerID", "opencodeProvider"], + ["modelID", "opencodeModel"], +] as const; + +/** + * Tracks block-comment state across lines. A "/*" inside a string or a // + * comment (e.g. the docs line mentioning /api/*) must not open a block. + */ +function endsInsideBlockComment(line: string, inBlock: boolean): boolean { + let i = 0; + while (i < line.length) { + if (inBlock) { + if (line.startsWith("*/", i)) { + inBlock = false; + i += 2; + continue; + } + i += 1; + continue; + } + if (line[i] === '"') { + i += 1; + while (i < line.length) { + if (line[i] === "\\") { + i += 2; + continue; + } + if (line[i] === '"') { + i += 1; + break; + } + i += 1; + } + continue; + } + if (line.startsWith("//", i)) return false; + if (line.startsWith("/*", i)) { + inBlock = true; + i += 2; + continue; + } + i += 1; + } + return inBlock; +} + +/** + * Rewrites only the opencodeProvider/opencodeModel values in place so comments + * and layout survive. Missing keys are appended to the root object. + * The caller must validate the result before writing it to disk. + */ +export function applyModelOverride(content: string, override: ModelOverride): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = (content.trim().length > 0 ? content : `{${eol}}`).split(/\r?\n/); + + const found = new Set(); + let inBlockComment = false; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!; + if (!inBlockComment) { + for (const [field, key] of KEYS) { + const pattern = new RegExp(`^(\\s*"${key}"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*")`); + const match = pattern.exec(line); + if (!match) continue; + lines[i] = `${match[1]}${JSON.stringify(override[field])}${line.slice(match[0].length)}`; + found.add(key); + } + } + inBlockComment = endsInsideBlockComment(line, inBlockComment); + } + + const missing = KEYS.filter(([, key]) => !found.has(key)); + if (missing.length > 0) { + let closing = -1; + for (let i = lines.length - 1; i >= 0; i--) { + if (lines[i]!.trim() === "}") { + closing = i; + break; + } + } + if (closing === -1) { + throw new Error("model-config: target file has no root object"); + } + + // The member that becomes second-to-last needs a separating comma. + let previous = closing - 1; + while (previous >= 0 && lines[previous]!.trim() === "") previous--; + if (previous >= 0) { + const trimmed = lines[previous]!.trimEnd(); + if (!trimmed.endsWith(",") && !trimmed.endsWith("{")) { + lines[previous] = `${trimmed},`; + } + } + + const inserted = missing.map( + ([field, key]) => ` "${key}": ${JSON.stringify(override[field])},` + ); + inserted[inserted.length - 1] = inserted[inserted.length - 1]!.replace(/,$/, ""); + lines.splice(closing, 0, ...inserted); + } + + return lines.join(eol); +} + +/** + * Writes the override to `targetPath` via tmp + rename. The rewritten content + * must still parse as JSONC and carry the requested values, otherwise nothing + * is written and the original file stays untouched. + */ +export function writeModelOverride(targetPath: string, override: ModelOverride): void { + const original = existsSync(targetPath) ? readFileSync(targetPath, "utf-8") : ""; + const next = applyModelOverride(original, override); + + const parsed = JSON.parse(stripJsoncComments(next)) as Record; + if ( + parsed.opencodeProvider !== override.providerID || + parsed.opencodeModel !== override.modelID + ) { + throw new Error("model-config: rewrite would not apply the requested override"); + } + + const tmpPath = `${targetPath}.tmp-${process.pid}-${Date.now()}`; + try { + writeFileSync(tmpPath, next, "utf-8"); + renameSync(tmpPath, targetPath); + } finally { + if (existsSync(tmpPath)) unlinkSync(tmpPath); + } +} diff --git a/src/services/web-server.ts b/src/services/web-server.ts index bcf74898..a10a42d7 100644 --- a/src/services/web-server.ts +++ b/src/services/web-server.ts @@ -32,6 +32,9 @@ import { handleDetectTagMigration, handleRunTagMigrationBatch, handleGetTagMigrationProgress, + handleGetTagMigrationModel, + handleSetTagMigrationModel, + type ProviderDirectoryEntry, handleDeletePrompt, handleBulkDeletePrompts, handleGetUserProfile, @@ -228,6 +231,12 @@ interface WebServerConfig { enabled: boolean; auth?: WebAuth; apiToken?: string; + /** Project root used for project-scoped config writes and reloads. */ + projectDirectory?: string; + /** Fresh provider directory straight from the host (snapshot may be empty). */ + loadProviderDirectory?: () => Promise; + /** Reloads the running config after a config file write. */ + reloadConfig?: () => void; } export class WebServer { @@ -685,6 +694,21 @@ export class WebServer { return this.jsonResponse(result); } + if (path === "/api/config/model-provider" && method === "GET") { + const result = await handleGetTagMigrationModel(this.config.loadProviderDirectory); + return this.jsonResponse(result); + } + + if (path === "/api/config/model-provider" && method === "PUT") { + const body = (await req.json()) as any; + const result = await handleSetTagMigrationModel( + body, + this.config.projectDirectory, + this.config.reloadConfig + ); + return this.jsonResponse(result, result.success ? 200 : 400); + } + if (path === "/api/migration/run" && method === "POST") { const body = (await req.json()) as any; const strategy = body.strategy || "fresh-start"; diff --git a/src/v2/plugin.ts b/src/v2/plugin.ts index 19153a54..b8fa32fb 100644 --- a/src/v2/plugin.ts +++ b/src/v2/plugin.ts @@ -18,6 +18,26 @@ const OpenCodeMemPluginV2: Plugin = { worktree: ctx.location.project.directory, project: ctx.location.project, serverUrl: undefined, + // The v2 client only exposes connected provider ids, so the web UI builds + // its picker straight from the native provider/model directories. + providerDirectory: async () => { + const [providers, models] = await Promise.all([ctx.provider.list(), ctx.model.list()]); + const connected = new Set( + providers.data + .filter( + (provider) => provider.activation === "auto" || provider.activation === "enabled" + ) + .map((provider) => provider.id) + ); + return providers.data.map((provider) => ({ + id: provider.id, + name: provider.name ?? provider.id, + connected: connected.has(provider.id), + models: models.data + .filter((model) => model.providerID === provider.id) + .map((model) => ({ id: model.modelID, name: model.name ?? model.modelID })), + })); + }, } as any)) as any; // The V1 initializer cannot discover a server URL from a native V2 diff --git a/tests/model-config-writer.test.ts b/tests/model-config-writer.test.ts new file mode 100644 index 00000000..9fac29ad --- /dev/null +++ b/tests/model-config-writer.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveModelConfigPath } from "../src/config"; +import { + applyModelOverride, + MODEL_ID_PATTERN, + writeModelOverride, +} from "../src/services/model-config-writer"; +import { stripJsoncComments } from "../src/services/jsonc"; + +function parse(content: string): Record { + return JSON.parse(stripJsoncComments(content)) as Record; +} + +describe("applyModelOverride", () => { + it("replaces existing values and keeps comments and sibling keys", () => { + const content = `{ + // Structured-output provider for tag migration + "opencodeProvider": "magpie", + /* model selection */ + "opencodeModel": "inherit", + "storagePath": "~/.opencode-mem/data", +} +`; + const next = applyModelOverride(content, { providerID: "magpie", modelID: "deepseek-v4" }); + + expect(parse(next)).toMatchObject({ + opencodeProvider: "magpie", + opencodeModel: "deepseek-v4", + storagePath: "~/.opencode-mem/data", + }); + expect(next).toContain("// Structured-output provider for tag migration"); + expect(next).toContain("/* model selection */"); + }); + + it("appends missing keys to the root object", () => { + const content = `{ + "storagePath": "~/.opencode-mem/data" +}`; + const next = applyModelOverride(content, { providerID: "magpie", modelID: "deepseek-v4" }); + + expect(parse(next)).toEqual({ + storagePath: "~/.opencode-mem/data", + opencodeProvider: "magpie", + opencodeModel: "deepseek-v4", + }); + }); + + it("appends missing keys when the last member already has a trailing comma", () => { + const content = `{ + "storagePath": "~/data", +}`; + const next = applyModelOverride(content, { providerID: "magpie", modelID: "deepseek-v4" }); + + expect(parse(next)).toMatchObject({ opencodeProvider: "magpie", opencodeModel: "deepseek-v4" }); + }); + + it("builds a root object for an empty file", () => { + const next = applyModelOverride("", { providerID: "magpie", modelID: "deepseek-v4" }); + + expect(parse(next)).toEqual({ opencodeProvider: "magpie", opencodeModel: "deepseek-v4" }); + }); + + it("does not touch commented-out model keys", () => { + const content = `{ + // "opencodeModel": "commented-out", + /* + "opencodeProvider": "commented-out", + */ + "opencodeProvider": "magpie", + "opencodeModel": "inherit" +}`; + const next = applyModelOverride(content, { providerID: "magpie", modelID: "deepseek-v4" }); + + expect(parse(next)).toEqual({ opencodeProvider: "magpie", opencodeModel: "deepseek-v4" }); + expect(next).toContain(`// "opencodeModel": "commented-out"`); + }); + + it("keeps CRLF line endings", () => { + const content = `{\r\n "opencodeModel": "inherit"\r\n}\r\n`; + const next = applyModelOverride(content, { providerID: "magpie", modelID: "deepseek-v4" }); + + expect(next).toContain("\r\n"); + expect(next.split(/\r?\n/).some((line) => line.includes(`"opencodeProvider"`))).toBe(true); + expect(next.includes("\n\n")).toBe(false); + }); + + it("accepts model ids that contain a slash", () => { + expect(MODEL_ID_PATTERN.test("auto/glm-5.3-flash")).toBe(true); + expect(MODEL_ID_PATTERN.test("Inherit")).toBe(false); + }); + + it("does not treat /* inside comments or strings as a block comment", () => { + const content = [ + "{", + " // Protects /api/* with a token.", + ' "opencodeProvider": "magpie",', + ' "opencodeModel": "inherit"', + "}", + ].join("\n"); + + const next = applyModelOverride(content, { providerID: "codearts", modelID: "auto/glm" }); + + expect(next.match(/"opencodeModel"/g)?.length).toBe(1); + expect(next).toContain('"opencodeProvider": "codearts"'); + expect(next).toContain('"opencodeModel": "auto/glm"'); + }); +}); + +describe("writeModelOverride", () => { + it("writes the override and leaves no tmp file behind", () => { + const dir = mkdtempSync(join(tmpdir(), "opencode-mem-model-config-")); + const path = join(dir, "opencode-mem.jsonc"); + writeFileSync(path, `{\n // keep me\n "opencodeModel": "inherit"\n}\n`, "utf-8"); + + writeModelOverride(path, { providerID: "magpie", modelID: "deepseek-v4" }); + + const written = readFileSync(path, "utf-8"); + expect(written).toContain("// keep me"); + expect(parse(written)).toMatchObject({ + opencodeModel: "deepseek-v4", + opencodeProvider: "magpie", + }); + expect(readdirSync(dir).filter((name) => name.includes(".tmp-"))).toEqual([]); + }); + + it("leaves the original file untouched when it does not parse", () => { + const dir = mkdtempSync(join(tmpdir(), "opencode-mem-model-config-")); + const path = join(dir, "opencode-mem.jsonc"); + const broken = `{\n "opencodeModel": "inherit",\n oops\n}\n`; + writeFileSync(path, broken, "utf-8"); + + expect(() => + writeModelOverride(path, { providerID: "magpie", modelID: "deepseek-v4" }) + ).toThrow(); + expect(readFileSync(path, "utf-8")).toBe(broken); + }); +}); + +describe("resolveModelConfigPath", () => { + it("prefers a project config that already sets the model keys", () => { + const dir = mkdtempSync(join(tmpdir(), "opencode-mem-project-")); + const projectFile = join(dir, ".opencode", "opencode-mem.jsonc"); + mkdirSync(join(dir, ".opencode"), { recursive: true }); + writeFileSync(projectFile, `{ "opencodeModel": "inherit" }`, "utf-8"); + + expect(resolveModelConfigPath(dir)).toBe(projectFile); + }); + + it("falls back to a global config when the project has none", () => { + const dir = mkdtempSync(join(tmpdir(), "opencode-mem-project-")); + + expect(resolveModelConfigPath(dir).endsWith("opencode-mem.jsonc")).toBe(true); + }); +}); diff --git a/web/sim/config-model-provider.json b/web/sim/config-model-provider.json new file mode 100644 index 00000000..47cbd8de --- /dev/null +++ b/web/sim/config-model-provider.json @@ -0,0 +1,29 @@ +{ + "success": true, + "data": { + "available": true, + "configured": false, + "providerID": "opencode", + "modelID": "inherit", + "providers": [ + { + "id": "opencode", + "name": "OpenCode", + "connected": true, + "models": [ + { "id": "opencode/big-pickle", "name": "Big Pickle" }, + { "id": "opencode/gpt-5-nano", "name": "GPT-5 Nano" } + ] + }, + { + "id": "ollama", + "name": "Ollama", + "connected": true, + "models": [ + { "id": "qwen2.5vl:3b", "name": "Qwen2.5-VL 3B" }, + { "id": "granite4.1:3b", "name": "Granite 4.1 3B" } + ] + } + ] + } +} diff --git a/web/src/App.svelte b/web/src/App.svelte index 03716fa8..ccb47f32 100644 --- a/web/src/App.svelte +++ b/web/src/App.svelte @@ -17,6 +17,7 @@ import SkillsView from "$lib/components/explorer/SkillsView.svelte"; import MarkdownVaultView from "$lib/components/explorer/MarkdownVaultView.svelte"; import StatsView from "$lib/components/explorer/StatsView.svelte"; + import ModelSettingsView from "$lib/components/explorer/ModelSettingsView.svelte"; import TagMigrationDialog from "$lib/components/explorer/TagMigrationDialog.svelte"; import TrashDialog from "$lib/components/explorer/TrashDialog.svelte"; import TagFilter from "$lib/components/explorer/TagFilter.svelte"; @@ -83,7 +84,9 @@ ? i18n.t("tab-markdown") : router.view === "stats" ? i18n.t("tab-stats") - : i18n.t("tab-profile") + : router.view === "model" + ? i18n.t("tab-model") + : i18n.t("tab-profile") ); $effect(() => { @@ -205,6 +208,7 @@ skillsLabel={i18n.t("tab-skills")} markdownLabel={i18n.t("tab-markdown")} statsLabel={i18n.t("tab-stats")} + modelLabel={i18n.t("tab-model")} showMarkdown={markdownVault.enabled} {langLabel} languageLabel={i18n.t("nav-language")} @@ -506,6 +510,8 @@ error={stats.error} onRefresh={stats.loadStats} /> + {:else if router.view === "model"} + {:else} import Activity from "@lucide/svelte/icons/activity"; import Brain from "@lucide/svelte/icons/brain"; + import Cpu from "@lucide/svelte/icons/cpu"; import FileText from "@lucide/svelte/icons/file-text"; import Folder from "@lucide/svelte/icons/folder"; import Languages from "@lucide/svelte/icons/languages"; @@ -36,6 +37,7 @@ skillsLabel: string; markdownLabel: string; statsLabel: string; + modelLabel: string; showMarkdown?: boolean; langLabel: string; languageLabel: string; @@ -55,6 +57,7 @@ skillsLabel, markdownLabel, statsLabel, + modelLabel, showMarkdown = false, langLabel, languageLabel, @@ -215,6 +218,19 @@ {statsLabel} {/if} + onNavClick(e, ROUTES.model)} + > +
diff --git a/web/src/lib/components/explorer/ModelPicker.svelte b/web/src/lib/components/explorer/ModelPicker.svelte new file mode 100644 index 00000000..b56c2d8c --- /dev/null +++ b/web/src/lib/components/explorer/ModelPicker.svelte @@ -0,0 +1,153 @@ + + +
+ {#if catalog?.available} +
+ + (selectedModel = "")} + > + + {#each catalog.providers as provider (provider.id)} + + {/each} + + + + + + {#each modelOptions as model (model.id)} + + {/each} + + +
+
+ +
+ {:else if catalog} +

+ {i18n.t("migration-model-unavailable", { reason: catalog.reason ?? "" })} +

+ {/if} + + {#if catalog && !catalog.configured} +

{i18n.t("migration-model-required")}

+ {/if} +
diff --git a/web/src/lib/components/explorer/ModelSettingsView.svelte b/web/src/lib/components/explorer/ModelSettingsView.svelte new file mode 100644 index 00000000..5eeb756b --- /dev/null +++ b/web/src/lib/components/explorer/ModelSettingsView.svelte @@ -0,0 +1,16 @@ + + +
+ + +

{i18n.t("model-settings-note")}

+
+
diff --git a/web/src/lib/components/explorer/TagMigrationDialog.svelte b/web/src/lib/components/explorer/TagMigrationDialog.svelte index bb939f02..daae039a 100644 --- a/web/src/lib/components/explorer/TagMigrationDialog.svelte +++ b/web/src/lib/components/explorer/TagMigrationDialog.svelte @@ -3,6 +3,7 @@ import { fetchAPI } from "$lib/api"; import AppDialog from "$lib/components/ui/app-dialog.svelte"; import DialogActions from "$lib/components/ui/dialog-actions.svelte"; + import ModelPicker from "$lib/components/explorer/ModelPicker.svelte"; import { useI18n } from "$lib/i18n/context.svelte"; import { STACK } from "$lib/ui/styles"; @@ -19,6 +20,7 @@ let running = $state(false); let status = $state(""); let progress = $state(0); + let modelConfigured = $state(false); $effect(() => { if (open && !running) { @@ -122,6 +124,9 @@ style={`width: ${progress}%`} >
+ + +

{i18n.t("migration-note")}

{#snippet footer()} @@ -129,6 +134,7 @@ handleOpenChange(false)} primaryLabel={i18n.t("btn-start-migration")} + primaryDisabled={!modelConfigured} onPrimary={() => void runTagMigration()} /> {/if} diff --git a/web/src/lib/i18n/translations.ts b/web/src/lib/i18n/translations.ts index 34ee2d42..2419bc92 100644 --- a/web/src/lib/i18n/translations.ts +++ b/web/src/lib/i18n/translations.ts @@ -1,5 +1,8 @@ export const translations = { en: { + "tab-model": "Model", + "model-settings-note": + "Both keys are shared: auto-capture and tag migration use the same provider and model.", "tab-stats": "Stats", "stats-overview": "Overview", "stats-total-memories": "Total memories", @@ -103,6 +106,14 @@ export const translations = { "btn-cancel": "Cancel", "btn-save": "Save Changes", "btn-start-migration": "Start Migration", + "label-model-provider": "Provider", + "label-model-name": "Model", + "migration-model-unavailable": + "Provider list unavailable ({reason}). Set opencodeProvider/opencodeModel in your config file instead.", + "migration-model-required": + 'Tag migration needs an explicit model: "inherit" only works with a live session. Pick a provider and model, then save.', + "toast-model-saved": "Model saved.", + "toast-model-save-failed": "Could not save the model.", "loading-init": "Initializing…", "loading-profile": "Loading profile…", "loading-changelog": "Loading changelog…", @@ -269,6 +280,9 @@ export const translations = { "toast-skill-load-failed": "Failed to load skills", }, de: { + "tab-model": "Modell", + "model-settings-note": + "Beide Schlüssel werden gemeinsam genutzt: automatisches Erfassen und Tag-Migration verwenden denselben Anbieter und dasselbe Modell.", "tab-stats": "Statistiken", "stats-overview": "Übersicht", "stats-total-memories": "Erinnerungen insgesamt", @@ -372,6 +386,14 @@ export const translations = { "btn-cancel": "Abbrechen", "btn-save": "Änderungen speichern", "btn-start-migration": "Migration starten", + "label-model-provider": "Anbieter", + "label-model-name": "Modell", + "migration-model-unavailable": + "Anbieterliste nicht verfügbar ({reason}). Setze stattdessen opencodeProvider/opencodeModel in deiner Konfigurationsdatei.", + "migration-model-required": + "Die Tag-Migration benötigt ein explizites Modell: „inherit“ funktioniert nur mit einer aktiven Sitzung. Wähle Anbieter und Modell und speichere.", + "toast-model-saved": "Modell gespeichert.", + "toast-model-save-failed": "Modell konnte nicht gespeichert werden.", "loading-init": "Wird initialisiert…", "loading-profile": "Profil wird geladen…", "loading-changelog": "Changelog wird geladen…", @@ -542,6 +564,8 @@ export const translations = { "toast-skill-load-failed": "Skills konnten nicht geladen werden", }, zh: { + "tab-model": "模型", + "model-settings-note": "这两个键是共用的:自动捕获与标签迁移使用同一个服务商与模型。", "tab-stats": "统计", "stats-overview": "概览", "stats-total-memories": "记忆总数", @@ -644,6 +668,14 @@ export const translations = { "btn-cancel": "取消", "btn-save": "保存更改", "btn-start-migration": "开始迁移", + "label-model-provider": "提供方", + "label-model-name": "模型", + "migration-model-unavailable": + "无法获取模型列表({reason})。请改为在配置文件中手动设置 opencodeProvider/opencodeModel。", + "migration-model-required": + "标签迁移需要一个明确的模型:“inherit” 只能在存在活动会话时使用。请选择提供方和模型后保存。", + "toast-model-saved": "模型已保存。", + "toast-model-save-failed": "模型保存失败。", "loading-init": "初始化中...", "loading-profile": "加载画像中...", "loading-changelog": "加载更新日志中...", @@ -808,6 +840,9 @@ export const translations = { "toast-skill-load-failed": "加载技能失败", }, ar: { + "tab-model": "النموذج", + "model-settings-note": + "المفتاحان مشتركان: يستخدم الالتقاط التلقائي وترحيل الوسوم المزوّد والنموذج نفسيهما.", "tab-stats": "الإحصائيات", "stats-overview": "نظرة عامة", "stats-total-memories": "إجمالي الذكريات", @@ -917,6 +952,14 @@ export const translations = { "btn-cancel": "إلغاء", "btn-save": "حفظ التغييرات", "btn-start-migration": "بدء الترحيل", + "label-model-provider": "المزوّد", + "label-model-name": "النموذج", + "migration-model-unavailable": + "قائمة المزوّدين غير متاحة ({reason}). عيّن opencodeProvider/opencodeModel في ملف الإعدادات بدلاً من ذلك.", + "migration-model-required": + 'تتطلب هجرة الوسوم نموذجًا صريحًا: "inherit" يعمل فقط مع جلسة نشطة. اختر المزوّد والنموذج ثم احفظ.', + "toast-model-saved": "تم حفظ النموذج.", + "toast-model-save-failed": "تعذّر حفظ النموذج.", "loading-init": "جاري التهيئة...", "loading-profile": "جاري تحميل الملف الشخصي...", @@ -1116,6 +1159,9 @@ export const translations = { "toast-skill-load-failed": "فشل تحميل المهارات", }, tr: { + "tab-model": "Model", + "model-settings-note": + "Bu iki anahtar ortaktır: otomatik yakalama ve etiket geçişi aynı sağlayıcıyı ve modeli kullanır.", "tab-stats": "İstatistikler", "stats-overview": "Genel bakış", "stats-total-memories": "Toplam anı", @@ -1219,6 +1265,14 @@ export const translations = { "btn-cancel": "İptal", "btn-save": "Değişiklikleri kaydet", "btn-start-migration": "Geçişi başlat", + "label-model-provider": "Sağlayıcı", + "label-model-name": "Model", + "migration-model-unavailable": + "Sağlayıcı listesi kullanılamıyor ({reason}). Bunun yerine yapılandırma dosyanızda opencodeProvider/opencodeModel ayarlayın.", + "migration-model-required": + 'Etiket geçişi açık bir model gerektirir: "inherit" yalnızca etkin bir oturumla çalışır. Bir sağlayıcı ve model seçip kaydedin.', + "toast-model-saved": "Model kaydedildi.", + "toast-model-save-failed": "Model kaydedilemedi.", "loading-init": "Başlatılıyor...", "loading-profile": "Profil yükleniyor...", "loading-changelog": "Değişiklik günlüğü yükleniyor...", @@ -1387,6 +1441,9 @@ export const translations = { "toast-skill-load-failed": "Beceriler yüklenemedi", }, nl: { + "tab-model": "Model", + "model-settings-note": + "Beide sleutels worden gedeeld: automatische vastlegging en tag-migratie gebruiken dezelfde provider en hetzelfde model.", "tab-stats": "Statistieken", "stats-overview": "Overzicht", "stats-total-memories": "Totaal aantal herinneringen", @@ -1490,6 +1547,14 @@ export const translations = { "btn-cancel": "Annuleren", "btn-save": "Wijzigingen opslaan", "btn-start-migration": "Migratie starten", + "label-model-provider": "Provider", + "label-model-name": "Model", + "migration-model-unavailable": + "Providerlijst niet beschikbaar ({reason}). Stel in plaats daarvan opencodeProvider/opencodeModel in je configuratiebestand in.", + "migration-model-required": + 'Tagmigratie vereist een expliciet model: "inherit" werkt alleen met een actieve sessie. Kies een provider en model en sla op.', + "toast-model-saved": "Model opgeslagen.", + "toast-model-save-failed": "Model opslaan mislukt.", "loading-init": "Initialiseren...", "loading-profile": "Profiel laden...", "loading-changelog": "Wijzigingslogboek laden...", @@ -1660,6 +1725,9 @@ export const translations = { "toast-skill-load-failed": "Skills laden mislukt", }, fr: { + "tab-model": "Modèle", + "model-settings-note": + "Ces deux clés sont partagées : la capture automatique et la migration des tags utilisent le même fournisseur et le même modèle.", "tab-stats": "Stats", "stats-overview": "Vue d'ensemble", "stats-total-memories": "Total des mémoires", @@ -1763,6 +1831,14 @@ export const translations = { "btn-cancel": "Annuler", "btn-save": "Enregistrer les modifications", "btn-start-migration": "Lancer la migration", + "label-model-provider": "Fournisseur", + "label-model-name": "Modèle", + "migration-model-unavailable": + "Liste des fournisseurs indisponible ({reason}). Définissez plutôt opencodeProvider/opencodeModel dans votre fichier de configuration.", + "migration-model-required": + "La migration des tags nécessite un modèle explicite : « inherit » ne fonctionne qu'avec une session active. Choisissez un fournisseur et un modèle, puis enregistrez.", + "toast-model-saved": "Modèle enregistré.", + "toast-model-save-failed": "Impossible d'enregistrer le modèle.", "loading-init": "Initialisation…", "loading-profile": "Chargement du profil…", "loading-changelog": "Chargement de l'historique…", diff --git a/web/src/lib/routes.ts b/web/src/lib/routes.ts index 07118e27..8b3bddbf 100644 --- a/web/src/lib/routes.ts +++ b/web/src/lib/routes.ts @@ -6,9 +6,10 @@ export const ROUTES = { skills: "/skill-library", markdown: "/markdown-vault", stats: "/stats", + model: "/model-settings", } as const; -export type AppView = "project" | "profile" | "skills" | "markdown" | "stats"; +export type AppView = "project" | "profile" | "skills" | "markdown" | "stats" | "model"; export function normalizePath(pathname: string): string { const path = pathname.replace(/\/+$/, "") || "/"; @@ -21,6 +22,7 @@ export function viewFromPath(pathname: string): AppView { if (path === ROUTES.skills) return "skills"; if (path === ROUTES.markdown) return "markdown"; if (path === ROUTES.stats) return "stats"; + if (path === ROUTES.model) return "model"; return "project"; } @@ -29,6 +31,7 @@ export function pathForView(view: AppView): string { if (view === "skills") return ROUTES.skills; if (view === "markdown") return ROUTES.markdown; if (view === "stats") return ROUTES.stats; + if (view === "model") return ROUTES.model; return ROUTES.project; } @@ -40,7 +43,8 @@ export function isAppPath(pathname: string): boolean { path === ROUTES.profile || path === ROUTES.skills || path === ROUTES.markdown || - path === ROUTES.stats + path === ROUTES.stats || + path === ROUTES.model ); } @@ -53,7 +57,8 @@ export function resolveAppPath(pathname: string): string { path === ROUTES.profile || path === ROUTES.skills || path === ROUTES.markdown || - path === ROUTES.stats + path === ROUTES.stats || + path === ROUTES.model ) return path; return ROUTES.project; diff --git a/web/vite-plugins/opencode-mem-sim.ts b/web/vite-plugins/opencode-mem-sim.ts index 8845becc..3900c737 100644 --- a/web/vite-plugins/opencode-mem-sim.ts +++ b/web/vite-plugins/opencode-mem-sim.ts @@ -53,6 +53,19 @@ type MarkdownStatus = { files: MarkdownVaultFile[]; }; +type ModelProviderCatalog = { + available: boolean; + configured: boolean; + providerID: string | null; + modelID: string | null; + providers: Array<{ + id: string; + name: string; + connected: boolean; + models: Array<{ id: string; name: string }>; + }>; +}; + function readJson(filePath: string): T { return JSON.parse(fs.readFileSync(filePath, "utf8")) as T; } @@ -152,6 +165,9 @@ export function opencodeMemSimPlugin(simRoot: string): Plugin { ...markdownFixture, files: markdownFixture.files.map((file) => ({ ...file })), }; + const modelProvider = readJson<{ data: ModelProviderCatalog }>( + path.join(simRoot, "config-model-provider.json") + ).data; function findMemory(id: string) { return memories.find((item) => item.id === id); @@ -203,6 +219,43 @@ export function opencodeMemSimPlugin(simRoot: string): Plugin { return; } + if (pathname === "/api/config/model-provider" && method === "GET") { + sendJson(res, 200, { success: true, data: modelProvider }); + return; + } + + if (pathname === "/api/config/model-provider" && method === "PUT") { + void readBody(req).then((raw) => { + try { + const parsed = raw + ? (JSON.parse(raw) as { providerID?: string; modelID?: string }) + : {}; + const providerID = String(parsed.providerID || "").trim(); + const modelID = String(parsed.modelID || "").trim(); + if (!providerID || !modelID) { + sendJson(res, 400, { + success: false, + error: "providerID and modelID are required", + }); + return; + } + modelProvider.providerID = providerID; + modelProvider.modelID = modelID; + modelProvider.configured = modelID !== "inherit"; + sendJson(res, 200, { + success: true, + data: { writtenTo: "sim", providerID, modelID, requiresReload: false }, + }); + } catch (error) { + sendJson(res, 400, { + success: false, + error: error instanceof Error ? error.message : String(error), + }); + } + }); + return; + } + if (pathname === "/api/user-profile" && method === "GET") { sendJson(res, 200, readJson(path.join(simRoot, "user-profile.json"))); return;