🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(llm-relay): local-model relay follow-ups and a one-minute client wait (#21081)
Arvin Xu2440efcea850
diff --git a/apps/server/src/globalConfig/serverFetchOnClient.test.ts b/apps/server/src/globalConfig/serverFetchOnClient.test.tsindex 8451ff66394..4be4e1cded1 100644--- a/apps/server/src/globalConfig/serverFetchOnClient.test.ts+++ b/apps/server/src/globalConfig/serverFetchOnClient.test.ts@@ -1,3 +1,4 @@+import { isProviderFetchOnClient } from 'model-bank/modelProviders';import { afterEach, describe, expect, it, vi } from 'vitest';import { getServerFetchOnClientOverride } from './serverFetchOnClient';@@ -14,8 +15,23 @@ describe('getServerFetchOnClientOverride', () => {expect(getServerFetchOnClientOverride('ollama')).toBe(false);});+ it('turns client fetch on for the other local providers', () => {+ expect(getServerFetchOnClientOverride('lmstudio')).toBe(true);+ expect(getServerFetchOnClientOverride('unsloth')).toBe(true);+ });++ // The settings switch shows this default; it must match what the relay does.+ it.each(['ollama', 'lmstudio', 'unsloth'])(+ 'shows the same default for %s as the relay applies',+ (provider) => {+ const fetchOnClient = getServerFetchOnClientOverride(provider);++ expect(fetchOnClient).toBe(isProviderFetchOnClient(provider, { fetchOnClient }));+ expect(fetchOnClient).toBe(isProviderFetchOnClient(provider, undefined));+ },+ );+it('leaves other providers on their own default', () => {- expect(getServerFetchOnClientOverride('lmstudio')).toBeUndefined();expect(getServerFetchOnClientOverride('openai')).toBeUndefined();});});diff --git a/apps/server/src/globalConfig/serverFetchOnClient.ts b/apps/server/src/globalConfig/serverFetchOnClient.tsindex 43f059bb8f8..f01e90f6947 100644--- a/apps/server/src/globalConfig/serverFetchOnClient.ts+++ b/apps/server/src/globalConfig/serverFetchOnClient.ts@@ -7,13 +7,15 @@ import { isDesktop } from '@/const/version';** - Desktop builds request local providers from the main process, never the* renderer.+ * - On the web, local providers run on this device (the relay sends them to the+ * tab), so the settings switch must show them on rather than unset.* - A deployment with `OLLAMA_PROXY_URL` proxies Ollama through the server.*/export const getServerFetchOnClientOverride = (provider: string): boolean | undefined => {switch (provider) {case 'lmstudio':case 'unsloth': {- return isDesktop ? false : undefined;+ return !isDesktop;}case 'ollama': {return isDesktop ? false : !process.env.OLLAMA_PROXY_URL;diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex e2d3f8ff505..c3cb30fffca 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -103,7 +103,13 @@ const KNOWN_ERROR_CODES = new Set<string>([export const createStreamExecutionError = (errorData: unknown) => {const errorRecord = toRecord(errorData);const body = toRecord(errorRecord?.body);- const message = pickString(errorRecord?.message) ?? pickString(body?.message);+ // A provider runtime error (`AgentRuntimeError.chat`, also what a relayed+ // device call reports) keeps its text under `error.message`.+ const nestedError = toRecord(errorRecord?.error);+ const message =+ pickString(errorRecord?.message) ??+ pickString(body?.message) ??+ pickString(nestedError?.message);const error = new Error(message ? `LLM stream error: ${message}` : `LLM stream error: ${JSON.stringify(errorData)}`,);@@ -122,7 +128,18 @@ export const createStreamExecutionError = (errorData: unknown) => {// fall through to the Error itself and emit `body: { body: {…}, type,// errorType }`, pushing `provider` / `context` one level below the// `ChatMessageError.body` contract that the renderers read.- Object.assign(error, { errorType, ...(body ? { _responseBody: body } : {}) });+ // Without a `body`, the provider error itself is the display body, shaped+ // as `/webapi/chat` answers it (`{ error, provider }`): the Ollama card+ // reads `body.error.message` to offer downloading a missing model.+ const responseBody =+ body ??+ (nestedError+ ? {+ error: nestedError,+ ...(errorRecord.provider === undefined ? {} : { provider: errorRecord.provider }),+ }+ : undefined);+ Object.assign(error, { errorType, ...(responseBody ? { _responseBody: responseBody } : {}) });}}diff --git a/apps/server/src/modules/AgentRuntime/adapters/streamExecutionError.test.ts b/apps/server/src/modules/AgentRuntime/adapters/streamExecutionError.test.tsindex 7d4b485af96..d4faed03702 100644--- a/apps/server/src/modules/AgentRuntime/adapters/streamExecutionError.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/streamExecutionError.test.ts@@ -60,6 +60,32 @@ describe('createStreamExecutionError', () => {expect((error as { errorType?: string }).errorType).toBeUndefined();});+ // Shape a provider runtime throws (`AgentRuntimeError.chat`) and a relayed+ // device call reports: the human text sits under `error.message`.+ const ollamaMissingModel = {+ error: { message: "model 'smollm2:135m' not found", name: 'ResponseError', status_code: 404 },+ errorType: AgentRuntimeErrorType.OllamaBizError,+ provider: 'ollama',+ };++ it('reads the message of a provider error from its nested error', () => {+ const error = createStreamExecutionError(ollamaMissingModel);++ expect(error.message).toBe("LLM stream error: model 'smollm2:135m' not found");+ });++ it('keeps a provider error under body.error so the provider error card can read it', () => {+ // The Ollama card reads `body.error.message` to offer downloading the+ // missing model; a stringified payload there left the message blank.+ const formatted = formatErrorForState(createStreamExecutionError(ollamaMissingModel));++ expect(formatted.type).toBe(AgentRuntimeErrorType.OllamaBizError);+ expect(formatted.body).toMatchObject({+ error: { message: "model 'smollm2:135m' not found", status_code: 404 },+ provider: 'ollama',+ });+ });+it('falls back to stringifying when no message can be found anywhere', () => {const error = createStreamExecutionError({ code: 42 });diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/clientWait.ts b/apps/server/src/modules/AgentRuntime/llmRelay/clientWait.tsindex 0e74baf2056..c682c20f337 100644--- a/apps/server/src/modules/AgentRuntime/llmRelay/clientWait.ts+++ b/apps/server/src/modules/AgentRuntime/llmRelay/clientWait.ts@@ -14,11 +14,13 @@ import type { ClientLlmUnavailableReason } from './errors';*//**- * How long a parked run waits for a client. Well inside the gateway's 30 min- * inactivity watchdog, so the parked stream is never reaped as dead first.- * `AGENT_LLM_RELAY_CLIENT_WAIT_MS` overrides it (self-hosting, tests).+ * How long a parked run waits for a client. Long enough to reload or reopen a+ * tab, short enough that a run with no client (schedule, bot, CLI) fails soon.+ * Well inside the gateway's 30 min inactivity watchdog, so the parked stream is+ * never reaped as dead first. `AGENT_LLM_RELAY_CLIENT_WAIT_MS` overrides it+ * (self-hosting, tests).*/-export const DEFAULT_LLM_RELAY_CLIENT_WAIT_MS = 10 * 60_000;+export const DEFAULT_LLM_RELAY_CLIENT_WAIT_MS = 60_000;const MAX_LLM_RELAY_CLIENT_WAIT_MS = 25 * 60_000;diff --git a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts b/apps/server/src/routers/lambda/__tests__/aiProvider.test.tsindex 767411cf93c..4358b099207 100644--- a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts@@ -155,8 +155,10 @@ describe('aiProviderRouter', () => {const caller = aiProviderRouter.createCaller(createMockContext());const result = await caller.checkProviderConnectivity({ id: 'ollama' });+ // The type alone does not tell a CLI user what to do; the reason does.expect(result).toEqual({- error: 'ClientLlmExecutorUnavailable',+ error:+ "ClientLlmExecutorUnavailable: ollama runs on the user's device, and no open LobeHub tab is attached to this request to run it.",model: 'qwen3:1.7b',ok: false,});diff --git a/apps/server/src/routers/lambda/aiProvider.ts b/apps/server/src/routers/lambda/aiProvider.tsindex 93d549c8f7f..c8036c4e646 100644--- a/apps/server/src/routers/lambda/aiProvider.ts+++ b/apps/server/src/routers/lambda/aiProvider.ts@@ -127,11 +127,17 @@ export const aiProviderRouter = router({return { error: errorBody, model, ok: false, status: response.status };} catch (error: any) {const errorType = error.errorType || error.type;- const msg =- errorType ||- (typeof error === 'string'+ // A provider error keeps its reason under `error.message` (e.g. a device-only+ // provider checked from the CLI with no tab to run it); the type alone does+ // not tell the user what to do.+ const reason = typeof error.error?.message === 'string' ? error.error.message : undefined;+ const msg = errorType+ ? reason+ ? `${errorType}: ${reason}`+ : errorType+ : typeof error === 'string'? error- : error.message || (typeof error === 'object' ? JSON.stringify(error) : String(error)));+ : error.message || (typeof error === 'object' ? JSON.stringify(error) : String(error));return { error: msg, model, ok: false };}}),diff --git a/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts b/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.tsindex 89f11ea76ca..2df7000150f 100644--- a/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts@@ -196,7 +196,7 @@ describe('waiting_for_client (U4c)', () => {expect(parked.clientLlmWait).toEqual({assistantMessageId: 'msg-assistant',context: { phase: 'user_input' },- expiresAt: new Date(NOW + 600_000).toISOString(),+ expiresAt: new Date(NOW + 60_000).toISOString(),parentMessageId: 'msg-user',parkedAt: new Date(NOW).toISOString(),provider: 'lmstudio',@@ -229,7 +229,7 @@ describe('waiting_for_client (U4c)', () => {expect(t.scheduleMessage).toHaveBeenCalledTimes(1);expect(t.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({- delay: 600_000,+ delay: 60_000,operationId: OPERATION_ID,payload: { clientLlmWaitExpired: new Date(NOW).toISOString() },stepIndex: 1,@@ -410,7 +410,7 @@ describe('waiting_for_client (U4c)', () => {});it('honours AGENT_LLM_RELAY_CLIENT_WAIT_MS for the wait window', async () => {- vi.stubEnv('AGENT_LLM_RELAY_CLIENT_WAIT_MS', '60000');+ vi.stubEnv('AGENT_LLM_RELAY_CLIENT_WAIT_MS', '120000');try {const t = createService();t.setStored(runningState());@@ -427,8 +427,8 @@ describe('waiting_for_client (U4c)', () => {stepIndex: 1,});- expect(t.getStored().clientLlmWait.expiresAt).toBe(new Date(NOW + 60_000).toISOString());- expect(t.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ delay: 60_000 }));+ expect(t.getStored().clientLlmWait.expiresAt).toBe(new Date(NOW + 120_000).toISOString());+ expect(t.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ delay: 120_000 }));} finally {vi.unstubAllEnvs();}@@ -605,14 +605,14 @@ describe('waiting_for_client (U4c)', () => {it('keeps the original deadline when a resumed call finds no client again', async () => {const t = createService();- const deadline = new Date(NOW + 120_000).toISOString();+ const deadline = new Date(NOW + 30_000).toISOString();t.setStored(waitingState({clientLlmWait: {assistantMessageId: 'msg-assistant',context: { phase: 'user_input' },expiresAt: deadline,- parkedAt: new Date(NOW - 480_000).toISOString(),+ parkedAt: new Date(NOW - 30_000).toISOString(),provider: 'lmstudio',reason: 'no_executor',},@@ -633,7 +633,7 @@ describe('waiting_for_client (U4c)', () => {expect(t.getStored().status).toBe('waiting_for_client');expect(t.getStored().clientLlmWait.expiresAt).toBe(deadline);- expect(t.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ delay: 120_000 }));+ expect(t.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ delay: 30_000 }));});it('leaves a wait past its deadline to the (late) expiry instead of resuming it', async () => {diff --git a/apps/server/src/services/taskReview/index.test.ts b/apps/server/src/services/taskReview/index.test.tsnew file mode 100644index 00000000000..12fd7007f3d--- /dev/null+++ b/apps/server/src/services/taskReview/index.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node+import type { ModelRuntime } from '@lobechat/model-runtime';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';+import * as ModelRuntimeModule from '@/server/modules/ModelRuntime';++import { TaskReviewService } from './index';++vi.mock('@/database/models/user', () => ({+ UserModel: class {+ getUserSettings = async () => ({+ systemAgent: { topic: { model: 'qwen3:1.7b', provider: 'ollama' } },+ });+ },+}));++const resolveProviderRelay = vi.hoisted(() => vi.fn());+vi.mock('@/server/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite', () => ({+ resolveProviderRelay,+}));+// A deployment that can relay (Agent Gateway + Redis).+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => ({}) }));+vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ createStreamEventManager: () => ({ openLlmRelayChannel: vi.fn(), sendLlmExecute: vi.fn() }),+}));++afterEach(() => {+ vi.restoreAllMocks();+ resolveProviderRelay.mockReset();+});++const reviewParams = {+ content: 'The task output.',+ judge: {},+ rubrics: [+ {+ config: { criteria: 'Is the output complete?' },+ id: 'r1',+ name: 'complete',+ type: 'llm-rubric' as const,+ weight: 1,+ },+ ],+ taskName: 'Ship it',+};++describe('TaskReviewService with a device-only judge model', () => {+ // The judge (here the topic model on Ollama) only runs on the user's device.+ // A review requested without a browser tab attached must say so, not call+ // the provider from the server.+ it('fails with no_executor when no browser tab is attached', async () => {+ resolveProviderRelay.mockResolvedValue({ runtimeProvider: 'ollama' });+ const init = vi.spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB').mockResolvedValue({+ generateObject: vi.fn().mockResolvedValue({ reason: 'ok', score: 1 }),+ } as unknown as ModelRuntime);+ const service = new TaskReviewService({} as LobeChatDatabase, 'user-1');++ await expect(service.review(reviewParams)).rejects.toMatchObject({+ error: expect.objectContaining({ reason: 'no_executor' }),+ errorType: 'ClientLlmExecutorUnavailable',+ });+ expect(init).not.toHaveBeenCalled();+ });++ it('keeps calling a cloud judge from the server', async () => {+ resolveProviderRelay.mockResolvedValue(undefined);+ const generateObject = vi.fn().mockResolvedValue({ reason: 'ok', score: 1 });+ const init = vi+ .spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB')+ .mockResolvedValue({ generateObject } as unknown as ModelRuntime);+ const service = new TaskReviewService({} as LobeChatDatabase, 'user-1');++ const result = await service.review(reviewParams);++ expect(init).toHaveBeenCalledWith({}, 'user-1', 'ollama', undefined);+ expect(generateObject).toHaveBeenCalled();+ expect(result.passed).toBe(true);+ });+});diff --git a/apps/server/src/services/taskReview/index.ts b/apps/server/src/services/taskReview/index.tsindex 8ff697f4b2c..1baee6bd0be 100644--- a/apps/server/src/services/taskReview/index.ts+++ b/apps/server/src/services/taskReview/index.ts@@ -5,7 +5,7 @@ import debug from 'debug';import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';import { resolveSystemAgentModelConfig } from '../systemAgent/modelConfig';@@ -65,13 +65,11 @@ export class TaskReviewService {rubrics.length,);- // 2. Initialize ModelRuntime for LLM-based rubrics- const modelRuntime = await initModelRuntimeFromDB(- this.db,- this.userId,- provider,- this.workspaceId,- );+ // 2. Initialize ModelRuntime for LLM-based rubrics. A judge only the user's+ // device reaches is relayed to the requesting tab (fails fast without one).+ const modelRuntime = await initModelRuntimeForRequest(this.db, this.userId, provider, {+ workspaceId: this.workspaceId,+ });// 3. Run evaluate() from @lobechat/eval-rubricconst result: EvaluateResult = await evaluate(diff --git a/packages/model-runtime/src/providers/ollama/generateObject.test.ts b/packages/model-runtime/src/providers/ollama/generateObject.test.tsnew file mode 100644index 00000000000..e202388de29--- /dev/null+++ b/packages/model-runtime/src/providers/ollama/generateObject.test.ts@@ -0,0 +1,182 @@+// @vitest-environment node+import { Ollama } from 'ollama/browser';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { StructuredOutputError } from '../../core/openaiCompatibleFactory/structuredOutput';+import { AgentRuntimeErrorType } from '../../types/error';+import { LobeOllamaAI } from './index';++vi.mock('ollama/browser');++const schema = {+ name: 'topic_title',+ schema: {+ properties: { title: { type: 'string' } },+ required: ['title'],+ type: 'object' as const,+ },+};++describe('LobeOllamaAI.generateObject', () => {+ let ollamaAI: LobeOllamaAI;++ beforeEach(() => {+ ollamaAI = new LobeOllamaAI({ baseURL: 'http://localhost:11434' });+ });++ afterEach(() => {+ vi.resetAllMocks();+ });++ it('constrains the reply with the JSON schema as Ollama `format` and parses it', async () => {+ vi.mocked(Ollama.prototype.chat).mockResolvedValue({+ eval_count: 12,+ message: { content: '{"title":"Sourdough basics"}', role: 'assistant' },+ prompt_eval_count: 30,+ } as any);+ const onUsage = vi.fn();++ const result = await ollamaAI.generateObject(+ { messages: [{ content: 'Name this chat', role: 'user' }], model: 'qwen3:1.7b', schema },+ { onUsage },+ );++ expect(result).toEqual({ title: 'Sourdough basics' });+ expect(Ollama.prototype.chat).toHaveBeenCalledWith(+ expect.objectContaining({+ format: schema.schema,+ messages: [{ content: 'Name this chat', role: 'user' }],+ model: 'qwen3:1.7b',+ stream: false,+ }),+ );+ expect(onUsage).toHaveBeenCalledWith(+ expect.objectContaining({ inputTextTokens: 30, outputTextTokens: 12, totalTokens: 42 }),+ );+ });++ it('turns thinking off only when the caller disables it', async () => {+ vi.mocked(Ollama.prototype.chat).mockResolvedValue({+ message: { content: '{"title":"x"}', role: 'assistant' },+ } as any);++ await ollamaAI.generateObject({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'qwen3:1.7b',+ schema,+ thinking: { budget_tokens: 0, type: 'disabled' },+ });+ expect(vi.mocked(Ollama.prototype.chat).mock.calls[0][0]).toMatchObject({ think: false });++ await ollamaAI.generateObject({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'llama3.2:3b',+ schema,+ });+ expect(vi.mocked(Ollama.prototype.chat).mock.calls[1][0]).not.toHaveProperty('think');+ });++ it('returns tool calls in the `{ arguments, name }[]` shape for tools-based calls', async () => {+ vi.mocked(Ollama.prototype.chat).mockResolvedValue({+ message: {+ content: '',+ role: 'assistant',+ tool_calls: [{ function: { arguments: { items: ['a', 'b'] }, name: 'suggest' } }],+ },+ } as any);+ const tools = [+ {+ function: {+ name: 'suggest',+ parameters: { properties: { items: { type: 'array' } }, type: 'object' },+ },+ type: 'function' as const,+ },+ ];++ const result = await ollamaAI.generateObject({+ messages: [{ content: 'follow ups?', role: 'user' }],+ model: 'llama3.2:3b',+ tools,+ });++ expect(result).toEqual([{ arguments: { items: ['a', 'b'] }, name: 'suggest' }]);+ expect(Ollama.prototype.chat).toHaveBeenCalledWith(+ expect.objectContaining({ stream: false, tools }),+ );+ });++ it('rejects a reply that is not valid JSON with a StructuredOutputError', async () => {+ vi.mocked(Ollama.prototype.chat).mockResolvedValue({+ message: { content: 'Sure! Here is a title', role: 'assistant' },+ } as any);++ await expect(+ ollamaAI.generateObject({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'qwen3:1.7b',+ schema,+ }),+ ).rejects.toBeInstanceOf(StructuredOutputError);+ });++ it('rejects a tools call that returns no tool calls', async () => {+ vi.mocked(Ollama.prototype.chat).mockResolvedValue({+ message: { content: 'no tools', role: 'assistant' },+ } as any);++ await expect(+ ollamaAI.generateObject({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'llama3.2:3b',+ tools: [{ function: { name: 'suggest', parameters: {} }, type: 'function' }],+ }),+ ).rejects.toBeInstanceOf(StructuredOutputError);+ });++ it('maps Ollama failures to an OllamaBizError', async () => {+ vi.mocked(Ollama.prototype.chat).mockRejectedValue({+ error: 'model "nope" not found',+ name: 'ResponseError',+ status_code: 404,+ });++ await expect(+ ollamaAI.generateObject({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'nope',+ schema,+ }),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.OllamaBizError });+ });++ // Regression: a non-streamed Ollama call is out of `client.abort()`'s reach, so a+ // cancelled relayed structured call used to keep Ollama generating until it finished.+ it('sends the request with the caller abort signal', async () => {+ vi.mocked(Ollama.prototype.chat).mockResolvedValue({+ message: { content: '{"title":"x"}', role: 'assistant' },+ } as any);+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}'));+ const controller = new AbortController();++ await ollamaAI.generateObject(+ { messages: [{ content: 'hi', role: 'user' }], model: 'qwen3:1.7b', schema },+ { signal: controller.signal },+ );++ const config = vi.mocked(Ollama).mock.calls.at(-1)?.[0];+ expect(config).toMatchObject({ host: 'http://localhost:11434' });+ await config?.fetch?.('http://localhost:11434/api/chat', { method: 'POST' });+ expect(fetchSpy).toHaveBeenCalledWith(+ 'http://localhost:11434/api/chat',+ expect.objectContaining({ method: 'POST', signal: controller.signal }),+ );+ fetchSpy.mockRestore();+ });++ it('requires a schema or tools', async () => {+ await expect(+ ollamaAI.generateObject({ messages: [{ content: 'hi', role: 'user' }], model: 'x' }),+ ).rejects.toThrow('tools or schema is required');+ });+});diff --git a/packages/model-runtime/src/providers/ollama/index.ts b/packages/model-runtime/src/providers/ollama/index.tsindex c84ba69ad97..861cd280242 100644--- a/packages/model-runtime/src/providers/ollama/index.ts+++ b/packages/model-runtime/src/providers/ollama/index.ts@@ -1,17 +1,24 @@import type { ChatModelCard } from '@lobechat/types';import { imageUrlToBase64 } from '@lobechat/utils';import { ModelProvider } from 'model-bank';-import type { Tool } from 'ollama/browser';+import type { ChatResponse, Tool } from 'ollama/browser';import { Ollama } from 'ollama/browser';import type { ClientOptions } from 'openai';import type { LobeRuntimeAI } from '../../core/BaseAI';+import {+ parseStructuredOutputText,+ parseStructuredToolArguments,+ StructuredOutputError,+} from '../../core/openaiCompatibleFactory/structuredOutput';import { convertIterableToStream, createModelPullStream, OllamaStream } from '../../core/streams';import type {ChatMethodOptions,ChatStreamPayload,Embeddings,EmbeddingsPayload,+ GenerateObjectOptions,+ GenerateObjectPayload,ModelRequestOptions,OpenAIChatMessage,PullModelParams,@@ -86,48 +93,104 @@ export class LobeOllamaAI implements LobeRuntimeAI {headers: options?.headers,});} catch (error) {- const e = error as {- error: any;- message: string;- name: string;- status_code: number;- };- const errorDetail = {- ...(typeof e.error !== 'string' ? e.error : undefined),- message: String(e.error?.message || e.message),- name: e.name,- status_code: e.status_code,- };+ throw await this.toRuntimeError(error);+ }+ }- const fetchErrorMessage = e.message?.toLowerCase();- if (fetchErrorMessage === 'fetch failed' || fetchErrorMessage === 'failed to fetch') {- // A long-running chat request can fail even while the local Ollama service remains healthy.- // See https://github.com/lobehub/lobehub/issues/17316- try {- await this.client.list();- } catch {- throw AgentRuntimeError.chat({- error: {- message: 'please check whether your ollama service is available',- },- errorType: AgentRuntimeErrorType.OllamaServiceUnavailable,- provider: ModelProvider.Ollama,- });- }+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {+ const { messages, model, schema, thinking, tools } = payload;+ if (!tools && !schema) throw new Error('tools or schema is required');++ // `client.abort()` only reaches streamed requests, so a cancelled structured+ // call gets a one-off client whose fetch carries the caller's signal.+ const signal = options?.signal;+ const client = signal+ ? new Ollama({+ fetch: (input, init) => fetch(input, { ...init, signal }),+ ...(this.baseURL && { host: this.baseURL }),+ })+ : this.client;++ let response: ChatResponse;+ try {+ response = await client.chat({+ format: tools ? undefined : schema!.schema,+ messages,+ model,+ stream: false,+ // Ollama rejects `think: true` on models without thinking, so only ever turn it off.+ ...(thinking?.type === 'disabled' && { think: false }),+ tools: tools as Tool[] | undefined,+ });+ } catch (error) {+ throw await this.toRuntimeError(error);+ }++ if (response.prompt_eval_count !== undefined || response.eval_count !== undefined) {+ const inputTokens = response.prompt_eval_count ?? 0;+ const outputTokens = response.eval_count ?? 0;+ await options?.onUsage?.({+ inputTextTokens: inputTokens,+ outputTextTokens: outputTokens,+ totalInputTokens: inputTokens,+ totalOutputTokens: outputTokens,+ totalTokens: inputTokens + outputTokens,+ });+ }++ if (!tools) return parseStructuredOutputText(response.message?.content);++ const toolCalls = response.message?.tool_calls;+ if (!toolCalls?.length) throw new StructuredOutputError('no tool calls returned');++ return toolCalls.map((item) => ({+ arguments: parseStructuredToolArguments(item.function.arguments),+ name: item.function.name,+ }));+ }++ private async toRuntimeError(error: unknown) {+ const e = error as {+ error: any;+ message: string;+ name: string;+ status_code: number;+ };+ const errorDetail = {+ ...(typeof e.error !== 'string' ? e.error : undefined),+ message: String(e.error?.message || e.message),+ name: e.name,+ status_code: e.status_code,+ };- throw AgentRuntimeError.chat({- error: errorDetail,- errorType: AgentRuntimeErrorType.ProviderNetworkError,+ const fetchErrorMessage = e.message?.toLowerCase();+ if (fetchErrorMessage === 'fetch failed' || fetchErrorMessage === 'failed to fetch') {+ // A long-running chat request can fail even while the local Ollama service remains healthy.+ // See https://github.com/lobehub/lobehub/issues/17316+ try {+ await this.client.list();+ } catch {+ return AgentRuntimeError.chat({+ error: {+ message: 'please check whether your ollama service is available',+ },+ errorType: AgentRuntimeErrorType.OllamaServiceUnavailable,provider: ModelProvider.Ollama,});}- throw AgentRuntimeError.chat({+ return AgentRuntimeError.chat({error: errorDetail,- errorType: AgentRuntimeErrorType.OllamaBizError,+ errorType: AgentRuntimeErrorType.ProviderNetworkError,provider: ModelProvider.Ollama,});}++ return AgentRuntimeError.chat({+ error: errorDetail,+ errorType: AgentRuntimeErrorType.OllamaBizError,+ provider: ModelProvider.Ollama,+ });}async embeddings(payload: EmbeddingsPayload): Promise<Embeddings[]> {diff --git a/src/features/Conversation/Error/OllamaBizError/index.tsx b/src/features/Conversation/Error/OllamaBizError/index.tsxindex 535d9c4e439..f81f6b5df28 100644--- a/src/features/Conversation/Error/OllamaBizError/index.tsx+++ b/src/features/Conversation/Error/OllamaBizError/index.tsx@@ -5,26 +5,14 @@ import { memo } from 'react';import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';import dynamic from '@/libs/next/dynamic';+import { getOllamaErrorMessage, getUnresolvedOllamaModel } from './parseOllamaError';+const loading = () => <Skeleton style={{ width: 300 }} />;const SetupGuide = dynamic(() => import('../OllamaSetupGuide'), { loading, ssr: false });const InvalidModel = dynamic(() => import('./InvalidOllamaModel'), { loading, ssr: false });-interface OllamaError {- code: string | null;- message: string;- param?: any;- type: string;-}--interface OllamaErrorResponse {- error: OllamaError;-}--// eslint-disable-next-line regexp/no-dupe-characters-character-class, regexp/no-obscure-range-const UNRESOLVED_MODEL_REGEXP = /model "([\w+,-_]+)" not found/;-interface OllamaBizErrorProps {alertError?: AlertProps;error?: ChatMessageError | null;@@ -32,12 +20,10 @@ interface OllamaBizErrorProps {}const OllamaBizError = memo<OllamaBizErrorProps>(({ alertError, error, id }) => {- const errorBody: OllamaErrorResponse = (error as any)?.body;-- const errorMessage = errorBody.error?.message;+ const errorMessage = getOllamaErrorMessage(error);// error of not pull the model- const unresolvedModel = errorMessage?.match(UNRESOLVED_MODEL_REGEXP)?.[1];+ const unresolvedModel = getUnresolvedOllamaModel(error);if (unresolvedModel) {return <InvalidModel id={id} model={unresolvedModel} />;}@@ -47,7 +33,8 @@ const OllamaBizError = memo<OllamaBizErrorProps>(({ alertError, error, id }) =>return <SetupGuide id={id} />;}- return <ErrorContent error={alertError} id={id} />;+ // Without the alert the message would render empty.+ return <ErrorContent error={alertError ?? { message: errorMessage, type: 'error' }} id={id} />;});export default OllamaBizError;diff --git a/src/features/Conversation/Error/OllamaBizError/parseOllamaError.test.ts b/src/features/Conversation/Error/OllamaBizError/parseOllamaError.test.tsnew file mode 100644index 00000000000..99118d418f6--- /dev/null+++ b/src/features/Conversation/Error/OllamaBizError/parseOllamaError.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { getOllamaErrorMessage, getUnresolvedOllamaModel } from './parseOllamaError';++const error = (body: unknown, message = 'error') =>+ ({ body, message, type: 'OllamaBizError' }) as any;++describe('getUnresolvedOllamaModel', () => {+ it('reads a single-quoted model name, as current Ollama reports it', () => {+ expect(+ getUnresolvedOllamaModel(+ error({ error: { message: "model 'smollm2:135m' not found" }, provider: 'ollama' }),+ ),+ ).toBe('smollm2:135m');+ });++ it('still reads the double-quoted form', () => {+ expect(+ getUnresolvedOllamaModel(error({ error: { message: 'model "llama3.2:3b" not found' } })),+ ).toBe('llama3.2:3b');+ });++ it('falls back to the body and error messages', () => {+ expect(getUnresolvedOllamaModel(error({ message: "model 'a:1b' not found" }))).toBe('a:1b');+ expect(getUnresolvedOllamaModel(error(undefined, "model 'b:2b' not found"))).toBe('b:2b');+ });++ it('returns nothing for other Ollama errors', () => {+ expect(getUnresolvedOllamaModel(error({ error: { message: 'Failed to fetch' } }))).toBe(+ undefined,+ );+ expect(getOllamaErrorMessage(error({ error: { message: 'Failed to fetch' } }))).toBe(+ 'Failed to fetch',+ );+ });+});diff --git a/src/features/Conversation/Error/OllamaBizError/parseOllamaError.ts b/src/features/Conversation/Error/OllamaBizError/parseOllamaError.tsnew file mode 100644index 00000000000..99926f54c01--- /dev/null+++ b/src/features/Conversation/Error/OllamaBizError/parseOllamaError.ts@@ -0,0 +1,24 @@+import { type ChatMessageError } from '@lobechat/types';++// Ollama has quoted the model name both ways: `model "x" not found` and `model 'x' not found`.+const UNRESOLVED_MODEL_REGEXP = /model ["']([^"']+)["'] not found/;++/**+ * The provider's own message. `body.error.message` is the `/webapi/chat` and+ * server-runtime shape; `body.message` / the error message are the fallbacks+ * for a body that was flattened on the way.+ */+export const getOllamaErrorMessage = (error?: ChatMessageError | null): string | undefined => {+ const body = error?.body as { error?: unknown; message?: unknown } | undefined;+ const nested = body?.error;+ const candidates = [+ nested && typeof nested === 'object' ? (nested as { message?: unknown }).message : nested,+ body?.message,+ error?.message,+ ];+ return candidates.find((value): value is string => typeof value === 'string' && !!value);+};++/** The model Ollama has not pulled yet, when that is what the error says. */+export const getUnresolvedOllamaModel = (error?: ChatMessageError | null): string | undefined =>+ getOllamaErrorMessage(error)?.match(UNRESOLVED_MODEL_REGEXP)?.[1];diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 2a2f35a1832..1304eaf7ebe 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -532,7 +532,9 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(}case AgentRuntimeErrorType.OllamaBizError: {- return <OllamaBizError {...data} />;+ return (+ <OllamaBizError {...data} alertError={{ ...alertError, message: displayMessage }} />+ );}case AgentRuntimeErrorType.ExceededContextWindow: {diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex e25dfb712ed..e1ac46afada 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -36,7 +36,7 @@ import {userGeneralSettingsSelectors,userProfileSelectors,} from '@/store/user/selectors';-import { type ChatStreamPayload, type OpenAIChatMessage } from '@/types/openai/chat';+import { type ChatStreamPayload } from '@/types/openai/chat';import { createErrorResponse } from '@/utils/errorResponse';import { createTraceHeader } from '@/utils/trace';@@ -88,10 +88,6 @@ export interface PreparedAssistantMessageContext {replayAssistantReasoning: boolean;}-type ChatStreamInputParams = Partial<Omit<ChatStreamPayload, 'messages'>> & {- messages?: (UIChatMessage | OpenAIChatMessage)[];-};-interface FetchAITaskResultParams extends FetchSSEOptions {abortController?: AbortController;onError?: (e: Error, rawError?: any) => void;@@ -101,9 +97,9 @@ interface FetchAITaskResultParams extends FetchSSEOptions {*/onLoadingChange?: (loading: boolean) => void;/**- * Request object+ * Request object. The messages are the task's complete prompt and are sent as-is.*/- params: ChatStreamInputParams;+ params: Partial<ChatStreamPayload>;trace?: TracePayload;/*** Request source recorded on spend / route-attempt logs. Required so every@@ -494,25 +490,20 @@ class ChatService {onLoadingChange?.(true);try {- const llmMessages = await contextEngineering({- messages: params.messages as any,- model: params.model!,- provider: params.provider!,- });-- await this.getChatCompletion(- { ...params, messages: llmMessages },- {- metadata: { trigger },- onErrorHandle: (error) => {- errorHandle(new Error(error.message), error);- },- onFinish,- onMessageHandle,- signal: abortController?.signal,- trace: this.mapTrace(trace, TraceTagMap.SystemChain),+ // A preset task (translate, compress, rewrite, …) carries its own complete+ // prompt. Running it through the agent context pipeline would mix in the+ // current agent's identity, workspace and management context, which small+ // models echo back verbatim.+ await this.getChatCompletion(params, {+ metadata: { trigger },+ onErrorHandle: (error) => {+ errorHandle(new Error(error.message), error);},- );+ onFinish,+ onMessageHandle,+ signal: abortController?.signal,+ trace: this.mapTrace(trace, TraceTagMap.SystemChain),+ });onLoadingChange?.(false);} catch (e) {diff --git a/src/services/chat/presetTask.test.ts b/src/services/chat/presetTask.test.tsnew file mode 100644index 00000000000..7dbdadd1a6b--- /dev/null+++ b/src/services/chat/presetTask.test.ts@@ -0,0 +1,50 @@+import { chainTranslate } from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useAgentStore } from '@/store/agent';++import { chatService } from './index';++vi.mock('i18next', () => ({+ t: vi.fn((key: string) => `translated_${key}`),+}));++afterEach(() => {+ vi.restoreAllMocks();+});++describe('ChatService.fetchPresetTaskResult context', () => {+ it('sends only the preset task prompt, without the current agent context', async () => {+ // The user is chatting with an agent in agent mode with auto skill+ // activation — the state that makes a chat turn carry agent management,+ // identity and system-date context.+ useAgentStore.setState({+ activeAgentId: 'agt_current',+ agentMap: {+ agt_current: {+ chatConfig: { enableAgentMode: true, skillActivateMode: 'auto' },+ model: 'qwen3:1.7b',+ provider: 'ollama',+ systemRole: 'You are the current agent.',+ title: 'Current Agent',+ },+ },+ } as any);++ const getChatCompletionSpy = vi+ .spyOn(chatService, 'getChatCompletion')+ .mockResolvedValue(new Response(''));++ const task = chainTranslate('你好,世界', 'English');++ await chatService.fetchPresetTaskResult({+ params: { ...task, model: 'qwen3:1.7b', provider: 'ollama' },+ trigger: RequestTrigger.Translate,+ });++ const sent = getChatCompletionSpy.mock.calls[0][0].messages;+ expect(sent).toEqual(task.messages);+ expect(JSON.stringify(sent)).not.toContain('agent_management_context');+ });+});diff --git a/src/services/goal.ts b/src/services/goal.tsindex d6ce66683df..2f80896d4e9 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -7,7 +7,13 @@ import type {GoalTickResult,} from '@lobechat/types';-import { lambdaClient } from '@/libs/trpc/client';+import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';+import { oneShotRelay } from '@/services/llmRelay';+import { useUserStore } from '@/store/user';+import { systemAgentSelectors } from '@/store/user/selectors';++/** The `goal` system agent's provider: advancing a goal decomposes and explores on it. */+const goalModelProvider = () => systemAgentSelectors.goal(useUserStore.getState()).provider;export interface GoalListParams {agentId?: string;@@ -80,16 +86,22 @@ class GoalService {/*** Run the coordinator now and report where it stopped. The goal also advances* on its own as its Work Tasks settle — this is the explicit nudge, not the- * engine, so the surface never has to hold a tick loop open.+ * engine, so the surface never has to hold a tick loop open. Planning runs+ * on the `goal` model inside this request; a model only this device reaches+ * is relayed back to this tab (one-shot relay).*/advance = async (id: string): Promise<GoalTickResult & { ticks: number }> => {- const { data } = await lambdaClient.goal.advance.mutate({ id });+ const { data } = await oneShotRelay.run(goalModelProvider(), (relay) =>+ lambdaClient.goal.advance.mutate({ id }, withLlmRelay(relay)),+ );return data;};- /** Advance the graph by exactly one coordinator step. */+ /** Advance the graph by exactly one coordinator step. Relayed like `advance`. */tick = async (id: string): Promise<GoalTickResult> => {- const { data } = await lambdaClient.goal.tick.mutate({ id });+ const { data } = await oneShotRelay.run(goalModelProvider(), (relay) =>+ lambdaClient.goal.tick.mutate({ id }, withLlmRelay(relay)),+ );return data;};diff --git a/src/services/systemAgentRelay.test.ts b/src/services/systemAgentRelay.test.tsindex b61a29c7f6c..8afbaa9fac2 100644--- a/src/services/systemAgentRelay.test.ts+++ b/src/services/systemAgentRelay.test.ts@@ -7,6 +7,7 @@ import { oneShotRelay } from '@/services/llmRelay';import { useUserStore } from '@/store/user';import { expertiseService } from './expertise';+import { goalService } from './goal';import { taskService } from './task';import { verifyService } from './verify';@@ -20,8 +21,13 @@ vi.mock('@/libs/trpc/client', async (importOriginal) => ({distillRules: { mutate: vi.fn(async () => ({})) },judgeRuleDirections: { mutate: vi.fn(async () => ({ judged: 0 })) },},+ goal: {+ advance: { mutate: vi.fn(async () => ({ data: {} })) },+ tick: { mutate: vi.fn(async () => ({ data: {} })) },+ },task: {analyzeIntent: { mutate: vi.fn(async () => ({})) },+ runReview: { mutate: vi.fn(async () => ({ data: {} })) },synthesizeInstruction: { mutate: vi.fn(async () => ({})) },},verify: {@@ -34,6 +40,7 @@ vi.mock('@/libs/trpc/client', async (importOriginal) => ({},}));vi.mock('@/services/llmRelay', () => ({+ buildLlmExecutorDeclaration: vi.fn(() => ({ providers: ['ollama', 'lmstudio'] })),oneShotRelay: { run: vi.fn() },}));@@ -95,6 +102,25 @@ describe('system-agent browser entries and the one-shot relay', () => {);});+ // `goal.advance` / `goal.tick` decompose and explore the goal inline, on+ // the goal model, inside the request.+ it('goal advance', async () => {+ await goalService.advance('goal-1');++ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function));+ expect(lambdaClient.goal.advance.mutate).toHaveBeenCalledWith(+ { id: 'goal-1' },+ RELAY_OPTIONS,+ );+ });++ it('goal tick', async () => {+ await goalService.tick('goal-1');++ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function));+ expect(lambdaClient.goal.tick.mutate).toHaveBeenCalledWith({ id: 'goal-1' }, RELAY_OPTIONS);+ });+it('generateGoalPlan', async () => {const params = { goal: 'ship it' };await verifyService.generateGoalPlan(params);@@ -199,4 +225,19 @@ describe('system-agent browser entries and the one-shot relay', () => {expect(lambdaClient.verify.executeVerify.mutate).toHaveBeenCalledWith(params, RELAY_OPTIONS);});});++ describe('task review', () => {+ // The judge model is resolved on the server (task judge, else the topic+ // model), so any device provider this tab runs is reason to stand by.+ it('runReview stands by for every device provider this tab runs', async () => {+ await taskService.runReview('task-1', { content: 'done' });++ const providers = vi.mocked(oneShotRelay.run).mock.calls[0][0] as () => string[];+ expect(providers()).toEqual(['ollama', 'lmstudio']);+ expect(lambdaClient.task.runReview.mutate).toHaveBeenCalledWith(+ { content: 'done', id: 'task-1' },+ RELAY_OPTIONS,+ );+ });+ });});diff --git a/src/services/task.ts b/src/services/task.tsindex 8d477a0fdda..e444c4cae29 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -7,7 +7,7 @@ import type {} from '@lobechat/types';import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';-import { oneShotRelay } from '@/services/llmRelay';+import { buildLlmExecutorDeclaration, oneShotRelay } from '@/services/llmRelay';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';@@ -244,8 +244,16 @@ class TaskService {...args: Parameters<typeof lambdaClient.task.updateVerifyConfig.mutate>) => lambdaClient.task.updateVerifyConfig.mutate(...args);+ /**+ * Judge the task's output against its rubrics. The server picks the judge+ * model (the task's own judge, else the topic model), so any device provider+ * this tab runs is reason to stand by as its executor.+ */runReview = async (id: string, params?: { content?: string; topicId?: string }) =>- lambdaClient.task.runReview.mutate({ id, ...params });+ oneShotRelay.run(+ () => buildLlmExecutorDeclaration()?.providers ?? [],+ (relay) => lambdaClient.task.runReview.mutate({ id, ...params }, withLlmRelay(relay)),+ );pinDocument = async (taskId: string, documentId: string, pinnedBy?: string) =>lambdaClient.task.pinDocument.mutate({ documentId, pinnedBy, taskId });diff --git a/src/store/chat/slices/translate/action.test.ts b/src/store/chat/slices/translate/action.test.tsindex 94496e57d47..1c68053a29f 100644--- a/src/store/chat/slices/translate/action.test.ts+++ b/src/store/chat/slices/translate/action.test.ts@@ -110,6 +110,47 @@ describe('ChatEnhanceAction', () => {expect(params.params).not.toHaveProperty('customPrompt');}});+ it('keeps the detected language when a small model adds text after the locale', async () => {+ const messageId = 'message-id';++ act(() => {+ useChatStore.setState({+ activeAgentId: 'session',+ dbMessagesMap: {+ [messageMapKey({ agentId: 'session' })]: [+ {+ id: messageId,+ content: '杭州西湖是中国著名的风景名胜区。',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ role: 'assistant',+ sessionId: 'session',+ },+ ],+ },+ });+ });++ // qwen3:1.7b answers the detection prompt with the locale, then echoes the input+ (chatService.fetchPresetTaskResult as Mock).mockImplementationOnce(async ({ onFinish }) => {+ await onFinish?.('zh-CN \n{杭州西湖是中国著名的风景名胜区。}');+ });+ (chatService.fetchPresetTaskResult as Mock).mockImplementationOnce(async ({ onFinish }) => {+ await onFinish?.('West Lake in Hangzhou is a famous scenic area in China.');+ });++ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.translateMessage(messageId, 'en-US');+ });++ expect(messageService.updateMessageTranslate).toHaveBeenLastCalledWith(messageId, {+ content: 'West Lake in Hangzhou is a famous scenic area in China.',+ from: 'zh-CN',+ to: 'en-US',+ });+ });});describe('clearTranslate', () => {diff --git a/src/store/chat/slices/translate/action.ts b/src/store/chat/slices/translate/action.tsindex e6bf87e5dee..2dd69d5fd50 100644--- a/src/store/chat/slices/translate/action.ts+++ b/src/store/chat/slices/translate/action.ts@@ -12,6 +12,19 @@ import { type StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';+/**+ * The locale the detection prompt answered with. Small local models append the+ * echoed input or a translation after it, so only the first token counts.+ */+const parseDetectedLocale = (output?: string) => {+ const token = output+ ?.trim()+ .split(/\s+/)[0]+ ?.replaceAll(/^[{"'`]+|[}"'`.,]+$/g, '');++ return token && supportLocales.includes(token) ? token : undefined;+};+/*** chat translate*/@@ -78,7 +91,8 @@ export class ChatTranslateActionImpl {// detect from languagechatService.fetchPresetTaskResult({onFinish: async (data) => {- if (data && supportLocales.includes(data)) from = data;+ const detected = parseDetectedLocale(data);+ if (detected) from = detected;await updateMessageTranslate(id, { content, from, to: targetLang });},