Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): answer a shell call made while the shell is off instead of ending the turn (#9319) (#9392)
Thinh Leab7a7adf7c79
diff --git a/web-app/src/lib/__tests__/disabledToolCalls.test.ts b/web-app/src/lib/__tests__/disabledToolCalls.test.tsnew file mode 100644index 000000000..822393c24--- /dev/null+++ b/web-app/src/lib/__tests__/disabledToolCalls.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from 'vitest'+import {+ jsonSchema,+ readUIMessageStream,+ streamText,+ type UIMessage,+ type UIMessageChunk,+} from 'ai'+import { MockLanguageModelV3, simulateReadableStream } from 'ai/test'+import { routeRefusedToolCalls } from '../disabledToolCalls'++// #9319: the real SDK, not a mocked transport. A model calls `name` although+// only `web_search` was advertised, which is what happens to the shell once the+// user switches it off.+function modelCalling(name: string) {+ return new MockLanguageModelV3({+ doStream: async () => ({+ stream: simulateReadableStream({+ chunks: [+ { type: 'stream-start' as const, warnings: [] },+ {+ type: 'tool-call' as const,+ toolCallId: 'call-1',+ toolName: name,+ input: '{"command":"echo hi"}',+ },+ {+ type: 'finish' as const,+ finishReason: { unified: 'tool-calls' as const, raw: 'tool_calls' },+ usage: {+ inputTokens: {+ total: 1,+ noCache: 1,+ cacheRead: undefined,+ cacheWrite: undefined,+ },+ outputTokens: { total: 1, text: 1, reasoning: undefined },+ },+ },+ ],+ }),+ }),+ })+}++async function lastMessage(+ stream: ReadableStream<UIMessageChunk>+): Promise<UIMessage | undefined> {+ let last: UIMessage | undefined+ for await (const m of readUIMessageStream({ stream })) last = m+ return last+}++function turn(name: string, isRefused: (toolName: string) => boolean) {+ const result = streamText({+ model: modelCalling(name),+ prompt: 'hi',+ tools: {+ web_search: {+ description: 'search',+ inputSchema: jsonSchema({ type: 'object', properties: {} }),+ },+ },+ })+ return routeRefusedToolCalls(+ result.toUIMessageStream({ onError: (e) => String(e) }),+ isRefused+ )+}++describe('routeRefusedToolCalls', () => {+ it('turns the SDK rejection of a refused tool into a call the chat can answer', async () => {+ const message = await lastMessage(turn('shell', (n) => n === 'shell'))+ // The static `tool-shell` shape an advertised tool has, so the stored turn+ // and the follow-up request carry the call once.+ const part = message?.parts.find((p) => p.type === 'tool-shell')+ // `input-available` is what reaches onToolCall; `output-error` would mean+ // the SDK already settled the call and no follow-up request would be sent.+ expect(part).toMatchObject({+ type: 'tool-shell',+ toolCallId: 'call-1',+ state: 'input-available',+ input: { command: 'echo hi' },+ })+ })++ it('leaves the SDK error in place for a tool that is not refused', async () => {+ const message = await lastMessage(turn('shell', () => false))+ const part = message?.parts.find((p) => p.type === 'dynamic-tool')+ expect(part).toMatchObject({+ state: 'output-error',+ errorText: expect.stringContaining('unavailable tool'),+ })+ })++ it('does not touch an unadvertised tool that is not the refused one', async () => {+ const message = await lastMessage(turn('rm_rf', (n) => n === 'shell'))+ const part = message?.parts.find((p) => p.type === 'dynamic-tool')+ expect(part).toMatchObject({ toolName: 'rm_rf', state: 'output-error' })+ })+})diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 9097ea9e1..dc9895ae6 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -43,6 +43,7 @@ import {refreshMemoryDigest,sandboxEnforces,} from '@/lib/agentTools'+import { routeRefusedToolCalls } from '@/lib/disabledToolCalls'import { useAppState, type ModelLoadProgress } from '@/hooks/useAppState'import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'import { engineFailure } from '@/lib/engineError'@@ -1741,11 +1742,20 @@ 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.- const finalStream = continueContent+ const continuedStream = continueContent? prependContinuationToUIStream(uiStream, continueContent): uiStream- return finalStream+ // A call to the built-in shell while the user has it switched off is not in+ // `this.tools`, so the SDK would reject it and end the turn. Hand it to the+ // tool loop instead, which answers it with the "turned off" refusal.+ return routeRefusedToolCalls(+ continuedStream,+ (toolName) =>+ CHAT_AGENT_TOOL_NAMES.has(toolName) &&+ !(toolName in this.tools) &&+ !useChatShell.getState().shellEnabled+ )}async reconnectToStream(diff --git a/web-app/src/lib/disabledToolCalls.ts b/web-app/src/lib/disabledToolCalls.tsnew file mode 100644index 000000000..e4654fc8a--- /dev/null+++ b/web-app/src/lib/disabledToolCalls.ts@@ -0,0 +1,61 @@+import type { UIMessageChunk } from 'ai'++type ToolChunk = {+ type: string+ toolCallId?: string+ toolName?: string+ input?: unknown+}++/**+ * The AI SDK rejects a call to a tool that was not advertised: the stream+ * carries `tool-input-error` plus `tool-output-error` and the chat never learns+ * a call was made, so no tool loop runs and no follow-up request is sent. For+ * a tool Jan refuses on purpose (the shell switched off) that ends the turn+ * instead of telling the model "turned off" and letting it continue.+ *+ * This rewrites such a call into an ordinary `tool-input-available`, which+ * reaches `onToolCall`; the thread route then records its refusal as the+ * call's result and the follow-up request goes out. The SDK's own error result+ * is dropped so the call is not answered twice.+ */+export function routeRefusedToolCalls(+ stream: ReadableStream<UIMessageChunk>,+ isRefused: (toolName: string) => boolean+): ReadableStream<UIMessageChunk> {+ const rerouted = new Set<string>()+ return stream.pipeThrough(+ new TransformStream<UIMessageChunk, UIMessageChunk>({+ transform(chunk, controller) {+ const c = chunk as ToolChunk+ if (+ c.type === 'tool-input-error' &&+ c.toolCallId &&+ c.toolName &&+ isRefused(c.toolName)+ ) {+ rerouted.add(c.toolCallId)+ // Not `dynamic`: an advertised tool is stored as a static `tool-<name>`+ // part. Emitting a `dynamic-tool` part here was observed to put the+ // same call into the follow-up request twice, so the call is+ // emitted in the static shape.+ controller.enqueue({+ type: 'tool-input-available',+ toolCallId: c.toolCallId,+ toolName: c.toolName,+ input: c.input,+ } as UIMessageChunk)+ return+ }+ if (+ c.type === 'tool-output-error' &&+ c.toolCallId &&+ rerouted.has(c.toolCallId)+ ) {+ return+ }+ controller.enqueue(chunk)+ },+ })+ )+}