Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(llm): name Claude Code's long-context models instead of "Default"
Elian Doranb1bbd7709838
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex 74e23fb74a..a780be9fbd 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -187,6 +187,9 @@ describe("ClaudeAgentProvider.chatChunks", () => {// A known model ID is mapped to its display name (the chat pane renders it verbatim).expect(await usageModel({ model: "claude-fable-5" })).toBe("Claude Fable 5");+ // A long-context ID is named after the model it varies, rather than falling+ // through to the raw `claude-opus-4-8[1m]`.+ expect(await usageModel({ model: "claude-opus-4-8[1m]" })).toBe("Claude Opus 4.8 (1M)");// An unrecognized ID passes through unchanged rather than becoming undefined.expect(await usageModel({ model: "some-unknown-model" })).toBe("some-unknown-model");});@@ -548,7 +551,10 @@ describe("ClaudeAgentProvider.chatChunks", () => {const models = provider.getAvailableModels();expect(models.some(m => m.id === "claude-sonnet-5" && m.isDefault)).toBe(true);expect(provider.getModelPricing("claude-sonnet-5")).toEqual(expect.objectContaining({ input: 0, output: 0 }));+ // A long-context variant prices like its base model, not as an unknown.+ expect(provider.getModelPricing("claude-opus-4-8[1m]")).toEqual(expect.objectContaining({ input: 0, output: 0 }));expect(provider.getModelPricing("no-such-model")).toBeUndefined();+ expect(provider.getModelPricing("no-such-model[1m]")).toBeUndefined();expect(() => provider.chat()).toThrow(/chatChunks/);});@@ -909,6 +915,35 @@ describe("buildSubscriptionModelList", () => {const fable = merged.find(m => m.id === "claude-fable-9");expect(fable).toEqual({ id: "claude-fable-9", name: "Claude Fable 9", contextWindow: undefined, isSubscription: true, pricing: { input: 0, output: 0 } });});++ it("drops the `default` alias so the concrete row it shadows keeps its own name", () => {+ // Claude Code lists `default` first, resolving to the same id as `opus[1m]`.+ // Kept, it would win the dedupe and label the row "Default (recommended)".+ const merged = buildSubscriptionModelList([+ { value: "default", resolvedModel: "claude-opus-4-6[1m]", displayName: "Default (recommended)" },+ { value: "opus[1m]", resolvedModel: "claude-opus-4-6[1m]", displayName: "Opus" },+ { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet" }+ ], curated);++ expect(merged.map(m => m.name)).toEqual(["Sonnet", "Opus"]);+ expect(merged.some(m => m.id === "claude-opus-4-6")).toBe(false);+ });++ it("treats a long-context id as a variant of its base model, next to it and without its default flag", () => {+ const merged = buildSubscriptionModelList([+ { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet" },+ { value: "sonnet[1m]", resolvedModel: "claude-sonnet-5[1m]" },+ { value: "claude-opus-4-6[1m]", displayName: "Opus" }+ ], curated);++ // Curated ordering survives: each variant sits directly after its base.+ expect(merged.map(m => m.id)).toEqual(["claude-sonnet-5", "claude-sonnet-5[1m]", "claude-opus-4-6[1m]"]);+ // Curated metadata is inherited, and the CLI's silence leaves the derived name.+ expect(merged[1]).toMatchObject({ name: "Claude Sonnet 5 (1M)", contextWindow: 1000000, isSubscription: true, isDefault: false });+ // ...including flags the base carries — but never a second default.+ expect(merged[2]).toMatchObject({ name: "Opus", contextWindow: 1000000, isLegacy: true, isDefault: false });+ expect(merged.filter(m => m.isDefault)).toHaveLength(1);+ });});describe("ClaudeAgentProvider.listModels", () => {@@ -1098,4 +1133,13 @@ describe("ClaudeAgentProvider.recommendedModelIds", () => {"claude-fable-5", "claude-haiku-4-5-20251001", "claude-opus-4-8", "claude-sonnet-5"]);});++ it("ranks long-context ids under their base model so they are recommended too", () => {+ // `claude-opus-4-8[1m]` doesn't parse as a family/version on its own; unranked+ // it would be left out even though it is the only Opus row Claude Code offers.+ const ids = new ClaudeAgentProvider().recommendedModelIds(+ ["claude-opus-4-8[1m]", "claude-opus-4-7", "claude-sonnet-5"].map(id => ({ id, name: id }))+ );+ expect([...ids].sort()).toEqual(["claude-opus-4-8[1m]", "claude-sonnet-5"]);+ });});diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex 77b448c0a8..7e0faa5a04 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -182,7 +182,10 @@ export class ClaudeAgentProvider implements LlmProvider {name = "claude-agent";getModelPricing(model: string): ModelPricing | undefined {- return MODEL_PRICING[model];+ // Long-context variants (`claude-opus-4-8[1m]`) are the same model on the+ // same plan, so they price like their base id rather than as unknowns.+ const base = parseContextVariant(model)?.base;+ return MODEL_PRICING[model] ?? (base ? MODEL_PRICING[base] : undefined);}getAvailableModels(): ModelInfo[] {@@ -193,9 +196,20 @@ export class ClaudeAgentProvider implements LlmProvider {* The subscription catalog shares Anthropic's `claude-*` id shape, so it* reuses the metered provider's per-family newest-version rule rather than* the generic non-preview/non-legacy default.+ *+ * Long-context ids (`claude-opus-4-8[1m]`) don't match that shape, so they are+ * ranked under their base id and the winners translated back to the ids+ * actually on offer — otherwise the one Opus row Claude Code lists would be+ * left out of the pre-selected set entirely.*/recommendedModelIds(models: ModelInfo[]): Set<string> {- return anthropicRecommendedIds(models);+ const idsByBase = new Map<string, string[]>();+ for (const model of models) {+ const base = parseContextVariant(model.id)?.base ?? model.id;+ idsByBase.set(base, [...(idsByBase.get(base) ?? []), model.id]);+ }+ const bases = anthropicRecommendedIds([...idsByBase.keys()].map(id => ({ id, name: id })));+ return new Set([...bases].flatMap(base => idsByBase.get(base) ?? []));}/**@@ -349,7 +363,7 @@ export class ClaudeAgentProvider implements LlmProvider {const model = config.model || AVAILABLE_MODELS.find(m => m.isDefault)?.id;// Report the friendly name in usage metadata (the chat pane renders it// verbatim); `model` itself must stay the raw ID for the query() call.- const modelDisplayName = AVAILABLE_MODELS.find(m => m.id === model)?.name ?? model;+ const modelDisplayName = describeModel(model);let sessionId: string | undefined;let assistantText = "";// tool_use id → name, for labelling results; also serves as the guard@@ -701,6 +715,16 @@ export function buildSubscriptionModelList(sdkModels: SubscriptionModelSource[],const remote: RemoteModel[] = [];const seen = new Set<string>();for (const model of sdkModels) {+ // `default` is an account-level alias rather than a model: it resolves to+ // whatever Claude Code currently recommends, and picking it would freeze+ // that resolution into the chat under the unhelpful label "Default+ // (recommended)". Worse, it sorts first, so the dedupe below would drop+ // the concrete row pointing at the same model (`opus[1m]` → "Opus") and+ // keep the alias's label instead. Trilium marks its own default via+ // `isDefault`, so nothing is lost by skipping it.+ if (model.value === "default") {+ continue;+ }const id = model.resolvedModel ?? model.value;if (!id || seen.has(id)) {continue;@@ -709,13 +733,90 @@ export function buildSubscriptionModelList(sdkModels: SubscriptionModelSource[],remote.push({ id, name: model.displayName });}- return mergeModelLists(curated, remote).map(model => ({+ return mergeModelLists(withContextVariants(curated, remote), remote).map(model => ({...model,isSubscription: true,pricing: model.pricing ?? { input: 0, output: 0 }}));}+/** A long-context model id: `claude-opus-4-8[1m]` → base `claude-opus-4-8`, label `1M`. */+const CONTEXT_VARIANT = /\[([^\]]+)\]$/;++function parseContextVariant(id: string): { base: string; label: string } | null {+ const match = CONTEXT_VARIANT.exec(id);+ if (!match) {+ return null;+ }+ return { base: id.slice(0, match.index), label: match[1].toUpperCase() };+}++/**+ * Re-key curated metadata onto the long-context ids the CLI reports.+ *+ * Claude Code offers extended-context variants under a suffixed id+ * (`claude-opus-4-8[1m]`) that no curated entry carries, so the merge would file+ * them as unknown models — losing the context window and legacy flag, and leaving+ * anything that looks a model up by id (pricing, the usage row's display name)+ * with nothing but the raw id to show. A synthetic entry per variant, inserted+ * next to the model it varies so the curated ordering survives, makes them known.+ * The suffix stays part of the id: it is what selects the larger window when the+ * id is handed back to the SDK.+ */+function withContextVariants(curated: ModelInfo[], remote: RemoteModel[]): ModelInfo[] {+ const curatedIds = new Set(curated.map(m => m.id));+ const variantsByBase = new Map<string, string[]>();+ for (const model of remote) {+ if (curatedIds.has(model.id)) {+ continue;+ }+ const variant = parseContextVariant(model.id);+ if (!variant || !curatedIds.has(variant.base)) {+ continue;+ }+ variantsByBase.set(variant.base, [...(variantsByBase.get(variant.base) ?? []), model.id]);+ }+ if (variantsByBase.size === 0) {+ return curated;+ }++ return curated.flatMap(entry => [+ entry,+ // A variant is a distinct row, so it must not inherit the base entry's+ // default flag — that would leave two models claiming to be the default.+ ...(variantsByBase.get(entry.id) ?? []).map(id => ({ ...entry, id, name: variantName(entry.name, id), isDefault: false }))+ ]);+}++/** Offline fallback name for a variant row: `Claude Opus 4.8` + `[1m]` → `Claude Opus 4.8 (1M)`. */+function variantName(baseName: string, id: string): string {+ const variant = parseContextVariant(id);+ return variant ? `${baseName} (${variant.label})` : baseName;+}++/**+ * Friendly name for the model id a chat turn was answered by, for the usage row.+ *+ * The live catalog is consulted first: it is the only source that names models+ * the curated list has never heard of, and it carries the CLI's own wording. It+ * is a cache though, so a chat sent before any model picker was opened falls+ * back to the curated list — by exact id, then by the base of a long-context id+ * — and finally to the raw id, which at least says which model answered.+ */+function describeModel(model: string | undefined): string | undefined {+ if (!model) {+ return undefined;+ }+ const listed = subscriptionModelCache?.models.find(m => m.id === model)+ ?? AVAILABLE_MODELS.find(m => m.id === model);+ if (listed) {+ return listed.name;+ }+ const base = parseContextVariant(model)?.base;+ const curated = base ? AVAILABLE_MODELS.find(m => m.id === base) : undefined;+ return curated ? variantName(curated.name, model) : model;+}+/*** Build the prompt for the current user turn. When the turn carries attachments* the model can consume natively, this returns a one-message stream of Anthropic