From da36b6b7c281b92eb5e12a92e862cabb6477ca0b Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Thu, 19 Nov 2026 16:20:38 +0800 Subject: [PATCH 1/9] feat(config): write opencode model overrides back to the jsonc config Locates the config file that already supplies opencodeProvider/opencodeModel (project file first, then the first global file) and rewrites just those two values in place, keeping comments, trailing commas and CRLF. The rewritten text is re-parsed before an atomic write, so a bad edit never lands. --- src/config.ts | 28 +++++- src/services/model-config-writer.ts | 105 ++++++++++++++++++++++ tests/model-config-writer.test.ts | 132 ++++++++++++++++++++++++++++ 3 files changed, 263 insertions(+), 2 deletions(-) create mode 100644 src/services/model-config-writer.ts create mode 100644 tests/model-config-writer.test.ts 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/services/model-config-writer.ts b/src/services/model-config-writer.ts new file mode 100644 index 00000000..352314fa --- /dev/null +++ b/src/services/model-config-writer.ts @@ -0,0 +1,105 @@ +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 (dot, dash, underscore allowed). */ +export const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9._-]*$/; + +const KEYS = [ + ["providerID", "opencodeProvider"], + ["modelID", "opencodeModel"], +] as const; + +/** + * 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]!; + const matchable = !inBlockComment && !/^\s*\/[/*]/.test(line); + const opensBlock = line.includes("/*"); + + if (matchable) { + 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); + } + } + + if (opensBlock && !line.includes("*/")) inBlockComment = true; + else if (inBlockComment && line.includes("*/")) inBlockComment = false; + } + + 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/tests/model-config-writer.test.ts b/tests/model-config-writer.test.ts new file mode 100644 index 00000000..44eb21f7 --- /dev/null +++ b/tests/model-config-writer.test.ts @@ -0,0 +1,132 @@ +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, 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); + }); +}); + +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); + }); +}); From cf7bf9f0ab0ec029e6573f03cc5387fb994910b5 Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Thu, 19 Nov 2026 16:20:51 +0800 Subject: [PATCH 2/9] feat(web): expose provider catalog and model override API The host already lists connected providers; cache that directory on the plugin side because the lazy V2 client only proxies session calls. GET/PUT /api/config/model-provider then lets the web UI read the directory and save an explicit provider/model for tag migration, reloading config in place. --- README.md | 2 + src/index.ts | 13 +++- src/services/ai/opencode-provider.ts | 17 +++++ src/services/api-handlers.ts | 101 +++++++++++++++++++++++++++ src/services/web-server.ts | 15 ++++ 5 files changed, 147 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d25e70dd..cd1a944f 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,8 @@ Open `http://127.0.0.1:4747` to browse the memory–prompt timeline, inspect cap 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/index.ts b/src/index.ts index 2dc657d5..b10fccd6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -422,8 +422,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)", @@ -529,6 +539,7 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => { enabled: CONFIG.webServerEnabled, auth: webAuth, apiToken: CONFIG.webServerApiToken, + projectDirectory: directory, }) .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..b89e2fe7 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,106 @@ export async function handleGetTagMigrationProgress(): Promise; + }>; +} + +export async function handleGetTagMigrationModel(): 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(); + const catalog = getProviderCatalog(); + 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.map((provider) => ({ + id: provider.id, + name: provider.name, + connected: isProviderConnected(provider.id), + models: provider.models, + })), + }, + }; + } catch (error) { + return { success: false, error: String(error) }; + } +} + +export async function handleSetTagMigrationModel( + body: unknown, + projectDirectory?: string +): 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 { + 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. + let requiresReload = true; + if (projectDirectory) { + initConfig(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/web-server.ts b/src/services/web-server.ts index bcf74898..19a8e3f7 100644 --- a/src/services/web-server.ts +++ b/src/services/web-server.ts @@ -32,6 +32,8 @@ import { handleDetectTagMigration, handleRunTagMigrationBatch, handleGetTagMigrationProgress, + handleGetTagMigrationModel, + handleSetTagMigrationModel, handleDeletePrompt, handleBulkDeletePrompts, handleGetUserProfile, @@ -228,6 +230,8 @@ interface WebServerConfig { enabled: boolean; auth?: WebAuth; apiToken?: string; + /** Project root used for project-scoped config writes and reloads. */ + projectDirectory?: string; } export class WebServer { @@ -685,6 +689,17 @@ export class WebServer { return this.jsonResponse(result); } + if (path === "/api/config/model-provider" && method === "GET") { + const result = await handleGetTagMigrationModel(); + 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); + 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"; From 075387b3d857b3da52f6f11c438715979239126e Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Thu, 19 Nov 2026 16:21:09 +0800 Subject: [PATCH 3/9] feat(web): add a model picker to the tag migration dialog Tag migration rejects the inherit model because it has no live session, so the dialog now shows the configured provider/model, lists connected providers and their models, and saves a selection before starting. The start button stays disabled until a concrete model is configured. --- .../explorer/TagMigrationDialog.svelte | 139 +++++++++++++++++- web/src/lib/i18n/translations.ts | 56 +++++++ 2 files changed, 194 insertions(+), 1 deletion(-) diff --git a/web/src/lib/components/explorer/TagMigrationDialog.svelte b/web/src/lib/components/explorer/TagMigrationDialog.svelte index bb939f02..c54267fa 100644 --- a/web/src/lib/components/explorer/TagMigrationDialog.svelte +++ b/web/src/lib/components/explorer/TagMigrationDialog.svelte @@ -2,9 +2,12 @@ import { toast } from "$lib/toast/toast.svelte"; import { fetchAPI } from "$lib/api"; import AppDialog from "$lib/components/ui/app-dialog.svelte"; + import Button from "$lib/components/ui/button.svelte"; import DialogActions from "$lib/components/ui/dialog-actions.svelte"; + import FormField from "$lib/components/ui/form-field.svelte"; + import NativeSelect from "$lib/components/ui/native-select.svelte"; import { useI18n } from "$lib/i18n/context.svelte"; - import { STACK } from "$lib/ui/styles"; + import { GAP_LOOSE, STACK } from "$lib/ui/styles"; type Props = { open?: boolean; @@ -13,6 +16,20 @@ onComplete?: () => void; }; + type ModelCatalog = { + available: boolean; + reason?: string; + configured: boolean; + providerID: string | null; + modelID: string | null; + providers: Array<{ + id: string; + name: string; + connected: boolean; + models: Array<{ id: string; name: string }>; + }>; + }; + let { open = $bindable(false), count = 0, onOpenChange, onComplete }: Props = $props(); const i18n = useI18n(); @@ -20,19 +37,81 @@ let status = $state(""); let progress = $state(0); + let catalog = $state(null); + let selectedProvider = $state(""); + let selectedModel = $state(""); + let savingModel = $state(false); + + const modelOptions = $derived( + catalog?.providers.find((provider) => provider.id === selectedProvider)?.models ?? [] + ); + const selectionDirty = $derived( + selectedProvider !== (catalog?.providerID ?? "") || selectedModel !== (catalog?.modelID ?? "") + ); + $effect(() => { if (open && !running) { status = i18n.t("migration-found-tags", { count }); progress = 0; + void loadCatalog(); } }); + async function loadCatalog() { + const result = await fetchAPI("/api/config/model-provider"); + if (!result.success || !result.data) { + catalog = { + available: false, + reason: result.error ?? "", + configured: false, + providerID: null, + modelID: null, + providers: [], + }; + return; + } + catalog = result.data; + const data = result.data; + const provider = data.providers.find((entry) => entry.id === data.providerID); + if (provider) { + selectedProvider = provider.id; + selectedModel = provider.models.some((model) => model.id === data.modelID) + ? (data.modelID ?? "") + : ""; + } + } + function handleOpenChange(next: boolean) { if (running && !next) return; open = next; onOpenChange?.(next); } + async function saveModel() { + savingModel = true; + const result = await fetchAPI<{ writtenTo: string; requiresReload: boolean }>( + "/api/config/model-provider", + { + method: "PUT", + body: JSON.stringify({ providerID: selectedProvider, modelID: selectedModel }), + } + ); + savingModel = false; + + if (!result.success || !result.data) { + toast.error(result.error ?? i18n.t("toast-model-save-failed")); + return; + } + // Re-read instead of trusting the response: a project config file may still + // override the value we just wrote. + await loadCatalog(); + if (catalog?.configured) { + toast.success(i18n.t("toast-model-saved")); + } else { + toast.error(i18n.t("toast-model-save-failed")); + } + } + async function runTagMigration() { running = true; status = i18n.t("status-migration-init"); @@ -122,6 +201,63 @@ style={`width: ${progress}%`} > + + {#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} +

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

{#snippet footer()} @@ -129,6 +265,7 @@ handleOpenChange(false)} primaryLabel={i18n.t("btn-start-migration")} + primaryDisabled={!catalog?.configured} onPrimary={() => void runTagMigration()} /> {/if} diff --git a/web/src/lib/i18n/translations.ts b/web/src/lib/i18n/translations.ts index 34ee2d42..a2e69ad9 100644 --- a/web/src/lib/i18n/translations.ts +++ b/web/src/lib/i18n/translations.ts @@ -103,6 +103,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…", @@ -372,6 +380,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…", @@ -644,6 +660,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": "加载更新日志中...", @@ -917,6 +941,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": "جاري تحميل الملف الشخصي...", @@ -1219,6 +1251,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...", @@ -1490,6 +1530,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...", @@ -1763,6 +1811,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…", From 76cb9541018e0070037fbd28b7566d0e426233ed Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Thu, 19 Nov 2026 17:10:56 +0800 Subject: [PATCH 4/9] fix(web): read the provider catalog from the native v2 context --- src/index.ts | 30 ++++++++++++++++++++++++++++++ src/services/api-handlers.ts | 34 ++++++++++++++++++++++------------ src/services/web-server.ts | 5 ++++- src/v2/plugin.ts | 20 ++++++++++++++++++++ 4 files changed, 76 insertions(+), 13 deletions(-) diff --git a/src/index.ts b/src/index.ts index b10fccd6..c2387a47 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"; @@ -448,6 +449,34 @@ 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. + 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. @@ -540,6 +569,7 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => { auth: webAuth, apiToken: CONFIG.webServerApiToken, projectDirectory: directory, + loadProviderDirectory, }) .then((server) => { webServer = server; diff --git a/src/services/api-handlers.ts b/src/services/api-handlers.ts index b89e2fe7..0c6f74ed 100644 --- a/src/services/api-handlers.ts +++ b/src/services/api-handlers.ts @@ -1728,7 +1728,16 @@ export interface TagMigrationModelCatalog extends TagMigrationModelStatus { }>; } -export async function handleGetTagMigrationModel(): 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, @@ -1738,7 +1747,17 @@ export async function handleGetTagMigrationModel(): Promise ({ + 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, @@ -1752,16 +1771,7 @@ export async function handleGetTagMigrationModel(): Promise ({ - id: provider.id, - name: provider.name, - connected: isProviderConnected(provider.id), - models: provider.models, - })), - }, + data: { ...status, available: true, providers: catalog }, }; } catch (error) { return { success: false, error: String(error) }; diff --git a/src/services/web-server.ts b/src/services/web-server.ts index 19a8e3f7..9cb8b889 100644 --- a/src/services/web-server.ts +++ b/src/services/web-server.ts @@ -34,6 +34,7 @@ import { handleGetTagMigrationProgress, handleGetTagMigrationModel, handleSetTagMigrationModel, + type ProviderDirectoryEntry, handleDeletePrompt, handleBulkDeletePrompts, handleGetUserProfile, @@ -232,6 +233,8 @@ interface WebServerConfig { 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; } export class WebServer { @@ -690,7 +693,7 @@ export class WebServer { } if (path === "/api/config/model-provider" && method === "GET") { - const result = await handleGetTagMigrationModel(); + const result = await handleGetTagMigrationModel(this.config.loadProviderDirectory); return this.jsonResponse(result); } 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 From b91059da5aadae26dccdc490b52f5baf6f5d69c1 Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Thu, 19 Nov 2026 17:17:32 +0800 Subject: [PATCH 5/9] fix(config): allow slashes in provider and model ids --- src/services/model-config-writer.ts | 4 ++-- tests/model-config-writer.test.ts | 11 ++++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/services/model-config-writer.ts b/src/services/model-config-writer.ts index 352314fa..70ea3bd8 100644 --- a/src/services/model-config-writer.ts +++ b/src/services/model-config-writer.ts @@ -6,8 +6,8 @@ export type ModelOverride = { modelID: string; }; -/** Provider/model ids as the host reports them (dot, dash, underscore allowed). */ -export const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9._-]*$/; +/** 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"], diff --git a/tests/model-config-writer.test.ts b/tests/model-config-writer.test.ts index 44eb21f7..d8198486 100644 --- a/tests/model-config-writer.test.ts +++ b/tests/model-config-writer.test.ts @@ -3,7 +3,11 @@ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from import { tmpdir } from "node:os"; import { join } from "node:path"; import { resolveModelConfigPath } from "../src/config"; -import { applyModelOverride, writeModelOverride } from "../src/services/model-config-writer"; +import { + applyModelOverride, + MODEL_ID_PATTERN, + writeModelOverride, +} from "../src/services/model-config-writer"; import { stripJsoncComments } from "../src/services/jsonc"; function parse(content: string): Record { @@ -82,6 +86,11 @@ describe("applyModelOverride", () => { 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); + }); }); describe("writeModelOverride", () => { From b715aeeb31d0fc3f49d38352fc8e5abf3af02b98 Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Thu, 19 Nov 2026 17:42:48 +0800 Subject: [PATCH 6/9] fix(config): keep the model override writer inside comments and strings The block-comment scan treated any /* in a line, including one inside a line comment such as "Protects /api/* with a token.", as opening a block, so every later key was skipped and each save appended another pair. Track the comment state per line instead, and reload through the plugin config instance because the lazily imported module is a second copy under bundling. --- src/index.ts | 4 +++ src/services/api-handlers.ts | 12 +++++-- src/services/model-config-writer.ts | 51 +++++++++++++++++++++++++---- src/services/web-server.ts | 8 ++++- tests/model-config-writer.test.ts | 16 +++++++++ 5 files changed, 81 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index c2387a47..e224aabb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -453,6 +453,9 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => { // 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 => { @@ -570,6 +573,7 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => { apiToken: CONFIG.webServerApiToken, projectDirectory: directory, loadProviderDirectory, + reloadConfig, }) .then((server) => { webServer = server; diff --git a/src/services/api-handlers.ts b/src/services/api-handlers.ts index 0c6f74ed..46508c12 100644 --- a/src/services/api-handlers.ts +++ b/src/services/api-handlers.ts @@ -1780,7 +1780,8 @@ export async function handleGetTagMigrationModel( export async function handleSetTagMigrationModel( body: unknown, - projectDirectory?: string + projectDirectory?: string, + reloadConfig?: () => void ): Promise< ApiResponse<{ writtenTo: string; @@ -1800,14 +1801,21 @@ export async function handleSetTagMigrationModel( } 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 (projectDirectory) { + if (reloadConfig) { + reloadConfig(); + } else if (projectDirectory) { initConfig(projectDirectory); + } + if (reloadConfig || projectDirectory) { requiresReload = CONFIG.opencodeProvider !== providerID || CONFIG.opencodeModel !== modelID; } diff --git a/src/services/model-config-writer.ts b/src/services/model-config-writer.ts index 70ea3bd8..6a610717 100644 --- a/src/services/model-config-writer.ts +++ b/src/services/model-config-writer.ts @@ -14,6 +14,48 @@ const KEYS = [ ["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. @@ -28,10 +70,7 @@ export function applyModelOverride(content: string, override: ModelOverride): st for (let i = 0; i < lines.length; i++) { const line = lines[i]!; - const matchable = !inBlockComment && !/^\s*\/[/*]/.test(line); - const opensBlock = line.includes("/*"); - - if (matchable) { + if (!inBlockComment) { for (const [field, key] of KEYS) { const pattern = new RegExp(`^(\\s*"${key}"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*")`); const match = pattern.exec(line); @@ -40,9 +79,7 @@ export function applyModelOverride(content: string, override: ModelOverride): st found.add(key); } } - - if (opensBlock && !line.includes("*/")) inBlockComment = true; - else if (inBlockComment && line.includes("*/")) inBlockComment = false; + inBlockComment = endsInsideBlockComment(line, inBlockComment); } const missing = KEYS.filter(([, key]) => !found.has(key)); diff --git a/src/services/web-server.ts b/src/services/web-server.ts index 9cb8b889..a10a42d7 100644 --- a/src/services/web-server.ts +++ b/src/services/web-server.ts @@ -235,6 +235,8 @@ interface WebServerConfig { 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 { @@ -699,7 +701,11 @@ export class WebServer { if (path === "/api/config/model-provider" && method === "PUT") { const body = (await req.json()) as any; - const result = await handleSetTagMigrationModel(body, this.config.projectDirectory); + const result = await handleSetTagMigrationModel( + body, + this.config.projectDirectory, + this.config.reloadConfig + ); return this.jsonResponse(result, result.success ? 200 : 400); } diff --git a/tests/model-config-writer.test.ts b/tests/model-config-writer.test.ts index d8198486..9fac29ad 100644 --- a/tests/model-config-writer.test.ts +++ b/tests/model-config-writer.test.ts @@ -91,6 +91,22 @@ describe("applyModelOverride", () => { 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", () => { From 3c8b9b38c3cb2ef19a34b4e8c6d58a664cd6dfd0 Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Thu, 19 Nov 2026 18:17:11 +0800 Subject: [PATCH 7/9] feat(web): add a model settings page The tag migration dialog could pick a provider and model, but only when it opened on its own. The sidebar now links to /model-settings, which renders the same picker as a page, plus a note that the two keys are shared with auto-capture. --- web/src/App.svelte | 8 +- .../lib/components/explorer/AppSidebar.svelte | 16 ++ .../components/explorer/ModelPicker.svelte | 160 ++++++++++++++++++ .../explorer/ModelSettingsView.svelte | 18 ++ .../explorer/TagMigrationDialog.svelte | 141 +-------------- web/src/lib/i18n/translations.ts | 20 +++ web/src/lib/routes.ts | 11 +- 7 files changed, 234 insertions(+), 140 deletions(-) create mode 100644 web/src/lib/components/explorer/ModelPicker.svelte create mode 100644 web/src/lib/components/explorer/ModelSettingsView.svelte 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..a924cafe --- /dev/null +++ b/web/src/lib/components/explorer/ModelPicker.svelte @@ -0,0 +1,160 @@ + + +
+ {#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..06c10409 --- /dev/null +++ b/web/src/lib/components/explorer/ModelSettingsView.svelte @@ -0,0 +1,18 @@ + + +
+ +
+ +

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

+
+
+
diff --git a/web/src/lib/components/explorer/TagMigrationDialog.svelte b/web/src/lib/components/explorer/TagMigrationDialog.svelte index c54267fa..daae039a 100644 --- a/web/src/lib/components/explorer/TagMigrationDialog.svelte +++ b/web/src/lib/components/explorer/TagMigrationDialog.svelte @@ -2,12 +2,10 @@ import { toast } from "$lib/toast/toast.svelte"; import { fetchAPI } from "$lib/api"; import AppDialog from "$lib/components/ui/app-dialog.svelte"; - import Button from "$lib/components/ui/button.svelte"; import DialogActions from "$lib/components/ui/dialog-actions.svelte"; - import FormField from "$lib/components/ui/form-field.svelte"; - import NativeSelect from "$lib/components/ui/native-select.svelte"; + import ModelPicker from "$lib/components/explorer/ModelPicker.svelte"; import { useI18n } from "$lib/i18n/context.svelte"; - import { GAP_LOOSE, STACK } from "$lib/ui/styles"; + import { STACK } from "$lib/ui/styles"; type Props = { open?: boolean; @@ -16,102 +14,27 @@ onComplete?: () => void; }; - type ModelCatalog = { - available: boolean; - reason?: string; - configured: boolean; - providerID: string | null; - modelID: string | null; - providers: Array<{ - id: string; - name: string; - connected: boolean; - models: Array<{ id: string; name: string }>; - }>; - }; - let { open = $bindable(false), count = 0, onOpenChange, onComplete }: Props = $props(); const i18n = useI18n(); let running = $state(false); let status = $state(""); let progress = $state(0); - - let catalog = $state(null); - let selectedProvider = $state(""); - let selectedModel = $state(""); - let savingModel = $state(false); - - const modelOptions = $derived( - catalog?.providers.find((provider) => provider.id === selectedProvider)?.models ?? [] - ); - const selectionDirty = $derived( - selectedProvider !== (catalog?.providerID ?? "") || selectedModel !== (catalog?.modelID ?? "") - ); + let modelConfigured = $state(false); $effect(() => { if (open && !running) { status = i18n.t("migration-found-tags", { count }); progress = 0; - void loadCatalog(); } }); - async function loadCatalog() { - const result = await fetchAPI("/api/config/model-provider"); - if (!result.success || !result.data) { - catalog = { - available: false, - reason: result.error ?? "", - configured: false, - providerID: null, - modelID: null, - providers: [], - }; - return; - } - catalog = result.data; - const data = result.data; - const provider = data.providers.find((entry) => entry.id === data.providerID); - if (provider) { - selectedProvider = provider.id; - selectedModel = provider.models.some((model) => model.id === data.modelID) - ? (data.modelID ?? "") - : ""; - } - } - function handleOpenChange(next: boolean) { if (running && !next) return; open = next; onOpenChange?.(next); } - async function saveModel() { - savingModel = true; - const result = await fetchAPI<{ writtenTo: string; requiresReload: boolean }>( - "/api/config/model-provider", - { - method: "PUT", - body: JSON.stringify({ providerID: selectedProvider, modelID: selectedModel }), - } - ); - savingModel = false; - - if (!result.success || !result.data) { - toast.error(result.error ?? i18n.t("toast-model-save-failed")); - return; - } - // Re-read instead of trusting the response: a project config file may still - // override the value we just wrote. - await loadCatalog(); - if (catalog?.configured) { - toast.success(i18n.t("toast-model-saved")); - } else { - toast.error(i18n.t("toast-model-save-failed")); - } - } - async function runTagMigration() { running = true; status = i18n.t("status-migration-init"); @@ -202,61 +125,7 @@ >
- {#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} +

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

@@ -265,7 +134,7 @@ handleOpenChange(false)} primaryLabel={i18n.t("btn-start-migration")} - primaryDisabled={!catalog?.configured} + primaryDisabled={!modelConfigured} onPrimary={() => void runTagMigration()} /> {/if} diff --git a/web/src/lib/i18n/translations.ts b/web/src/lib/i18n/translations.ts index a2e69ad9..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", @@ -277,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", @@ -558,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": "记忆总数", @@ -832,6 +840,9 @@ export const translations = { "toast-skill-load-failed": "加载技能失败", }, ar: { + "tab-model": "النموذج", + "model-settings-note": + "المفتاحان مشتركان: يستخدم الالتقاط التلقائي وترحيل الوسوم المزوّد والنموذج نفسيهما.", "tab-stats": "الإحصائيات", "stats-overview": "نظرة عامة", "stats-total-memories": "إجمالي الذكريات", @@ -1148,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ı", @@ -1427,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", @@ -1708,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", 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; From 98f3cfd8559f8aba30b81368e6c07f325fd1e4a2 Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Fri, 20 Nov 2026 09:22:30 +0800 Subject: [PATCH 8/9] refactor(web): simplify the model picker and settings page Drop the unused onSaved callback and the extra padding wrapper inside BorderedPanel, which already supplies its own. README now lists six views. --- README.md | 2 +- web/src/lib/components/explorer/ModelPicker.svelte | 9 +-------- web/src/lib/components/explorer/ModelSettingsView.svelte | 8 +++----- 3 files changed, 5 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index cd1a944f..acbdcc74 100644 --- a/README.md +++ b/README.md @@ -270,7 +270,7 @@ 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. diff --git a/web/src/lib/components/explorer/ModelPicker.svelte b/web/src/lib/components/explorer/ModelPicker.svelte index a924cafe..b56c2d8c 100644 --- a/web/src/lib/components/explorer/ModelPicker.svelte +++ b/web/src/lib/components/explorer/ModelPicker.svelte @@ -11,7 +11,6 @@ idPrefix?: string; disabled?: boolean; configured?: boolean; - onSaved?: () => void; }; type ModelCatalog = { @@ -28,12 +27,7 @@ }>; }; - let { - idPrefix = "model", - disabled = false, - configured = $bindable(false), - onSaved, - }: Props = $props(); + let { idPrefix = "model", disabled = false, configured = $bindable(false) }: Props = $props(); const i18n = useI18n(); let catalog = $state(null); @@ -98,7 +92,6 @@ await loadCatalog(); if (catalog?.configured) { toast.success(i18n.t("toast-model-saved")); - onSaved?.(); } else { toast.error(i18n.t("toast-model-save-failed")); } diff --git a/web/src/lib/components/explorer/ModelSettingsView.svelte b/web/src/lib/components/explorer/ModelSettingsView.svelte index 06c10409..5eeb756b 100644 --- a/web/src/lib/components/explorer/ModelSettingsView.svelte +++ b/web/src/lib/components/explorer/ModelSettingsView.svelte @@ -2,7 +2,7 @@ import BorderedPanel from "$lib/components/ui/bordered-panel.svelte"; import ModelPicker from "$lib/components/explorer/ModelPicker.svelte"; import { useI18n } from "$lib/i18n/context.svelte"; - import { CARD_PAD, STACK, STACK_SECTION } from "$lib/ui/styles"; + import { STACK_SECTION } from "$lib/ui/styles"; import { cn } from "$lib/utils"; const i18n = useI18n(); @@ -10,9 +10,7 @@
-
- -

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

-
+ +

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

From 5b2a841956e973de533f817bcfd8035db8ebeeb3 Mon Sep 17 00:00:00 2001 From: rwjxrj <2206232778@qq.com> Date: Fri, 20 Nov 2026 09:27:09 +0800 Subject: [PATCH 9/9] feat(web): cover the model picker in sim mode Sim mode had no answer for /api/config/model-provider, so the picker always showed the unavailable branch. Serve the catalog from a fixture and keep PUT selections for the session, matching the other simulated mutations. --- web/sim/config-model-provider.json | 29 +++++++++++++++ web/vite-plugins/opencode-mem-sim.ts | 53 ++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 web/sim/config-model-provider.json 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/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;