Skip to content

🤯 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.

✨ feat(llm-tracing): collect implicit feedback for follow-up chips and task briefs (#15517)

Arvin Xu9e6495235f37
diff --git a/apps/server/src/services/brief/index.test.ts b/apps/server/src/services/brief/index.test.ts
index 8966d8245a2..02707fa8d52 100644
--- a/apps/server/src/services/brief/index.test.ts
+++ b/apps/server/src/services/brief/index.test.ts
@@ -29,6 +29,12 @@ vi.mock('@/server/services/taskRunner', () => ({
}),
}));
+// Stub tracing writes to assert the action→signal mapping without a DB.
+const { recordFeedback } = vi.hoisted(() => ({ recordFeedback: vi.fn() }));
+vi.mock('@/server/services/llmGenerationTracing', () => ({
+ getLLMGenerationTracingService: () => ({ recordFeedback }),
+}));
+
describe('BriefService', () => {
const db = {} as LobeChatDatabase;
const userId = 'user-1';
@@ -558,4 +564,111 @@ describe('BriefService', () => {
expect(mockTaskModel.updateStatus).not.toHaveBeenCalled();
});
});
+
+ describe('resolve → implicit feedback', () => {
+ const briefWithTracing = (extra: Record<string, unknown>) => ({
+ id: 'b1',
+ metadata: { tracingId: 'trace-1' },
+ taskId: 'task-1',
+ type: 'decision',
+ ...extra,
+ });
+
+ it('reports a positive signal when a brief is approved', async () => {
+ const service = new BriefService(db, userId);
+ mockBriefModel.resolve.mockResolvedValue(briefWithTracing({ type: 'insight' }));
+
+ await service.resolve('b1', { action: 'approve' });
+
+ expect(recordFeedback).toHaveBeenCalledWith(
+ 'user-1',
+ 'trace-1',
+ {
+ data: { briefType: 'insight', hasComment: false },
+ signal: 'positive',
+ source: 'brief_approved',
+ },
+ undefined,
+ );
+ });
+
+ it('reports a negative signal carrying the comment flag for feedback actions', async () => {
+ const service = new BriefService(db, userId);
+ mockBriefModel.resolve.mockResolvedValue(briefWithTracing({}));
+
+ await service.resolve('b1', { action: 'feedback', comment: 'tighten it' });
+
+ expect(recordFeedback).toHaveBeenCalledWith(
+ 'user-1',
+ 'trace-1',
+ {
+ data: { briefType: 'decision', hasComment: true },
+ signal: 'negative',
+ source: 'brief_feedback',
+ },
+ undefined,
+ );
+ });
+
+ it('reports a negative signal for ignore', async () => {
+ const service = new BriefService(db, userId);
+ mockBriefModel.resolve.mockResolvedValue(briefWithTracing({}));
+
+ await service.resolve('b1', { action: 'ignore' });
+
+ expect(recordFeedback).toHaveBeenCalledWith(
+ 'user-1',
+ 'trace-1',
+ expect.objectContaining({ signal: 'negative', source: 'brief_ignored' }),
+ undefined,
+ );
+ });
+
+ it('falls back to a neutral signal for ambiguous actions', async () => {
+ const service = new BriefService(db, userId);
+ mockBriefModel.resolve.mockResolvedValue(briefWithTracing({}));
+
+ await service.resolve('b1', { action: 'acknowledge' });
+
+ expect(recordFeedback).toHaveBeenCalledWith(
+ 'user-1',
+ 'trace-1',
+ expect.objectContaining({ signal: 'neutral', source: 'brief_acknowledge' }),
+ undefined,
+ );
+ });
+
+ it('records feedback in the brief workspace scope', async () => {
+ const service = new BriefService(db, userId, 'workspace-1');
+ mockBriefModel.resolve.mockResolvedValue(briefWithTracing({}));
+
+ await service.resolve('b1', { action: 'approve' });
+
+ expect(recordFeedback).toHaveBeenCalledWith(
+ 'user-1',
+ 'trace-1',
+ expect.objectContaining({ signal: 'positive', source: 'brief_approved' }),
+ 'workspace-1',
+ );
+ });
+
+ it('does not report feedback for briefs without a tracingId', async () => {
+ const service = new BriefService(db, userId);
+ mockBriefModel.resolve.mockResolvedValue({ id: 'b9', taskId: null, type: 'insight' });
+
+ await service.resolve('b9', { action: 'approve' });
+
+ expect(recordFeedback).not.toHaveBeenCalled();
+ });
+
+ it('never lets a tracing failure break brief resolution', async () => {
+ const service = new BriefService(db, userId);
+ mockBriefModel.resolve.mockResolvedValue(briefWithTracing({}));
+ recordFeedback.mockRejectedValueOnce(new Error('db down'));
+
+ const brief = await service.resolve('b1', { action: 'ignore' });
+
+ expect(brief).not.toBeNull();
+ });
+ });
});
diff --git a/apps/server/src/services/brief/index.ts b/apps/server/src/services/brief/index.ts
index 1c1766891cf..cf944e90885 100644
--- a/apps/server/src/services/brief/index.ts
+++ b/apps/server/src/services/brief/index.ts
@@ -5,6 +5,7 @@ import { BriefModel } from '@/database/models/brief';
import { TaskModel } from '@/database/models/task';
import type { BriefItem } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
+import { getLLMGenerationTracingService } from '@/server/services/llmGenerationTracing';
import { TaskRunnerService } from '@/server/services/taskRunner';
export interface AgentAvatarInfo {
@@ -251,6 +252,66 @@ export class BriefService {
}
}
+ // Implicit feedback for the LLM that synthesized this brief. Only briefs
+ // carrying a `tracingId` (task-synthesized ones) participate — others (e.g.
+ // signal briefs) simply have nothing to score.
+ await this.recordBriefFeedback(brief, options);
+
return brief;
}
+
+ /**
+ * Translate the user's resolve action into a feedback signal against the
+ * brief's source generation. This is a proxy for task-result satisfaction,
+ * not a direct rating of the summary prompt. The write is awaited, but
+ * failures are swallowed so they cannot break brief resolution.
+ */
+ private async recordBriefFeedback(
+ brief: BriefItem,
+ options?: BriefResolveOptions,
+ ): Promise<void> {
+ const tracingId = brief.metadata?.tracingId;
+ if (!tracingId) return;
+
+ const action = options?.action;
+ const { signal, source } = ((): {
+ signal: 'positive' | 'negative' | 'neutral';
+ source: string;
+ } => {
+ switch (action) {
+ case 'approve': {
+ return { signal: 'positive', source: 'brief_approved' };
+ }
+ case 'feedback': {
+ return { signal: 'negative', source: 'brief_feedback' };
+ }
+ case 'ignore': {
+ return { signal: 'negative', source: 'brief_ignored' };
+ }
+ // acknowledge / retry / dismiss / unknown — neither a clear accept nor
+ // reject of the brief's content.
+ default: {
+ return { signal: 'neutral', source: `brief_${action ?? 'resolved'}` };
+ }
+ }
+ })();
+
+ try {
+ await getLLMGenerationTracingService().recordFeedback(
+ this.userId,
+ tracingId,
+ {
+ data: {
+ briefType: brief.type,
+ hasComment: !!options?.comment,
+ },
+ signal,
+ source,
+ },
+ this.workspaceId,
+ );
+ } catch (error) {
+ console.warn('[brief:resolve] recordFeedback failed', error);
+ }
+ }
}
diff --git a/apps/server/src/services/followUpAction/index.test.ts b/apps/server/src/services/followUpAction/index.test.ts
index bf8872b0dc6..aae2238bffb 100644
--- a/apps/server/src/services/followUpAction/index.test.ts
+++ b/apps/server/src/services/followUpAction/index.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { notShareVisitorMessage } from '@/database/utils/shareVisitor';
import * as ModelRuntimeModule from '@/server/modules/ModelRuntime';
+import * as TracingServiceModule from '@/server/services/llmGenerationTracing';
import { FollowUpActionService } from './index';
@@ -287,6 +288,35 @@ describe('FollowUpActionService.extract', () => {
);
});
+ const mockTracingEnabled = (enabled: boolean) =>
+ vi
+ .spyOn(TracingServiceModule, 'getLLMGenerationTracingService')
+ .mockReturnValue({ isEnabled: () => enabled } as any);
+
+ it('returns a tracingId when the tracing store is enabled', async () => {
+ mockTracingEnabled(true);
+ queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'q?' });
+ runtimeMock.generateObject.mockResolvedValue({ chips: [{ label: 'ok', message: 'ok' }] });
+
+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });
+
+ expect(typeof result.tracingId).toBe('string');
+ // The id handed to the client must be the same one passed to the tracing hook.
+ expect(runtimeMock.generateObject.mock.calls[0][1].tracing.tracingId).toBe(result.tracingId);
+ });
+
+ it('omits the tracingId when the tracing store is disabled (no row would exist)', async () => {
+ mockTracingEnabled(false);
+ queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'q?' });
+ runtimeMock.generateObject.mockResolvedValue({ chips: [{ label: 'ok', message: 'ok' }] });
+
+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });
+
+ expect(result.chips).toHaveLength(1);
+ expect(result.tracingId).toBeUndefined();
+ expect(runtimeMock.generateObject.mock.calls[0][1].tracing.tracingId).toBeUndefined();
+ });
+
it('appends onboarding addendum to system prompt when hint is onboarding', async () => {
queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'q?' });
runtimeMock.generateObject.mockResolvedValue({ chips: [] });
diff --git a/apps/server/src/services/followUpAction/index.ts b/apps/server/src/services/followUpAction/index.ts
index 10a1109e08f..ed04c7150fd 100644
--- a/apps/server/src/services/followUpAction/index.ts
+++ b/apps/server/src/services/followUpAction/index.ts
@@ -1,3 +1,5 @@
+import { randomUUID } from 'node:crypto';
+
import { TRACING_SCENARIOS } from '@lobechat/const';
import type { TracingOptions } from '@lobechat/llm-generation-tracing';
import {
@@ -12,6 +14,7 @@ import debug from 'debug';
import type { LobeChatDatabase } from '@/database/type';
import { notShareVisitorMessage } from '@/database/utils/shareVisitor';
import { AiGenerationService } from '@/server/services/aiGeneration';
+import { getLLMGenerationTracingService } from '@/server/services/llmGenerationTracing';
import { RawResponseSchema } from './schema';
@@ -70,6 +73,15 @@ export class FollowUpActionService {
const { model, provider } = modelConfig;
const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
+ // Pre-allocate the tracing row id so it can be returned to the client
+ // synchronously — the client holds it for the chip's lifetime to report a
+ // click (positive) / dismissal (negative) back via `recordFeedback`.
+ //
+ // Gate on the tracing store actually being configured: when it isn't (e.g.
+ // prod without ENABLE_LLM_GENERATION_TRACING_S3), the tracing hook is a
+ // no-op and never inserts a row, so handing the client an id would make
+ // every feedback call resolve to NOT_FOUND.
+ const tracingId = getLLMGenerationTracingService().isEnabled() ? randomUUID() : undefined;
let raw: unknown;
try {
raw = await ai.generateObject(
@@ -86,6 +98,7 @@ export class FollowUpActionService {
scenario: TRACING_SCENARIOS.FollowUp,
schemaName: FOLLOW_UP_JSON_SCHEMA.name,
topicId,
+ tracingId,
} satisfies TracingOptions,
},
);
@@ -110,6 +123,10 @@ export class FollowUpActionService {
)
.slice(0, 4);
- return { chips, messageId: row.id };
+ // Only surface the tracingId when chips actually rendered (nothing to act
+ // on otherwise) AND tracing is enabled (a row exists to attach feedback to).
+ return chips.length > 0 && tracingId
+ ? { chips, messageId: row.id, tracingId }
+ : { chips, messageId: row.id };
}
}
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 3e04fef0eca..165aca9f453 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -44,6 +44,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { translation } from '@/libs/i18n/serverTranslation';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';
+import { getLLMGenerationTracingService } from '@/server/services/llmGenerationTracing';
import { SystemAgentService } from '@/server/services/systemAgent';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
import { createTaskSchedulerModule } from '@/server/services/taskScheduler';
@@ -983,6 +984,16 @@ export class TaskLifecycleService {
provider,
this.workspaceId,
);
+ // Pre-allocate the tracing row id so it can be stamped onto the brief —
+ // the user's later resolve action (approve / feedback / ignore) is then
+ // reported back as implicit feedback against this exact generation.
+ //
+ // Gate on tracing being enabled: with no store configured the hook never
+ // writes a row, so stamping an id would make every resolve's feedback
+ // call resolve to NOT_FOUND.
+ const briefTracingId = getLLMGenerationTracingService().isEnabled()
+ ? randomUUID()
+ : undefined;
const result = await modelRuntime.generateObject(
{
messages: payload.messages as any[],
@@ -995,6 +1006,8 @@ export class TaskLifecycleService {
promptVersion: GENERATE_BRIEF_PROMPT_VERSION,
scenario: TRACING_SCENARIOS.TaskBrief,
schemaName: GENERATE_BRIEF_SCHEMA_NAME,
+ topicId,
+ tracingId: briefTracingId,
} satisfies TracingOptions,
},
);
@@ -1017,6 +1030,7 @@ export class TaskLifecycleService {
actions,
agentId: currentTask.assigneeAgentId || undefined,
artifacts,
+ metadata: briefTracingId ? { tracingId: briefTracingId } : undefined,
priority,
summary: generated.summary,
taskId,
diff --git a/packages/types/src/brief/index.ts b/packages/types/src/brief/index.ts
index a44292d2730..3c0644c0f1d 100644
--- a/packages/types/src/brief/index.ts
+++ b/packages/types/src/brief/index.ts
@@ -71,4 +71,10 @@ export interface BriefMetadata {
[key: string]: unknown;
/** Agent Signal extension metadata. */
agentSignal?: BriefAgentSignalMetadata;
+ /**
+ * `llm_generation_tracing` row id of the generation that produced this brief's
+ * title/summary. Set for LLM-synthesized briefs so the user's resolve action
+ * (approve / feedback / ignore) can be reported back as implicit feedback.
+ */
+ tracingId?: string;
}
diff --git a/packages/types/src/followUpAction.ts b/packages/types/src/followUpAction.ts
index 990e3bf8613..678a926ef4e 100644
--- a/packages/types/src/followUpAction.ts
+++ b/packages/types/src/followUpAction.ts
@@ -27,6 +27,13 @@ export interface FollowUpExtractResult {
chips: FollowUpChip[];
/** Resolved server-side id of the assistant message the chips were extracted from. Empty string if no eligible message was found. */
messageId: string;
+ /**
+ * `llm_generation_tracing` row id for this chip generation. Present only when
+ * chips were actually generated. The client holds it for the chip's lifetime
+ * so a click (positive) or dismissal (negative) can be reported back via
+ * `llmGenerationTracing.recordFeedback`.
+ */
+ tracingId?: string;
}
export const FollowUpHintSchema = z.union([
diff --git a/src/features/Conversation/FollowUp/FollowUpChips.tsx b/src/features/Conversation/FollowUp/FollowUpChips.tsx
index f1e588a57df..7bc60b4eb2f 100644
--- a/src/features/Conversation/FollowUp/FollowUpChips.tsx
+++ b/src/features/Conversation/FollowUp/FollowUpChips.tsx
@@ -25,15 +25,17 @@ const FollowUpChips = memo<FollowUpChipsProps>(({ conversationKey, messageId })
);
const chips = useFollowUpActionStore(selector);
const fillInputMessage = useConversationStore((s) => s.fillInputMessage);
+ const recordChipClick = useFollowUpActionStore((s) => s.recordChipClick);
const isGenerating = useConversationStore(
messageStateSelectors.isAssistantGroupItemGenerating(messageId),
);
const handleClick = useCallback(
- (chip: FollowUpChip) => {
+ (chip: FollowUpChip, chipIndex: number) => {
+ recordChipClick(conversationKey, chipIndex);
fillInputMessage(chip.message);
},
- [fillInputMessage],
+ [recordChipClick, conversationKey, fillInputMessage],
);
if (chips.length === 0 || isGenerating) return null;
@@ -47,7 +49,7 @@ const FollowUpChips = memo<FollowUpChipsProps>(({ conversationKey, messageId })
key={`${messageId}-${i}`}
style={{ animationDelay: `${i * 60}ms` }}
type="button"
- onClick={() => handleClick(chip)}
+ onClick={() => handleClick(chip, i)}
>
<Reply className={`${styles.chipIcon} followup-icon`} size={14} />
<span>{chip.label}</span>
diff --git a/src/store/followUpAction/action.ts b/src/store/followUpAction/action.ts
index e131300f61b..823ba9d7148 100644
--- a/src/store/followUpAction/action.ts
+++ b/src/store/followUpAction/action.ts
@@ -1,5 +1,6 @@
import type { FollowUpChip, FollowUpHint, FollowUpModelConfig } from '@lobechat/types';
+import { aiChatService } from '@/services/aiChat';
import { followUpActionService } from '@/services/followUpAction';
import { type StoreSetter } from '@/store/types';
@@ -72,6 +73,10 @@ export class FollowUpActionImpl {
const existing = this.#get().slots[conversationKey];
if (existing?.status === 'loading') return;
+ // A ready-but-unacted chip set being replaced by a new turn is a dismissal.
+ // (Normally `onBeforeSendMessage` clears first, so this is a belt-and-braces
+ // guard for paths that fetch without an explicit clear.)
+ this.#maybeRecordDismissal(existing);
existing?.abortController?.abort();
const controller = new AbortController();
@@ -116,6 +121,7 @@ export class FollowUpActionImpl {
chips: result.chips,
messageId: result.messageId,
status: 'ready',
+ tracingId: result.tracingId,
},
'fetchFor:ready',
);
@@ -124,6 +130,7 @@ export class FollowUpActionImpl {
abort = (conversationKey: string): void => {
const slot = this.#get().slots[conversationKey];
if (!slot) return;
+ this.#maybeRecordDismissal(slot);
slot.abortController?.abort();
writeSlot(this.#set, conversationKey, { ...IDLE_SLOT }, 'abort');
};
@@ -131,6 +138,7 @@ export class FollowUpActionImpl {
clear = (conversationKey: string): void => {
const slot = this.#get().slots[conversationKey];
if (!slot) return;
+ this.#maybeRecordDismissal(slot);
slot.abortController?.abort();
removeSlot(this.#set, conversationKey, 'clear');
};
@@ -139,6 +147,47 @@ export class FollowUpActionImpl {
void chip;
this.clear(conversationKey);
};
+
+ /**
+ * Report that the user clicked a chip — a positive feedback signal for the
+ * generated suggestion set. Marks the slot so the subsequent clear-on-send
+ * doesn't additionally fire a dismissal for the same chips.
+ */
+ recordChipClick = (conversationKey: string, chipIndex: number): void => {
+ const slot = this.#get().slots[conversationKey];
+ if (!slot || slot.status !== 'ready' || !slot.tracingId || slot.feedbackDone) return;
+
+ void aiChatService
+ .recordTracingFeedback({
+ data: { chipIndex, totalChips: slot.chips.length },
+ signal: 'positive',
+ source: 'followup_clicked',
+ tracingId: slot.tracingId,
+ })
+ .catch((err) => console.warn('[FollowUp] recordFeedback (clicked) failed', err));
+
+ writeSlot(this.#set, conversationKey, { ...slot, feedbackDone: true }, 'recordChipClick');
+ };
+
+ /**
+ * Fire a `negative` dismissal when an unclicked chip set is cleared or replaced.
+ * Leaving the conversation does not produce a dismissal, so these signals
+ * alone do not measure click-through rate across all impressions. No-op unless
+ * the slot was actually shown (`ready`), carries a tracingId, and hasn't
+ * already produced a click signal.
+ */
+ #maybeRecordDismissal = (slot: FollowUpActionSlot | undefined): void => {
+ if (!slot || slot.status !== 'ready' || !slot.tracingId || slot.feedbackDone) return;
+
+ void aiChatService
+ .recordTracingFeedback({
+ data: { totalChips: slot.chips.length },
+ signal: 'negative',
+ source: 'followup_dismissed',
+ tracingId: slot.tracingId,
+ })
+ .catch((err) => console.warn('[FollowUp] recordFeedback (dismissed) failed', err));
+ };
}
export type FollowUpActionAction = Pick<FollowUpActionImpl, keyof FollowUpActionImpl>;
diff --git a/src/store/followUpAction/index.test.ts b/src/store/followUpAction/index.test.ts
index 7621f3553c4..188f5539244 100644
--- a/src/store/followUpAction/index.test.ts
+++ b/src/store/followUpAction/index.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { aiChatService } from '@/services/aiChat';
import { followUpActionService } from '@/services/followUpAction';
import { followUpActionSelectors } from './selectors';
@@ -216,6 +217,88 @@ describe('useFollowUpActionStore', () => {
});
});
+describe('follow-up implicit feedback', () => {
+ const TRACING_ID = 'tracing-1';
+ const readySlot = (extra?: Record<string, unknown>) => ({
+ chips: [{ label: 'x', message: 'hello' }],
+ messageId: MSG,
+ status: 'ready' as const,
+ tracingId: TRACING_ID,
+ ...extra,
+ });
+
+ beforeEach(() => {
+ useFollowUpActionStore.getState().reset?.();
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('fetchFor stores the tracingId returned by the service', async () => {
+ vi.spyOn(followUpActionService, 'extract').mockResolvedValue({
+ chips: [{ label: 'a', message: 'a' }],
+ messageId: MSG,
+ tracingId: TRACING_ID,
+ });
+ await useFollowUpActionStore.getState().fetchFor(KEY_A, FETCH_PARAMS_A);
+ expect(slotA().tracingId).toBe(TRACING_ID);
+ });
+
+ it('recordChipClick reports a positive signal and marks the slot done', () => {
+ const spy = vi.spyOn(aiChatService, 'recordTracingFeedback').mockResolvedValue({ ok: true });
+ useFollowUpActionStore.setState({ slots: { [KEY_A]: readySlot() } });
+
+ useFollowUpActionStore.getState().recordChipClick(KEY_A, 2);
+
+ expect(spy).toHaveBeenCalledWith({
+ data: { chipIndex: 2, totalChips: 1 },
+ signal: 'positive',
+ source: 'followup_clicked',
+ tracingId: TRACING_ID,
+ });
+ expect(slotA().feedbackDone).toBe(true);
+ });
+
+ it('clear reports a dismissal for a shown-but-unacted chip set', () => {
+ const spy = vi.spyOn(aiChatService, 'recordTracingFeedback').mockResolvedValue({ ok: true });
+ useFollowUpActionStore.setState({ slots: { [KEY_A]: readySlot() } });
+
+ useFollowUpActionStore.getState().clear(KEY_A);
+
+ expect(spy).toHaveBeenCalledWith({
+ data: { totalChips: 1 },
+ signal: 'negative',
+ source: 'followup_dismissed',
+ tracingId: TRACING_ID,
+ });
+ });
+
+ it('a click followed by clear does not double-report (no dismissal after click)', () => {
+ const spy = vi.spyOn(aiChatService, 'recordTracingFeedback').mockResolvedValue({ ok: true });
+ useFollowUpActionStore.setState({ slots: { [KEY_A]: readySlot() } });
+
+ useFollowUpActionStore.getState().recordChipClick(KEY_A, 0);
+ useFollowUpActionStore.getState().clear(KEY_A);
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(expect.objectContaining({ signal: 'positive' }));
+ });
+
+ it('does not report feedback when the slot carries no tracingId', () => {
+ const spy = vi.spyOn(aiChatService, 'recordTracingFeedback').mockResolvedValue({ ok: true });
+ useFollowUpActionStore.setState({
+ slots: {
+ [KEY_A]: { chips: [{ label: 'x', message: 'h' }], messageId: MSG, status: 'ready' },
+ },
+ });
+
+ useFollowUpActionStore.getState().recordChipClick(KEY_A, 0);
+ useFollowUpActionStore.getState().clear(KEY_A);
+
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
describe('followUpActionSelectors.chipsFor', () => {
beforeEach(() => {
useFollowUpActionStore.getState().reset?.();
diff --git a/src/store/followUpAction/initialState.ts b/src/store/followUpAction/initialState.ts
index 4e7952b2097..830515c9373 100644
--- a/src/store/followUpAction/initialState.ts
+++ b/src/store/followUpAction/initialState.ts
@@ -6,8 +6,12 @@ export type FollowUpActionStatus = 'idle' | 'loading' | 'ready';
export interface FollowUpActionSlot {
abortController?: AbortController;
chips: FollowUpChip[];
+ /** Guards against double-reporting feedback (a click followed by the clear-on-send). */
+ feedbackDone?: boolean;
messageId?: string;
status: FollowUpActionStatus;
+ /** `llm_generation_tracing` row id this chip set was generated under, if any. */
+ tracingId?: string;
}
export interface FollowUpActionState {