🤯 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: filter failed assistant placeholders and harden Claude prefill guard (#17737)
YuTengjingb6a8fcf0dc16
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 009b7d0b920..8412166c845 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -474,6 +474,7 @@"inbox.desc": "Collaborate in one Workspace and move ideas into outcomes.","inbox.title": "Lobe AI","input.addAi": "Add an AI message",+ "input.addAiPrefillUnsupported": "The current model doesn’t support ending the conversation with an assistant message. Follow it with a user message before sending.","input.addUser": "Add a user message","input.agentModeUnsupportedModel": "The current model doesn’t support agentic tool calling. Switch to a model with agent capability for the best experience.","input.costEstimate.creditsPerMillionTokens": "{{credits}} credits/M tokens",@@ -579,6 +580,7 @@"mention.title": "Mention Members","messageAction.collapse": "Collapse Message","messageAction.continueGeneration": "Continue Generating",+ "messageAction.continueGenerationUnsupported": "The current model doesn’t support continuing an assistant message. Try regenerating instead.","messageAction.copyOperationId": "Copy Operation ID","messageAction.delAndRegenerate": "Delete and Regenerate","messageAction.deleteDisabledByThreads": "This message has a subtopic and can’t be deleted",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex b484084b441..c7ebe2af2fe 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -474,6 +474,7 @@"inbox.desc": "在同一工作区协作,把想法推进成结果","inbox.title": "Lobe AI","input.addAi": "添加一条助理消息",+ "input.addAiPrefillUnsupported": "当前模型不支持以助理消息结尾发送,请在其后继续添加一条用户消息再发送。","input.addUser": "添加一条用户消息","input.agentModeUnsupportedModel": "当前模型不支持 Agentic 工具调用,建议切换为具备 Agent 能力的模型以获得最佳体验。","input.costEstimate.creditsPerMillionTokens": "{{credits}} 积分/百万标记",@@ -579,6 +580,7 @@"mention.title": "提及成员","messageAction.collapse": "收起消息","messageAction.continueGeneration": "继续生成",+ "messageAction.continueGenerationUnsupported": "当前模型不支持继续生成助理消息,请尝试重新生成。","messageAction.copyOperationId": "复制 Operation ID","messageAction.delAndRegenerate": "删除并重新生成","messageAction.deleteDisabledByThreads": "该消息有子话题,无法删除",diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex 7dd0e1ab6a6..27f5dba15fd 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -14,6 +14,7 @@ import {InputTemplateProcessor,MessageCleanupProcessor,MessageContentProcessor,+ PlaceholderMessageFilterProcessor,PlaceholderVariablesProcessor,ReactionFeedbackProcessor,SupervisorRoleRestoreProcessor,@@ -229,6 +230,15 @@ export class MessagesEngine {};return [+ // =============================================+ // Phase 0: Placeholder Residue Filtering+ // Drop failed/abandoned assistant placeholders ("..." rows) BEFORE+ // truncation so residue never consumes history slots and never lands+ // at the payload tail (Claude 4.6+ rejects trailing assistant turns)+ // =============================================++ new PlaceholderMessageFilterProcessor(),+// =============================================// Phase 1: History Truncation// MUST run first — all subsequent processors work on truncated messages only@@ -426,6 +436,13 @@ export class MessagesEngine {new TasksFlattenProcessor(),// Task message processingnew TaskMessageProcessor(),+ // Second placeholder pass: the flatten steps above can expand "..."+ // residue hidden inside group/council/tasks children (invisible to the+ // Phase 0 pass, which only sees top-level messages), and+ // TaskMessageProcessor converts flattened `task` rows into assistant+ // messages — so this pass must run AFTER that conversion to catch+ // task-shaped residue too.+ new PlaceholderMessageFilterProcessor(),// Verify (delivery-checker) cards: drop empty UI-only ones; surface// auto-repair failure feedback as a user turn for the repair runnew VerifyMessageProcessor(),diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.tsindex c955a530c13..145b0341bdd 100644--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts@@ -124,6 +124,89 @@ describe('MessagesEngine', () => {});});+ it('should drop placeholder residue hidden inside tasks containers (LOBE-12572)', async () => {+ // TasksFlattenProcessor emits children as role='task' and+ // TaskMessageProcessor converts them to assistant AFTER the flatten —+ // the post-flatten placeholder pass must run after that conversion, or+ // a "..." task child re-enters the payload as a trailing assistant.+ const result = await new MessagesEngine(+ createBasicParams({+ messages: [+ {+ content: 'Hello',+ createdAt: Date.now(),+ id: 'msg-1',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: '',+ createdAt: Date.now(),+ id: 'tasks-1',+ role: 'tasks',+ tasks: [{ content: '...', id: 'task-child-1' }],+ updatedAt: Date.now(),+ } as unknown as UIChatMessage,+ ],+ }),+ ).process();++ expect(result.messages).toHaveLength(1);+ expect(result.messages[0].role).toBe('user');+ });++ it('should not let placeholder-only containers consume history slots (LOBE-12572)', async () => {+ // History truncation counts each container as one group; a placeholder-+ // only container must be dropped BEFORE truncation or it eats a slot and+ // then vanishes at the flatten phase, losing a real history turn.+ const now = Date.now();+ const result = await new MessagesEngine(+ createBasicParams({+ enableHistoryCount: true,+ historyCount: 3,+ messages: [+ {+ content: 'real question',+ createdAt: now,+ id: 'u1',+ role: 'user',+ updatedAt: now,+ } as UIChatMessage,+ {+ content: 'real answer',+ createdAt: now,+ id: 'a1',+ role: 'assistant',+ updatedAt: now,+ } as UIChatMessage,+ {+ content: '',+ createdAt: now,+ id: 'tasks-1',+ role: 'tasks',+ tasks: [{ content: '...', id: 'task-child-1' }],+ updatedAt: now,+ } as unknown as UIChatMessage,+ {+ content: 'follow-up',+ createdAt: now,+ id: 'u2',+ role: 'user',+ updatedAt: now,+ } as UIChatMessage,+ ],+ }),+ ).process();++ // Without the pre-truncation prune, the container occupies one of the 3+ // slots and 'real question' falls out of the window.+ expect(result.messages.map((m) => m.content)).toEqual([+ 'real question',+ 'real answer',+ 'follow-up',+ ]);+ });+it('should process messages and return result with stats', async () => {const params = createBasicParams();const engine = new MessagesEngine(params);diff --git a/packages/context-engine/src/processors/PlaceholderMessageFilter.ts b/packages/context-engine/src/processors/PlaceholderMessageFilter.tsnew file mode 100644index 00000000000..e8112adf1db--- /dev/null+++ b/packages/context-engine/src/processors/PlaceholderMessageFilter.ts@@ -0,0 +1,172 @@+import { LOADING_FLAT } from '@lobechat/const';+import debug from 'debug';++import { BaseProcessor } from '../base/BaseProcessor';+import type { PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ placeholderMessageFilter?: {+ removedCount: number;+ };+ }+}++const log = debug('context-engine:processor:PlaceholderMessageFilterProcessor');++/**+ * Placeholder Message Filter Processor+ *+ * Removes assistant placeholder residue from the context. When a generation+ * fails or is abandoned mid-flight, its optimistic assistant row can stay+ * persisted with the `LOADING_FLAT` placeholder content (with or without an+ * `error` — a crashed run never writes one). Replaying these rows poisons the+ * conversation: they carry zero information for the model, and once one lands+ * at the tail of the payload, Claude 4.6+ rejects the whole request as an+ * unsupported assistant prefill (400), which persists yet another placeholder+ * and makes the topic permanently unsendable.+ *+ * A message is treated as placeholder residue only when it has no meaningful+ * output at all: no content (empty or `LOADING_FLAT`), no tool-call fields, no+ * reasoning text, and no multimodal attachments (image/video/audio/file lists,+ * which legitimately pair with an empty text content). Failed messages that+ * carry partial content are kept — intentionally added assistant messages+ * (prefill) always carry content, so they are never touched.+ *+ * `tools` / `tool_calls` are checked for PRESENCE (any array, even empty), not+ * length: placeholder rows are persisted with these fields unset, while the+ * long-standing pipeline contract keeps an empty-content assistant whose+ * `tool_calls: []` field exists (see contextEngineering "empty tool calls"+ * test).+ *+ * Residue hiding inside group/tasks containers is pruned too (and a container+ * left empty is dropped), so a placeholder-only container cannot consume a+ * history-truncation slot before the flatten phase erases it.+ */+export class PlaceholderMessageFilterProcessor extends BaseProcessor {+ readonly name = 'PlaceholderMessageFilterProcessor';++ constructor(options: ProcessorOptions = {}) {+ super(options);+ }++ /** Container roles whose child arrays can hide placeholder residue */+ private static readonly NESTED_CHILD_FIELDS: Record<string, string> = {+ agentCouncil: 'members',+ assistantGroup: 'children',+ groupTasks: 'tasks',+ supervisor: 'children',+ tasks: 'tasks',+ };++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ const clonedContext = this.cloneContext(context);++ // Prune residue nested inside group/tasks containers first: it must go+ // BEFORE history truncation, where each container counts as one history+ // group — a placeholder-only container would consume a slot and then+ // vanish at the flatten phase, silently shrinking the real history.+ let removedCount = 0;+ clonedContext.messages = clonedContext.messages+ .map((message) => {+ const pruned = this.pruneContainerResidue(message);+ removedCount += pruned.removedChildren;+ return pruned.message;+ })+ .filter((message): message is NonNullable<typeof message> => message !== null);++ const before = clonedContext.messages.length;+ clonedContext.messages = clonedContext.messages.filter(+ (message) => !this.isPlaceholderResidue(message),+ );+ removedCount += before - clonedContext.messages.length;++ // The processor runs twice in the pipeline (top-level pass + post-flatten+ // pass for residue expanded out of group children) — accumulate the count.+ const priorRemovedCount = clonedContext.metadata.placeholderMessageFilter?.removedCount ?? 0;+ clonedContext.metadata.placeholderMessageFilter = {+ removedCount: priorRemovedCount + removedCount,+ };++ if (removedCount > 0) {+ log(`Removed ${removedCount} assistant placeholder residue message(s)`);+ }++ return this.markAsExecuted(clonedContext);+ }++ /**+ * Remove placeholder residue from a container message's child array+ * (tasks/groupTasks → `tasks`, assistantGroup/supervisor → `children`).+ * Returns the container with residue children removed, or `null` when every+ * child was residue (an empty container flattens to nothing anyway, but+ * left in place it would still consume a history-truncation slot).+ */+ private pruneContainerResidue(message: any): { message: any | null; removedChildren: number } {+ const field = (PlaceholderMessageFilterProcessor.NESTED_CHILD_FIELDS as any)[message.role];+ const children = field ? message[field] : undefined;+ if (!Array.isArray(children) || children.length === 0) return { message, removedChildren: 0 };++ let removedChildren = 0;+ const kept: any[] = [];+ for (const child of children) {+ // Containers nest (an agentCouncil member can be an assistantGroup) —+ // recurse first so an all-residue nested container is dropped too.+ const prunedChild = this.pruneContainerResidue(child);+ removedChildren += prunedChild.removedChildren;+ if (prunedChild.message === null) continue;++ // Only judge assistant-like children; tool/user children inside a group+ // are legitimately empty-content and must never be dropped here. Task+ // children have no role until TasksFlatten assigns 'task'.+ const role = prunedChild.message.role ?? 'assistant';+ if (+ (role === 'assistant' || role === 'task') &&+ this.isPlaceholderResidue({ ...prunedChild.message, role: 'assistant' })+ ) {+ removedChildren += 1;+ continue;+ }++ kept.push(prunedChild.message);+ }++ if (removedChildren === 0) return { message, removedChildren: 0 };+ if (kept.length === 0) return { message: null, removedChildren: removedChildren + 1 };++ return { message: { ...message, [field]: kept }, removedChildren };+ }++ private isPlaceholderResidue(message: any): boolean {+ if (message.role !== 'assistant') return false;++ // Presence of a tool-call field (even an empty array) means the row went+ // through the tool pipeline, not the placeholder path — keep it.+ if (Array.isArray(message.tools)) return false;+ if (Array.isArray(message.tool_calls)) return false;++ // Any replayable reasoning payload is meaningful output even without+ // content: visible text, an encrypted signature, or Responses reasoning+ // items (a thinking run can finish with hidden reasoning state only,+ // which the next request must replay).+ if (+ message.reasoning?.content ||+ message.reasoning?.signature ||+ message.reasoning?.responseItems?.length > 0+ )+ return false;++ // Multimodal attachments legitimately pair with an empty text content+ // (e.g. an image-only assistant reply) — keep them.+ if (message.imageList?.length > 0) return false;+ if (message.videoList?.length > 0) return false;+ if (message.audioList?.length > 0) return false;+ if (message.fileList?.length > 0) return false;++ // Non-string content (multimodal parts) is meaningful output.+ if (typeof message.content !== 'string') return message.content == null;++ const content = message.content.trim();+ return content === '' || content === LOADING_FLAT;+ }+}diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderMessageFilter.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderMessageFilter.test.tsnew file mode 100644index 00000000000..1df9b676e1a--- /dev/null+++ b/packages/context-engine/src/processors/__tests__/PlaceholderMessageFilter.test.ts@@ -0,0 +1,238 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { PlaceholderMessageFilterProcessor } from '../PlaceholderMessageFilter';++describe('PlaceholderMessageFilterProcessor', () => {+ const createContext = (messages: any[]): PipelineContext => ({+ initialState: {+ messages: [],+ model: 'test-model',+ provider: 'test-provider',+ },+ isAborted: false,+ messages,+ metadata: {},+ });++ const processor = new PlaceholderMessageFilterProcessor();++ it('should remove failed assistant placeholders that carry an error', async () => {+ // Regression: persisted "..." rows from failed generations poisoned the+ // topic — replayed at the payload tail they trigger the Claude 4.6++ // assistant-prefill 400 on every subsequent send (LOBE-12572).+ const context = createContext([+ { content: 'hi', id: 'u1', role: 'user' },+ { content: '...', error: { type: 'CapabilityNotSupported' }, id: 'a1', role: 'assistant' },+ { content: 'retry', id: 'u2', role: 'user' },+ ]);++ const result = await processor.process(context);++ expect(result.messages.map((m) => m.id)).toEqual(['u1', 'u2']);+ expect(result.metadata.placeholderMessageFilter).toEqual({ removedCount: 1 });+ });++ it('should remove orphaned placeholders that never got an error written', async () => {+ // A crashed/abandoned run leaves the placeholder row with error = null.+ const context = createContext([+ { content: 'hi', id: 'u1', role: 'user' },+ { content: '...', error: null, id: 'a1', role: 'assistant' },+ { content: '', id: 'a2', role: 'assistant' },+ { content: null, id: 'a3', role: 'assistant' },+ ]);++ const result = await processor.process(context);++ expect(result.messages.map((m) => m.id)).toEqual(['u1']);+ expect(result.metadata.placeholderMessageFilter).toEqual({ removedCount: 3 });+ });++ it('should keep assistant messages with real content, even when errored', async () => {+ const context = createContext([+ {+ content: 'partial answer before failing',+ error: { type: 'Timeout' },+ id: 'a1',+ role: 'assistant',+ },+ { content: 'a full answer', id: 'a2', role: 'assistant' },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(2);+ expect(result.metadata.placeholderMessageFilter).toEqual({ removedCount: 0 });+ });++ it('should keep placeholder-content messages that carry tool calls', async () => {+ const context = createContext([+ { content: '...', id: 'a1', role: 'assistant', tools: [{ id: 'tool_1' }] },+ {+ content: '...',+ id: 'a2',+ role: 'assistant',+ tool_calls: [{ id: 'call_1', type: 'function' }],+ },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(2);+ });++ it('should keep empty-content messages whose tool_calls field exists but is empty', async () => {+ // Pipeline contract: an assistant row that went through the tool pipeline+ // keeps its (possibly empty) tool_calls array — presence, not length,+ // marks it as non-placeholder (see contextEngineering "empty tool calls").+ const context = createContext([+ { content: '', id: 'a1', role: 'assistant', tool_calls: [] },+ { content: '', id: 'a2', role: 'assistant', tools: [] },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(2);+ expect(result.metadata.placeholderMessageFilter).toEqual({ removedCount: 0 });+ });++ it('should keep empty-content messages that carry multimodal attachments', async () => {+ const context = createContext([+ {+ content: '',+ id: 'a1',+ imageList: [{ id: 'img1', url: 'https://x/img.png' }],+ role: 'assistant',+ },+ { content: '', fileList: [{ id: 'f1' }], id: 'a2', role: 'assistant' },+ { audioList: [{ id: 'au1' }], content: '', id: 'a3', role: 'assistant' },+ { content: '', id: 'a4', role: 'assistant', videoList: [{ id: 'v1' }] },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(4);+ expect(result.metadata.placeholderMessageFilter).toEqual({ removedCount: 0 });+ });++ it('should prune placeholder residue nested inside containers and drop emptied ones', async () => {+ // A placeholder-only container would otherwise consume one history-+ // truncation slot and then vanish at the flatten phase.+ const context = createContext([+ { content: 'hi', id: 'u1', role: 'user' },+ { content: '', id: 'g1', role: 'tasks', tasks: [{ content: '...', id: 'c1' }] },+ {+ children: [+ { content: '...', id: 'c2', role: 'assistant' },+ { content: 'real reply', id: 'c3', role: 'assistant' },+ { content: '', id: 'c4', role: 'tool', tool_call_id: 'call_1' },+ ],+ content: '',+ id: 'g2',+ role: 'assistantGroup',+ },+ ]);++ const result = await processor.process(context);++ expect(result.messages.map((m) => m.id)).toEqual(['u1', 'g2']);+ // Empty-content tool child stays; only the "..." assistant child is pruned.+ expect(result.messages[1].children.map((c: any) => c.id)).toEqual(['c3', 'c4']);+ // c1 + dropped g1 container + c2+ expect(result.metadata.placeholderMessageFilter).toEqual({ removedCount: 3 });+ });++ it('should prune council members recursively and drop placeholder-only councils', async () => {+ // agentCouncil members can themselves be assistantGroup containers — an+ // all-residue council must vanish before history truncation counts it.+ const context = createContext([+ { content: 'hi', id: 'u1', role: 'user' },+ {+ content: '',+ id: 'council-1',+ members: [+ { content: '...', id: 'm1', role: 'assistant' },+ {+ children: [{ content: '...', id: 'm2c1', role: 'assistant' }],+ content: '',+ id: 'm2',+ role: 'assistantGroup',+ },+ ],+ role: 'agentCouncil',+ },+ ]);++ const result = await processor.process(context);++ expect(result.messages.map((m) => m.id)).toEqual(['u1']);+ });++ it('should accumulate removedCount across two pipeline passes', async () => {+ // The processor runs twice per pipeline (top-level + post-flatten for+ // residue expanded out of group children) — counts must not reset.+ const first = await processor.process(+ createContext([{ content: '...', id: 'a1', role: 'assistant' }]),+ );+ const second = await new PlaceholderMessageFilterProcessor().process({+ ...first,+ messages: [{ content: '...', id: 'a2', role: 'assistant' }],+ });++ expect(second.metadata.placeholderMessageFilter).toEqual({ removedCount: 2 });+ });++ it('should keep placeholder-content messages that carry reasoning text', async () => {+ const context = createContext([+ { content: '...', id: 'a1', reasoning: { content: 'thought hard' }, role: 'assistant' },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(1);+ });++ it('should keep hidden reasoning-only turns (signature / responseItems, no text)', async () => {+ // A Responses/thinking run can finish with no visible assistant text but+ // persisted encrypted reasoning state the next request must replay.+ const context = createContext([+ { content: '', id: 'a1', reasoning: { signature: 'enc-sig' }, role: 'assistant' },+ {+ content: '...',+ id: 'a2',+ reasoning: { responseItems: [{ id: 'rs_1', type: 'reasoning' }] },+ role: 'assistant',+ },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(2);+ expect(result.metadata.placeholderMessageFilter).toEqual({ removedCount: 0 });+ });++ it('should keep multimodal array content and non-assistant messages untouched', async () => {+ const context = createContext([+ { content: [{ text: 'img', type: 'text' }], id: 'a1', role: 'assistant' },+ { content: '...', id: 'u1', role: 'user' },+ { content: '', id: 't1', role: 'tool', tool_call_id: 'call_1' },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(3);+ });++ it('should keep intentionally added assistant messages (manual prefill)', async () => {+ // The "add an assistant message" input-menu feature persists a plain+ // assistant row with user-typed content and no error — must never filter.+ const context = createContext([+ { content: 'hi', id: 'u1', role: 'user' },+ { content: 'Sure! Here is my draft:', id: 'a1', role: 'assistant' },+ ]);++ const result = await processor.process(context);++ expect(result.messages).toHaveLength(2);+ });+});diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.tsindex 425d240247f..9c598235b5e 100644--- a/packages/context-engine/src/processors/index.ts+++ b/packages/context-engine/src/processors/index.ts@@ -13,6 +13,7 @@ export { getSlicedMessages, HistoryTruncateProcessor } from './HistoryTruncate';export { InputTemplateProcessor } from './InputTemplate';export { MessageCleanupProcessor } from './MessageCleanup';export { MessageContentProcessor } from './MessageContent';+export { PlaceholderMessageFilterProcessor } from './PlaceholderMessageFilter';export {buildPlaceholderGenerators,formatPlaceholderValues,diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 06a0b30bcdd..61850e83dff 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -507,6 +507,8 @@ export default {'inbox.desc': 'Collaborate in one Workspace and move ideas into outcomes.','inbox.title': 'Lobe AI','input.addAi': 'Add an AI message',+ 'input.addAiPrefillUnsupported':+ 'The current model doesn’t support ending the conversation with an assistant message. Follow it with a user message before sending.','input.addUser': 'Add a user message','input.agentModeUnsupportedModel':'The current model doesn’t support agentic tool calling. Switch to a model with agent capability for the best experience.',@@ -588,6 +590,8 @@ export default {'mention.title': 'Mention Members','messageAction.collapse': 'Collapse Message','messageAction.continueGeneration': 'Continue Generating',+ 'messageAction.continueGenerationUnsupported':+ 'The current model doesn’t support continuing an assistant message. Try regenerating instead.','messageAction.copyOperationId': 'Copy Operation ID','messageAction.delAndRegenerate': 'Delete and Regenerate','messageAction.interrupted': 'Interrupted',diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.jsonindex beafd72aafa..d9a8a8de842 100644--- a/packages/model-runtime/package.json+++ b/packages/model-runtime/package.json@@ -7,6 +7,7 @@"./errors": "./src/errors/index.ts","./getModelPropertyWithFallback": "./src/utils/getFallbackModelProperty.ts","./helpers/parseToolCalls": "./src/helpers/parseToolCalls.ts",+ "./providers/anthropic/modelId": "./src/providers/anthropic/modelId.ts","./providers/openai/modelId": "./src/providers/openai/modelId.ts","./resolveImageSinglePrice": "./src/core/usageConverters/utils/resolveImageSinglePrice.ts","./resolveVideoSinglePrice": "./src/core/usageConverters/utils/resolveVideoSinglePrice.ts",diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.tsindex 489387aaa18..ee84753bd82 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts@@ -1,7 +1,10 @@// @vitest-environment nodeimport { describe, expect, it, vi } from 'vitest';-import { createAnthropicGenerateObject } from './generateObject';+import {+ buildAnthropicGenerateObjectRequest,+ createAnthropicGenerateObject,+} from './generateObject';describe('Anthropic generateObject', () => {it('should throw error when neither tools nor schema is provided', async () => {@@ -21,6 +24,44 @@ describe('Anthropic generateObject', () => {);});+ it('should strip trailing assistant messages for models without prefill support (LOBE-12572)', async () => {+ const { requestParams } = await buildAnthropicGenerateObjectRequest({+ messages: [+ { content: 'Generate data', role: 'user' as const },+ { content: '...', role: 'assistant' as const },+ { content: '...', role: 'assistant' as const },+ ],+ model: 'claude-opus-5',+ schema: {+ name: 'extractor',+ schema: { properties: {}, type: 'object' as const },+ },+ } as any);++ expect(requestParams.messages).toEqual([{ content: 'Generate data', role: 'user' }]);+ });++ it('should key the prefill strip on config.requestModel when the logical id is unrecognized', async () => {+ // A custom logical id the parser doesn't recognize can map to a Claude 5+ // upstream id — the strip must follow the model actually sent.+ const { requestParams } = await buildAnthropicGenerateObjectRequest(+ {+ messages: [+ { content: 'Generate data', role: 'user' as const },+ { content: '...', role: 'assistant' as const },+ ],+ model: 'my-custom-router-model',+ schema: {+ name: 'extractor',+ schema: { properties: {}, type: 'object' as const },+ },+ } as any,+ { requestModel: 'claude-opus-5' },+ );++ expect(requestParams.messages).toEqual([{ content: 'Generate data', role: 'user' }]);+ });+describe('use struct output schema', () => {it('should return structured data on successful API call', async () => {const mockClient = {diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.tsindex 2a77586ea99..f823a0a32e1 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts@@ -2,6 +2,7 @@ import type Anthropic from '@anthropic-ai/sdk';import debug from 'debug';import type { Pricing } from 'model-bank';+import { stripUnsupportedClaudeAssistantPrefill } from '../../providers/anthropic/claudePrefill';import type { GenerateObjectOptions, GenerateObjectPayload } from '../../types';import { buildAnthropicMessages, buildAnthropicTools } from '../contextBuilders/anthropic';import { buildAnthropicInitialUsage } from '../usageConverters/anthropic';@@ -47,7 +48,13 @@ export const buildAnthropicGenerateObjectRequest = async (const systemPromptText =typeof system_message === 'string' && system_message.trim() ? system_message : undefined;const user_messages = messages.filter((m) => m.role !== 'system');- const anthropicMessages = await buildAnthropicMessages(user_messages);+ // Key the prefill guard on the model actually sent: a custom logical id the+ // parser doesn't recognize can map to a Claude 4.6+/5 `requestModel`, which+ // would otherwise skip the strip and 400 on a trailing assistant turn.+ const anthropicMessages = stripUnsupportedClaudeAssistantPrefill(+ config?.requestModel ?? model,+ await buildAnthropicMessages(user_messages),+ );log('converted %d messages to Anthropic format', anthropicMessages.length);diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.tsindex eb66551a750..4e2f8075ae2 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts@@ -213,6 +213,52 @@ describe('createAnthropicCompatibleRuntime', () => {expect(createClient.mock.calls[0][0]).not.toHaveProperty('modelIdMapping');});+ it('should strip trailing assistant prefill when a logical id maps to a Claude 5 model', async () => {+ // The prefill strip inside handlePayload sees the logical id; when the+ // mapping only later resolves to a Claude 4.6+/5 upstream id, chat() must+ // re-strip against the model actually sent (LOBE-12572).+ const messagesCreate = vi.fn().mockResolvedValue({ content: [] });+ const Runtime = createAnthropicCompatibleRuntime({+ chatCompletion: {+ handlePayload: (payload) => ({+ max_tokens: 1024,+ messages: [+ { content: 'hi', role: 'user' },+ { content: '...', role: 'assistant' },+ ],+ model: payload.model,+ }),+ },+ customClient: {+ createClient: () =>+ ({+ baseURL: 'https://aihubmix.com',+ messages: { create: messagesCreate },+ }) as unknown as Anthropic,+ },+ provider: 'test-provider',+ });+ const runtime = new Runtime({+ apiKey: 'test-key',+ modelIdMapping: { 'logical-model': 'claude-opus-5' },+ });++ await runtime.chat({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'logical-model',+ responseMode: 'json',+ stream: false,+ } as any);++ expect(messagesCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'claude-opus-5',+ }),+ expect.anything(),+ );+ });+it('should keep logical model for generateObject and pass mapped id as request config', async () => {const generateObject = vi.fn().mockResolvedValue({ ok: true });const Runtime = createAnthropicCompatibleRuntime({diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.tsindex ac89beaa138..fa0c457876f 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts@@ -6,10 +6,8 @@ import debug from 'debug';import type { Pricing } from 'model-bank';import { ErrorClassifier } from '../../errors';-import {- rejectsDisabledThinkingAtEffort,- shouldDropUnsupportedClaudeAssistantPrefill,-} from '../../providers/anthropic/modelId';+import { stripUnsupportedClaudeAssistantPrefill } from '../../providers/anthropic/claudePrefill';+import { rejectsDisabledThinkingAtEffort } from '../../providers/anthropic/modelId';import type {ChatCompletionErrorPayload,ChatMethodOptions,@@ -186,14 +184,10 @@ export const buildDefaultAnthropicPayload = async (] as Anthropic.TextBlockParam[]): undefined;- const postMessages = await buildAnthropicMessages(userMessages, { enabledContextCaching });-- if (- shouldDropUnsupportedClaudeAssistantPrefill(model) &&- postMessages.at(-1)?.role === 'assistant'- ) {- postMessages.pop();- }+ const postMessages = stripUnsupportedClaudeAssistantPrefill(+ model,+ await buildAnthropicMessages(userMessages, { enabledContextCaching }),+ );let postTools = buildAnthropicTools(tools, { enabledContextCaching }) asAnthropicTools[] | undefined;@@ -553,6 +547,17 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =const finalPayload = { ...postPayload, stream: shouldStream };const requestPayload = this.withMappedRequestModel(finalPayload, payload.model);+ // Re-apply the prefill guard against the ACTUAL request model:+ // handlePayload stripped by the logical id, but a custom logical id the+ // parser doesn't recognize can map to a Claude 4.6+/5 request model+ // here. The strip is idempotent, so this is a no-op otherwise.+ if (requestPayload.model && Array.isArray(requestPayload.messages)) {+ requestPayload.messages = stripUnsupportedClaudeAssistantPrefill(+ requestPayload.model,+ requestPayload.messages,+ );+ }+if (debugParams?.chatCompletion?.()) {debugPayload(requestPayload);}diff --git a/packages/model-runtime/src/providers/anthropic/claudePrefill.test.ts b/packages/model-runtime/src/providers/anthropic/claudePrefill.test.tsnew file mode 100644index 00000000000..02313683438--- /dev/null+++ b/packages/model-runtime/src/providers/anthropic/claudePrefill.test.ts@@ -0,0 +1,54 @@+import type Anthropic from '@anthropic-ai/sdk';+import { describe, expect, it } from 'vitest';++import { stripUnsupportedClaudeAssistantPrefill } from './claudePrefill';++const user = (text: string): Anthropic.MessageParam => ({ content: text, role: 'user' });+const assistant = (text: string): Anthropic.MessageParam => ({ content: text, role: 'assistant' });++describe('stripUnsupportedClaudeAssistantPrefill', () => {+ it('should strip a single trailing assistant message on Claude 5', () => {+ const messages = [user('hi'), assistant('draft')];++ expect(stripUnsupportedClaudeAssistantPrefill('claude-opus-5', messages)).toEqual([user('hi')]);+ });++ it('should strip ALL stacked trailing assistant messages', () => {+ // Regression LOBE-12572: failed-run placeholders can stack multiple+ // assistant turns at the tail; popping only one still returns 400.+ const messages = [+ user('hi'),+ assistant('a'),+ user('retry'),+ assistant('...'),+ assistant('...'),+ ];++ expect(stripUnsupportedClaudeAssistantPrefill('claude-opus-5', messages)).toEqual([+ user('hi'),+ assistant('a'),+ user('retry'),+ ]);+ });++ it('should keep mid-conversation assistant messages untouched', () => {+ const messages = [user('hi'), assistant('a'), user('ok')];++ expect(stripUnsupportedClaudeAssistantPrefill('claude-opus-5', messages)).toBe(messages);+ });++ it('should leave prefill-capable models untouched', () => {+ const messages = [user('hi'), assistant('draft')];++ expect(stripUnsupportedClaudeAssistantPrefill('claude-opus-4-5', messages)).toBe(messages);+ expect(stripUnsupportedClaudeAssistantPrefill('claude-3-5-haiku-20241022', messages)).toBe(+ messages,+ );+ });++ it('should return an empty list when every message is assistant', () => {+ expect(+ stripUnsupportedClaudeAssistantPrefill('claude-opus-5', [assistant('a'), assistant('b')]),+ ).toEqual([]);+ });+});diff --git a/packages/model-runtime/src/providers/anthropic/claudePrefill.ts b/packages/model-runtime/src/providers/anthropic/claudePrefill.tsnew file mode 100644index 00000000000..cfdcd3c961f--- /dev/null+++ b/packages/model-runtime/src/providers/anthropic/claudePrefill.ts@@ -0,0 +1,26 @@+import type Anthropic from '@anthropic-ai/sdk';++import { shouldDropUnsupportedClaudeAssistantPrefill } from './modelId';++/**+ * Claude 4.6+ (including every Claude 5 model) rejects requests whose+ * conversation ends with an assistant turn — the API treats it as an+ * unsupported assistant prefill and returns 400 before generation starts.+ *+ * A single trailing pop is not enough: failed-run placeholder rows can stack+ * multiple assistant messages at the payload tail (see LOBE-12572), so strip+ * until the conversation ends with a non-assistant turn. Models that still+ * support prefill are left untouched.+ * @see https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prefill-claudes-response+ */+export const stripUnsupportedClaudeAssistantPrefill = (+ model: string,+ messages: Anthropic.MessageParam[],+): Anthropic.MessageParam[] => {+ if (!shouldDropUnsupportedClaudeAssistantPrefill(model)) return messages;++ let end = messages.length;+ while (end > 0 && messages[end - 1].role === 'assistant') end--;++ return end === messages.length ? messages : messages.slice(0, end);+};diff --git a/packages/model-runtime/src/providers/anthropic/index.test.ts b/packages/model-runtime/src/providers/anthropic/index.test.tsindex 300492f6679..9b2b7ff9d34 100644--- a/packages/model-runtime/src/providers/anthropic/index.test.ts+++ b/packages/model-runtime/src/providers/anthropic/index.test.ts@@ -909,6 +909,28 @@ describe('LobeAnthropicAI', () => {]);});+ it('should drop ALL stacked trailing assistant messages (LOBE-12572)', async () => {+ // Failed-run placeholder rows can stack several assistant turns at the+ // payload tail; popping only one still triggers the prefill 400.+ const payload: ChatStreamPayload = {+ messages: [+ { content: 'Continue this answer', role: 'user' },+ { content: '...', role: 'assistant' },+ { content: '...', role: 'assistant' },+ ],+ model: 'claude-opus-5',+ };++ const result = await buildDefaultAnthropicPayload(payload);++ expect(result.messages).toEqual([+ {+ content: 'Continue this answer',+ role: 'user',+ },+ ]);+ });+it('should respect max_tokens in thinking mode when provided', async () => {const payload: ChatStreamPayload = {max_tokens: 1000,diff --git a/packages/model-runtime/src/providers/anthropic/modelId.test.ts b/packages/model-runtime/src/providers/anthropic/modelId.test.tsindex ac0f58e5c7a..fcdfc143790 100644--- a/packages/model-runtime/src/providers/anthropic/modelId.test.ts+++ b/packages/model-runtime/src/providers/anthropic/modelId.test.ts@@ -322,4 +322,15 @@ describe('shouldDropUnsupportedClaudeAssistantPrefill', () => {it('should preserve existing OpenRouter behavior', () => {expect(shouldDropUnsupportedClaudeAssistantPrefill('anthropic/claude-5-mythos')).toBe(false);});++ it('should cover every 4.6+ family and future 4.x minors (official cutoff is "4.6 and later")', () => {+ expect(shouldDropUnsupportedClaudeAssistantPrefill('claude-haiku-4-6')).toBe(true);+ expect(shouldDropUnsupportedClaudeAssistantPrefill('claude-opus-4-9')).toBe(true);+ });++ it('should return false for models before 4.6', () => {+ expect(shouldDropUnsupportedClaudeAssistantPrefill('claude-haiku-4-5')).toBe(false);+ expect(shouldDropUnsupportedClaudeAssistantPrefill('claude-opus-4-5')).toBe(false);+ expect(shouldDropUnsupportedClaudeAssistantPrefill('claude-3-7-sonnet-20250219')).toBe(false);+ });});diff --git a/packages/model-runtime/src/providers/anthropic/modelId.ts b/packages/model-runtime/src/providers/anthropic/modelId.tsindex ffca012bdd7..93938c31b29 100644--- a/packages/model-runtime/src/providers/anthropic/modelId.ts+++ b/packages/model-runtime/src/providers/anthropic/modelId.ts@@ -200,16 +200,16 @@ export const shouldOmitSamplingParams = (model: string): boolean => {return parsed.source !== 'openRouter' || parsed.minorSeparator === '.';};+/**+ * Anthropic dropped assistant prefill on "Claude 4.6 and later models" — any family,+ * with no upper minor bound — and every Claude 5 model. Requests ending with an+ * assistant turn return a 400 on these models.+ * @see https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prefill-claudes-response+ */export const shouldDropUnsupportedClaudeAssistantPrefill = (model: string): boolean => {const parsed = parseClaudeModelId(model);if (!parsed || parsed.source === 'openRouter') return false;if (parsed.majorVersion >= 5) return true;- return (- parsed.majorVersion === 4 &&- isClaudeFamily(parsed, ['opus', 'sonnet']) &&- parsed.minorVersion !== undefined &&- parsed.minorVersion >= 6 &&- parsed.minorVersion <= 8- );+ return parsed.majorVersion === 4 && hasMinorVersionAtLeast(parsed, 6);};diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.tsindex 96e5f80f2dc..79ebb7f6b09 100644--- a/packages/model-runtime/src/providers/bedrock/index.test.ts+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts@@ -244,6 +244,73 @@ describe('LobeBedrockAI', () => {]);});+ it('should drop ALL stacked trailing assistant messages (LOBE-12572)', async () => {+ const mockStream = new ReadableStream({+ start(controller) {+ controller.enqueue('Hello, world!');+ controller.close();+ },+ });+ (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));++ // Failed-run placeholder rows can stack several assistant turns at the+ // payload tail; popping only one still triggers the prefill 400.+ await instance.chat({+ messages: [+ { content: 'Continue this answer', role: 'user' },+ { content: '...', role: 'assistant' },+ { content: '...', role: 'assistant' },+ ],+ model: 'global.anthropic.claude-opus-5',+ });++ const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock+ .calls[0][0];+ const body = JSON.parse(commandInput.body);++ expect(body.messages).toEqual([+ {+ content: 'Continue this answer',+ role: 'user',+ },+ ]);+ });++ it('should drop assistant prefill when a logical id maps to a Claude 5 Bedrock id', async () => {+ // The channel modelIdMapping resolves the actually-sent Bedrock model+ // id; the prefill guard must follow it, not the logical id (LOBE-12572).+ const mappedInstance = new LobeBedrockAI({+ accessKeyId: 'test-access-key-id',+ accessKeySecret: 'test-access-key-secret',+ modelIdMapping: { 'my-router-model': 'global.anthropic.claude-opus-5' },+ region: 'us-west-2',+ });+ const mockStream = new ReadableStream({+ start(controller) {+ controller.enqueue('Hello, world!');+ controller.close();+ },+ });+ vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(+ Promise.resolve(mockStream) as any,+ );++ await mappedInstance.chat({+ messages: [+ { content: 'Continue this answer', role: 'user' },+ { content: '...', role: 'assistant' },+ ],+ model: 'my-router-model',+ });++ const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock+ .calls[0][0];+ expect(commandInput.modelId).toBe('global.anthropic.claude-opus-5');+ expect(JSON.parse(commandInput.body).messages).toEqual([+ { content: 'Continue this answer', role: 'user' },+ ]);+ });+it('should convert Claude assistant reasoning signatures to thinking content', async () => {const mockStream = new ReadableStream({start(controller) {@@ -1289,6 +1356,49 @@ describe('LobeBedrockAI', () => {expect(commandInput.modelId).toBe('us.anthropic.claude-opus-4-8');});+ it('should drop assistant prefill in generateObject when a logical id maps to Claude 5', async () => {+ // The prefill guard must follow the resolved Bedrock model id, not the+ // logical alias the channel mapping hides it behind (LOBE-12572).+ const mappedInstance = new LobeBedrockAI({+ accessKeyId: 'test-access-key-id',+ accessKeySecret: 'test-access-key-secret',+ modelIdMapping: { 'my-router-model': 'global.anthropic.claude-opus-5' },+ region: 'us-east-1',+ });+ const mockResponse = {+ body: new TextEncoder().encode(+ JSON.stringify({+ content: [{ input: { title: 'Mapped' }, name: 'mapped_schema', type: 'tool_use' }],+ }),+ ),+ };+ vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(mockResponse as any);++ await mappedInstance.generateObject({+ messages: [+ { content: 'Create a title.', role: 'user' },+ { content: '...', role: 'assistant' },+ ],+ model: 'my-router-model',+ schema: {+ name: 'mapped_schema',+ schema: {+ additionalProperties: false,+ properties: { title: { type: 'string' } },+ required: ['title'],+ type: 'object',+ },+ strict: true,+ },+ });++ const commandInput = (InvokeModelCommand as unknown as Mock).mock.calls.at(-1)?.[0];+ expect(commandInput.modelId).toBe('global.anthropic.claude-opus-5');+ expect(JSON.parse(commandInput.body).messages).toEqual([+ { content: 'Create a title.', role: 'user' },+ ]);+ });+it('should return tool calls when tools are provided', async () => {const mockResponse = {body: new TextEncoder().encode(diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.tsindex b04cfb20c74..dd58f2b3667 100644--- a/packages/model-runtime/src/providers/bedrock/index.ts+++ b/packages/model-runtime/src/providers/bedrock/index.ts@@ -38,11 +38,9 @@ import { AgentRuntimeError } from '../../utils/createError';import { debugStream } from '../../utils/debugStream';import { getModelPricing } from '../../utils/getModelPricing';import { StreamingResponse } from '../../utils/response';+import { stripUnsupportedClaudeAssistantPrefill } from '../anthropic/claudePrefill';import { normalizeClaudeThinkingHistoryMessages } from '../anthropic/claudeThinkingHistory';-import {- rejectsDisabledThinkingAtEffort,- shouldDropUnsupportedClaudeAssistantPrefill,-} from '../anthropic/modelId';+import { rejectsDisabledThinkingAtEffort } from '../anthropic/modelId';/*** A prompt constructor for HuggingFace LLama 2 chat models.@@ -182,7 +180,9 @@ export class LobeBedrockAI implements LobeRuntimeAI {) as GenerateObjectPayload['messages'];const { requestParams, schemaToolName } = await buildAnthropicGenerateObjectRequest({ ...payload, messages: [...systemMessages, ...normalizedMessages] },- { maxTokens: resolvedMaxTokens },+ // requestModel keys the prefill guard on the Bedrock id actually sent+ // below, so channel modelIdMapping aliases still get the strip.+ { maxTokens: resolvedMaxTokens, requestModel: this.resolveModelId(payload.model) },);const bedrockRequestParams: Omit<Anthropic.MessageCreateParams, 'model'> & {model?: Anthropic.MessageCreateParams['model'];@@ -309,14 +309,13 @@ export class LobeBedrockAI implements LobeRuntimeAI {enabledContextCaching,});- const postMessages = await buildAnthropicMessages(user_messages, { enabledContextCaching });-- if (- shouldDropUnsupportedClaudeAssistantPrefill(model) &&- postMessages.at(-1)?.role === 'assistant'- ) {- postMessages.pop();- }+ // Key the prefill guard on the resolved Bedrock model id: a custom logical+ // id can map to a Claude 4.6+/5 Bedrock id via the channel modelIdMapping,+ // which would otherwise skip the strip and 400 on a trailing assistant turn.+ const postMessages = stripUnsupportedClaudeAssistantPrefill(+ this.resolveModelId(model),+ await buildAnthropicMessages(user_messages, { enabledContextCaching }),+ );const anthropicBase = {anthropic_version: 'bedrock-2023-05-31',diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 9e3756ffdd8..df175285085 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -1,5 +1,6 @@import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';import { HETERO_CONTINUE_PROMPT, LOADING_FLAT } from '@lobechat/const';+import { shouldDropUnsupportedClaudeAssistantPrefill } from '@lobechat/model-runtime/providers/anthropic/modelId';import type {ChatImageItem,ChatTTS,@@ -14,6 +15,7 @@ import { message as antdMessage } from '@/components/AntdStaticMethods';import { MESSAGE_CANCEL_FLAT } from '@/const/index';import { saveDraft } from '@/features/ChatInput/draftStorage';import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';+import { getEffectiveConversationModel } from '@/features/Conversation/store/utils/effectiveModel';import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';import { resolveWorkspaceScoped } from '@/helpers/executionTarget';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';@@ -551,6 +553,18 @@ export const generationSlice: StateCreator<// the session and confuse the model. The button is a no-op in this mode.if (runtimeType === 'hetero') return;+ // Claude 4.6+/5 removed assistant prefill: a payload ending with an+ // assistant turn is rejected (400), and the model runtime strips trailing+ // assistant messages for these models — so "continue" would silently+ // regenerate instead of continuing. Surface that instead of pretending.+ // Resolve the effective model (topic override > agent default) — the topic+ // may have been switched to/from a prefill-capable model independently.+ const continueModel = getEffectiveConversationModel(context);+ if (continueModel && shouldDropUnsupportedClaudeAssistantPrefill(continueModel)) {+ antdMessage.warning(t('messageAction.continueGenerationUnsupported', { ns: 'chat' }));+ return;+ }+// Create continue operation with ConversationStore context (includes groupId)const { operationId } = chatStore.startOperation({context: { ...context, messageId: displayMessageId },diff --git a/src/features/Conversation/store/slices/message/action/index.ts b/src/features/Conversation/store/slices/message/action/index.tsindex cbf44a45d8c..20e073ab3f3 100644--- a/src/features/Conversation/store/slices/message/action/index.ts+++ b/src/features/Conversation/store/slices/message/action/index.ts@@ -1,5 +1,10 @@+import { shouldDropUnsupportedClaudeAssistantPrefill } from '@lobechat/model-runtime/providers/anthropic/modelId';+import { toast } from '@lobehub/ui/base-ui';+import { t } from 'i18next';import type { StateCreator } from 'zustand';+import { getEffectiveConversationModel } from '@/features/Conversation/store/utils/effectiveModel';+import type { Store as ConversationStore } from '../../../action';import { type MessageCRUDAction, messageCRUDSlice } from './crud';import { type MessageReactionAction, messageReactionSlice } from './reaction';@@ -79,6 +84,16 @@ export const messageSlice: StateCreator<// Clear input after successful creationset({ inputMessage: '' });++ // Claude 4.6+/5 reject conversations ending with an assistant turn+ // (assistant prefill removed upstream), and the runtime strips trailing+ // assistant messages for them. Adding mid-conversation stays legal, so+ // don't block — just tell the user to follow up with a user message.+ // Effective model = topic override > agent default (see helper JSDoc).+ const model = getEffectiveConversationModel({ agentId, topicId });+ if (model && shouldDropUnsupportedClaudeAssistantPrefill(model)) {+ toast.info(t('input.addAiPrefillUnsupported', { ns: 'chat' }));+ }}return id;diff --git a/src/features/Conversation/store/utils/effectiveModel.test.ts b/src/features/Conversation/store/utils/effectiveModel.test.tsnew file mode 100644index 00000000000..8098387adfa--- /dev/null+++ b/src/features/Conversation/store/utils/effectiveModel.test.ts@@ -0,0 +1,88 @@+import { afterEach, describe, expect, it } from 'vitest';++import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';+import { useUserStore } from '@/store/user';++import { getEffectiveConversationModel } from './effectiveModel';++const AGENT_ID = 'agt_test';+const TOPIC_ID = 'tpc_test';++const initialAgentState = useAgentStore.getState();+const initialChatState = useChatStore.getState();+const initialUserState = useUserStore.getState();++afterEach(() => {+ useAgentStore.setState(initialAgentState, true);+ useChatStore.setState(initialChatState, true);+ useUserStore.setState(initialUserState, true);+});++describe('getEffectiveConversationModel', () => {+ it('prefers the topic-scoped model override over the agent default', () => {+ // A topic switched to a Claude 5 model must drive capability guards even+ // when the agent default is still a prefill-capable model (LOBE-12572).+ useAgentStore.setState({+ agentMap: { [AGENT_ID]: { chatConfig: {}, model: 'gpt-5.2' } },+ } as any);+ useChatStore.setState({+ activeAgentId: AGENT_ID,+ topicDataMap: {+ [`agent_${AGENT_ID}`]: {+ items: [{ id: TOPIC_ID, model: 'claude-opus-5', provider: 'anthropic' }],+ },+ },+ } as any);++ expect(getEffectiveConversationModel({ agentId: AGENT_ID, topicId: TOPIC_ID })).toBe(+ 'claude-opus-5',+ );+ });++ it('falls back to the agent default when the topic has no model recorded', () => {+ useAgentStore.setState({+ agentMap: { [AGENT_ID]: { chatConfig: {}, model: 'gpt-5.2' } },+ } as any);+ useChatStore.setState({+ activeAgentId: AGENT_ID,+ topicDataMap: {+ [`agent_${AGENT_ID}`]: { items: [{ id: TOPIC_ID }] },+ },+ } as any);++ expect(getEffectiveConversationModel({ agentId: AGENT_ID, topicId: TOPIC_ID })).toBe('gpt-5.2');+ });++ it('applies the workspace member model override for public workspace agents', () => {+ // Generation resolves member overrides via resolveAgentModelConfig for+ // public workspace agents used by non-authors — capability guards must+ // follow the same chain (no current user → non-author).+ useAgentStore.setState({+ agentMap: {+ [AGENT_ID]: {+ chatConfig: {},+ model: 'gpt-5.2',+ userId: 'user_author',+ visibility: 'public',+ workspaceId: 'ws_1',+ },+ },+ } as any);+ useUserStore.setState({+ workspaceUserPreference: {+ agentModelOverrides: { [AGENT_ID]: { model: 'claude-opus-5', provider: 'anthropic' } },+ },+ } as any);++ expect(getEffectiveConversationModel({ agentId: AGENT_ID })).toBe('claude-opus-5');+ });++ it('falls back to the agent default without a topic', () => {+ useAgentStore.setState({+ agentMap: { [AGENT_ID]: { chatConfig: {}, model: 'gpt-5.2' } },+ } as any);++ expect(getEffectiveConversationModel({ agentId: AGENT_ID })).toBe('gpt-5.2');+ });+});diff --git a/src/features/Conversation/store/utils/effectiveModel.ts b/src/features/Conversation/store/utils/effectiveModel.tsnew file mode 100644index 00000000000..46f10ee45e9--- /dev/null+++ b/src/features/Conversation/store/utils/effectiveModel.ts@@ -0,0 +1,62 @@+import { resolveAgentModelConfig } from '@lobechat/types';++import { getAgentStoreState } from '@/store/agent';+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++/**+ * Resolve the model a generation in this conversation would actually use.+ *+ * Resolution mirrors the generation chain (`streamingExecutor` ++ * `agentConfigResolver`):+ * 1. Topic-scoped override — a topic snapshots the model it was created with+ * and remembers switches made while active (top-level `topics.model`,+ * read via `getTopicModelById`).+ * 2. Member override — public workspace agents in member-selection mode read+ * the per-user `workspaceUserPreference.agentModelOverrides` entry through+ * `resolveAgentModelConfig`, leaving the shared default untouched.+ * 3. Shared agent default.+ *+ * UI guards keyed on model capabilities (e.g. the Claude prefill checks) must+ * resolve the same effective model, not the shared agent default.+ */+export const getEffectiveConversationModel = (context: {+ agentId?: string | null;+ topicId?: string | null;+}): string | undefined => {+ // Guard on topicDataMap: this runs inside UI actions whose tests build+ // partially-mocked chat stores, and a capability guard must never throw.+ const chatState = useChatStore.getState();+ const topicModel =+ context.topicId && chatState.topicDataMap+ ? topicSelectors.getTopicModelById(context.topicId)(chatState)?.model+ : undefined;+ if (topicModel) return topicModel;++ if (!context.agentId) return undefined;++ const agentState = getAgentStoreState();+ const sharedConfig = agentSelectors.getAgentConfigById(context.agentId)(agentState);+ const agent = agentByIdSelectors.getAgentById(context.agentId)(agentState);+ const userState = useUserStore.getState();+ const currentUserId = userProfileSelectors.userId(userState);+ const isAuthor = !!currentUserId && agent?.userId === currentUserId;+ const usesWorkspaceMemberSelection =+ !!agent?.workspaceId && agent.visibility !== 'private' && !isAuthor;+ const memberOverride = usesWorkspaceMemberSelection+ ? userState.workspaceUserPreference?.agentModelOverrides?.[context.agentId]+ : undefined;++ return resolveAgentModelConfig(+ {+ ...sharedConfig,+ canManage: isAuthor,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ },+ memberOverride,+ ).model;+};