Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: catch errors on agent chat to address common issues

Vanalitee866c190f144
diff --git a/src-tauri/src/core/openclaw/commands.rs b/src-tauri/src/core/openclaw/commands.rs
index 1a8c897e5..654e8d18c 100644
--- a/src-tauri/src/core/openclaw/commands.rs
+++ b/src-tauri/src/core/openclaw/commands.rs
@@ -1568,11 +1568,9 @@ pub async fn openclaw_configure(config_input: Option<OpenClawConfigInput>) -> Re
existing["models"]["providers"]["jan"]["apiKey"] =
serde_json::json!(config.models.providers.jan.api_key);
}
- // Always update the jan provider baseUrl when an explicit URL was provided
- if config.models.providers.jan.base_url != DEFAULT_JAN_BASE_URL {
- existing["models"]["providers"]["jan"]["baseUrl"] =
- serde_json::json!(config.models.providers.jan.base_url);
- }
+ // Always update the jan provider baseUrl so a stale port is never kept
+ existing["models"]["providers"]["jan"]["baseUrl"] =
+ serde_json::json!(config.models.providers.jan.base_url);
existing
} else {
defaults
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 9ec19b95b..130c440ca 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -16,7 +16,7 @@ import { ModelFactory } from './model-factory'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useAssistant } from '@/hooks/useAssistant'
import { useAgentMode } from '@/hooks/useAgentMode'
-import { getOpenClawAuthToken, ensureOpenClawHttpApi, OPENCLAW_GATEWAY_URL } from '@/utils/openclaw'
+import { getOpenClawAuthToken, ensureOpenClawHttpApi, OPENCLAW_GATEWAY_URL, checkOpenClawGatewayReachable } from '@/utils/openclaw'
import { useThreads } from '@/hooks/useThreads'
import { useAttachments } from '@/hooks/useAttachments'
import { ExtensionManager } from '@/lib/extension'
@@ -64,16 +64,20 @@ function prependTextDeltaToUIStream(
let prefixEmitted = false
return new ReadableStream<UIMessageChunk>({
async pull(controller) {
- const { done, value } = await reader.read()
- if (done) {
- controller.close()
- return
- }
- controller.enqueue(value)
- if (!prefixEmitted && (value as { type: string }).type === 'text-start') {
- prefixEmitted = true
- const id = (value as { type: 'text-start'; id: string }).id
- controller.enqueue({ type: 'text-delta', id, delta: prefixText } as UIMessageChunk)
+ try {
+ const { done, value } = await reader.read()
+ if (done) {
+ controller.close()
+ return
+ }
+ controller.enqueue(value)
+ if (!prefixEmitted && (value as { type: string }).type === 'text-start') {
+ prefixEmitted = true
+ const id = (value as { type: 'text-start'; id: string }).id
+ controller.enqueue({ type: 'text-delta', id, delta: prefixText } as UIMessageChunk)
+ }
+ } catch (error) {
+ controller.error(error)
}
},
cancel() {
@@ -282,6 +286,8 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
throw new Error('OpenClaw is not available. Please check that it is running in Settings > Remote Access.')
}
+ await checkOpenClawGatewayReachable()
+
const openclawProvider: ProviderObject = {
active: true,
provider: 'openclaw',
@@ -425,19 +431,49 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
return undefined
},
onError: (error) => {
- // Note: By default, the AI SDK will return "An error occurred",
- // which is intentionally vague in case the error contains sensitive information like API keys.
- // If you want to provide more detailed error messages, keep the code below. Otherwise, remove this whole onError callback.
- if (error == null) {
- return 'Unknown error'
- }
- if (typeof error === 'string') {
- return error
- }
- if (error instanceof Error) {
- return error.message
+ const errorMessage = error == null
+ ? 'Unknown error'
+ : typeof error === 'string'
+ ? error
+ : error instanceof Error
+ ? error.message
+ : JSON.stringify(error)
+
+ if (isAgentMode) {
+ const lower = errorMessage.toLowerCase()
+
+ if (
+ lower.includes('connection refused') ||
+ lower.includes('econnrefused') ||
+ lower.includes('failed to fetch') ||
+ lower.includes('network error') ||
+ lower.includes('connect error')
+ ) {
+ return `Cannot connect to the local server. Please check that the API server is running.\n\nOriginal error: ${errorMessage}`
+ }
+
+ if (
+ lower.includes('model not found') ||
+ lower.includes('model_not_found') ||
+ lower.includes('no model loaded') ||
+ lower.includes('no running session') ||
+ lower.includes('no slot available')
+ ) {
+ return `No model is currently loaded. Please start a model first in the model settings.\n\nOriginal error: ${errorMessage}`
+ }
+
+ if (
+ (lower.includes('context') && (lower.includes('size') || lower.includes('length') || lower.includes('limit') || lower.includes('exceed'))) ||
+ lower.includes('prompt is too long') ||
+ lower.includes('maximum context') ||
+ lower.includes('token limit') ||
+ lower.includes('too many tokens')
+ ) {
+ return `The prompt exceeds the model's context size. Try increasing the context size in model settings or using a shorter prompt.\n\nOriginal error: ${errorMessage}`
+ }
}
- return JSON.stringify(error)
+
+ return errorMessage
},
onFinish: ({ responseMessage }) => {
// Call the token usage callback with usage data when stream completes
@@ -456,9 +492,39 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// When continuing a truncated response, inject the partial content as the
// very first text-delta so the new message immediately shows it and the
// user sees a seamless continuation rather than an empty box.
- return continueContent
+ const finalStream = continueContent
? prependTextDeltaToUIStream(uiStream, continueContent)
: uiStream
+
+ // In agent mode, detect empty responses (HTTP 200 but no text content)
+ // and inject an error chunk so the UI shows a message instead of an empty bubble.
+ if (!isAgentMode) return finalStream
+
+ let hasTextContent = false
+ let hasError = false
+ return finalStream.pipeThrough(
+ new TransformStream<UIMessageChunk, UIMessageChunk>({
+ transform(chunk, controller) {
+ if ((chunk as { type: string }).type === 'text-delta') {
+ hasTextContent = true
+ }
+ if ((chunk as { type: string }).type === 'error') {
+ hasError = true
+ }
+ controller.enqueue(chunk)
+ },
+ flush(controller) {
+ if (!hasTextContent && !hasError) {
+ controller.enqueue({
+ type: 'error',
+ errorText:
+ 'The agent returned an empty response. This usually means ' +
+ 'the local model server is not running or the model failed to process the request.',
+ } as UIMessageChunk)
+ }
+ },
+ })
+ )
}
async reconnectToStream(
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 52ec86096..80ab7fd35 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -53,6 +53,7 @@ import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'
import { ExtensionManager } from '@/lib/extension'
import { Shimmer } from '@/components/ai-elements/shimmer'
+import { useAgentMode } from '@/hooks/useAgentMode'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -793,9 +794,12 @@ function ThreadDetail() {
handleContextSizeIncreaseRef.current = handleContextSizeIncrease
setContinueFromContentRef.current = setContinueFromContent
- // Auto-trigger context size increase when the model reports a context limit error
+ // Skip auto-context-increase in agent mode
+ const agentModeActive = useAgentMode(
+ (s) => s.agentThreads[threadId] === true
+ )
useEffect(() => {
- if (!error) return
+ if (!error || agentModeActive) return
const isContextError =
(error.message?.toLowerCase().includes('context') &&
(error.message?.toLowerCase().includes('size') ||
@@ -808,11 +812,13 @@ function ThreadDetail() {
}
}, [error]) // eslint-disable-line react-hooks/exhaustive-deps
- // Clear once the new stream starts
useEffect(() => {
- if (isAutoIncreasingContext && status === 'streaming') {
+ if (isAutoIncreasingContext && (status === 'streaming' || status === 'error')) {
setIsAutoIncreasingContext(false)
}
+ if (status === 'error' && pendingContinueMessage) {
+ setPendingContinueMessage(null)
+ }
}, [status]) // eslint-disable-line react-hooks/exhaustive-deps
const threadModel = useMemo(
diff --git a/web-app/src/utils/openclaw.ts b/web-app/src/utils/openclaw.ts
index 6953e5163..be3cd23ca 100644
--- a/web-app/src/utils/openclaw.ts
+++ b/web-app/src/utils/openclaw.ts
@@ -1,4 +1,5 @@
import { invoke } from '@tauri-apps/api/core'
+import { fetch as httpFetch } from '@tauri-apps/plugin-http'
import { useAgentMode } from '@/hooks/useAgentMode'
import { useAppState } from '@/hooks/useAppState'
@@ -148,10 +149,13 @@ export async function ensureOpenClawHttpApi(): Promise<void> {
const changed = await invoke<boolean>('openclaw_ensure_http_api')
if (changed) {
await invoke('openclaw_restart')
+ await new Promise((resolve) => setTimeout(resolve, 2000))
}
httpApiEnsured = true
- } catch {
- // Fail silently — the send will fail with a clearer error
+ } catch (error) {
+ throw new Error(
+ `Failed to initialize OpenClaw HTTP API: ${error instanceof Error ? error.message : String(error)}`
+ )
}
}
@@ -180,3 +184,28 @@ export async function getOpenClawModel(): Promise<string | null> {
return null
}
}
+
+/** Verify the OpenClaw gateway is reachable. Throws if not. */
+export async function checkOpenClawGatewayReachable(): Promise<void> {
+ try {
+ const res = await httpFetch(`${OPENCLAW_GATEWAY_URL}/models`, {
+ method: 'GET',
+ signal: AbortSignal.timeout(5_000),
+ })
+ if (!res.ok) {
+ const body = await res.text().catch(() => '')
+ throw new Error(
+ `OpenClaw gateway returned HTTP ${res.status}${body ? `: ${body}` : ''}`
+ )
+ }
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith('OpenClaw gateway returned')) {
+ throw error
+ }
+ const msg = error instanceof Error ? error.message : String(error)
+ throw new Error(
+ `Cannot reach the OpenClaw gateway at ${OPENCLAW_GATEWAY_URL}. ` +
+ `Please make sure the local API server is running.\n\nDetails: ${msg}`
+ )
+ }
+}