OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(dashboard): AI chat recovers from a turn cut off mid tool call (#587)
Carl-Gerhard Lindesvärdc016d4e90931
diff --git a/packages/core/src/modules/assistant/src/chat.ts b/packages/core/src/modules/assistant/src/chat.tsindex f41b7ba41..daa25b59c 100644--- a/packages/core/src/modules/assistant/src/chat.ts+++ b/packages/core/src/modules/assistant/src/chat.ts@@ -5,6 +5,7 @@ import {createUIMessageStreamResponse,isStepCount,streamText,+ type Tool,toUIMessageStream,} from 'ai';import type { HttpCtx } from '../../../context';@@ -17,6 +18,7 @@ import {} from '../assistant.constants';import { createChatActions } from './actions';import type { ChatToolContext } from './context';+import { failInterruptedToolParts } from './interrupted-tools';import type { AssistantUIMessage } from './message';import { deleteMessagesFrom, loadMessages, saveMessages } from './persistence';import { buildSystemPrompt } from './prompt';@@ -62,6 +64,17 @@ function describeError(error: unknown): string {return 'Something went wrong.';}+/** An abort right after the model started leaves only a step marker or an empty text part. */+function isSubstantive(part: AssistantUIMessage['parts'][number]): boolean {+ if (part.type === 'step-start') {+ return false;+ }+ if (part.type === 'text' || part.type === 'reasoning') {+ return part.text.trim().length > 0;+ }+ return true;+}+/** One chat turn: load history, run the model with tools, stream UI parts, persist on finish. */export async function runChat(deps: ServiceDeps,@@ -99,6 +112,16 @@ export async function runChat(await deleteMessagesFrom(deps, request.id, request.messageId);}}+ // A turn cut off mid tool call stores calls without results, and the model+ // refuses such a history outright. Repaired rows are written back on finish.+ const repaired = new Map<string, AssistantUIMessage>();+ history = history.map((message) => {+ const fixed = failInterruptedToolParts(message);+ if (fixed !== message && message.id !== incoming?.id) {+ repaired.set(message.id, fixed);+ }+ return fixed;+ });if (incoming) {const existing = history.findIndex((message) => message.id === incoming.id);history =@@ -125,6 +148,8 @@ export async function runChat(actions: await createChatActions(httpCtx),};const tools = createChatTools(toolContext);+ const runsInBrowser = (toolName: string) =>+ (tools as Record<string, Tool | undefined>)[toolName]?.execute == null;const modelMessages = await convertToModelMessages(history, { tools });const startedAt = Date.now();let title: string | null = null;@@ -210,14 +235,22 @@ export async function runChat(},onError: describeError,onEnd: async ({ responseMessage }) => {- const toSave: AssistantUIMessage[] = [];+ const toSave: AssistantUIMessage[] = [...repaired.values()];if (incoming?.role === 'user') {toSave.push({...incoming,metadata: { ...incoming.metadata, createdAt: startedAt },});}- toSave.push(responseMessage);+ // An aborted turn ends with server tools still running; a client tool+ // is meant to end the stream and wait for the browser.+ const response = failInterruptedToolParts(responseMessage, runsInBrowser);+ if (response.parts.some(isSubstantive)) {+ toSave.push(response);+ }+ if (toSave.length === 0) {+ return;+ }await saveMessages(deps, {conversationId: request.id,projectId: request.projectId,diff --git a/packages/core/src/modules/assistant/src/interrupted-tools.test.ts b/packages/core/src/modules/assistant/src/interrupted-tools.test.tsnew file mode 100644index 000000000..aa6c7c14c--- /dev/null+++ b/packages/core/src/modules/assistant/src/interrupted-tools.test.ts@@ -0,0 +1,130 @@+import { describe, expect, test } from 'bun:test';+import {+ failInterruptedToolParts,+ INTERRUPTED_TOOL_ERROR_TEXT,+} from './interrupted-tools';+import type { AssistantUIMessage } from './message';++type Part = AssistantUIMessage['parts'][number];++function assistant(parts: Part[]): AssistantUIMessage {+ return { id: 'a1', role: 'assistant', parts };+}++/** Fixtures carry only the fields under test, not a full tool output. */+function part(value: Record<string, unknown>): Part {+ return value as unknown as Part;+}++const pending = part({+ type: 'tool-describe_data',+ toolCallId: 'call_A',+ state: 'input-available',+ input: {},+});++const done = part({+ type: 'tool-get_billing',+ toolCallId: 'call_B',+ state: 'output-available',+ input: {},+ output: { plan: 'growth' },+});++describe('failInterruptedToolParts', () => {+ test('marks calls without a result as failed and keeps the rest', () => {+ const repaired = failInterruptedToolParts(+ assistant([{ type: 'step-start' }, pending, done])+ );+ expect(repaired.parts).toEqual([+ { type: 'step-start' },+ {+ type: 'tool-describe_data',+ toolCallId: 'call_A',+ state: 'output-error',+ input: {},+ errorText: INTERRUPTED_TOOL_ERROR_TEXT,+ },+ done,+ ]);+ });++ test('a call whose input was still streaming fails too', () => {+ const streaming = {+ type: 'tool-get_breakdown',+ toolCallId: 'call_C',+ state: 'input-streaming',+ input: undefined,+ rawInput: '{"metr',+ } as Part;+ const [part] = failInterruptedToolParts(assistant([streaming])).parts;+ expect(part).toMatchObject({+ state: 'output-error',+ rawInput: '{"metr',+ errorText: INTERRUPTED_TOOL_ERROR_TEXT,+ });+ });++ test('an approved call that never ran fails; a denied or open approval stays', () => {+ const approved = {+ type: 'tool-save_chart',+ toolCallId: 'call_D',+ state: 'approval-responded',+ input: {},+ approval: { id: 'ap_1', approved: true },+ } as Part;+ const denied = {+ type: 'tool-save_chart',+ toolCallId: 'call_E',+ state: 'approval-responded',+ input: {},+ approval: { id: 'ap_2', approved: false },+ } as Part;+ const open = {+ type: 'tool-save_chart',+ toolCallId: 'call_F',+ state: 'approval-requested',+ input: {},+ approval: { id: 'ap_3' },+ } as Part;+ const { parts } = failInterruptedToolParts(+ assistant([approved, denied, open])+ );+ expect(parts[0]).toMatchObject({+ state: 'output-error',+ approval: { id: 'ap_1', approved: true },+ });+ expect(parts[1]).toBe(denied);+ expect(parts[2]).toBe(open);+ });++ test('tools named as still pending are left alone', () => {+ const navigate = {+ type: 'tool-navigate',+ toolCallId: 'call_G',+ state: 'input-available',+ input: { route: 'overview' },+ } as Part;+ const message = assistant([navigate, pending]);+ const { parts } = failInterruptedToolParts(+ message,+ (name) => name === 'navigate'+ );+ expect(parts[0]).toBe(navigate);+ expect(parts[1]).toMatchObject({ state: 'output-error' });+ });++ test('returns the same object when nothing needs repair', () => {+ const message = assistant([+ done,+ { type: 'text', text: 'Hi', state: 'done' },+ ]);+ expect(failInterruptedToolParts(message)).toBe(message);+ const user: AssistantUIMessage = {+ id: 'u1',+ role: 'user',+ parts: [{ type: 'text', text: 'Hej' }],+ };+ expect(failInterruptedToolParts(user)).toBe(user);+ });+});diff --git a/packages/core/src/modules/assistant/src/interrupted-tools.ts b/packages/core/src/modules/assistant/src/interrupted-tools.tsnew file mode 100644index 000000000..3c35cdaaa--- /dev/null+++ b/packages/core/src/modules/assistant/src/interrupted-tools.ts@@ -0,0 +1,51 @@+import { getToolName, isToolUIPart } from 'ai';+import type { AssistantUIMessage, AssistantUIMessagePart } from './message';++export const INTERRUPTED_TOOL_ERROR_TEXT =+ 'Interrupted before the tool finished.';++type ToolPart = Extract<AssistantUIMessagePart, { toolCallId: string }>;++/** A call the model made that never got a result: the model refuses the whole history until it has one. */+function awaitsResult(part: ToolPart): boolean {+ if (part.state === 'input-streaming' || part.state === 'input-available') {+ return true;+ }+ return part.state === 'approval-responded' && part.approval.approved;+}++function failed(part: ToolPart): ToolPart {+ const { output: _output, errorText: _errorText, ...rest } = part;+ // The SDK's part union cannot be re-tagged generically without an assertion.+ return {+ ...rest,+ state: 'output-error',+ errorText: INTERRUPTED_TOOL_ERROR_TEXT,+ } as ToolPart;+}++/**+ * Turns tool calls that will never get a result into failed ones, so the+ * conversation can continue. `stillPending` names tools whose result is+ * legitimately outstanding at this point (client tools waiting on the browser).+ */+export function failInterruptedToolParts(+ message: AssistantUIMessage,+ stillPending: (toolName: string) => boolean = () => false+): AssistantUIMessage {+ if (message.role !== 'assistant') {+ return message;+ }+ let changed = false;+ const parts = message.parts.map((part) => {+ if (+ !(isToolUIPart(part) && awaitsResult(part)) ||+ stillPending(getToolName(part))+ ) {+ return part;+ }+ changed = true;+ return failed(part);+ });+ return changed ? { ...message, parts } : message;+}diff --git a/packages/core/src/modules/assistant/src/persistence.test.ts b/packages/core/src/modules/assistant/src/persistence.test.tsnew file mode 100644index 000000000..d6a201a77--- /dev/null+++ b/packages/core/src/modules/assistant/src/persistence.test.ts@@ -0,0 +1,36 @@+import { expect, test } from 'bun:test';+import { stripNullCharacters } from './persistence';++test('stripNullCharacters removes NUL from nested strings and keys', () => {+ const parts: unknown = [+ { type: 'text', text: 'a\u0000b' },+ {+ type: 'tool-query_events',+ output: {+ rows: [{ 'na\u0000me': 'x\u0000', count: 1, ok: true, none: null }],+ },+ },+ ];+ expect(stripNullCharacters(parts)).toEqual([+ { type: 'text', text: 'ab' },+ {+ type: 'tool-query_events',+ output: { rows: [{ name: 'x', count: 1, ok: true, none: null }] },+ },+ ]);+});++test('stripNullCharacters keeps a clean value as is', () => {+ const value = { text: 'clean', list: [1, 'two', { three: 3 }] };+ expect(stripNullCharacters(value)).toEqual(value);+});++test('stripNullCharacters keeps a __proto__ key as a plain entry', () => {+ const value: unknown = JSON.parse(+ '{"__proto__": {"polluted": true}, "__pr\\u0000oto__": 1}'+ );+ const cleaned = stripNullCharacters(value) as Record<string, unknown>;+ expect(Object.getPrototypeOf(cleaned)).toBe(Object.prototype);+ expect(Object.hasOwn(cleaned, '__proto__')).toBe(true);+ expect(JSON.stringify(cleaned)).toBe('{"__proto__":1}');+});diff --git a/packages/core/src/modules/assistant/src/persistence.ts b/packages/core/src/modules/assistant/src/persistence.tsindex cc08dea6c..d3ecfd250 100644--- a/packages/core/src/modules/assistant/src/persistence.ts+++ b/packages/core/src/modules/assistant/src/persistence.ts@@ -1,6 +1,28 @@import type { ServiceDeps } from '../../../services';import type { AssistantUIMessage } from './message';+const NULL_CHARACTER = '\u0000';++/** Postgres json cannot hold NUL, and tool outputs echo raw event data. */+export function stripNullCharacters<T>(value: T): T {+ if (typeof value === 'string') {+ return value.replaceAll(NULL_CHARACTER, '') as T;+ }+ if (Array.isArray(value)) {+ return value.map(stripNullCharacters) as T;+ }+ if (value !== null && typeof value === 'object') {+ // fromEntries defines own properties, so a "__proto__" key survives.+ return Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [+ stripNullCharacters(key),+ stripNullCharacters(entry),+ ])+ ) as T;+ }+ return value;+}+/** Rows are one UI message each; `parts` is the message's parts array. */export async function loadMessages(deps: ServiceDeps,@@ -41,6 +63,7 @@ export async function saveMessages(if (foreign) {throw new Error(`Message ${foreign.id} belongs to another conversation`);}+ const title = stripNullCharacters(input.title ?? undefined);await tx.conversation.upsert({where: { id: input.conversationId },create: {@@ -48,18 +71,20 @@ export async function saveMessages(projectId: input.projectId,organizationId: input.organizationId,userId: input.userId,- title: input.title ?? undefined,+ title,},update: {updatedAt: new Date(),- ...(input.title ? { title: input.title } : {}),+ ...(title ? { title } : {}),},});// Rows saved together must load in this order; the default timestamp can tie.const baseTime = Date.now();for (const [index, message] of input.messages.entries()) {- const parts = message.parts as unknown[];- const metadata = (message.metadata ?? {}) as Record<string, unknown>;+ const parts = stripNullCharacters(message.parts as unknown[]);+ const metadata = stripNullCharacters(+ (message.metadata ?? {}) as Record<string, unknown>+ );await tx.chatMessage.upsert({where: { id: message.id },create: {