π€― 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
chore(llm-generation-tracing): pre-allocate tracingId + recordFeedback router (#15146)
Arvin Xu46f884d5ed3a
diff --git a/package.json b/package.jsonindex c52861a626d..fb59d9f7bb3 100644--- a/package.json+++ b/package.json@@ -280,7 +280,7 @@"@lobehub/analytics": "^1.6.2","@lobehub/charts": "^5.0.0","@lobehub/desktop-ipc-typings": "workspace:*",- "@lobehub/editor": "^4.9.3",+ "@lobehub/editor": "^4.12.0","@lobehub/icons": "^5.0.0","@lobehub/market-sdk": "0.33.3","@lobehub/tts": "^5.1.2",diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex 58cae7b3909..56ef923fec6 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -18,6 +18,7 @@ export const TRACING_SCENARIOS = {SignalSkillIntent: 'signal_skill_intent',SignalSkillManagement: 'signal_skill_management',SignupEmailReview: 'signup_email_review',+ TaskHandoff: 'task_handoff',TopicTitle: 'topic_title',Unknown: 'unknown',} as const;diff --git a/packages/database/src/models/__tests__/llmGenerationTracing.test.ts b/packages/database/src/models/__tests__/llmGenerationTracing.test.tsindex 990d9956831..d277d58e372 100644--- a/packages/database/src/models/__tests__/llmGenerationTracing.test.ts+++ b/packages/database/src/models/__tests__/llmGenerationTracing.test.ts@@ -92,7 +92,7 @@ describe('LlmGenerationTracingModel', () => {});describe('updateFeedback', () => {- it('writes feedback columns and the updated timestamp', async () => {+ it('writes feedback columns + timestamp and returns updated:true on a match', async () => {const model = new LlmGenerationTracingModel(serverDB, userId);const { id } = await model.record({promptHash: 'aaaaaa',@@ -101,12 +101,13 @@ describe('LlmGenerationTracingModel', () => {success: true,});- await model.updateFeedback(id, {+ const result = await model.updateFeedback(id, {data: { clicked_question_index: 1 },score: 1,signal: 'positive',source: 'explicit_thumbs',});+ expect(result).toEqual({ updated: true });const row = await model.findById(id);expect(row).toMatchObject({@@ -118,7 +119,7 @@ describe('LlmGenerationTracingModel', () => {expect(row?.feedbackUpdatedAt).toBeInstanceOf(Date);});- it("does not touch another user's row", async () => {+ it('returns updated:false (no-op) when the row is owned by another user', async () => {const owner = new LlmGenerationTracingModel(serverDB, userId);const intruder = new LlmGenerationTracingModel(serverDB, otherUserId);@@ -129,14 +130,24 @@ describe('LlmGenerationTracingModel', () => {success: true,});- await intruder.updateFeedback(id, {+ const result = await intruder.updateFeedback(id, {signal: 'negative',source: 'manual_edit',});+ expect(result).toEqual({ updated: false });const row = await owner.findById(id);expect(row?.feedbackSignal).toBeNull();});++ it('returns updated:false when the id does not exist', async () => {+ const model = new LlmGenerationTracingModel(serverDB, userId);+ const result = await model.updateFeedback('00000000-0000-0000-0000-000000000000', {+ signal: 'positive',+ source: 'explicit_thumbs',+ });+ expect(result).toEqual({ updated: false });+ });});describe('findById / listRecent', () => {diff --git a/packages/database/src/models/llmGenerationTracing.ts b/packages/database/src/models/llmGenerationTracing.tsindex 6b3637e1fa3..b22df378e95 100644--- a/packages/database/src/models/llmGenerationTracing.ts+++ b/packages/database/src/models/llmGenerationTracing.ts@@ -13,6 +13,13 @@ export interface RecordLlmGenerationParams {costUsd?: number | null;errorCode?: string | null;errorDetail?: string | null;+ /**+ * Caller-supplied row id. When omitted the DB autogenerates one. Pass an+ * explicit UUID when the id needs to be known **before** the insert+ * completes (e.g. so a tRPC route can return it in the response and the+ * client can wire feedback against it).+ */+ id?: string;inputHash?: string | null;inputHint?: string | null;inputTokens?: number | null;@@ -57,6 +64,7 @@ export class LlmGenerationTracingModel {costUsd: params.costUsd ?? null,errorCode: params.errorCode ?? null,errorDetail: params.errorDetail ?? null,+ ...(params.id ? { id: params.id } : {}),inputHash: params.inputHash ?? null,inputHint: params.inputHint ?? null,inputTokens: params.inputTokens ?? null,@@ -88,8 +96,18 @@ export class LlmGenerationTracingModel {return { id: row.id };}- async updateFeedback(id: string, params: UpdateLlmGenerationFeedbackParams): Promise<void> {- await this.db+ /**+ * Returns `{ updated: true }` when a row matched `id + this.userId` and was+ * patched. `{ updated: false }` means no row matched β either the id doesn't+ * exist, or it belongs to a different user. Callers (e.g. the tracing+ * service / tRPC router) must treat the `false` case as a NOT_FOUND so the+ * client doesn't see a misleading success.+ */+ async updateFeedback(+ id: string,+ params: UpdateLlmGenerationFeedbackParams,+ ): Promise<{ updated: boolean }> {+ const rows = await this.db.update(llmGenerationTracing).set({feedbackData: params.data,@@ -98,7 +116,9 @@ export class LlmGenerationTracingModel {feedbackSource: params.source,feedbackUpdatedAt: new Date(),})- .where(and(eq(llmGenerationTracing.id, id), eq(llmGenerationTracing.userId, this.userId)));+ .where(and(eq(llmGenerationTracing.id, id), eq(llmGenerationTracing.userId, this.userId)))+ .returning({ id: llmGenerationTracing.id });+ return { updated: rows.length > 0 };}async findById(id: string) {diff --git a/packages/llm-generation-tracing/src/types.ts b/packages/llm-generation-tracing/src/types.tsindex 8c489ed4387..bf64017d4f8 100644--- a/packages/llm-generation-tracing/src/types.ts+++ b/packages/llm-generation-tracing/src/types.ts@@ -95,6 +95,13 @@ export interface TracingOptions {systemPrompt?: string;/** Topic / conversation ID. */topicId?: string;+ /**+ * Caller-supplied UUID used as the tracing row's primary key. Pass this+ * when the id needs to be known **before** the generation completes β+ * e.g. so the calling route can return it in the response and the client+ * can later post feedback against it. Omit to let the service generate one.+ */+ tracingId?: string;/** RequestTrigger string. */trigger?: string;}diff --git a/packages/prompts/src/chains/taskTopicHandoff.ts b/packages/prompts/src/chains/taskTopicHandoff.tsindex c660fd56ef8..2c92b310f9a 100644--- a/packages/prompts/src/chains/taskTopicHandoff.ts+++ b/packages/prompts/src/chains/taskTopicHandoff.ts@@ -1,5 +1,14 @@import type { ChatStreamPayload } from '@lobechat/types';+/**+ * Bump when editing the system prompt or schema below. Plumbed through+ * `tracing.promptVersion` at the call site so per-call tracing groups runs+ * by prompt iteration.+ */+export const TASK_TOPIC_HANDOFF_PROMPT_VERSION = 'v1.0';++export const TASK_TOPIC_HANDOFF_SCHEMA_NAME = 'task_topic_handoff';+/*** Generate a handoff summary for a completed task topic.* Returns both a title and structured handoff data for the next topic.diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex f9bf73b44f5..ba1d26acd82 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -210,8 +210,14 @@ export const StructureOutputSchema = z.object({* Structured tracing config (scenario / promptVersion / schemaName /* agentId / topicId / inputHint / ...). See `TracingOptions` from* `@lobechat/llm-generation-tracing` for the typed shape.+ *+ * `tracingId` is validated as UUID here because the value is reused as the+ * `llm_generation_tracing.id` primary key (uuid column) and is also accepted+ * back through `llmGenerationTracing.recordFeedback` (`z.string().uuid()`).+ * Letting a malformed value through would echo a tracingId the client can't+ * use for the feedback flow. Other fields stay free-form via `catchall`.*/- tracing: z.record(z.string(), z.unknown()).optional(),+ tracing: z.object({ tracingId: z.string().uuid().optional() }).catchall(z.unknown()).optional(),});interface IStructureSchema {diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 268fcf64e3f..e5be3557710 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -198,17 +198,25 @@ const InputEditor = memo<{});}, [storeApi]);+ // Map each in-flight suggestion to its tracing row so the Tab/Esc/typing+ // callbacks below can report `recordFeedback` against the correct id.+ // Keyed by editor-provided `suggestionId`; entries are dropped on+ // accept/reject (the plugin guarantees one of those eventually fires).+ const tracingIdBySuggestionRef = useRef<Map<string, string>>(new Map());+const handleAutoComplete = useCallback(async ({abortSignal,afterText,input,+ suggestionId,}: {abortSignal: AbortSignal;afterText: string;editor: any;input: string;selectionType: string;+ suggestionId?: string;}): Promise<string | null> => {// Skip autocomplete during IME composition (e.g. Chinese input method)if (isComposingRef.current) return null;@@ -228,9 +236,9 @@ const InputEditor = memo<{const currentTopicId = useChatStore.getState().activeTopicId;- let response: { completion?: string } | null;+ let envelope: { data?: { completion?: string } | null; tracingId?: string } | null;try {- response = (await aiChatService.generateJSON(+ envelope = (await aiChatService.generateJSON({messages,model: config.model,@@ -249,28 +257,97 @@ const InputEditor = memo<{},},abortController,- )) as { completion?: string } | null;+ )) as { data?: { completion?: string } | null; tracingId?: string } | null;} catch {return null;}if (abortSignal.aborted) return null;- const completion = response?.completion?.trimEnd();- return completion || null;+ const completion = envelope?.data?.completion?.trimEnd();+ if (!completion) return null;++ if (suggestionId && envelope?.tracingId) {+ tracingIdBySuggestionRef.current.set(suggestionId, envelope.tracingId);+ }+ return completion;},[isComposingRef, agentId],);+ const handleSuggestionAccepted = useCallback(+ ({+ acceptedText,+ suggestionId,+ visibleMs,+ }: {+ acceptedText: string;+ suggestionId: string;+ visibleMs: number;+ }) => {+ const tracingId = tracingIdBySuggestionRef.current.get(suggestionId);+ if (!tracingId) return;+ tracingIdBySuggestionRef.current.delete(suggestionId);+ aiChatService+ .recordTracingFeedback({+ data: { acceptedText, visibleMs },+ signal: 'positive',+ source: 'autocomplete_tab',+ tracingId,+ })+ .catch((err) => {+ console.warn('[InputCompletion] recordFeedback (accepted) failed', err);+ });+ },+ [],+ );++ const handleSuggestionRejected = useCallback(+ ({+ reason,+ suggestionId,+ visibleMs,+ }: {+ reason: 'cursor-move' | 'typing' | 'esc' | 'blur' | 'other';+ suggestionId: string;+ visibleMs: number;+ }) => {+ const tracingId = tracingIdBySuggestionRef.current.get(suggestionId);+ if (!tracingId) return;+ tracingIdBySuggestionRef.current.delete(suggestionId);+ // IME composition starts by dispatching KEY_ESCAPE_COMMAND from this+ // component (see onCompositionStart below); that arrives here with+ // reason='esc' but it isn't a real reject β recode as neutral so the+ // signal isn't poisoned for CJK input users.+ const isImeClear = reason === 'esc' && isComposingRef.current;+ const signal: 'positive' | 'negative' | 'neutral' =+ !isImeClear && reason === 'esc' ? 'negative' : 'neutral';+ const source = isImeClear ? 'autocomplete_ime' : `autocomplete_${reason}`;+ aiChatService+ .recordTracingFeedback({+ data: { reason, visibleMs },+ signal,+ source,+ tracingId,+ })+ .catch((err) => {+ console.warn('[InputCompletion] recordFeedback (rejected) failed', err);+ });+ },+ [isComposingRef],+ );+const autoCompletePlugin = useMemo(() =>isAutoCompleteEnabled? Editor.withProps(ReactAutoCompletePlugin, {delay: 600,onAutoComplete: handleAutoComplete,+ onSuggestionAccepted: handleSuggestionAccepted,+ onSuggestionRejected: handleSuggestionRejected,}): null,- [isAutoCompleteEnabled, handleAutoComplete],+ [isAutoCompleteEnabled, handleAutoComplete, handleSuggestionAccepted, handleSuggestionRejected],);// --- Stable mentionOption & slashOption to prevent infinite re-render on paste ---diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsxindex bae55143468..b7834f57b60 100644--- a/src/features/Conversation/ChatInput/QueueTray.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.tsx@@ -105,6 +105,7 @@ const QueuedFilePreview = memo<QueuedFilePreviewProps>(({ file }) => {size={PREVIEW_SIZE}src={file.url}title={file.name}+ variant={'borderless'}styles={{image: { height: PREVIEW_SIZE, width: PREVIEW_SIZE },wrapper: { height: PREVIEW_SIZE, width: PREVIEW_SIZE },diff --git a/src/server/routers/lambda/__tests__/aiChat.test.ts b/src/server/routers/lambda/__tests__/aiChat.test.tsindex a7a3a97bb54..caa63f823ab 100644--- a/src/server/routers/lambda/__tests__/aiChat.test.ts+++ b/src/server/routers/lambda/__tests__/aiChat.test.ts@@ -966,9 +966,13 @@ describe('aiChatRouter', () => {schema: input.schema,tools: undefined,},- { metadata: { trigger: 'chat' } },+ {+ metadata: { trigger: 'chat' },+ tracing: { tracingId: expect.stringMatching(/^[0-9a-f-]{36}$/) },+ },);- expect(result).toEqual(mockResult);+ expect(result.data).toEqual(mockResult);+ expect(result.tracingId).toMatch(/^[0-9a-f-]{36}$/);});it('should handle tools parameter when provided', async () => {@@ -1010,11 +1014,14 @@ describe('aiChatRouter', () => {schema: undefined,tools: mockTools,},- { metadata: { trigger: 'chat' } },+ {+ metadata: { trigger: 'chat' },+ tracing: { tracingId: expect.stringMatching(/^[0-9a-f-]{36}$/) },+ },);});- it('merges caller metadata over the default trigger', async () => {+ it('merges caller metadata over the default trigger and forwards tracing', async () => {const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');const mockGenerateObject = vi.fn().mockResolvedValue({ completion: 'hi there' });vi.mocked(initModelRuntimeFromDB).mockResolvedValue({@@ -1022,13 +1029,9 @@ describe('aiChatRouter', () => {} as any);const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);- await caller.outputJSON({+ const result = await caller.outputJSON({messages: [{ content: 'be helpful', role: 'system' }],- metadata: {- promptVersion: 'v2.0',- scenario: 'input_completion',- schemaName: 'InputCompletion',- },+ metadata: { correlationId: 'cid-1' },model: 'gpt-4o-mini',provider: 'openai',schema: {@@ -1040,16 +1043,64 @@ describe('aiChatRouter', () => {type: 'object' as const,},},+ tracing: {+ promptVersion: 'v2.0',+ scenario: 'input_completion',+ schemaName: 'InputCompletion',+ },});expect(mockGenerateObject.mock.calls[0][1]).toEqual({- metadata: {+ metadata: { correlationId: 'cid-1', trigger: 'chat' },+ tracing: {promptVersion: 'v2.0',scenario: 'input_completion',schemaName: 'InputCompletion',- trigger: 'chat',+ tracingId: expect.stringMatching(/^[0-9a-f-]{36}$/),},});+ expect(result.tracingId).toMatch(/^[0-9a-f-]{36}$/);+ });++ it('rejects a caller-supplied tracing.tracingId that is not a UUID', async () => {+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');+ const mockGenerateObject = vi.fn();+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ generateObject: mockGenerateObject,+ } as any);++ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);++ await expect(+ caller.outputJSON({+ messages: [],+ model: 'gpt-4o-mini',+ provider: 'openai',+ tracing: { tracingId: 'not-a-uuid' },+ }),+ ).rejects.toThrow();++ expect(mockGenerateObject).not.toHaveBeenCalled();+ });++ it('honours caller-supplied tracing.tracingId instead of generating a new one', async () => {+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');+ const mockGenerateObject = vi.fn().mockResolvedValue({ completion: 'ok' });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ generateObject: mockGenerateObject,+ } as any);++ const callerSuppliedId = '00000000-0000-0000-0000-000000000001';+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);+ const result = await caller.outputJSON({+ messages: [],+ model: 'gpt-4o-mini',+ provider: 'openai',+ tracing: { tracingId: callerSuppliedId },+ });++ expect(result.tracingId).toBe(callerSuppliedId);+ expect(mockGenerateObject.mock.calls[0][1].tracing.tracingId).toBe(callerSuppliedId);});});});diff --git a/src/server/routers/lambda/__tests__/llmGenerationTracing.test.ts b/src/server/routers/lambda/__tests__/llmGenerationTracing.test.tsnew file mode 100644index 00000000000..e9508c2891c--- /dev/null+++ b/src/server/routers/lambda/__tests__/llmGenerationTracing.test.ts@@ -0,0 +1,121 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { describe, expect, it, vi } from 'vitest';++import type * as TracingService from '@/server/services/llmGenerationTracing';++const recordFeedback = vi.fn<(...args: unknown[]) => Promise<void>>(async () => {});++// Mock the service module but keep the real `LLMGenerationFeedbackError` class β+// the router does an `instanceof` check, so the constructor reference must match.+vi.mock('@/server/services/llmGenerationTracing', async () => {+ const actual = await vi.importActual<typeof TracingService>(+ '@/server/services/llmGenerationTracing',+ );+ return {+ ...actual,+ getLLMGenerationTracingService: () => ({ recordFeedback }),+ };+});++const { llmGenerationTracingRouter } = await import('../llmGenerationTracing');+const { LLMGenerationFeedbackError } = await import('@/server/services/llmGenerationTracing');++const mockCtx = { userId: 'u1' };++describe('llmGenerationTracingRouter.recordFeedback', () => {+ it('forwards { tracingId, signal, source, score, data } through to the service', async () => {+ recordFeedback.mockClear();+ recordFeedback.mockResolvedValueOnce(undefined);+ const caller = llmGenerationTracingRouter.createCaller(mockCtx as any);+ const tracingId = '00000000-0000-0000-0000-000000000001';++ const result = await caller.recordFeedback({+ data: { accepted_text: 'hello' },+ score: 1,+ signal: 'positive',+ source: 'explicit_thumbs',+ tracingId,+ });++ expect(result).toEqual({ ok: true });+ expect(recordFeedback).toHaveBeenCalledWith('u1', tracingId, {+ data: { accepted_text: 'hello' },+ score: 1,+ signal: 'positive',+ source: 'explicit_thumbs',+ });+ });++ it('translates LLMGenerationFeedbackError(not_found) into TRPCError NOT_FOUND', async () => {+ recordFeedback.mockClear();+ recordFeedback.mockRejectedValueOnce(+ new LLMGenerationFeedbackError('not_found', 'no tracing row matched id=β¦'),+ );+ const caller = llmGenerationTracingRouter.createCaller(mockCtx as any);+ try {+ await caller.recordFeedback({+ signal: 'positive',+ source: 'explicit_thumbs',+ tracingId: '00000000-0000-0000-0000-000000000001',+ });+ throw new Error('expected mutation to reject');+ } catch (err) {+ expect(err).toBeInstanceOf(TRPCError);+ expect((err as TRPCError).code).toBe('NOT_FOUND');+ }+ });++ it('translates LLMGenerationFeedbackError(db_failure) into TRPCError INTERNAL_SERVER_ERROR', async () => {+ recordFeedback.mockClear();+ recordFeedback.mockRejectedValueOnce(+ new LLMGenerationFeedbackError('db_failure', 'database not reachable'),+ );+ const caller = llmGenerationTracingRouter.createCaller(mockCtx as any);+ try {+ await caller.recordFeedback({+ signal: 'positive',+ source: 'explicit_thumbs',+ tracingId: '00000000-0000-0000-0000-000000000001',+ });+ throw new Error('expected mutation to reject');+ } catch (err) {+ expect(err).toBeInstanceOf(TRPCError);+ expect((err as TRPCError).code).toBe('INTERNAL_SERVER_ERROR');+ }+ });++ it('rejects an invalid signal value', async () => {+ const caller = llmGenerationTracingRouter.createCaller(mockCtx as any);+ await expect(+ caller.recordFeedback({+ signal: 'meh' as any,+ source: 'explicit_thumbs',+ tracingId: '00000000-0000-0000-0000-000000000001',+ }),+ ).rejects.toThrow();+ });++ it('rejects a malformed tracingId', async () => {+ const caller = llmGenerationTracingRouter.createCaller(mockCtx as any);+ await expect(+ caller.recordFeedback({+ signal: 'positive',+ source: 'explicit_thumbs',+ tracingId: 'not-a-uuid',+ }),+ ).rejects.toThrow();+ });++ it('rejects an out-of-range score', async () => {+ const caller = llmGenerationTracingRouter.createCaller(mockCtx as any);+ await expect(+ caller.recordFeedback({+ score: 2,+ signal: 'positive',+ source: 'explicit_thumbs',+ tracingId: '00000000-0000-0000-0000-000000000001',+ }),+ ).rejects.toThrow();+ });+});diff --git a/src/server/routers/lambda/aiChat.ts b/src/server/routers/lambda/aiChat.tsindex dee52f0add7..a502025dbc6 100644--- a/src/server/routers/lambda/aiChat.ts+++ b/src/server/routers/lambda/aiChat.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import type { CreateMessageParams, SendMessageServerResponse } from '@lobechat/types';import { AiSendMessageServerSchema, RequestTrigger, StructureOutputSchema } from '@lobechat/types';import { createTimingHelpers, createTimingRequestId } from '@lobechat/utils';@@ -44,11 +46,18 @@ export const aiChatRouter = router({log('messages count: %d', input.messages.length);log('schema: %O', input.schema);+ // Pre-allocate the tracing row id so we can return it to the client even+ // though the actual `service.record()` call happens in Next's `after()`+ // (after the response has been sent). Honour the caller-supplied id when+ // one was passed via `tracing.tracingId` β the schema already validates+ // it as UUID, so a malformed value never reaches here.+ const tracingId = input.tracing?.tracingId ?? randomUUID();+// Always stamp a trigger on metadata so cross-cutting hooks (timing,// routing) and the tracing registry have a fallback when the caller// forgets to set one. `tracing` carries the structured tracing config// (scenario / promptVersion / schemaName / inputHint / ...).- const result = await ctx.aiGenerationService.generateObject(+ const data = await ctx.aiGenerationService.generateObject({messages: input.messages,model: input.model,@@ -58,12 +67,12 @@ export const aiChatRouter = router({},{metadata: { trigger: RequestTrigger.Chat, ...input.metadata },- tracing: input.tracing,+ tracing: { ...input.tracing, tracingId },},);- log('generateObject completed, result: %O', result);- return result;+ log('generateObject completed, result: %O', data);+ return { data, tracingId };}),sendMessageInServer: aiChatProcedurediff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex 2f89e8e3e38..4d95ff9ab12 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -43,6 +43,7 @@ import { importerRouter } from './importer';import { klavisRouter } from './klavis';import { knowledgeRouter } from './knowledge';import { knowledgeBaseRouter } from './knowledgeBase';+import { llmGenerationTracingRouter } from './llmGenerationTracing';import { marketRouter } from './market';import { messageRouter } from './message';import { messengerRouter } from './messenger';@@ -104,6 +105,7 @@ export const lambdaRouter = router({klavis: klavisRouter,knowledge: knowledgeRouter,knowledgeBase: knowledgeBaseRouter,+ llmGenerationTracing: llmGenerationTracingRouter,market: marketRouter,message: messageRouter,messenger: messengerRouter,diff --git a/src/server/routers/lambda/llmGenerationTracing.ts b/src/server/routers/lambda/llmGenerationTracing.tsnew file mode 100644index 00000000000..09ec8e0f455--- /dev/null+++ b/src/server/routers/lambda/llmGenerationTracing.ts@@ -0,0 +1,64 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { authedProcedure, router } from '@/libs/trpc/lambda';+import {+ getLLMGenerationTracingService,+ LLMGenerationFeedbackError,+} from '@/server/services/llmGenerationTracing';++/**+ * General-purpose feedback endpoint for any `llm_generation_tracing` row.+ *+ * Designed scenario-agnostically: any caller that holds a `tracingId`+ * (returned by the originating mutation, e.g. `aiChat.outputJSON`) can+ * report a positive / negative / neutral signal. Scenario-specific detail+ * goes into `data` so we don't need a new endpoint per use case.+ *+ * **Failure surfacing**: `{ ok: true }` only flows back when a row actually+ * matched and was patched. A missing/foreign row produces `NOT_FOUND`; a DB+ * outage produces `INTERNAL_SERVER_ERROR`. Callers can therefore distinguish+ * "give up, this id is stale" from "transient, retry later".+ */+export const llmGenerationTracingRouter = router({+ recordFeedback: authedProcedure+ .input(+ z.object({+ /** Free-form jsonb detail (e.g. accepted suggestion text, retry count). */+ data: z.record(z.string(), z.unknown()).optional(),+ /** Continuous score in [-1, 1], if the caller has a finer-grained metric. */+ score: z.number().min(-1).max(1).optional(),+ /** Feedback polarity. */+ signal: z.enum(['positive', 'negative', 'neutral']),+ /**+ * What triggered the feedback. Common values include `explicit_thumbs`,+ * `implicit_regenerate`, `downstream_acceptance`, `manual_edit`,+ * `usage_in_followup`. Free-form string so callers can introduce new+ * sources without DB migration.+ */+ source: z.string().min(1),+ /** Tracing row id returned by the originating generation route. */+ tracingId: z.string().uuid(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ await getLLMGenerationTracingService().recordFeedback(ctx.userId, input.tracingId, {+ data: input.data,+ score: input.score,+ signal: input.signal,+ source: input.source,+ });+ } catch (err) {+ if (err instanceof LLMGenerationFeedbackError) {+ throw new TRPCError({+ cause: err,+ code: err.kind === 'not_found' ? 'NOT_FOUND' : 'INTERNAL_SERVER_ERROR',+ message: err.message,+ });+ }+ throw err;+ }+ return { ok: true as const };+ }),+});diff --git a/src/server/services/llmGenerationTracing/hook.test.ts b/src/server/services/llmGenerationTracing/hook.test.tsindex 481f44259ae..fbc83768995 100644--- a/src/server/services/llmGenerationTracing/hook.test.ts+++ b/src/server/services/llmGenerationTracing/hook.test.ts@@ -86,6 +86,20 @@ describe('createLLMGenerationTracingHook', () => {expect(call.promptHash).toHaveLength(6);});+ it('forwards caller-supplied tracingId through to the service', async () => {+ const hooks = createLLMGenerationTracingHook('user-1', 'openai');+ const preAllocated = '00000000-0000-0000-0000-000000000abc';+ hooks.onGenerateObjectComplete!(+ { latencyMs: 5, success: true },+ {+ options: { tracing: { scenario: 'input_completion', tracingId: preAllocated } },+ payload: { messages: [], model: 'gpt-4o', schema: {} } as any,+ },+ );+ await flushMicrotasks();+ expect(record.mock.calls[0][0].tracingId).toBe(preAllocated);+ });+it('forwards caller-supplied inputHint through to the service', async () => {const hooks = createLLMGenerationTracingHook('user-1', 'openai');hooks.onGenerateObjectComplete!(diff --git a/src/server/services/llmGenerationTracing/hook.ts b/src/server/services/llmGenerationTracing/hook.tsindex 751bf536270..f76972fab62 100644--- a/src/server/services/llmGenerationTracing/hook.ts+++ b/src/server/services/llmGenerationTracing/hook.ts@@ -34,6 +34,7 @@ const parseTracingOptions = (raw: Record<string, unknown> | undefined): TracingOschemaName: pickString(raw.schemaName),systemPrompt: pickString(raw.systemPrompt),topicId: pickString(raw.topicId),+ tracingId: pickString(raw.tracingId),trigger: pickString(raw.trigger),};};@@ -128,6 +129,7 @@ export const createLLMGenerationTracingHook = (schemaName: tracing.schemaName,success: data.success,topicId: tracing.topicId,+ tracingId: tracing.tracingId,trigger,userId,validationFailed,diff --git a/src/server/services/llmGenerationTracing/index.test.ts b/src/server/services/llmGenerationTracing/index.test.tsindex 6ede8c7ff0d..7ee95ab365b 100644--- a/src/server/services/llmGenerationTracing/index.test.ts+++ b/src/server/services/llmGenerationTracing/index.test.ts@@ -116,6 +116,26 @@ describe('LLMGenerationTracingService.record', () => {});});+ it('honours a caller-supplied tracingId as the row primary key', async () => {+ const service = new LLMGenerationTracingService(stubStore);+ const preAllocated = '00000000-0000-0000-0000-000000000abc';+ const result = await service.record({+ promptHash: 'ffffff',+ promptVersion: 'v1.0',+ scenario: 'input_completion',+ success: true,+ tracingId: preAllocated,+ userId,+ });++ expect(result?.tracingId).toBe(preAllocated);+ const [row] = await serverDB+ .select()+ .from(llmGenerationTracing)+ .where(eq(llmGenerationTracing.id, preAllocated));+ expect(row?.id).toBe(preAllocated);+ });+it('honours an explicit inputHint override instead of auto-extracting from the first user message', async () => {const service = new LLMGenerationTracingService(stubStore);const result = await service.record({@@ -224,4 +244,38 @@ describe('LLMGenerationTracingService.recordFeedback', () => {feedbackSource: 'explicit_thumbs',});});++ it('throws LLMGenerationFeedbackError(not_found) when no row matches the tracingId', async () => {+ const service = new LLMGenerationTracingService(stubStore);+ await expect(+ service.recordFeedback(userId, '00000000-0000-0000-0000-000000000abc', {+ signal: 'positive',+ source: 'explicit_thumbs',+ }),+ ).rejects.toMatchObject({+ kind: 'not_found',+ name: 'LLMGenerationFeedbackError',+ });+ });++ it('throws LLMGenerationFeedbackError(not_found) when the row belongs to another user', async () => {+ const service = new LLMGenerationTracingService(stubStore);+ const { tracingId } = (await service.record({+ promptHash: 'cafecafe',+ promptVersion: 'v1.0',+ scenario: 'agent_welcome',+ success: true,+ userId,+ }))!;++ await expect(+ service.recordFeedback('some-other-user', tracingId, {+ signal: 'negative',+ source: 'manual_edit',+ }),+ ).rejects.toMatchObject({+ kind: 'not_found',+ name: 'LLMGenerationFeedbackError',+ });+ });});diff --git a/src/server/services/llmGenerationTracing/index.ts b/src/server/services/llmGenerationTracing/index.tsindex 7fbb2ffa8d0..ed686dd0742 100644--- a/src/server/services/llmGenerationTracing/index.ts+++ b/src/server/services/llmGenerationTracing/index.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import {computeInputHash,FileTracingStore,@@ -55,6 +57,12 @@ export interface RecordLLMGenerationCallParams {success: boolean;topicId?: string | null;traceId?: string | null;+ /**+ * Caller-supplied UUID for the row. When omitted the service generates one+ * up-front (before DB insert), so the id is always known and returnable+ * synchronously to the calling route.+ */+ tracingId?: string;trigger?: string | null;userId: string;validationFailed?: boolean;@@ -93,11 +101,17 @@ export class LLMGenerationTracingService {const model = new LlmGenerationTracingModel(db, params.userId);+ // Allocate the id up-front so the route can return it synchronously to+ // the client (e.g. for feedback wiring) even though the actual `record()`+ // call runs inside Next's `after()` after the response has been sent.+ const id = params.tracingId ?? randomUUID();+const dbValues: RecordLlmGenerationParams = {agentId: params.agentId,costUsd: params.costUsd,errorCode: params.errorCode,errorDetail: params.errorDetail,+ id,inputHash: params.payload?.input ? computeInputHash(params.payload.input) : null,inputHint: resolveInputHint(params.inputHint, params.payload?.input),inputTokens: params.inputTokens,@@ -119,12 +133,11 @@ export class LLMGenerationTracingService {validationFailed: params.validationFailed,};- // Insert first so the storage key can embed the row's id β every blob then- // points at exactly one row.- let tracingId: string;+ // `id` was already allocated up-front (caller-supplied or randomUUID()).+ // Insert first so the storage key can embed the row's id β every blob+ // then points at exactly one row.try {- const row = await model.record(dbValues);- tracingId = row.id;+ await model.record(dbValues);} catch (err) {log('DB insert failed: %O', err);return null;@@ -150,7 +163,7 @@ export class LLMGenerationTracingService {scenario: params.scenario,schema: params.payload?.schema,system_prompt: params.payload?.systemPrompt,- tracing_id: tracingId,+ tracing_id: id,validation_failed: params.validationFailed,version: '1.0',};@@ -174,14 +187,25 @@ export class LLMGenerationTracingService {: (params.metadata ?? {}),storageKey,})- .where(eq(llmGenerationTracing.id, tracingId));+ .where(eq(llmGenerationTracing.id, id));} catch (err) {log('Failed to patch storage_key onto row: %O', err);}- return { tracingId };+ return { tracingId: id };}+ /**+ * Write a feedback row to `llm_generation_tracing`. Surfaces failures so+ * callers can distinguish "actually persisted" from "silently dropped":+ *+ * - DB init / update throws β `LLMGenerationFeedbackError({ kind: 'db_failure' })`+ * - WHERE matched no row (wrong id, or row owned by another user) β+ * `LLMGenerationFeedbackError({ kind: 'not_found' })`+ *+ * The tRPC route translates these into `INTERNAL_SERVER_ERROR` /+ * `NOT_FOUND` so the client can choose retry vs give-up semantics.+ */async recordFeedback(userId: string,tracingId: string,@@ -191,18 +215,46 @@ export class LLMGenerationTracingService {try {db = await getServerDB();} catch (err) {- log('Skipping feedback β getServerDB failed: %O', err);- return;+ log('Feedback DB init failed: %O', err);+ throw new LLMGenerationFeedbackError('db_failure', 'database not reachable', {+ cause: err,+ });}const model = new LlmGenerationTracingModel(db, userId);+ let result: { updated: boolean };try {- await model.updateFeedback(tracingId, params);+ result = await model.updateFeedback(tracingId, params);} catch (err) {log('Feedback update failed: %O', err);+ throw new LLMGenerationFeedbackError('db_failure', 'database update failed', {+ cause: err,+ });+ }+ if (!result.updated) {+ log('Feedback update affected 0 rows (id=%s userId=%s)', tracingId, userId);+ throw new LLMGenerationFeedbackError(+ 'not_found',+ `no tracing row matched id=${tracingId} for the calling user`,+ );}}}+/**+ * Typed failure for `recordFeedback`. `kind` discriminates between an absent+ * row (caller probably retrying with a wrong id or wrong user) and an actual+ * DB outage (caller may want to retry).+ */+export class LLMGenerationFeedbackError extends Error {+ readonly kind: 'not_found' | 'db_failure';++ constructor(kind: 'not_found' | 'db_failure', message: string, options?: { cause?: unknown }) {+ super(message, options);+ this.name = 'LLMGenerationFeedbackError';+ this.kind = kind;+ }+}+const createDefaultStore = (): ITracingStore | null => {if (process.env.ENABLE_LLM_GENERATION_TRACING_S3 === '1') {try {diff --git a/src/server/services/taskLifecycle/index.ts b/src/server/services/taskLifecycle/index.tsindex 5d92fa4db4b..49344b90ca5 100644--- a/src/server/services/taskLifecycle/index.ts+++ b/src/server/services/taskLifecycle/index.ts@@ -1,10 +1,14 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import type { TracingOptions } from '@lobechat/llm-generation-tracing';import {chainGenerateBrief,chainJudgeBriefEmit,chainTaskTopicHandoff,GENERATE_BRIEF_SCHEMA,JUDGE_BRIEF_EMIT_SCHEMA,+ TASK_TOPIC_HANDOFF_PROMPT_VERSION,TASK_TOPIC_HANDOFF_SCHEMA,+ TASK_TOPIC_HANDOFF_SCHEMA_NAME,} from '@lobechat/prompts';import type {BriefArtifacts,@@ -351,9 +355,16 @@ export class TaskLifecycleService {{messages: payload.messages as any[],model,- schema: { name: 'task_topic_handoff', schema: TASK_TOPIC_HANDOFF_SCHEMA },+ schema: { name: TASK_TOPIC_HANDOFF_SCHEMA_NAME, schema: TASK_TOPIC_HANDOFF_SCHEMA },+ },+ {+ metadata: { trigger: 'task-handoff' },+ tracing: {+ promptVersion: TASK_TOPIC_HANDOFF_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TaskHandoff,+ schemaName: TASK_TOPIC_HANDOFF_SCHEMA_NAME,+ } satisfies TracingOptions,},- { metadata: { trigger: 'task-handoff' } },);const handoff = result as {diff --git a/src/services/aiChat.ts b/src/services/aiChat.tsindex b427e20a341..48c1f231b2a 100644--- a/src/services/aiChat.ts+++ b/src/services/aiChat.ts@@ -3,6 +3,14 @@ import { cleanObject } from '@lobechat/utils';import { lambdaClient } from '@/libs/trpc/client';+export interface RecordTracingFeedbackParams {+ data?: Record<string, unknown>;+ score?: number;+ signal: 'positive' | 'negative' | 'neutral';+ source: string;+ tracingId: string;+}+class AiChatService {sendMessageInServer = async (params: SendMessageServerParams,@@ -20,6 +28,12 @@ class AiChatService {signal: abortController?.signal,});};++ recordTracingFeedback = async (params: RecordTracingFeedbackParams) => {+ return lambdaClient.llmGenerationTracing.recordFeedback.mutate(params, {+ context: { showNotification: false },+ });+ };}export const aiChatService = new AiChatService();diff --git a/src/store/chat/slices/message/supervisor.test.ts b/src/store/chat/slices/message/supervisor.test.tsindex 82637d3ee2e..cc46bc9517c 100644--- a/src/store/chat/slices/message/supervisor.test.ts+++ b/src/store/chat/slices/message/supervisor.test.ts@@ -60,18 +60,21 @@ describe('GroupChatSupervisor', () => {it('should request structured completion and return filtered decisions', async () => {const logSpy = vi.spyOn(console, 'info').mockImplementation(() => {});- vi.mocked(aiChatService.generateJSON).mockResolvedValue([- { tool_name: 'create_todo', parameter: { content: 'Review action items' } },- { tool_name: 'create_todo', parameter: { content: 'Prepare summary' } },- {- tool_name: 'trigger_agent',- parameter: { id: 'agent-1', instruction: 'Say hello', target: 'user' },- },- {- tool_name: 'trigger_agent',- parameter: { id: 'unknown-agent', instruction: 'Ignore me' },- },- ]);+ vi.mocked(aiChatService.generateJSON).mockResolvedValue({+ data: [+ { tool_name: 'create_todo', parameter: { content: 'Review action items' } },+ { tool_name: 'create_todo', parameter: { content: 'Prepare summary' } },+ {+ tool_name: 'trigger_agent',+ parameter: { id: 'agent-1', instruction: 'Say hello', target: 'user' },+ },+ {+ tool_name: 'trigger_agent',+ parameter: { id: 'unknown-agent', instruction: 'Ignore me' },+ },+ ],+ tracingId: '00000000-0000-0000-0000-000000000001',+ } as any);const result = await supervisor.makeDecision({ ...baseContext });@@ -134,7 +137,10 @@ describe('GroupChatSupervisor', () => {'```',].join('\n');- vi.mocked(aiChatService.generateJSON).mockResolvedValue(payload);+ vi.mocked(aiChatService.generateJSON).mockResolvedValue({+ data: payload,+ tracingId: '00000000-0000-0000-0000-000000000002',+ } as any);const result = await supervisor.makeDecision({ ...baseContext });diff --git a/src/store/chat/slices/message/supervisor.ts b/src/store/chat/slices/message/supervisor.tsindex 837cb787581..6c2be51045b 100644--- a/src/store/chat/slices/message/supervisor.ts+++ b/src/store/chat/slices/message/supervisor.ts@@ -102,7 +102,10 @@ export class GroupChatSupervisor {});try {- const response = await aiChatService.generateJSON(+ // `aiChatService.generateJSON` returns `{ data, tracingId }` β supervisor+ // only consumes the generated payload, so unwrap eagerly. The tracingId+ // is intentionally discarded (no feedback path here yet).+ const envelope = await aiChatService.generateJSON({...(contexts as any),model: context.model,@@ -110,6 +113,7 @@ export class GroupChatSupervisor {},context.abortController || new AbortController(),);+ const response = envelope?.data;console.info('SUPERVISOR RESPONSE', JSON.stringify(response, null, 2));@@ -341,7 +345,7 @@ export class GroupChatSupervisor {private extractTodoData(parameter: unknown): { assignee?: string; content: string | null } {if (typeof parameter === 'string') {const trimmed = parameter.trim();- return { content: trimmed ? trimmed : null };+ return { content: trimmed || null };}if (!parameter || typeof parameter !== 'object') return { content: null };