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(bot): wake records tab — owners review and mark each wake decision (#21934)

Arvin Xubfbd37604cc1
diff --git a/apps/server/src/routers/lambda/_helpers/agentBotProviderProcedure.ts b/apps/server/src/routers/lambda/_helpers/agentBotProviderProcedure.ts
new file mode 100644
index 00000000000..4ba57005d76
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/agentBotProviderProcedure.ts
@@ -0,0 +1,24 @@
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+
+/** Bot-provider reads: `ctx.agentBotProviderModel` scoped to the caller and active workspace. */
+export const agentBotProviderProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+
+ return opts.next({
+ ctx: {
+ agentBotProviderModel: new AgentBotProviderModel(ctx.serverDB, ctx.userId, gateKeeper, wsId),
+ },
+ });
+});
+
+// Write variant gates viewers out of bot-provider mutations
+// (create/update/delete + start/test connections). Reads keep the bare proc.
+export const agentBotProviderProcedureWrite = agentBotProviderProcedure.use(
+ withScopedPermission('agent:update'),
+);
diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.ts
index cbd4a112c8e..bd4004887ec 100644
--- a/apps/server/src/routers/lambda/agentBotProvider.ts
+++ b/apps/server/src/routers/lambda/agentBotProvider.ts
@@ -8,14 +8,10 @@ import {
assertBotFeatureAccess,
withBotPlatformAccessMeta,
} from '@/business/server/bot/featureAccess';
-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { LobeChatDatabase } from '@/database/type';
import { authedProcedure, router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { flattenBotWakeSettings } from '@/server/services/agentSignal/scenarios/botWake/config';
import {
assertBotAccessSettings,
@@ -44,26 +40,12 @@ import {
import { GatewayService } from '@/server/services/gateway';
import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';
+import {
+ agentBotProviderProcedure,
+ agentBotProviderProcedureWrite,
+} from './_helpers/agentBotProviderProcedure';
import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
-const agentBotProviderProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
-
- return opts.next({
- ctx: {
- agentBotProviderModel: new AgentBotProviderModel(ctx.serverDB, ctx.userId, gateKeeper, wsId),
- },
- });
-});
-
-// Write variant gates viewers out of bot-provider mutations
-// (create/update/delete + start/test connections). Reads keep the bare proc.
-const agentBotProviderProcedureWrite = agentBotProviderProcedure.use(
- withScopedPermission('agent:update'),
-);
-
const BOT_NOT_FOUND_MESSAGE = 'Bot integration not found';
/**
diff --git a/apps/server/src/routers/lambda/agentBotWake.test.ts b/apps/server/src/routers/lambda/agentBotWake.test.ts
new file mode 100644
index 00000000000..1165d9a25f6
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentBotWake.test.ts
@@ -0,0 +1,320 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// serverDatabase middleware calls getServerDB(); the models are mocked, so the
+// handle it returns is never dereferenced.
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn(async () => ({})) },
+}));
+
+const mockFindBot = vi.fn();
+const botModelCtor = vi.fn();
+vi.mock('@/database/models/agentBotProvider', () => ({
+ AgentBotProviderModel: vi.fn(function (...args: unknown[]) {
+ botModelCtor(...args);
+ return { findById: mockFindBot };
+ }),
+}));
+
+const mockListByScope = vi.fn();
+const mockSummaryByScope = vi.fn();
+const mockFindDecision = vi.fn();
+const mockAddLabel = vi.fn();
+const mockListLabels = vi.fn();
+const decisionModelCtor = vi.fn();
+vi.mock('@/database/models/signalDecision', () => ({
+ SCOPE_READ_DEFAULT_DAYS: 30,
+ SCOPE_READ_MAX_LIMIT: 50,
+ SignalDecisionModel: vi.fn(function (...args: unknown[]) {
+ decisionModelCtor(...args);
+ return {
+ addLabel: mockAddLabel,
+ findById: mockFindDecision,
+ listLabels: mockListLabels,
+ listByScope: mockListByScope,
+ summaryByScope: mockSummaryByScope,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/bot/BotMessageRouter/wakeDecision', () => ({
+ BOT_WAKE_FOLLOWUP_REASONS: ['watch-keyword', 'in-duty'],
+}));
+
+vi.mock('@/server/services/bot/noReplyLabel', () => ({
+ NO_REPLY_LABEL_SOURCE: 'agent:no_reply',
+}));
+
+const { agentBotWakeRouter } = await import('./agentBotWake');
+
+const BOT_ID = 'bot-1';
+const DECISION_ID = '7f1c2a40-5b7e-4d8a-9f61-0c2b3d4e5f60';
+/** A teammate's bot in the caller's workspace: decisions live under its owner and that workspace. */
+const bot = {
+ applicationId: 'app-1',
+ id: BOT_ID,
+ platform: 'discord',
+ userId: 'owner-1',
+ workspaceId: 'ws-1',
+};
+const ctx: any = { serverDB: {}, userId: 'caller-1', workspaceId: 'ws-1' };
+
+const decision = (overrides = {}) => ({
+ id: DECISION_ID,
+ outcome: 'wake',
+ scopeKey: 'discord:app-1',
+ userId: 'owner-1',
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockFindBot.mockResolvedValue(bot);
+ mockFindDecision.mockResolvedValue(decision());
+ mockAddLabel.mockImplementation(async (_id, input) => ({
+ createdAt: new Date('2026-10-30T00:00:00Z'),
+ label: input.label,
+ metadata: input.metadata,
+ }));
+ mockListByScope.mockResolvedValue({ items: [] });
+ mockSummaryByScope.mockResolvedValue({
+ defer: 0,
+ followupWakes: 0,
+ labels: {},
+ skip: 0,
+ total: 0,
+ wake: 0,
+ });
+});
+
+describe('agentBotWakeRouter', () => {
+ describe('bot scope', () => {
+ it('looks the bot up in the caller’s scope and reads under the bot owner’s channel', async () => {
+ const caller = agentBotWakeRouter.createCaller(ctx);
+
+ await caller.listWakeDecisions({ botId: BOT_ID });
+
+ expect(botModelCtor).toHaveBeenCalledWith({}, 'caller-1', {}, 'ws-1');
+ expect(mockFindBot).toHaveBeenCalledWith(BOT_ID);
+ // The record's own scope, not the caller's: the read must match the `workspace_id` the wake
+ // pipeline wrote, so a bot recreated elsewhere cannot read the earlier scope's history.
+ expect(decisionModelCtor).toHaveBeenCalledWith({}, 'owner-1', 'ws-1');
+ expect(mockListByScope).toHaveBeenCalledWith(
+ expect.objectContaining({ scopeKey: 'discord:app-1' }),
+ );
+ });
+
+ it.each([
+ ['listWakeDecisions', (c: any) => c.listWakeDecisions({ botId: BOT_ID })],
+ ['getWakeSummary', (c: any) => c.getWakeSummary({ botId: BOT_ID })],
+ [
+ 'labelWakeDecision',
+ (c: any) =>
+ c.labelWakeDecision({ botId: BOT_ID, decisionId: DECISION_ID, label: 'correct' }),
+ ],
+ ])('%s refuses a bot outside the caller’s scope', async (_name, call) => {
+ mockFindBot.mockResolvedValue(undefined);
+
+ await expect(call(agentBotWakeRouter.createCaller(ctx))).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(decisionModelCtor).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('listWakeDecisions', () => {
+ it('maps filters onto the scope read', async () => {
+ await agentBotWakeRouter.createCaller(ctx).listWakeDecisions({
+ botId: BOT_ID,
+ followupOnly: true,
+ outcome: 'skip',
+ unmarkedOnly: true,
+ });
+
+ expect(mockListByScope).toHaveBeenCalledWith(
+ expect.objectContaining({
+ finalReasons: ['watch-keyword', 'in-duty'],
+ labeled: { by: 'user', has: false },
+ outcome: 'skip',
+ }),
+ );
+ });
+
+ it('splits current labels into the agent’s silence and the owner’s mark', async () => {
+ mockListByScope.mockResolvedValue({
+ items: [
+ {
+ finalReason: 'watch-keyword',
+ id: DECISION_ID,
+ labels: [
+ { label: 'false_wake', metadata: { reason: 'off_topic' }, source: 'agent:no_reply' },
+ { label: 'correct', metadata: { rationale: 'fine' }, source: 'user' },
+ { label: 'correct', metadata: {}, source: 'llm_judge' },
+ ],
+ outcome: 'wake',
+ verdicts: [
+ {
+ confidence: 0.83,
+ latencyMs: 400,
+ mode: 'enforce',
+ policyId: 'bot-wake:classifier',
+ reason: 'score 0.83',
+ verdict: 'allow',
+ version: 1,
+ },
+ ],
+ },
+ ],
+ });
+
+ const { items } = await agentBotWakeRouter
+ .createCaller(ctx)
+ .listWakeDecisions({ botId: BOT_ID });
+
+ expect(items[0]).toMatchObject({
+ agentLabel: { label: 'false_wake', reason: 'off_topic' },
+ followup: true,
+ judge: { kind: 'addressed', score: 0.83, verdict: 'allow' },
+ userLabel: { label: 'correct', note: 'fine' },
+ });
+ expect(items[0]).not.toHaveProperty('labels');
+ expect(items[0]).not.toHaveProperty('verdicts');
+ });
+ });
+
+ describe('getWakeSummary', () => {
+ it('folds label counts into silenced and marked totals', async () => {
+ mockSummaryByScope.mockResolvedValue({
+ defer: 1,
+ followupWakes: 2,
+ labels: {
+ 'agent:no_reply': { correct: 1, dup_wake: 1, false_wake: 2 },
+ 'user': { correct: 3, missed_wake: 1 },
+ },
+ skip: 4,
+ total: 10,
+ wake: 5,
+ });
+
+ const summary = await agentBotWakeRouter.createCaller(ctx).getWakeSummary({ botId: BOT_ID });
+
+ expect(summary).toMatchObject({
+ followupWakes: 2,
+ marked: 4,
+ markedByLabel: { correct: 3, missed_wake: 1 },
+ silenced: 3,
+ wake: 5,
+ });
+ });
+ });
+
+ describe('labelWakeDecision', () => {
+ it('appends the owner’s mark with who set it and where', async () => {
+ await agentBotWakeRouter.createCaller(ctx).labelWakeDecision({
+ botId: BOT_ID,
+ decisionId: DECISION_ID,
+ label: 'false_wake',
+ note: ' not for the bot ',
+ });
+
+ expect(mockAddLabel).toHaveBeenCalledWith(DECISION_ID, {
+ actor: 'caller-1',
+ label: 'false_wake',
+ metadata: { rationale: 'not for the bot', surface: 'bot_settings' },
+ source: 'user',
+ });
+ });
+
+ it('refuses a decision from another channel of the same owner', async () => {
+ mockFindDecision.mockResolvedValue(decision({ scopeKey: 'discord:app-2' }));
+
+ await expect(
+ agentBotWakeRouter
+ .createCaller(ctx)
+ .labelWakeDecision({ botId: BOT_ID, decisionId: DECISION_ID, label: 'correct' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockAddLabel).not.toHaveBeenCalled();
+ });
+
+ it('refuses a decision the bot owner does not own', async () => {
+ // The model is scoped to the owner, so another user's decision is not found.
+ mockFindDecision.mockResolvedValue(undefined);
+
+ await expect(
+ agentBotWakeRouter
+ .createCaller(ctx)
+ .labelWakeDecision({ botId: BOT_ID, decisionId: DECISION_ID, label: 'correct' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mockAddLabel).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['wake', 'missed_wake'],
+ ['skip', 'false_wake'],
+ ])('refuses to mark a %s as %s', async (outcome, label) => {
+ mockFindDecision.mockResolvedValue(decision({ outcome }));
+
+ await expect(
+ agentBotWakeRouter
+ .createCaller(ctx)
+ .labelWakeDecision({ botId: BOT_ID, decisionId: DECISION_ID, label: label as any }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mockAddLabel).not.toHaveBeenCalled();
+ });
+
+ it('accepts every mark on a deferred message', async () => {
+ mockFindDecision.mockResolvedValue(decision({ outcome: 'defer' }));
+ const caller = agentBotWakeRouter.createCaller(ctx);
+
+ for (const label of ['correct', 'false_wake', 'missed_wake'] as const) {
+ await caller.labelWakeDecision({ botId: BOT_ID, decisionId: DECISION_ID, label });
+ }
+
+ expect(mockAddLabel).toHaveBeenCalledTimes(3);
+ });
+ it('takes the mark back by appending `cleared`', async () => {
+ mockListLabels.mockResolvedValue([
+ { label: 'false_wake', source: 'user' },
+ { label: 'correct', source: 'llm_judge' },
+ ]);
+
+ const result = await agentBotWakeRouter
+ .createCaller(ctx)
+ .labelWakeDecision({ botId: BOT_ID, decisionId: DECISION_ID, label: null });
+
+ expect(result).toBeNull();
+ expect(mockAddLabel).toHaveBeenCalledWith(DECISION_ID, {
+ actor: 'caller-1',
+ label: 'cleared',
+ metadata: { surface: 'bot_settings' },
+ source: 'user',
+ });
+ });
+
+ it.each([
+ ['never marked', [{ label: 'correct', source: 'llm_judge' }]],
+ ['already taken back', [{ label: 'cleared', source: 'user' }]],
+ ])('writes nothing to take back a mark when %s', async (_case, labels) => {
+ mockListLabels.mockResolvedValue(labels);
+
+ await expect(
+ agentBotWakeRouter
+ .createCaller(ctx)
+ .labelWakeDecision({ botId: BOT_ID, decisionId: DECISION_ID, label: null }),
+ ).resolves.toBeNull();
+ expect(mockAddLabel).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentBotWake.ts b/apps/server/src/routers/lambda/agentBotWake.ts
new file mode 100644
index 00000000000..dbe5fd13c29
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentBotWake.ts
@@ -0,0 +1,218 @@
+import {
+ BOT_WAKE_USER_LABEL_SOURCE,
+ BOT_WAKE_USER_LABELS,
+ BOT_WAKE_USER_LABELS_BY_OUTCOME,
+ type BotWakeDecisionPage,
+ type BotWakeSummary,
+ type BotWakeUserLabel,
+ type BotWakeUserMark,
+ SIGNAL_DECISION_LABEL_CLEARED,
+ SIGNAL_DECISION_OUTCOMES,
+ type SignalDecisionLabel,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import type { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import {
+ type CurrentDecisionLabel,
+ SCOPE_READ_DEFAULT_DAYS,
+ SCOPE_READ_MAX_LIMIT,
+ SignalDecisionModel,
+} from '@/database/models/signalDecision';
+import type { LobeChatDatabase } from '@/database/type';
+import { router } from '@/libs/trpc/lambda';
+import { BOT_WAKE_FOLLOWUP_REASONS } from '@/server/services/bot/BotMessageRouter/wakeDecision';
+import { NO_REPLY_LABEL_SOURCE } from '@/server/services/bot/noReplyLabel';
+import { pickWakeJudgeScore } from '@/server/services/bot/wake/judgeScore';
+
+import {
+ agentBotProviderProcedure,
+ agentBotProviderProcedureWrite,
+} from './_helpers/agentBotProviderProcedure';
+
+const BOT_NOT_FOUND_MESSAGE = 'Bot integration not found';
+const DECISION_NOT_FOUND_MESSAGE = 'Wake record not found';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** The agent's own silence labels that mean "this wake did not need an answer". */
+const SILENCE_LABELS = new Set<SignalDecisionLabel>(['false_wake', 'dup_wake']);
+
+interface BotScopeCtx {
+ agentBotProviderModel: Pick<AgentBotProviderModel, 'findById'>;
+ serverDB: LobeChatDatabase;
+}
+
+/**
+ * The bot the caller may see, and its decisions' scope. Found through the same scoped lookup as the
+ * settings page, so a bot outside the caller's user / workspace reads as missing. Decisions are
+ * stored under the bot owner's user id, which is not the caller's for a teammate's bot.
+ */
+const resolveBotScope = async (ctx: BotScopeCtx, botId: string) => {
+ const bot = await ctx.agentBotProviderModel.findById(botId);
+ if (!bot) throw new TRPCError({ code: 'NOT_FOUND', message: BOT_NOT_FOUND_MESSAGE });
+
+ return {
+ // The bot's own workspace, not the caller's: a teammate may read a bot its workspace owns, and
+ // the scope read must match the `workspace_id` the wake pipeline recorded the decisions under.
+ decisions: new SignalDecisionModel(ctx.serverDB, bot.userId, bot.workspaceId ?? undefined),
+ scopeKey: `${bot.platform}:${bot.applicationId}`,
+ };
+};
+
+const pickLabel = (labels: CurrentDecisionLabel[], source: string) =>
+ labels.find((label) => label.source === source);
+
+const cursorSchema = z.object({
+ createdAt: z.string().datetime(),
+ id: z.string().uuid(),
+});
+
+export const agentBotWakeRouter = router({
+ /**
+ * One bot's wake decisions, newest first, from the last {@link SCOPE_READ_DEFAULT_DAYS} days:
+ * the message preview, what the router did and why, the model score behind it (`judge`), the
+ * agent's own silence label and the owner's current mark. The raw verdicts stay on the server.
+ */
+ listWakeDecisions: agentBotProviderProcedure
+ .input(
+ z.object({
+ botId: z.string(),
+ cursor: cursorSchema.optional(),
+ followupOnly: z.boolean().optional(),
+ limit: z.number().int().min(1).max(SCOPE_READ_MAX_LIMIT).optional(),
+ outcome: z.enum(SIGNAL_DECISION_OUTCOMES).optional(),
+ unmarkedOnly: z.boolean().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }): Promise<BotWakeDecisionPage> => {
+ const { decisions, scopeKey } = await resolveBotScope(ctx, input.botId);
+ const followups = new Set(BOT_WAKE_FOLLOWUP_REASONS);
+
+ const page = await decisions.listByScope({
+ cursor: input.cursor,
+ finalReasons: input.followupOnly ? BOT_WAKE_FOLLOWUP_REASONS : undefined,
+ labeled: input.unmarkedOnly ? { by: BOT_WAKE_USER_LABEL_SOURCE, has: false } : undefined,
+ limit: input.limit,
+ outcome: input.outcome,
+ scopeKey,
+ });
+
+ return {
+ items: page.items.map(({ labels, verdicts, ...item }) => {
+ const agent = pickLabel(labels, NO_REPLY_LABEL_SOURCE);
+ const user = pickLabel(labels, BOT_WAKE_USER_LABEL_SOURCE);
+
+ return {
+ ...item,
+ agentLabel: agent ? { label: agent.label, reason: agent.metadata.reason } : null,
+ followup: !!item.finalReason && followups.has(item.finalReason),
+ judge: pickWakeJudgeScore(verdicts, item.finalReason) ?? null,
+ userLabel: user
+ ? { createdAt: user.createdAt, label: user.label, note: user.metadata.rationale }
+ : null,
+ };
+ }),
+ nextCursor: page.nextCursor,
+ };
+ }),
+
+ /** Counts for the last {@link SCOPE_READ_DEFAULT_DAYS} days of one bot's wake decisions. */
+ getWakeSummary: agentBotProviderProcedure
+ .input(z.object({ botId: z.string() }))
+ .query(async ({ ctx, input }): Promise<BotWakeSummary> => {
+ const { decisions, scopeKey } = await resolveBotScope(ctx, input.botId);
+
+ const summary = await decisions.summaryByScope({
+ followupReasons: BOT_WAKE_FOLLOWUP_REASONS,
+ labelSources: [BOT_WAKE_USER_LABEL_SOURCE, NO_REPLY_LABEL_SOURCE],
+ scopeKey,
+ since: new Date(Date.now() - SCOPE_READ_DEFAULT_DAYS * DAY_MS),
+ });
+
+ const agentLabels = summary.labels[NO_REPLY_LABEL_SOURCE] ?? {};
+ const userLabels = summary.labels[BOT_WAKE_USER_LABEL_SOURCE] ?? {};
+
+ return {
+ days: SCOPE_READ_DEFAULT_DAYS,
+ defer: summary.defer,
+ followupWakes: summary.followupWakes,
+ marked: Object.values(userLabels).reduce((sum, count) => sum + (count ?? 0), 0),
+ markedByLabel: userLabels,
+ silenced: Object.entries(agentLabels).reduce(
+ (sum, [label, count]) =>
+ SILENCE_LABELS.has(label as SignalDecisionLabel) ? sum + (count ?? 0) : sum,
+ 0,
+ ),
+ skip: summary.skip,
+ total: summary.total,
+ wake: summary.wake,
+ };
+ }),
+
+ /**
+ * The owner marks whether a decision was right, or takes the mark back (`label: null`). Labels are
+ * append-only, so a changed mind is a new row and the latest one is the mark; taking it back
+ * appends `cleared`, which reads as no mark. Returns the mark now in force.
+ */
+ labelWakeDecision: agentBotProviderProcedureWrite
+ .input(
+ z.object({
+ botId: z.string(),
+ decisionId: z.string().uuid(),
+ label: z.enum(BOT_WAKE_USER_LABELS).nullable(),
+ note: z.string().trim().max(500).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }): Promise<BotWakeUserMark> => {
+ const { decisions, scopeKey } = await resolveBotScope(ctx, input.botId);
+
+ // The decision must be this bot's: same owner (the model is scoped to it) and same channel.
+ const decision = await decisions.findById(input.decisionId);
+ if (!decision || decision.scopeKey !== scopeKey) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: DECISION_NOT_FOUND_MESSAGE });
+ }
+
+ if (input.label === null) {
+ const latest = (await decisions.listLabels(decision.id)).find(
+ (row) => row.source === BOT_WAKE_USER_LABEL_SOURCE,
+ );
+ // Nothing to take back: no row, so the history only records real changes of mind.
+ if (!latest || latest.label === SIGNAL_DECISION_LABEL_CLEARED) return null;
+
+ const row = await decisions.addLabel(decision.id, {
+ actor: ctx.userId,
+ label: SIGNAL_DECISION_LABEL_CLEARED,
+ metadata: { surface: 'bot_settings' },
+ source: BOT_WAKE_USER_LABEL_SOURCE,
+ });
+ if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: DECISION_NOT_FOUND_MESSAGE });
+
+ return null;
+ }
+
+ const allowed: readonly BotWakeUserLabel[] =
+ BOT_WAKE_USER_LABELS_BY_OUTCOME[decision.outcome] ?? [];
+ if (!allowed.includes(input.label)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `A ${decision.outcome} decision cannot be marked ${input.label}`,
+ });
+ }
+
+ const row = await decisions.addLabel(decision.id, {
+ actor: ctx.userId,
+ label: input.label,
+ metadata: { surface: 'bot_settings', ...(input.note ? { rationale: input.note } : {}) },
+ source: BOT_WAKE_USER_LABEL_SOURCE,
+ });
+ if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: DECISION_NOT_FOUND_MESSAGE });
+
+ return {
+ createdAt: row.createdAt,
+ label: row.label as BotWakeUserLabel,
+ note: row.metadata.rationale,
+ };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index a1204623bd0..f9ef80cfeed 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -26,6 +26,7 @@ import { acceptanceRouter } from './acceptance';
import { acceptanceCommentRouter } from './acceptanceComment';
import { agentRouter } from './agent';
import { agentBotProviderRouter } from './agentBotProvider';
+import { agentBotWakeRouter } from './agentBotWake';
import { agentDocumentRouter } from './agentDocument';
import { agentEvalRouter } from './agentEval';
import { agentEvalExternalRouter } from './agentEvalExternal';
@@ -126,6 +127,7 @@ export const lambdaRouter = router({
acceptanceComment: acceptanceCommentRouter,
agent: agentRouter,
agentBotProvider: agentBotProviderRouter,
+ agentBotWake: agentBotWakeRouter,
agentNotify: agentNotifyRouter,
botMessage: botMessageRouter,
agentDocument: agentDocumentRouter,
diff --git a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
index 672bcc91299..eaffc778656 100644
--- a/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/wakeDecision.ts
@@ -131,6 +131,18 @@ const KIND_BY_REASON: Record<BotWakeReason, BotWakeKind> = {
export const botWakeKindFor = (reason: BotWakeReason): BotWakeKind => KIND_BY_REASON[reason];
+/**
+ * Every `finalReason` of a wake nobody asked for: the `followup` reasons above, plus the retired
+ * ones older rows still carry (`classifier-confident`, `proactive-help` were follow-ups too).
+ */
+export const BOT_WAKE_FOLLOWUP_REASONS: readonly string[] = [
+ ...(Object.keys(KIND_BY_REASON) as BotWakeReason[]).filter(
+ (reason) => KIND_BY_REASON[reason] === 'followup',
+ ),
+ 'classifier-confident',
+ 'proactive-help',
+];
+
const TAG_BY_REASON: Record<BotWakeReason, string> = {
'access-gate-rejected': 'blocked',
'addressed': 'addressed',
diff --git a/apps/server/src/services/bot/wake/__tests__/judgeScore.test.ts b/apps/server/src/services/bot/wake/__tests__/judgeScore.test.ts
new file mode 100644
index 00000000000..3a549a16b4f
--- /dev/null
+++ b/apps/server/src/services/bot/wake/__tests__/judgeScore.test.ts
@@ -0,0 +1,59 @@
+import type { SignalDecisionVerdict } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { pickWakeJudgeScore } from '../judgeScore';
+
+const v = (
+ policyId: string,
+ verdict: SignalDecisionVerdict['verdict'],
+ confidence: number,
+ reason = 'score',
+): SignalDecisionVerdict => ({
+ confidence,
+ latencyMs: 300,
+ mode: 'enforce',
+ policyId,
+ reason,
+ verdict,
+ version: 1,
+});
+
+const CLASSIFIER = 'bot-wake:classifier';
+const DUTY = 'bot-wake:duty';
+
+describe('pickWakeJudgeScore', () => {
+ it('uses the duty judge for an in-duty wake', () => {
+ expect(
+ pickWakeJudgeScore([v(CLASSIFIER, 'deny', 0.12), v(DUTY, 'allow', 0.81)], 'in-duty'),
+ ).toEqual({ kind: 'duty', score: 0.81, verdict: 'allow' });
+ });
+
+ it('uses the addressed classifier otherwise', () => {
+ expect(
+ pickWakeJudgeScore([v(DUTY, 'deny', 0.3), v(CLASSIFIER, 'allow', 0.74)], 'named-in-text'),
+ ).toEqual({ kind: 'addressed', score: 0.74, verdict: 'allow' });
+ });
+
+ it('falls back to the other judge when the preferred one did not score', () => {
+ expect(
+ pickWakeJudgeScore(
+ [v(DUTY, 'abstain', 0, 'too-short'), v(CLASSIFIER, 'deny', 0.2)],
+ 'in-duty',
+ ),
+ ).toEqual({ kind: 'addressed', score: 0.2, verdict: 'deny' });
+ });
+
+ it.each([
+ ['a classifier timeout', [v(CLASSIFIER, 'allow', 0, 'classifier-timeout')]],
+ ['a classifier error', [v(CLASSIFIER, 'allow', 0, 'classifier-error: 500')]],
+ ['a duty timeout', [v(DUTY, 'abstain', 0, 'duty-timeout')]],
+ ['only rule policies', [v('bot-wake:owner-rules', 'deny', 1, 'owner-present')]],
+ ['no verdicts', []],
+ ])('has no score for %s', (_case, verdicts) => {
+ expect(pickWakeJudgeScore(verdicts, 'not-addressed')).toBeUndefined();
+ });
+
+ it('has no score without verdicts at all', () => {
+ expect(pickWakeJudgeScore(null, null)).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/bot/wake/judgeScore.ts b/apps/server/src/services/bot/wake/judgeScore.ts
new file mode 100644
index 00000000000..b728220602d
--- /dev/null
+++ b/apps/server/src/services/bot/wake/judgeScore.ts
@@ -0,0 +1,42 @@
+import type { BotWakeJudgeKind, BotWakeJudgeScore, SignalDecisionVerdict } from '@lobechat/types';
+
+import { CLASSIFIER_POLICY_ID } from '@/server/services/agentSignal/scenarios/botWake/policies/classifier';
+import { DUTY_POLICY_ID } from '@/server/services/agentSignal/scenarios/botWake/policies/duty';
+
+const KIND_BY_POLICY: Record<string, BotWakeJudgeKind> = {
+ [CLASSIFIER_POLICY_ID]: 'addressed',
+ [DUTY_POLICY_ID]: 'duty',
+};
+
+/**
+ * A verdict that carries no score: the model timed out or failed (`*-timeout`, `*-error: …`), or
+ * the duty judge abstained without asking it (a message too short, a reply to someone else).
+ */
+const isScored = (verdict: SignalDecisionVerdict) =>
+ verdict.verdict !== 'abstain' && !/-timeout$|-error:/.test(verdict.reason);
+
+/**
+ * The model score behind a wake decision, for the owner to judge the decision by.
+ *
+ * Returns:
+ * - the duty judge's score for an `in-duty` decision, since that is the one that woke the bot
+ * - otherwise the addressed classifier's, then the duty judge's, whichever scored
+ * - `undefined` when no model scored (an @-mention, a command, a rule, a failed call)
+ */
+export const pickWakeJudgeScore = (
+ verdicts: readonly SignalDecisionVerdict[] | null | undefined,
+ finalReason: string | null,
+): BotWakeJudgeScore | undefined => {
+ const scored = (verdicts ?? []).filter((v) => KIND_BY_POLICY[v.policyId] && isScored(v));
+ const byKind = (kind: BotWakeJudgeKind) =>
+ scored.find((v) => KIND_BY_POLICY[v.policyId] === kind);
+ const order: BotWakeJudgeKind[] =
+ finalReason === 'in-duty' ? ['duty', 'addressed'] : ['addressed', 'duty'];
+
+ for (const kind of order) {
+ const verdict = byKind(kind);
+ if (verdict) return { kind, score: verdict.confidence, verdict: verdict.verdict };
+ }
+
+ return undefined;
+};
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index dd76503835f..d689acb13fb 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -452,6 +452,73 @@
"channel.reactionModeMinimalHint": "Acknowledge, mark as thinking, then remove when done",
"channel.reactionModeNone": "Off",
"channel.reactionModeNoneHint": "Never add status reactions",
+ "channel.records.column.mark": "Right?",
+ "channel.records.column.message": "Message",
+ "channel.records.column.outcome": "Result",
+ "channel.records.column.reason": "Why",
+ "channel.records.column.score": "Score",
+ "channel.records.column.time": "Time",
+ "channel.records.empty.desc": "Records show up here once the bot judges a message in a channel it can see.",
+ "channel.records.empty.title": "No records yet",
+ "channel.records.emptyFiltered.clear": "Clear filters",
+ "channel.records.emptyFiltered.title": "Nothing matches these filters",
+ "channel.records.end": "That's everything from the last {{days}} days.",
+ "channel.records.filter.all": "All",
+ "channel.records.filter.followupOnly": "Proactive only",
+ "channel.records.filter.unmarkedOnly": "Unmarked only",
+ "channel.records.intro": "Every message the bot judged in the last {{days}} days: whether it woke up, and why. Mark the ones it got wrong.",
+ "channel.records.judge.addressed": "Is it meant for the bot",
+ "channel.records.judge.allow": "over the threshold",
+ "channel.records.judge.deny": "under the threshold",
+ "channel.records.judge.duty": "Is it within its duties",
+ "channel.records.judge.hint": "{{judge}}: {{verdict}}",
+ "channel.records.loadMore": "Load more",
+ "channel.records.mark.correct": "Right call",
+ "channel.records.mark.failed": "Couldn't save your mark. Try again.",
+ "channel.records.mark.false_wake": "Shouldn't have woken",
+ "channel.records.mark.missed_wake": "Should have woken",
+ "channel.records.mark.undo": "Click again to remove the mark",
+ "channel.records.mark.wrong": "Wrong call",
+ "channel.records.noReplyReason.already_handled": "Already handled",
+ "channel.records.noReplyReason.duplicate": "Already answered",
+ "channel.records.noReplyReason.empty_completion": "Empty reply",
+ "channel.records.noReplyReason.not_addressed": "Not talking to it",
+ "channel.records.noReplyReason.nothing_to_add": "Nothing to add",
+ "channel.records.noReplyReason.off_topic": "Off topic",
+ "channel.records.noReplyReason.stand_down": "Asked to step back",
+ "channel.records.noReplyReason.unspecified": "No reason given",
+ "channel.records.openMessage": "Open the message",
+ "channel.records.outcome.defer": "Deferred",
+ "channel.records.outcome.skip": "Skipped",
+ "channel.records.outcome.wake": "Woke",
+ "channel.records.proactive": "Proactive",
+ "channel.records.purged": "Message expired",
+ "channel.records.purgedHint": "Message text is kept for 7 days.",
+ "channel.records.reason.access-gate-rejected": "Blocked by access rules",
+ "channel.records.reason.addressed": "A reply to the bot",
+ "channel.records.reason.classifier-confident": "Judged as meant for it",
+ "channel.records.reason.command": "Command",
+ "channel.records.reason.direct-message": "Direct message",
+ "channel.records.reason.explicit-mention": "@-mentioned",
+ "channel.records.reason.followup-window": "Follow-up right after it spoke",
+ "channel.records.reason.in-duty": "Within its duties",
+ "channel.records.reason.monitoring-not-allowed": "Channel not open to proactive replies",
+ "channel.records.reason.named-in-text": "Called by name",
+ "channel.records.reason.not-addressed": "Not addressed to it",
+ "channel.records.reason.policy-denied": "Wake rules said no",
+ "channel.records.reason.proactive-help": "Offered help",
+ "channel.records.reason.scheduled": "Held to read with the next messages",
+ "channel.records.reason.solo-conversation": "One-on-one conversation",
+ "channel.records.reason.watch-keyword": "Watch keyword matched",
+ "channel.records.refresh": "Refresh",
+ "channel.records.silenced": "Chose not to reply",
+ "channel.records.silencedWithReason": "Chose not to reply: {{reason}}",
+ "channel.records.summary.defer": "Deferred",
+ "channel.records.summary.followup": "Proactive wakes",
+ "channel.records.summary.followupHint": "Woke up without being @-mentioned",
+ "channel.records.summary.marked": "Marked by you",
+ "channel.records.summary.skip": "Skipped",
+ "channel.records.summary.wake": "Woke",
"channel.refreshStatus": "Refresh status",
"channel.removeChannel": "Remove IM Bot",
"channel.removeFailed": "Failed to remove bot",
@@ -515,6 +582,7 @@
"channel.tab.access": "Access",
"channel.tab.advanced": "Advanced",
"channel.tab.connect": "Connect",
+ "channel.tab.records": "Wake records",
"channel.tab.reply": "Replies",
"channel.tab.unsaved": "Unsaved changes",
"channel.tab.wake": "Wake policy",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index ac830cb8b01..dd9f410fcf7 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -452,6 +452,73 @@
"channel.reactionModeMinimalHint": "收到时确认、开始思考时标记,完成后移除",
"channel.reactionModeNone": "关闭",
"channel.reactionModeNoneHint": "不添加任何状态表情",
+ "channel.records.column.mark": "判断对吗",
+ "channel.records.column.message": "消息",
+ "channel.records.column.outcome": "结果",
+ "channel.records.column.reason": "原因",
+ "channel.records.column.score": "置信度",
+ "channel.records.column.time": "时间",
+ "channel.records.empty.desc": "机器人在它能看到的频道里判断过消息后,记录会出现在这里。",
+ "channel.records.empty.title": "还没有唤醒记录",
+ "channel.records.emptyFiltered.clear": "清除筛选",
+ "channel.records.emptyFiltered.title": "没有符合筛选条件的记录",
+ "channel.records.end": "最近 {{days}} 天的记录已全部显示。",
+ "channel.records.filter.all": "全部",
+ "channel.records.filter.followupOnly": "只看主动唤醒",
+ "channel.records.filter.unmarkedOnly": "只看未标记",
+ "channel.records.intro": "最近 {{days}} 天里机器人判断过的每条消息:有没有被唤醒,以及为什么。判断错的可以标记出来。",
+ "channel.records.judge.addressed": "判断是不是在对它说",
+ "channel.records.judge.allow": "达到阈值",
+ "channel.records.judge.deny": "未达阈值",
+ "channel.records.judge.duty": "判断是否属于它的职责",
+ "channel.records.judge.hint": "{{judge}}:{{verdict}}",
+ "channel.records.loadMore": "加载更多",
+ "channel.records.mark.correct": "判断正确",
+ "channel.records.mark.failed": "标记没保存,请重试",
+ "channel.records.mark.false_wake": "不该唤醒",
+ "channel.records.mark.missed_wake": "应该唤醒",
+ "channel.records.mark.undo": "再点一次取消标记",
+ "channel.records.mark.wrong": "判断错误",
+ "channel.records.noReplyReason.already_handled": "已经有人处理",
+ "channel.records.noReplyReason.duplicate": "已经回答过",
+ "channel.records.noReplyReason.empty_completion": "回复为空",
+ "channel.records.noReplyReason.not_addressed": "不是在对它说",
+ "channel.records.noReplyReason.nothing_to_add": "没有要补充的",
+ "channel.records.noReplyReason.off_topic": "与它无关",
+ "channel.records.noReplyReason.stand_down": "被要求退出对话",
+ "channel.records.noReplyReason.unspecified": "未说明原因",
+ "channel.records.openMessage": "打开原消息",
+ "channel.records.outcome.defer": "暂缓处理",
+ "channel.records.outcome.skip": "未唤醒",
+ "channel.records.outcome.wake": "已唤醒",
+ "channel.records.proactive": "主动",
+ "channel.records.purged": "消息内容已过期",
+ "channel.records.purgedHint": "消息正文只保留 7 天。",
+ "channel.records.reason.access-gate-rejected": "被访问控制拦下",
+ "channel.records.reason.addressed": "回复了机器人",
+ "channel.records.reason.classifier-confident": "判断是在对它说",
+ "channel.records.reason.command": "命令",
+ "channel.records.reason.direct-message": "私信",
+ "channel.records.reason.explicit-mention": "被 @",
+ "channel.records.reason.followup-window": "它刚发言后有人接着说",
+ "channel.records.reason.in-duty": "属于它的职责",
+ "channel.records.reason.monitoring-not-allowed": "这个频道没开放主动参与",
+ "channel.records.reason.named-in-text": "消息里叫了它的名字",
+ "channel.records.reason.not-addressed": "不是在对它说",
+ "channel.records.reason.policy-denied": "唤醒规则判定不参与",
+ "channel.records.reason.proactive-help": "主动提供帮助",
+ "channel.records.reason.scheduled": "等后续消息一起处理",
+ "channel.records.reason.solo-conversation": "一对一对话",
+ "channel.records.reason.watch-keyword": "命中监听关键词",
+ "channel.records.refresh": "刷新",
+ "channel.records.silenced": "选择不回复",
+ "channel.records.silencedWithReason": "选择不回复:{{reason}}",
+ "channel.records.summary.defer": "暂缓处理",
+ "channel.records.summary.followup": "主动唤醒",
+ "channel.records.summary.followupHint": "没人 @ 它时自己醒来的次数",
+ "channel.records.summary.marked": "你已标记",
+ "channel.records.summary.skip": "未唤醒",
+ "channel.records.summary.wake": "已唤醒",
"channel.refreshStatus": "刷新状态",
"channel.removeChannel": "移除 IM 机器人",
"channel.removeFailed": "移除 Bot 失败",
@@ -515,6 +582,7 @@
"channel.tab.access": "访问控制",
"channel.tab.advanced": "高级",
"channel.tab.connect": "接入",
+ "channel.tab.records": "唤醒记录",
"channel.tab.reply": "回复方式",
"channel.tab.unsaved": "有未保存的修改",
"channel.tab.wake": "唤醒策略",
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index be6b9efbf32..2b05f8ff28b 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -177,6 +177,9 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
agent: rw('agent:read', 'agent:write'),
// bot channel wiring carries channel credentials
agentBotProvider: 'blocked',
+ // a bot's wake records: channel message previews and the owner's marks, read through the same
+ // bot lookup as agentBotProvider
+ agentBotWake: 'blocked',
agentDocument: rw('knowledge:read', 'knowledge:write'),
agentEval: 'blocked',
agentEvalExternal: 'blocked',
diff --git a/packages/database/src/models/__tests__/signalDecision.scope.test.ts b/packages/database/src/models/__tests__/signalDecision.scope.test.ts
new file mode 100644
index 00000000000..c973476586f
--- /dev/null
+++ b/packages/database/src/models/__tests__/signalDecision.scope.test.ts
@@ -0,0 +1,353 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ signalDecisionLabels,
+ signalDecisions,
+ signals,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { SignalModel } from '../signal';
+import { SignalDecisionModel } from '../signalDecision';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'signal-decision-scope-user';
+const otherUserId = 'signal-decision-scope-other';
+const agentId = 'signal-decision-scope-agent';
+const scopeKey = 'discord:app-1';
+
+const FOLLOWUPS = ['watch-keyword', 'in-duty'];
+const SOURCES = ['user', 'agent:no_reply'];
+
+/** `minutesAgo` keeps the order explicit; rows recorded in one test otherwise share a clock. */
+const seed = async (
+ externalId: string,
+ {
+ minutesAgo = 0,
+ outcome = 'wake' as const,
+ reason = 'explicit-mention',
+ scope = scopeKey,
+ text = `text of ${externalId}`,
+ owner = userId,
+ workspace,
+ }: {
+ minutesAgo?: number;
+ outcome?: 'defer' | 'skip' | 'wake';
+ owner?: string;
+ reason?: string;
+ scope?: string;
+ text?: string;
+ /** The workspace that owns the binding; omitted means personal scope. */
+ workspace?: string;
+ } = {},
+) => {
+ const signal = (await new SignalModel(serverDB, owner, workspace).record({
+ externalId,
+ metadata: { address: { messageId: externalId, platform: 'discord' } },
+ payload: { text },
+ scopeKey: scope,
+ source: 'bot:discord',
+ type: 'bot.message.merged',
+ }))!;
+ const decision = (await new SignalDecisionModel(serverDB, owner, workspace).record({
+ agentId,
+ finalReason: reason,
+ outcome,
+ pipelineVersion: 'bot-wake@3',
+ scopeKey: scope,
+ signalId: signal.id,
+ }))!;
+ await serverDB
+ .update(signalDecisions)
+ .set({ createdAt: new Date(Date.now() - minutesAgo * 60_000) })
+ .where(eq(signalDecisions.id, decision.id));
+
+ return { decision, signal };
+};
+
+const label = (decisionId: string, source: string, value: any, minutesAgo: number) =>
+ serverDB.insert(signalDecisionLabels).values({
+ createdAt: new Date(Date.now() - minutesAgo * 60_000),
+ decisionId,
+ label: value,
+ source,
+ });
+
+let workspaceA = '';
+let workspaceB = '';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(agents).values([
+ { id: agentId, userId },
+ { id: `${agentId}-other`, userId: otherUserId },
+ ]);
+
+ const [wsA] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'wsA', primaryOwnerId: userId, slug: 'signal-decision-scope-ws-a' })
+ .returning();
+ const [wsB] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'wsB', primaryOwnerId: userId, slug: 'signal-decision-scope-ws-b' })
+ .returning();
+ workspaceA = wsA.id;
+ workspaceB = wsB.id;
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('SignalDecisionModel scope reads', () => {
+ describe('listByScope', () => {
+ it('lists one channel newest first and pages by cursor without gaps or repeats', async () => {
+ for (let i = 0; i < 5; i++) await seed(`m${i}`, { minutesAgo: 10 - i });
+ // Another channel, and the same channel of another user, never show up.
+ await seed('elsewhere', { scope: 'discord:app-2' });
+ const model = new SignalDecisionModel(serverDB, userId);
+
+ const first = await model.listByScope({ limit: 2, scopeKey });
+ expect(first.items.map((i) => i.text)).toEqual(['text of m4', 'text of m3']);
+ expect(first.nextCursor).toBeDefined();
+
+ const second = await model.listByScope({ cursor: first.nextCursor, limit: 2, scopeKey });
+ const third = await model.listByScope({ cursor: second.nextCursor, limit: 2, scopeKey });
+
+ expect(second.items.map((i) => i.text)).toEqual(['text of m2', 'text of m1']);
+ expect(third.items.map((i) => i.text)).toEqual(['text of m0']);
+ expect(third.nextCursor).toBeUndefined();
+ });
+
+ it('keeps rows that share a millisecond apart through the cursor', async () => {
+ const a = await seed('same-a');
+ const b = await seed('same-b');
+ const at = new Date();
+ // Same instant: only the id tie-break orders them.
+ await serverDB.update(signalDecisions).set({ createdAt: at });
+ const model = new SignalDecisionModel(serverDB, userId);
+
+ const first = await model.listByScope({ limit: 1, scopeKey });
+ const second = await model.listByScope({ cursor: first.nextCursor, limit: 1, scopeKey });
+
+ expect(new Set([...first.items, ...second.items].map((i) => i.id))).toEqual(
+ new Set([a.decision.id, b.decision.id]),
+ );
+ });
+
+ it('does not read another user’s decisions on the same channel', async () => {
+ await seed('theirs', { owner: otherUserId });
+
+ const page = await new SignalDecisionModel(serverDB, userId).listByScope({ scopeKey });
+
+ expect(page.items).toEqual([]);
+ });
+
+ it('does not read decisions a different scope recorded on the same channel', async () => {
+ // Deleting a binding in workspace A and recreating the same platform app in workspace B
+ // reuses `discord:app-1` under the same owner; the two histories must not merge.
+ await seed('shared-a', { workspace: workspaceA });
+ await seed('personal');
+ await seed('shared-b', { workspace: workspaceB });
+
+ const fromA = await new SignalDecisionModel(serverDB, userId, workspaceA).listByScope({
+ scopeKey,
+ });
+ const fromB = await new SignalDecisionModel(serverDB, userId, workspaceB).listByScope({
+ scopeKey,
+ });
+ const personal = await new SignalDecisionModel(serverDB, userId).listByScope({ scopeKey });
+
+ expect(fromA.items.map((i) => i.text)).toEqual(['text of shared-a']);
+ expect(fromB.items.map((i) => i.text)).toEqual(['text of shared-b']);
+ expect(personal.items.map((i) => i.text)).toEqual(['text of personal']);
+ });
+
+ it('leaves out decisions older than the window', async () => {
+ await seed('old', { minutesAgo: 60 * 24 * 31 });
+ await seed('recent', { minutesAgo: 5 });
+
+ const page = await new SignalDecisionModel(serverDB, userId).listByScope({ scopeKey });
+
+ expect(page.items.map((i) => i.text)).toEqual(['text of recent']);
+ });
+
+ it('filters by outcome, reason and whether a source has labelled it', async () => {
+ const woke = await seed('woke', { minutesAgo: 3, reason: 'watch-keyword' });
+ const skipped = await seed('skipped', {
+ minutesAgo: 2,
+ outcome: 'skip',
+ reason: 'not-addressed',
+ });
+ await seed('mention', { minutesAgo: 1 });
+ await label(woke.decision.id, 'agent:no_reply', 'false_wake', 1);
+ await label(skipped.decision.id, 'user', 'missed_wake', 1);
+ const model = new SignalDecisionModel(serverDB, userId);
+
+ const ids = async (params: Parameters<typeof model.listByScope>[0]) =>
+ (await model.listByScope(params)).items.map((i) => i.id);
+
+ expect(await ids({ outcome: 'skip', scopeKey })).toEqual([skipped.decision.id]);
+ expect(await ids({ finalReasons: FOLLOWUPS, scopeKey })).toEqual([woke.decision.id]);
+ expect(await ids({ labeled: { by: 'user', has: true }, scopeKey })).toEqual([
+ skipped.decision.id,
+ ]);
+ // The agent's own label does not count as the user's mark.
+ expect(await ids({ labeled: { by: 'user', has: false }, scopeKey })).toHaveLength(2);
+ });
+
+ it('attaches the latest label of each source', async () => {
+ const { decision } = await seed('labelled');
+ await label(decision.id, 'user', 'false_wake', 5);
+ await label(decision.id, 'user', 'correct', 1);
+ await label(decision.id, 'agent:no_reply', 'dup_wake', 3);
+
+ const [item] = (await new SignalDecisionModel(serverDB, userId).listByScope({ scopeKey }))
+ .items;
+
+ expect(
+ item.labels.map((l) => [l.source, l.label]).sort(([a], [b]) => a.localeCompare(b)),
+ ).toEqual([
+ ['agent:no_reply', 'dup_wake'],
+ ['user', 'correct'],
+ ]);
+ });
+
+ it('treats a mark taken back (`cleared`) as no mark', async () => {
+ const cleared = await seed('cleared', { minutesAgo: 3 });
+ const remarked = await seed('remarked', { minutesAgo: 2 });
+ await label(cleared.decision.id, 'user', 'false_wake', 5);
+ await label(cleared.decision.id, 'user', 'cleared', 1);
+ await label(remarked.decision.id, 'user', 'cleared', 5);
+ await label(remarked.decision.id, 'user', 'correct', 1);
+ const model = new SignalDecisionModel(serverDB, userId);
+
+ const items = (await model.listByScope({ scopeKey })).items;
+ const byId = new Map(items.map((i) => [i.id, i]));
+ expect(byId.get(cleared.decision.id)?.labels).toEqual([]);
+ expect(byId.get(remarked.decision.id)?.labels.map((l) => l.label)).toEqual(['correct']);
+
+ const ids = async (has: boolean) =>
+ (await model.listByScope({ labeled: { by: 'user', has }, scopeKey })).items.map(
+ (i) => i.id,
+ );
+ expect(await ids(true)).toEqual([remarked.decision.id]);
+ expect(await ids(false)).toEqual([cleared.decision.id]);
+
+ const summary = await model.summaryByScope({
+ followupReasons: FOLLOWUPS,
+ labelSources: SOURCES,
+ scopeKey,
+ since: new Date(Date.now() - 24 * 60 * 60_000),
+ });
+ expect(summary.labels).toEqual({ user: { correct: 1 } });
+ });
+
+ it('cuts the preview and hides purged text while keeping the address', async () => {
+ const long = await seed('long', { minutesAgo: 2, text: 'x'.repeat(500) });
+ const purged = await seed('purged', { minutesAgo: 1 });
+ await serverDB
+ .update(signals)
+ .set({ payload: {}, payloadPurgedAt: new Date() })
+ .where(eq(signals.id, purged.signal.id));
+
+ const items = (await new SignalDecisionModel(serverDB, userId).listByScope({ scopeKey }))
+ .items;
+ const byId = new Map(items.map((i) => [i.id, i]));
+
+ expect(byId.get(long.decision.id)).toMatchObject({ textPurged: false });
+ expect(byId.get(long.decision.id)?.text).toHaveLength(200);
+ expect(byId.get(purged.decision.id)).toMatchObject({
+ address: { messageId: 'purged', platform: 'discord' },
+ text: null,
+ textPurged: true,
+ });
+ });
+ });
+
+ describe('summaryByScope', () => {
+ it('counts only the scope’s own decisions', async () => {
+ await seed('shared-a', { workspace: workspaceA });
+ await seed('shared-b-1', { workspace: workspaceB });
+ await seed('shared-b-2', { workspace: workspaceB });
+ await seed('personal');
+
+ const since = new Date(Date.now() - 30 * 24 * 60 * 60_000);
+ const fromB = await new SignalDecisionModel(serverDB, userId, workspaceB).summaryByScope({
+ followupReasons: FOLLOWUPS,
+ labelSources: SOURCES,
+ scopeKey,
+ since,
+ });
+ const personal = await new SignalDecisionModel(serverDB, userId).summaryByScope({
+ followupReasons: FOLLOWUPS,
+ labelSources: SOURCES,
+ scopeKey,
+ since,
+ });
+
+ expect(fromB.total).toBe(2);
+ expect(personal.total).toBe(1);
+ });
+
+ it('counts outcomes, follow-up wakes and current labels per source', async () => {
+ const keyword = await seed('keyword', { reason: 'watch-keyword' });
+ const mention = await seed('mention');
+ const skipped = await seed('skip', { outcome: 'skip', reason: 'not-addressed' });
+ await seed('defer', { outcome: 'defer', reason: 'in-duty' });
+ await seed('old', { minutesAgo: 60 * 24 * 40 });
+ await seed('theirs', { owner: otherUserId });
+
+ await label(keyword.decision.id, 'agent:no_reply', 'false_wake', 2);
+ // Only the latest user label counts.
+ await label(mention.decision.id, 'user', 'false_wake', 3);
+ await label(mention.decision.id, 'user', 'correct', 1);
+ await label(skipped.decision.id, 'user', 'missed_wake', 1);
+ await label(skipped.decision.id, 'llm_judge', 'correct', 1);
+
+ const summary = await new SignalDecisionModel(serverDB, userId).summaryByScope({
+ followupReasons: FOLLOWUPS,
+ labelSources: SOURCES,
+ scopeKey,
+ since: new Date(Date.now() - 30 * 24 * 60 * 60_000),
+ });
+
+ expect(summary).toEqual({
+ defer: 1,
+ followupWakes: 1,
+ labels: {
+ 'agent:no_reply': { false_wake: 1 },
+ 'user': { correct: 1, missed_wake: 1 },
+ },
+ skip: 1,
+ total: 4,
+ wake: 2,
+ });
+ });
+
+ it('returns zeros for a channel with no decisions', async () => {
+ const summary = await new SignalDecisionModel(serverDB, userId).summaryByScope({
+ followupReasons: FOLLOWUPS,
+ labelSources: SOURCES,
+ scopeKey,
+ since: new Date(0),
+ });
+
+ expect(summary).toEqual({
+ defer: 0,
+ followupWakes: 0,
+ labels: {},
+ skip: 0,
+ total: 0,
+ wake: 0,
+ });
+ });
+ });
+});
diff --git a/packages/database/src/models/signalDecision.ts b/packages/database/src/models/signalDecision.ts
index 87aadf5eaa9..769719f782f 100644
--- a/packages/database/src/models/signalDecision.ts
+++ b/packages/database/src/models/signalDecision.ts
@@ -1,5 +1,12 @@
-import type { SignalDecisionLabel, SignalDecisionLabelMetadata } from '@lobechat/types';
-import { and, asc, desc, eq } from 'drizzle-orm';
+import type {
+ SignalDecisionLabel,
+ SignalDecisionLabelMetadata,
+ SignalDecisionOutcome,
+ SignalDecisionVerdict,
+} from '@lobechat/types';
+import { SIGNAL_DECISION_LABEL_CLEARED } from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { and, asc, desc, eq, gte, inArray, isNull, ne, sql } from 'drizzle-orm';
import type { NewSignalDecision, SignalDecisionItem, SignalDecisionLabelItem } from '../schemas';
import { signalDecisionLabels, signalDecisions, signals } from '../schemas';
@@ -26,6 +33,92 @@ export interface AddSignalDecisionLabelInput {
source: string;
}
+/** How far back a scope read looks when the caller does not say. */
+export const SCOPE_READ_DEFAULT_DAYS = 30;
+/** Longest message preview a scope read returns. */
+export const SCOPE_READ_TEXT_PREVIEW = 200;
+/** Largest page a scope read returns. */
+export const SCOPE_READ_MAX_LIMIT = 50;
+
+/** Keyset position: the last row of the previous page, `createdAt` as ISO with microseconds. */
+export interface ScopeDecisionCursor {
+ createdAt: string;
+ id: string;
+}
+
+export interface ListDecisionsByScopeParams {
+ cursor?: ScopeDecisionCursor;
+ /** Only decisions whose `final_reason` is one of these; ignored when empty. */
+ finalReasons?: readonly string[];
+ /**
+ * `has: true`: only decisions whose current label from source `by` is set; `has: false`: only
+ * those without one (never labeled, or the latest label is `cleared`).
+ */
+ labeled?: { by: string; has: boolean };
+ /** 1..{@link SCOPE_READ_MAX_LIMIT}; defaults to 20. */
+ limit?: number;
+ outcome?: SignalDecisionOutcome;
+ scopeKey: string;
+ /** Lower bound on `created_at`; defaults to {@link SCOPE_READ_DEFAULT_DAYS} days ago. */
+ since?: Date;
+}
+
+/** The latest label of one source on a decision: that source's current opinion. */
+export interface CurrentDecisionLabel {
+ createdAt: Date;
+ label: SignalDecisionLabel;
+ metadata: SignalDecisionLabelMetadata;
+ source: string;
+}
+
+export interface ScopeDecisionListItem {
+ /** Where the message was addressed (`signals.metadata.address`); survives the payload purge. */
+ address: Record<string, string> | null;
+ createdAt: Date;
+ finalReason: string | null;
+ id: string;
+ /** Current label per source. */
+ labels: CurrentDecisionLabel[];
+ outcome: SignalDecisionOutcome;
+ /** First {@link SCOPE_READ_TEXT_PREVIEW} characters of the message; null once purged. */
+ text: string | null;
+ /** The retention sweep blanked the message, or its signal is gone. */
+ textPurged: boolean;
+ toTag: string | null;
+ /** Every policy's opinion, shadow ones included. */
+ verdicts: SignalDecisionVerdict[];
+}
+
+export interface ScopeDecisionPage {
+ items: ScopeDecisionListItem[];
+ nextCursor?: ScopeDecisionCursor;
+}
+
+export interface SummarizeDecisionsByScopeParams {
+ /** Reasons counted as follow-up (unprompted) wakes. */
+ followupReasons: readonly string[];
+ /** Label sources whose current labels are counted, e.g. `['user', 'agent:no_reply']`. */
+ labelSources: readonly string[];
+ scopeKey: string;
+ since: Date;
+}
+
+export interface ScopeDecisionSummary {
+ defer: number;
+ /** Wakes whose reason is one of `followupReasons`. */
+ followupWakes: number;
+ /** Count of decisions per `source` → current `label`. */
+ labels: Record<string, Partial<Record<SignalDecisionLabel, number>>>;
+ skip: number;
+ total: number;
+ wake: number;
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** `created_at` at full (microsecond) precision, so a keyset cursor never skips a row. */
+const createdAtIso = sql<string>`to_char(${signalDecisions.createdAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+
/**
* User-scoped access to `signal_decisions` and their append-only `signal_decision_labels`.
*/
@@ -40,6 +133,21 @@ export class SignalDecisionModel {
this.workspaceId = workspaceId;
}
+ /**
+ * The scope that recorded a decision, as a predicate: workspace rows carry their `workspace_id`,
+ * personal ones leave it null.
+ *
+ * Scope reads cannot skip this. A bot binding is looked up by `platform:applicationId`, so
+ * deleting a binding in one scope and recreating the same platform app in another reuses the
+ * exact same `scope_key` under the same owner — owner + scope key alone would hand the new
+ * scope's members the previous scope's history.
+ */
+ private get scopeOfRecord() {
+ return this.workspaceId
+ ? eq(signalDecisions.workspaceId, this.workspaceId)
+ : isNull(signalDecisions.workspaceId);
+ }
+
/**
* Records what the pipeline decided for one signal.
*
@@ -144,4 +252,189 @@ export class SignalDecisionModel {
.where(eq(signalDecisionLabels.decisionId, decisionId))
.orderBy(desc(signalDecisionLabels.createdAt), desc(signalDecisionLabels.id));
};
+
+ // --------------- Scope reads (one channel's decisions) ---------------
+
+ /**
+ * One channel's decisions, newest first, with the message preview and each source's current
+ * label. Every predicate starts from `(user_id, scope_key, created_at)`, so the read stays on the
+ * composite index; labels come in one extra query for the page's ids.
+ */
+ listByScope = async (params: ListDecisionsByScopeParams): Promise<ScopeDecisionPage> => {
+ const limit = Math.min(Math.max(params.limit ?? 20, 1), SCOPE_READ_MAX_LIMIT);
+ const since = params.since ?? new Date(Date.now() - SCOPE_READ_DEFAULT_DAYS * DAY_MS);
+
+ const conditions: SQL[] = [
+ eq(signalDecisions.userId, this.userId),
+ eq(signalDecisions.scopeKey, params.scopeKey),
+ gte(signalDecisions.createdAt, since),
+ this.scopeOfRecord,
+ ];
+ if (params.outcome) conditions.push(eq(signalDecisions.outcome, params.outcome));
+ if (params.finalReasons?.length)
+ conditions.push(inArray(signalDecisions.finalReason, [...params.finalReasons]));
+ if (params.cursor)
+ conditions.push(
+ sql`(${signalDecisions.createdAt}, ${signalDecisions.id}) < (${params.cursor.createdAt}::timestamptz, ${params.cursor.id}::uuid)`,
+ );
+ if (params.labeled) {
+ // The source's latest label; `cleared` (or none) means it has no current opinion.
+ const latest = sql`coalesce((select ${signalDecisionLabels.label} from ${signalDecisionLabels} where ${signalDecisionLabels.decisionId} = ${signalDecisions.id} and ${signalDecisionLabels.source} = ${params.labeled.by} order by ${signalDecisionLabels.createdAt} desc, ${signalDecisionLabels.id} desc limit 1), ${SIGNAL_DECISION_LABEL_CLEARED})`;
+ conditions.push(
+ params.labeled.has
+ ? sql`${latest} <> ${SIGNAL_DECISION_LABEL_CLEARED}`
+ : sql`${latest} = ${SIGNAL_DECISION_LABEL_CLEARED}`,
+ );
+ }
+
+ const rows = await this.db
+ .select({
+ address: sql<Record<string, string> | null>`${signals.metadata} -> 'address'`,
+ createdAt: signalDecisions.createdAt,
+ createdAtIso,
+ finalReason: signalDecisions.finalReason,
+ id: signalDecisions.id,
+ outcome: signalDecisions.outcome,
+ purged: sql<boolean>`(${signals.id} is null or ${signals.payloadPurgedAt} is not null)`,
+ text: sql<
+ string | null
+ >`case when ${signals.payloadPurgedAt} is null then left(${signals.payload} ->> 'text', ${SCOPE_READ_TEXT_PREVIEW}) end`,
+ toTag: signalDecisions.toTag,
+ verdicts: signalDecisions.verdicts,
+ })
+ .from(signalDecisions)
+ .leftJoin(signals, eq(signals.id, signalDecisions.signalId))
+ .where(and(...conditions))
+ .orderBy(desc(signalDecisions.createdAt), desc(signalDecisions.id))
+ .limit(limit + 1);
+
+ const page = rows.slice(0, limit);
+ const labels = await this.currentLabels(page.map((row) => row.id));
+ const last = page.at(-1);
+
+ return {
+ items: page.map((row) => ({
+ address: row.address ?? null,
+ createdAt: row.createdAt,
+ finalReason: row.finalReason,
+ id: row.id,
+ labels: labels.get(row.id) ?? [],
+ outcome: row.outcome,
+ text: row.purged ? null : (row.text ?? null),
+ textPurged: row.purged,
+ toTag: row.toTag,
+ verdicts: row.verdicts ?? [],
+ })),
+ nextCursor:
+ rows.length > limit && last ? { createdAt: last.createdAtIso, id: last.id } : undefined,
+ };
+ };
+
+ /**
+ * Counts for one channel since `since`: decisions by outcome, follow-up wakes, and how many
+ * decisions each label source currently holds each label for. Two aggregates, both bounded by
+ * the `(user_id, scope_key, created_at)` index range.
+ */
+ summaryByScope = async (
+ params: SummarizeDecisionsByScopeParams,
+ ): Promise<ScopeDecisionSummary> => {
+ const inScope = and(
+ eq(signalDecisions.userId, this.userId),
+ eq(signalDecisions.scopeKey, params.scopeKey),
+ gte(signalDecisions.createdAt, params.since),
+ this.scopeOfRecord,
+ );
+ const followup = params.followupReasons.length
+ ? inArray(signalDecisions.finalReason, [...params.followupReasons])
+ : sql`false`;
+
+ const [counts] = await this.db
+ .select({
+ defer: sql<number>`count(*) filter (where ${signalDecisions.outcome} = 'defer')::int`,
+ followupWakes: sql<number>`count(*) filter (where ${signalDecisions.outcome} = 'wake' and ${followup})::int`,
+ skip: sql<number>`count(*) filter (where ${signalDecisions.outcome} = 'skip')::int`,
+ total: sql<number>`count(*)::int`,
+ wake: sql<number>`count(*) filter (where ${signalDecisions.outcome} = 'wake')::int`,
+ })
+ .from(signalDecisions)
+ .where(inScope);
+
+ const labels: ScopeDecisionSummary['labels'] = {};
+ if (params.labelSources.length > 0 && (counts?.total ?? 0) > 0) {
+ const current = this.db
+ .selectDistinctOn([signalDecisionLabels.decisionId, signalDecisionLabels.source], {
+ label: signalDecisionLabels.label,
+ source: signalDecisionLabels.source,
+ })
+ .from(signalDecisionLabels)
+ .innerJoin(signalDecisions, eq(signalDecisions.id, signalDecisionLabels.decisionId))
+ .where(and(inScope, inArray(signalDecisionLabels.source, [...params.labelSources])))
+ .orderBy(
+ signalDecisionLabels.decisionId,
+ signalDecisionLabels.source,
+ desc(signalDecisionLabels.createdAt),
+ desc(signalDecisionLabels.id),
+ )
+ .as('current');
+
+ const grouped = await this.db
+ .select({
+ count: sql<number>`count(*)::int`,
+ label: current.label,
+ source: current.source,
+ })
+ .from(current)
+ .where(ne(current.label, SIGNAL_DECISION_LABEL_CLEARED))
+ .groupBy(current.source, current.label);
+
+ for (const row of grouped) {
+ (labels[row.source] ??= {})[row.label] = row.count;
+ }
+ }
+
+ return {
+ defer: counts?.defer ?? 0,
+ followupWakes: counts?.followupWakes ?? 0,
+ labels,
+ skip: counts?.skip ?? 0,
+ total: counts?.total ?? 0,
+ wake: counts?.wake ?? 0,
+ };
+ };
+
+ /**
+ * Current label per source for each decision, keyed by decision id; a source whose latest label
+ * is `cleared` is left out. Callers pass owned ids.
+ */
+ private currentLabels = async (decisionIds: string[]) => {
+ const byDecision = new Map<string, CurrentDecisionLabel[]>();
+ if (decisionIds.length === 0) return byDecision;
+
+ const rows = await this.db
+ .selectDistinctOn([signalDecisionLabels.decisionId, signalDecisionLabels.source], {
+ createdAt: signalDecisionLabels.createdAt,
+ decisionId: signalDecisionLabels.decisionId,
+ label: signalDecisionLabels.label,
+ metadata: signalDecisionLabels.metadata,
+ source: signalDecisionLabels.source,
+ })
+ .from(signalDecisionLabels)
+ .where(inArray(signalDecisionLabels.decisionId, decisionIds))
+ .orderBy(
+ signalDecisionLabels.decisionId,
+ signalDecisionLabels.source,
+ desc(signalDecisionLabels.createdAt),
+ desc(signalDecisionLabels.id),
+ );
+
+ for (const { decisionId, ...label } of rows) {
+ // A withdrawn label leaves the source without a current one.
+ if (label.label === SIGNAL_DECISION_LABEL_CLEARED) continue;
+ const list = byDecision.get(decisionId) ?? [];
+ list.push(label);
+ byDecision.set(decisionId, list);
+ }
+
+ return byDecision;
+ };
}
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index b41b0eb0694..4a09038032c 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -669,6 +669,76 @@ export default {
'channel.wake.section.more': 'More',
'channel.tab.advanced': 'Advanced',
'channel.tab.unsaved': 'Unsaved changes',
+ 'channel.tab.records': 'Wake records',
+ 'channel.records.intro':
+ 'Every message the bot judged in the last {{days}} days: whether it woke up, and why. Mark the ones it got wrong.',
+ 'channel.records.summary.wake': 'Woke',
+ 'channel.records.summary.skip': 'Skipped',
+ 'channel.records.summary.defer': 'Deferred',
+ 'channel.records.summary.followup': 'Proactive wakes',
+ 'channel.records.summary.followupHint': 'Woke up without being @-mentioned',
+ 'channel.records.summary.marked': 'Marked by you',
+ 'channel.records.filter.all': 'All',
+ 'channel.records.filter.followupOnly': 'Proactive only',
+ 'channel.records.filter.unmarkedOnly': 'Unmarked only',
+ 'channel.records.outcome.wake': 'Woke',
+ 'channel.records.outcome.skip': 'Skipped',
+ 'channel.records.outcome.defer': 'Deferred',
+ 'channel.records.proactive': 'Proactive',
+ 'channel.records.refresh': 'Refresh',
+ 'channel.records.purged': 'Message expired',
+ 'channel.records.purgedHint': 'Message text is kept for 7 days.',
+ 'channel.records.silenced': 'Chose not to reply',
+ 'channel.records.silencedWithReason': 'Chose not to reply: {{reason}}',
+ 'channel.records.reason.access-gate-rejected': 'Blocked by access rules',
+ 'channel.records.reason.addressed': 'A reply to the bot',
+ 'channel.records.reason.classifier-confident': 'Judged as meant for it',
+ 'channel.records.reason.command': 'Command',
+ 'channel.records.reason.direct-message': 'Direct message',
+ 'channel.records.reason.explicit-mention': '@-mentioned',
+ 'channel.records.reason.followup-window': 'Follow-up right after it spoke',
+ 'channel.records.reason.in-duty': 'Within its duties',
+ 'channel.records.reason.monitoring-not-allowed': 'Channel not open to proactive replies',
+ 'channel.records.reason.named-in-text': 'Called by name',
+ 'channel.records.reason.not-addressed': 'Not addressed to it',
+ 'channel.records.reason.policy-denied': 'Wake rules said no',
+ 'channel.records.reason.proactive-help': 'Offered help',
+ 'channel.records.reason.scheduled': 'Held to read with the next messages',
+ 'channel.records.reason.solo-conversation': 'One-on-one conversation',
+ 'channel.records.reason.watch-keyword': 'Watch keyword matched',
+ 'channel.records.noReplyReason.already_handled': 'Already handled',
+ 'channel.records.noReplyReason.duplicate': 'Already answered',
+ 'channel.records.noReplyReason.empty_completion': 'Empty reply',
+ 'channel.records.noReplyReason.not_addressed': 'Not talking to it',
+ 'channel.records.noReplyReason.nothing_to_add': 'Nothing to add',
+ 'channel.records.noReplyReason.off_topic': 'Off topic',
+ 'channel.records.noReplyReason.stand_down': 'Asked to step back',
+ 'channel.records.noReplyReason.unspecified': 'No reason given',
+ 'channel.records.mark.correct': 'Right call',
+ 'channel.records.mark.false_wake': "Shouldn't have woken",
+ 'channel.records.mark.missed_wake': 'Should have woken',
+ 'channel.records.mark.failed': "Couldn't save your mark. Try again.",
+ 'channel.records.column.time': 'Time',
+ 'channel.records.column.message': 'Message',
+ 'channel.records.column.outcome': 'Result',
+ 'channel.records.column.reason': 'Why',
+ 'channel.records.column.mark': 'Right?',
+ 'channel.records.mark.wrong': 'Wrong call',
+ 'channel.records.openMessage': 'Open the message',
+ 'channel.records.column.score': 'Score',
+ 'channel.records.judge.addressed': 'Is it meant for the bot',
+ 'channel.records.judge.duty': 'Is it within its duties',
+ 'channel.records.judge.allow': 'over the threshold',
+ 'channel.records.judge.deny': 'under the threshold',
+ 'channel.records.judge.hint': '{{judge}}: {{verdict}}',
+ 'channel.records.mark.undo': 'Click again to remove the mark',
+ 'channel.records.empty.title': 'No records yet',
+ 'channel.records.empty.desc':
+ 'Records show up here once the bot judges a message in a channel it can see.',
+ 'channel.records.emptyFiltered.title': 'Nothing matches these filters',
+ 'channel.records.emptyFiltered.clear': 'Clear filters',
+ 'channel.records.loadMore': 'Load more',
+ 'channel.records.end': "That's everything from the last {{days}} days.",
'channel.module.save': 'Save',
'channel.module.unsaved': 'Unsaved changes',
'channel.group.connection': 'Connection options',
diff --git a/packages/types/src/signal.ts b/packages/types/src/signal.ts
index 3922761c975..4c700f5dbf3 100644
--- a/packages/types/src/signal.ts
+++ b/packages/types/src/signal.ts
@@ -97,16 +97,107 @@ export interface SignalDecisionLabelMetadata {
surface?: string;
}
-/** Judgement attached to a decision after the fact. Append-only; a later label never edits an earlier one. */
+/**
+ * Judgement attached to a decision after the fact. Append-only; a later label never edits an earlier one.
+ *
+ * `cleared` is not a judgement: it withdraws the source's earlier label, so that source has no
+ * current opinion on the decision. Readers of the current label treat it as no label.
+ */
export const SIGNAL_DECISION_LABELS = [
'false_wake',
'dup_wake',
'bad_reply',
'missed_wake',
'correct',
+ 'cleared',
] as const;
export type SignalDecisionLabel = (typeof SIGNAL_DECISION_LABELS)[number];
+/** The label that withdraws a source's earlier one; see {@link SIGNAL_DECISION_LABELS}. */
+export const SIGNAL_DECISION_LABEL_CLEARED = 'cleared' satisfies SignalDecisionLabel;
+
+/** `signal_decision_labels.source` for a mark the bot's owner set in its settings. */
+export const BOT_WAKE_USER_LABEL_SOURCE = 'user';
+
+/** The labels a mark can be, a subset of {@link SIGNAL_DECISION_LABELS}. */
+export const BOT_WAKE_USER_LABELS = ['correct', 'false_wake', 'missed_wake'] as const;
+export type BotWakeUserLabel = (typeof BOT_WAKE_USER_LABELS)[number];
+
+/**
+ * What the owner can mark a wake decision as, by what the router did with it: a wake was right or
+ * should not have happened, a skip was right or should have woken, and a deferred message can be
+ * either.
+ */
+export const BOT_WAKE_USER_LABELS_BY_OUTCOME: Record<
+ SignalDecisionOutcome,
+ readonly BotWakeUserLabel[]
+> = {
+ defer: ['correct', 'false_wake', 'missed_wake'],
+ skip: ['correct', 'missed_wake'],
+ wake: ['correct', 'false_wake'],
+};
+
+/** Which model scored a wake decision: is the message for the bot, or within its duties. */
+export type BotWakeJudgeKind = 'addressed' | 'duty';
+
+/** The model score behind a wake decision, as the owner sees it next to the decision. */
+export interface BotWakeJudgeScore {
+ kind: BotWakeJudgeKind;
+ /** 0..1, as the judge returned it. */
+ score: number;
+ verdict: SignalDecisionVerdict['verdict'];
+}
+
+/** One bot wake decision as the bot's settings page lists it. */
+export interface BotWakeDecisionItem {
+ /** Where the message was addressed (`platform`, `platformThreadId`, `messageId`, …). */
+ address: Record<string, string> | null;
+ /** The agent's own silence label, when it woke and chose not to reply. */
+ agentLabel: { label: SignalDecisionLabel; reason?: string } | null;
+ createdAt: Date;
+ finalReason: string | null;
+ /** The bot woke on its own judgement, nobody addressed it. */
+ followup: boolean;
+ id: string;
+ /** The model score behind the decision; null when no model scored. */
+ judge: BotWakeJudgeScore | null;
+ outcome: SignalDecisionOutcome;
+ /** First 200 characters of the message; null once purged. */
+ text: string | null;
+ textPurged: boolean;
+ toTag: string | null;
+ /** The owner's current mark. */
+ userLabel: { createdAt: Date; label: SignalDecisionLabel; note?: string } | null;
+}
+
+export interface BotWakeDecisionPage {
+ items: BotWakeDecisionItem[];
+ /** Keyset position of the next page; absent on the last one. */
+ nextCursor?: { createdAt: string; id: string };
+}
+
+/** Counts of one bot's wake decisions over the last `days` days. */
+export interface BotWakeSummary {
+ days: number;
+ defer: number;
+ followupWakes: number;
+ /** Decisions the owner currently has a mark on. */
+ marked: number;
+ markedByLabel: Partial<Record<SignalDecisionLabel, number>>;
+ /** Wakes the agent stayed silent on (`false_wake` / `dup_wake` from its own label). */
+ silenced: number;
+ skip: number;
+ total: number;
+ wake: number;
+}
+
+/** The mark now in force after `labelWakeDecision`; null once it was taken back. */
+export type BotWakeUserMark = {
+ createdAt: Date;
+ label: BotWakeUserLabel;
+ note?: string;
+} | null;
+
/**
* How a bot wake reached the agent.
*
diff --git a/src/features/AgentChannel/PlatformDetail/Body.tsx b/src/features/AgentChannel/PlatformDetail/Body.tsx
index 4bc5e0f1c2c..960bfe852bc 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.tsx
@@ -3,7 +3,7 @@
import { Button, confirmModal, Flexbox, Text } from '@lobehub/ui';
import { Form, type FormInstance } from '@lobehub/ui/form';
import { RotateCcw } from 'lucide-react';
-import { Fragment, memo, type ReactNode, useCallback, useMemo } from 'react';
+import { Fragment, memo, type ReactNode, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type {
@@ -20,6 +20,7 @@ import {
} from '../platform/registry';
import { getInlineFieldKeys } from '../quickSetup/guides';
import QuickSetupSection from '../quickSetup/QuickSetupSection';
+import { WakeRecords } from '../WakeRecords';
import { AccessSection } from './AccessSection';
import styles from './Body.module.css';
import type { ChannelTab } from './channelTabs';
@@ -80,6 +81,8 @@ interface BodyProps {
currentConfig?: {
applicationId: string;
credentials: Record<string, string>;
+ /** The saved bot's id; the wake records tab reads its history by it. */
+ id?: string;
settings?: Record<string, unknown> | null;
};
disabled?: boolean;
@@ -123,6 +126,11 @@ const Body = memo<BodyProps>(
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
+ // The records tab is a history read, not settings: it mounts the first time it is opened and
+ // then stays, so switching tabs keeps its filters and loaded pages.
+ const [recordsOpened, setRecordsOpened] = useState(false);
+ if (activeTab === 'records' && !recordsOpened) setRecordsOpened(true);
+
const CustomCredentialBody = platformCredentialBodyMap[platformDef.id];
const CredentialExtras = platformCredentialExtrasMap[platformDef.id];
const WakeNotice = platformWakeNoticeMap[platformDef.id];
@@ -485,6 +493,15 @@ const Body = memo<BodyProps>(
)}
</Panel>
))}
+ {recordsOpened && currentConfig?.id && (
+ <Panel active={activeTab === 'records'} tab="records">
+ <WakeRecords
+ active={activeTab === 'records'}
+ botId={currentConfig.id}
+ disabled={disabled}
+ />
+ </Panel>
+ )}
</Form>
);
},
diff --git a/src/features/AgentChannel/PlatformDetail/Footer.tsx b/src/features/AgentChannel/PlatformDetail/Footer.tsx
index 0fbdc4f0189..12458b7168d 100644
--- a/src/features/AgentChannel/PlatformDetail/Footer.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Footer.tsx
@@ -94,6 +94,12 @@ interface FooterNoticesProps {
currentConfig?: CurrentConfig;
form: FormInstance<ChannelFormValues>;
hasConfig: boolean;
+ /**
+ * Leave out what the settings still need (the missing user id, the QQ webhook move): on a tab
+ * that shows history rather than settings there is nothing to fill in. What just happened
+ * (saved, connected, tested) still shows.
+ */
+ hideSetupHints?: boolean;
platformDef: SerializedPlatformDefinition;
saveResult?: TestResult;
testResult?: TestResult;
@@ -106,7 +112,16 @@ interface FooterNoticesProps {
* the person has to see.
*/
export const FooterNotices = memo<FooterNoticesProps>(
- ({ platformDef, currentConfig, form, hasConfig, connectResult, saveResult, testResult }) => {
+ ({
+ platformDef,
+ currentConfig,
+ form,
+ hasConfig,
+ hideSetupHints,
+ connectResult,
+ saveResult,
+ testResult,
+ }) => {
const { t } = useTranslation('agent');
const platformId = platformDef.id;
const settingsConnectionMode = useWatch(form, 'settings.connectionMode');
@@ -136,6 +151,7 @@ export const FooterNotices = memo<FooterNoticesProps>(
}, [watchedUserId]);
const effectiveUserId = formHydrated ? watchedUserId : savedUserId;
const userIdMissing =
+ !hideSetupHints &&
hasConfig &&
hasUserIdField &&
!(typeof effectiveUserId === 'string' && effectiveUserId.trim());
@@ -214,7 +230,7 @@ export const FooterNotices = memo<FooterNoticesProps>(
/>
)}
- {hasConfig && showWebhookUrl && platformId === 'qq' && (
+ {!hideSetupHints && hasConfig && showWebhookUrl && platformId === 'qq' && (
<Alert
closable
showIcon
diff --git a/src/features/AgentChannel/PlatformDetail/channelTabs.test.ts b/src/features/AgentChannel/PlatformDetail/channelTabs.test.ts
index f2720ff8c9e..edffb532ce9 100644
--- a/src/features/AgentChannel/PlatformDetail/channelTabs.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/channelTabs.test.ts
@@ -29,6 +29,23 @@ describe('resolveTabs', () => {
expect(resolveTabs(['reply'])).toEqual(['connect', 'reply']);
expect(resolveTabs([])).toEqual(['connect']);
});
+
+ it('adds wake records last, only for a saved bot that can wake on its own', () => {
+ expect(resolveTabs(['wake', 'reply'], { hasConfig: true })).toEqual([
+ 'connect',
+ 'wake',
+ 'reply',
+ 'records',
+ ]);
+ // Not saved yet: nothing has been judged.
+ expect(resolveTabs(['wake', 'reply'], { hasConfig: false })).toEqual([
+ 'connect',
+ 'wake',
+ 'reply',
+ ]);
+ // No wake settings on this platform: it never judges a message.
+ expect(resolveTabs(['reply'], { hasConfig: true })).toEqual(['connect', 'reply']);
+ });
});
describe('defaultTab', () => {
@@ -41,6 +58,10 @@ describe('defaultTab', () => {
expect(defaultTab(['connect', 'reply'], true)).toBe('reply');
});
+ it('never opens on the records tab by itself', () => {
+ expect(defaultTab(['connect', 'wake', 'records'], true)).toBe('wake');
+ });
+
it('stays on connect when there is nothing else', () => {
expect(defaultTab(['connect'], true)).toBe('connect');
});
@@ -96,4 +117,8 @@ describe('footerSaveHidden', () => {
// A saved bot: the steps fold away and have no save step.
expect(footerSaveHidden({ activeTab: 'connect', hasConfig: true, stepSave: true })).toBe(false);
});
+
+ it('has nothing to save on the records tab', () => {
+ expect(footerSaveHidden({ activeTab: 'records', hasConfig: true, stepSave: false })).toBe(true);
+ });
});
diff --git a/src/features/AgentChannel/PlatformDetail/channelTabs.ts b/src/features/AgentChannel/PlatformDetail/channelTabs.ts
index 39873c775d1..2692451cf76 100644
--- a/src/features/AgentChannel/PlatformDetail/channelTabs.ts
+++ b/src/features/AgentChannel/PlatformDetail/channelTabs.ts
@@ -5,22 +5,46 @@ import { getSchemaFields, type SettingsGroupKey } from './settingsGroups';
/**
* The page is one tab per question a person asks, in the order they ask them:
- * how is it connected, who may use it, when may it speak up unprompted, how does it reply, what else is there.
+ * how is it connected, who may use it, when may it speak up unprompted, how does it reply, what else is there,
+ * and last, what did it actually decide.
*/
-export type ChannelTab = 'access' | 'advanced' | 'connect' | 'reply' | 'wake';
+export type ChannelTab = SettingsGroupKey | 'records';
-export const TAB_ORDER: ChannelTab[] = ['connect', 'access', 'wake', 'reply', 'advanced'];
+export const TAB_ORDER: ChannelTab[] = [
+ 'connect',
+ 'access',
+ 'wake',
+ 'reply',
+ 'advanced',
+ 'records',
+];
-/** Connecting always exists; the other tabs exist when the platform has settings for them. */
-export const resolveTabs = (settingsGroupKeys: SettingsGroupKey[]): ChannelTab[] =>
- TAB_ORDER.filter((tab) => tab === 'connect' || settingsGroupKeys.includes(tab));
+/**
+ * Tabs that show a history instead of settings: no fields, no dirty state, no Save. Their content
+ * mounts only once opened.
+ */
+export const isRecordTab = (tab: ChannelTab): tab is 'records' => tab === 'records';
+
+/**
+ * Connecting always exists; the settings tabs exist when the platform has settings for them. Wake
+ * records exist for a saved bot whose platform can wake on its own: before that nothing was judged.
+ */
+export const resolveTabs = (
+ settingsGroupKeys: SettingsGroupKey[],
+ { hasConfig = false }: { hasConfig?: boolean } = {},
+): ChannelTab[] =>
+ TAB_ORDER.filter((tab) =>
+ isRecordTab(tab)
+ ? hasConfig && settingsGroupKeys.includes('wake')
+ : tab === 'connect' || settingsGroupKeys.includes(tab),
+ );
/**
* A new channel starts on connecting, since nothing else works before it. A
* saved one opens on the first settings tab: the connection is done.
*/
export const defaultTab = (tabs: ChannelTab[], hasConfig: boolean): ChannelTab =>
- (hasConfig ? tabs.find((tab) => tab !== 'connect') : undefined) ?? 'connect';
+ (hasConfig ? tabs.find((tab) => tab !== 'connect' && !isRecordTab(tab)) : undefined) ?? 'connect';
export interface ChannelValues {
applicationId?: string;
@@ -52,7 +76,8 @@ export const tabsWithIssues = (values: ChannelValues, schema: FieldSchema[]): Ch
/**
* Whether the bottom bar leaves out its Save button. While a bot is being set up, the Connect
* tab's steps end with a "Save and connect" step of their own; the bar repeating it below reads as
- * a second, different action. Other tabs have no such step, so the bar keeps it there.
+ * a second, different action. Other settings tabs have no such step, so the bar keeps it there; a
+ * record tab has nothing to save.
*/
export const footerSaveHidden = ({
activeTab,
@@ -63,4 +88,4 @@ export const footerSaveHidden = ({
hasConfig: boolean;
/** The platform's setup steps include the save step. */
stepSave: boolean;
-}): boolean => !hasConfig && stepSave && activeTab === 'connect';
+}): boolean => isRecordTab(activeTab) || (!hasConfig && stepSave && activeTab === 'connect');
diff --git a/src/features/AgentChannel/PlatformDetail/index.tsx b/src/features/AgentChannel/PlatformDetail/index.tsx
index 12bde0e6541..031f353175b 100644
--- a/src/features/AgentChannel/PlatformDetail/index.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.tsx
@@ -39,6 +39,7 @@ import {
type ChannelTab,
defaultTab,
footerSaveHidden,
+ isRecordTab,
resolveTabs,
tabsWithIssues,
} from './channelTabs';
@@ -65,6 +66,7 @@ import {
tabOfModule,
} from './saveModules';
import { getSchemaFields, groupSettingsFields, REPLY_KEYS } from './settingsGroups';
+import { useFoldPreviewOnRecords } from './useFoldPreviewOnRecords';
import { useNarrowLayout } from './useNarrowLayout';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -271,11 +273,13 @@ const PlatformDetail = memo<PlatformDetailProps>(
groupSettingsFields(getSchemaFields(platformDef.schema, 'settings', featureFlags)).map(
(group) => group.key,
),
+ { hasConfig: !!currentConfig },
),
- [featureFlags, platformDef.schema],
+ [featureFlags, platformDef.schema, currentConfig],
);
const activeTab =
pickedTab && tabs.includes(pickedTab) ? pickedTab : defaultTab(tabs, !!currentConfig);
+ useFoldPreviewOnRecords(activeTab, previewOpen, setPreviewOpen);
// The blocks the page saves one by one. A platform with its own credential body (WeChat)
// connects through its own flow, so it has no credentials block.
const saveModules = useMemo(() => {
@@ -1036,6 +1040,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
currentConfig={currentConfig}
form={form}
hasConfig={!!currentConfig}
+ hideSetupHints={isRecordTab(activeTab)}
platformDef={platformDef}
saveResult={saveResult}
testResult={testResult}
diff --git a/src/features/AgentChannel/PlatformDetail/useFoldPreviewOnRecords.test.ts b/src/features/AgentChannel/PlatformDetail/useFoldPreviewOnRecords.test.ts
new file mode 100644
index 00000000000..972a245b9a8
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/useFoldPreviewOnRecords.test.ts
@@ -0,0 +1,52 @@
+import { act, renderHook } from '@testing-library/react';
+import { useState } from 'react';
+import { describe, expect, it } from 'vitest';
+
+import type { ChannelTab } from './channelTabs';
+import { useFoldPreviewOnRecords } from './useFoldPreviewOnRecords';
+
+const setup = (initialOpen: boolean) =>
+ renderHook(
+ ({ tab }: { tab: ChannelTab }) => {
+ const [open, setOpen] = useState(initialOpen);
+ useFoldPreviewOnRecords(tab, open, setOpen);
+ return { open, setOpen };
+ },
+ { initialProps: { tab: 'wake' as ChannelTab } },
+ );
+
+describe('useFoldPreviewOnRecords', () => {
+ it('folds the preview on the records tab and restores it on leaving', () => {
+ const { result, rerender } = setup(true);
+
+ rerender({ tab: 'records' });
+ expect(result.current.open).toBe(false);
+
+ rerender({ tab: 'reply' });
+ expect(result.current.open).toBe(true);
+ });
+
+ it('keeps a preview that was already folded folded', () => {
+ const { result, rerender } = setup(false);
+
+ rerender({ tab: 'records' });
+ rerender({ tab: 'wake' });
+ expect(result.current.open).toBe(false);
+ });
+
+ it('lets the preview be opened by hand on the records tab', () => {
+ const { result, rerender } = setup(true);
+
+ rerender({ tab: 'records' });
+ act(() => result.current.setOpen(true));
+ expect(result.current.open).toBe(true);
+ });
+
+ it('leaves the preview alone between settings tabs', () => {
+ const { result, rerender } = setup(true);
+
+ act(() => result.current.setOpen(false));
+ rerender({ tab: 'reply' });
+ expect(result.current.open).toBe(false);
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/useFoldPreviewOnRecords.ts b/src/features/AgentChannel/PlatformDetail/useFoldPreviewOnRecords.ts
new file mode 100644
index 00000000000..ccf4f3591b9
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/useFoldPreviewOnRecords.ts
@@ -0,0 +1,30 @@
+import { type Dispatch, type SetStateAction, useEffect, useRef } from 'react';
+
+import { type ChannelTab, isRecordTab } from './channelTabs';
+
+/**
+ * The chat preview shows how the settings behave; the wake records are a wide table with nothing
+ * to preview. Opening the records tab folds the preview away, and leaving it puts the preview back
+ * the way it was. Opening the preview by hand on the records tab is kept until the tab is left.
+ */
+export const useFoldPreviewOnRecords = (
+ activeTab: ChannelTab,
+ previewOpen: boolean,
+ setPreviewOpen: Dispatch<SetStateAction<boolean>>,
+) => {
+ const openRef = useRef(previewOpen);
+ openRef.current = previewOpen;
+ // What the preview was before the records tab folded it; unset while not folded by it.
+ const restoreRef = useRef<boolean>(undefined);
+ const onRecords = isRecordTab(activeTab);
+
+ useEffect(() => {
+ if (onRecords) {
+ restoreRef.current = openRef.current;
+ setPreviewOpen(false);
+ } else if (restoreRef.current !== undefined) {
+ setPreviewOpen(restoreRef.current);
+ restoreRef.current = undefined;
+ }
+ }, [onRecords, setPreviewOpen]);
+};
diff --git a/src/features/AgentChannel/WakeRecords/MarkButtons.tsx b/src/features/AgentChannel/WakeRecords/MarkButtons.tsx
new file mode 100644
index 00000000000..86ae3d398ad
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/MarkButtons.tsx
@@ -0,0 +1,114 @@
+'use client';
+
+import {
+ BOT_WAKE_USER_LABELS_BY_OUTCOME,
+ type BotWakeUserLabel,
+ type SignalDecisionOutcome,
+} from '@lobechat/types';
+import { ActionIcon, DropdownMenu, Flexbox, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Check, X } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = stylex.create({
+ right: { color: cssVar.colorSuccess },
+ wrong: { color: cssVar.colorError },
+});
+
+type WrongLabel = Exclude<BotWakeUserLabel, 'correct'>;
+
+interface MarkButtonsProps {
+ current?: BotWakeUserLabel;
+ disabled?: boolean;
+ /** `null` takes the current mark back. */
+ onMark: (label: BotWakeUserLabel | null) => Promise<void>;
+ outcome: SignalDecisionOutcome;
+}
+
+/**
+ * Whether the bot judged this message right: ✓ right, ✗ wrong. A wake that was wrong should not
+ * have woken, a skip that was wrong should have; a deferred message can be wrong either way, so its
+ * ✗ asks which. The current mark is coloured; clicking it again takes it back.
+ */
+export const MarkButtons = ({ current, disabled, onMark, outcome }: MarkButtonsProps) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+ const [pending, setPending] = useState(false);
+ const wrongChoices = (BOT_WAKE_USER_LABELS_BY_OUTCOME[outcome] ?? []).filter(
+ (label): label is WrongLabel => label !== 'correct',
+ );
+ const wrongCurrent = current && current !== 'correct' ? current : undefined;
+
+ const mark = async (label: BotWakeUserLabel) => {
+ if (pending) return;
+ setPending(true);
+ try {
+ await onMark(label === current ? null : label);
+ } catch {
+ toast.error(t('channel.records.mark.failed'));
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const hint = (label: BotWakeUserLabel) =>
+ current === label
+ ? `${t(`channel.records.mark.${label}`)} · ${t('channel.records.mark.undo')}`
+ : t(`channel.records.mark.${label}`);
+
+ const right = (
+ <ActionIcon
+ active={current === 'correct'}
+ aria-label={t('channel.records.mark.correct')}
+ aria-pressed={current === 'correct'}
+ disabled={disabled || pending}
+ icon={Check}
+ size={'small'}
+ title={hint('correct')}
+ onClick={() => void mark('correct')}
+ {...(current === 'correct' && stylex.props(styles.right))}
+ />
+ );
+
+ const wrongIcon = (label: WrongLabel | undefined, onClick?: () => void) => (
+ <ActionIcon
+ active={!!wrongCurrent}
+ aria-label={label ? t(`channel.records.mark.${label}`) : t('channel.records.mark.wrong')}
+ aria-pressed={!!wrongCurrent}
+ disabled={disabled || pending}
+ icon={X}
+ size={'small'}
+ title={label ? hint(label) : t('channel.records.mark.wrong')}
+ onClick={onClick}
+ {...(wrongCurrent && stylex.props(styles.wrong))}
+ />
+ );
+
+ // One way to be wrong (a wake or a skip): ✗ marks it directly.
+ // Two ways (a deferred message): ✗ takes back a current wrong mark, or asks which way.
+ const wrong =
+ wrongChoices.length === 1 ? (
+ wrongIcon(wrongChoices[0], () => void mark(wrongChoices[0]))
+ ) : wrongCurrent ? (
+ wrongIcon(wrongCurrent, () => void mark(wrongCurrent))
+ ) : (
+ <DropdownMenu
+ items={wrongChoices.map((label) => ({
+ key: label,
+ label: t(`channel.records.mark.${label}`),
+ onClick: () => void mark(label),
+ }))}
+ >
+ {wrongIcon(undefined)}
+ </DropdownMenu>
+ );
+
+ return (
+ <Flexbox horizontal gap={4}>
+ {right}
+ {wrong}
+ </Flexbox>
+ );
+};
diff --git a/src/features/AgentChannel/WakeRecords/RecordTable.tsx b/src/features/AgentChannel/WakeRecords/RecordTable.tsx
new file mode 100644
index 00000000000..3edec152dfe
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/RecordTable.tsx
@@ -0,0 +1,219 @@
+'use client';
+
+import type { BotWakeDecisionItem, BotWakeUserLabel } from '@lobechat/types';
+import { ActionIcon, Flexbox, Table, type TableColumn, Text, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import dayjs from 'dayjs';
+import { ExternalLink } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { MarkButtons } from './MarkButtons';
+import { platformMessageUrl } from './messageLink';
+
+const HOVER = '@media (hover: hover)';
+
+const OUTCOME_DOT: Record<string, string> = {
+ defer: cssVar.colorInfo,
+ skip: cssVar.colorTextQuaternary,
+ wake: cssVar.colorSuccess,
+};
+
+const styles = stylex.create({
+ dot: (color: string) => ({
+ backgroundColor: color,
+ borderRadius: '50%',
+ flexShrink: 0,
+ height: 6,
+ width: 6,
+ }),
+ // Shown on a pointer device only while the row is hovered or focused; always on touch.
+ link: {
+ opacity: {
+ default: 1,
+ [HOVER]: {
+ default: 0,
+ [stylex.when.ancestor(':hover')]: 1,
+ [stylex.when.ancestor(':focus-within')]: 1,
+ },
+ },
+ },
+ score: {
+ fontVariantNumeric: 'tabular-nums',
+ },
+ preview: {
+ flex: '1',
+ minWidth: 0,
+ overflowWrap: 'anywhere',
+ whiteSpace: 'pre-wrap',
+ },
+});
+
+interface RecordTableProps {
+ disabled?: boolean;
+ items: BotWakeDecisionItem[];
+ onMark: (decisionId: string, label: BotWakeUserLabel | null) => Promise<void>;
+}
+
+/**
+ * One row per judged message: when, what it said (with a link to it on the platform, shown on
+ * hover), what the bot did, the model score behind it, why, and the owner's ✓ / ✗ mark.
+ */
+export const RecordTable = ({ disabled, items, onMark }: RecordTableProps) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string, options?: Record<string, unknown>) => string;
+ // The pipeline's vocabulary grows; a reason this build has no copy for shows as recorded.
+ const translate = (group: string, value: string) =>
+ t(`channel.records.${group}.${value}`, { defaultValue: value });
+
+ const columns: TableColumn<BotWakeDecisionItem>[] = [
+ {
+ dataIndex: 'createdAt',
+ key: 'time',
+ render: (_, item) => {
+ const at = dayjs(item.createdAt);
+ return (
+ <Tooltip title={at.format('YYYY-MM-DD HH:mm:ss')}>
+ <Text fontSize={12} style={{ whiteSpace: 'nowrap' }} type={'secondary'}>
+ {at.format('MM-DD HH:mm')}
+ </Text>
+ </Tooltip>
+ );
+ },
+ title: t('channel.records.column.time'),
+ width: 96,
+ },
+ {
+ key: 'message',
+ render: (_, item) => {
+ const url = platformMessageUrl(item.address);
+ return (
+ <Flexbox horizontal align={'center'} gap={4}>
+ {item.text ? (
+ <Text
+ ellipsis={{ rows: 2, tooltipWhenOverflow: true }}
+ {...stylex.props(styles.preview)}
+ >
+ {item.text}
+ </Text>
+ ) : (
+ <Tooltip title={t('channel.records.purgedHint')}>
+ <Text italic type={'secondary'} {...stylex.props(styles.preview)}>
+ {t('channel.records.purged')}
+ </Text>
+ </Tooltip>
+ )}
+ {url && (
+ <a
+ aria-label={t('channel.records.openMessage')}
+ href={url}
+ {...stylex.props(styles.link)}
+ rel={'noopener noreferrer'}
+ target={'_blank'}
+ >
+ <ActionIcon
+ icon={ExternalLink}
+ size={'small'}
+ title={t('channel.records.openMessage')}
+ />
+ </a>
+ )}
+ </Flexbox>
+ );
+ },
+ title: t('channel.records.column.message'),
+ },
+ {
+ key: 'outcome',
+ render: (_, item) => (
+ <Flexbox horizontal align={'center'} gap={6}>
+ <span
+ {...stylex.props(styles.dot(OUTCOME_DOT[item.outcome] ?? cssVar.colorTextQuaternary))}
+ />
+ <Text fontSize={12} style={{ whiteSpace: 'nowrap' }}>
+ {translate('outcome', item.outcome)}
+ {item.followup && (
+ <Text as={'span'} fontSize={12} type={'secondary'}>
+ {` · ${t('channel.records.proactive')}`}
+ </Text>
+ )}
+ </Text>
+ </Flexbox>
+ ),
+ title: t('channel.records.column.outcome'),
+ width: 116,
+ },
+ {
+ align: 'right',
+ key: 'score',
+ render: (_, item) =>
+ item.judge ? (
+ <Tooltip
+ title={t('channel.records.judge.hint', {
+ judge: t(`channel.records.judge.${item.judge.kind}`),
+ verdict: t(`channel.records.judge.${item.judge.verdict}`, {
+ defaultValue: item.judge.verdict,
+ }),
+ })}
+ >
+ <Text fontSize={12} {...stylex.props(styles.score)}>
+ {item.judge.score.toFixed(2)}
+ </Text>
+ </Tooltip>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ --
+ </Text>
+ ),
+ title: t('channel.records.column.score'),
+ width: 72,
+ },
+ {
+ key: 'reason',
+ render: (_, item) => (
+ <Flexbox gap={2}>
+ <Text fontSize={12}>
+ {item.finalReason ? translate('reason', item.finalReason) : '--'}
+ </Text>
+ {item.agentLabel && (
+ <Text fontSize={12} type={'secondary'}>
+ {item.agentLabel.reason
+ ? t('channel.records.silencedWithReason', {
+ reason: translate('noReplyReason', item.agentLabel.reason),
+ })
+ : t('channel.records.silenced')}
+ </Text>
+ )}
+ </Flexbox>
+ ),
+ title: t('channel.records.column.reason'),
+ width: 208,
+ },
+ {
+ align: 'center',
+ key: 'mark',
+ render: (_, item) => (
+ <MarkButtons
+ current={item.userLabel?.label as BotWakeUserLabel | undefined}
+ disabled={disabled}
+ outcome={item.outcome}
+ onMark={(label) => onMark(item.id, label)}
+ />
+ ),
+ title: t('channel.records.column.mark'),
+ width: 84,
+ },
+ ];
+
+ return (
+ <Table<BotWakeDecisionItem>
+ columns={columns}
+ dataSource={items}
+ pagination={false}
+ rowKey={'id'}
+ size={'small'}
+ // Each row marks itself so the message link can show on hovering it.
+ onRow={() => stylex.props(stylex.defaultMarker())}
+ />
+ );
+};
diff --git a/src/features/AgentChannel/WakeRecords/Summary.tsx b/src/features/AgentChannel/WakeRecords/Summary.tsx
new file mode 100644
index 00000000000..1737b95d6b1
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/Summary.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { Flexbox, Skeleton, Text, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { formatShortenNumber } from '@/utils/format';
+
+import { useWakeSummary } from './useWakeRecords';
+
+const styles = stylex.create({
+ cell: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderRadius: 8,
+ flex: '1',
+ minWidth: 104,
+ paddingBlock: 10,
+ paddingInline: 12,
+ },
+});
+
+const METRICS = ['wake', 'skip', 'defer', 'followupWakes', 'marked'] as const;
+type Metric = (typeof METRICS)[number];
+
+const LABEL_KEY: Record<Metric, string> = {
+ defer: 'channel.records.summary.defer',
+ followupWakes: 'channel.records.summary.followup',
+ marked: 'channel.records.summary.marked',
+ skip: 'channel.records.summary.skip',
+ wake: 'channel.records.summary.wake',
+};
+
+/** Last-30-days counts: what the bot did with the messages it judged, and how many you marked. */
+export const Summary = ({ botId }: { botId: string }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+ const { data, error, isLoading, mutate } = useWakeSummary(botId);
+
+ return (
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {METRICS.map((metric) => (
+ <Flexbox gap={2} key={metric} {...stylex.props(styles.cell)}>
+ {metric === 'followupWakes' ? (
+ <Tooltip title={t('channel.records.summary.followupHint')}>
+ <Text fontSize={12} type={'secondary'}>
+ {t(LABEL_KEY[metric])}
+ </Text>
+ </Tooltip>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {t(LABEL_KEY[metric])}
+ </Text>
+ )}
+ {data ? (
+ <Text fontSize={20} weight={500}>
+ {formatShortenNumber(data[metric])}
+ </Text>
+ ) : isLoading || !error ? (
+ <Skeleton height={28} radius={6} width={48} />
+ ) : (
+ <AsyncError error={error} variant={'metric'} onRetry={() => void mutate()} />
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ );
+};
diff --git a/src/features/AgentChannel/WakeRecords/index.tsx b/src/features/AgentChannel/WakeRecords/index.tsx
new file mode 100644
index 00000000000..2a54891c48b
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/index.tsx
@@ -0,0 +1,180 @@
+'use client';
+
+import type { SignalDecisionOutcome } from '@lobechat/types';
+import { ActionIcon, Button, Empty, Flexbox, Segmented, Skeleton, Switch, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { History, RotateCw } from 'lucide-react';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import AsyncError from '@/components/AsyncError';
+import { mutate as mutateGlobal } from '@/libs/swr';
+import { botWakeKeys } from '@/libs/swr/keys';
+
+import { RecordTable } from './RecordTable';
+import { Summary } from './Summary';
+import { useRefreshOnReturn } from './useRefreshOnReturn';
+import { useWakeDecisions, type WakeRecordFilters } from './useWakeRecords';
+
+/** Matches `SCOPE_READ_DEFAULT_DAYS` on the server; the summary reports it too. */
+const WINDOW_DAYS = 30;
+
+const OUTCOMES = ['wake', 'skip', 'defer'] as const;
+const ALL = 'all';
+
+const NO_FILTERS: WakeRecordFilters = { followupOnly: false, unmarkedOnly: false };
+
+const styles = stylex.create({
+ list: {
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: 8,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+});
+
+const ListSkeleton = () => (
+ <Flexbox {...stylex.props(styles.list)}>
+ {Array.from({ length: 4 }, (_, i) => (
+ <Flexbox gap={8} key={i} padding={16}>
+ <Skeleton height={20} width={160} />
+ <Skeleton.Text rows={2} />
+ </Flexbox>
+ ))}
+ </Flexbox>
+);
+
+interface WakeRecordsProps {
+ /** The tab is showing. The panel stays mounted while hidden; showing it again refetches. */
+ active?: boolean;
+ /** `agent_bot_providers.id` of a saved bot. */
+ botId: string;
+ /** The caller cannot write (a viewer, or a plan gate): marks are read-only. */
+ disabled?: boolean;
+}
+
+/**
+ * Every message the bot judged lately, what it did and why, and a one-click mark of whether that
+ * was right. Read-only history: nothing here takes part in the settings form or its Save.
+ */
+export const WakeRecords = ({ active = true, botId, disabled }: WakeRecordsProps) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string, options?: Record<string, unknown>) => string;
+ const [filters, setFilters] = useState<WakeRecordFilters>(NO_FILTERS);
+ const { data, error, isLoading, isValidating, markDecision, mutate, setSize, size } =
+ useWakeDecisions(botId, filters);
+
+ // New decisions arrive while the owner is elsewhere (testing the bot): refetch the loaded pages
+ // and the summary on coming back, and on demand.
+ const refresh = useCallback(() => {
+ void mutate();
+ void mutateGlobal(botWakeKeys.summary(botId));
+ }, [botId, mutate]);
+ useRefreshOnReturn(active, refresh);
+
+ const items = data?.flatMap((page) => page.items) ?? [];
+ const filtered = filters.outcome || filters.followupOnly || filters.unmarkedOnly;
+ const hasMore = !!data?.at(-1)?.nextCursor;
+ // A next page was asked for and has not arrived (or failed) yet.
+ const loadingMore = !!data && data.length < size;
+ const loadMoreFailed = loadingMore && !!error && !isValidating;
+
+ return (
+ <Flexbox gap={16}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('channel.records.intro', { days: WINDOW_DAYS })}
+ </Text>
+ <Summary botId={botId} />
+ <Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>
+ <Segmented
+ size={'small'}
+ value={filters.outcome ?? ALL}
+ options={[
+ { label: t('channel.records.filter.all'), value: ALL },
+ ...OUTCOMES.map((outcome) => ({
+ label: t(`channel.records.outcome.${outcome}`),
+ value: outcome,
+ })),
+ ]}
+ onChange={(value) =>
+ setFilters((prev) => ({
+ ...prev,
+ outcome: value === ALL ? undefined : (value as SignalDecisionOutcome),
+ }))
+ }
+ />
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Switch
+ checked={filters.followupOnly}
+ size={'small'}
+ onChange={(checked) => setFilters((prev) => ({ ...prev, followupOnly: checked }))}
+ />
+ <Text>{t('channel.records.filter.followupOnly')}</Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Switch
+ checked={filters.unmarkedOnly}
+ size={'small'}
+ onChange={(checked) => setFilters((prev) => ({ ...prev, unmarkedOnly: checked }))}
+ />
+ <Text>{t('channel.records.filter.unmarkedOnly')}</Text>
+ </Flexbox>
+ <ActionIcon
+ aria-label={t('channel.records.refresh')}
+ icon={RotateCw}
+ loading={isValidating && !isLoading}
+ size={'small'}
+ style={{ marginInlineStart: 'auto' }}
+ title={t('channel.records.refresh')}
+ onClick={refresh}
+ />
+ </Flexbox>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={items.length === 0}
+ isLoading={isLoading}
+ loading={<ListSkeleton />}
+ empty={
+ filtered ? (
+ <Empty
+ title={t('channel.records.emptyFiltered.title')}
+ action={
+ <Button onClick={() => setFilters(NO_FILTERS)}>
+ {t('channel.records.emptyFiltered.clear')}
+ </Button>
+ }
+ />
+ ) : (
+ <Empty
+ description={t('channel.records.empty.desc')}
+ icon={History}
+ title={t('channel.records.empty.title')}
+ />
+ )
+ }
+ onRetry={() => void mutate()}
+ >
+ <RecordTable disabled={disabled} items={items} onMark={markDecision} />
+ {loadMoreFailed ? (
+ <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />
+ ) : hasMore || loadingMore ? (
+ <Flexbox horizontal justify={'center'}>
+ <Button loading={loadingMore} onClick={() => void setSize(size + 1)}>
+ {t('channel.records.loadMore')}
+ </Button>
+ </Flexbox>
+ ) : (
+ items.length > 0 && (
+ <Text align={'center'} fontSize={12} type={'secondary'}>
+ {t('channel.records.end', { days: WINDOW_DAYS })}
+ </Text>
+ )
+ )}
+ </AsyncBoundary>
+ </Flexbox>
+ );
+};
diff --git a/src/features/AgentChannel/WakeRecords/messageLink.test.ts b/src/features/AgentChannel/WakeRecords/messageLink.test.ts
new file mode 100644
index 00000000000..6f5026dc62d
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/messageLink.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { platformMessageUrl } from './messageLink';
+
+describe('platformMessageUrl', () => {
+ it('links a Discord channel message', () => {
+ expect(
+ platformMessageUrl({
+ messageId: '333',
+ platform: 'discord',
+ platformThreadId: 'discord:111:222',
+ }),
+ ).toBe('https://discord.com/channels/111/222/333');
+ });
+
+ it('opens a message in a thread inside the thread', () => {
+ expect(
+ platformMessageUrl({
+ messageId: '444',
+ platform: 'discord',
+ platformThreadId: 'discord:111:222:333',
+ }),
+ ).toBe('https://discord.com/channels/111/333/444');
+ });
+
+ it('links a direct message under @me', () => {
+ expect(
+ platformMessageUrl({
+ messageId: '9',
+ platform: 'discord',
+ platformThreadId: 'discord:@me:555',
+ }),
+ ).toBe('https://discord.com/channels/@me/555/9');
+ });
+
+ it.each([
+ ['another platform', { messageId: '1', platform: 'telegram', platformThreadId: 'telegram:42' }],
+ ['no message id', { platform: 'discord', platformThreadId: 'discord:111:222' }],
+ ['a short thread id', { messageId: '1', platform: 'discord', platformThreadId: 'discord:111' }],
+ ])('has no link for %s', (_case, address) => {
+ expect(platformMessageUrl(address as Record<string, string>)).toBeUndefined();
+ });
+
+ it('has no link without an address', () => {
+ expect(platformMessageUrl(null)).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentChannel/WakeRecords/messageLink.ts b/src/features/AgentChannel/WakeRecords/messageLink.ts
new file mode 100644
index 00000000000..c678518dba8
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/messageLink.ts
@@ -0,0 +1,23 @@
+/**
+ * The web link that opens the judged message on its platform, from the address the signal kept
+ * (`signals.metadata.address`, which outlives the payload purge).
+ *
+ * Returns:
+ * - Discord: `https://discord.com/channels/<guild | @me>/<thread | channel>/<message>`; a message
+ * in a thread opens in the thread
+ * - `undefined` for other platforms (no stable web link) and for an incomplete address
+ */
+export const platformMessageUrl = (
+ address: Record<string, string> | null | undefined,
+): string | undefined => {
+ if (!address?.messageId || !address.platformThreadId) return undefined;
+
+ if (address.platform === 'discord') {
+ const [prefix, guildId, channelId, threadId] = address.platformThreadId.split(':');
+ if (prefix !== 'discord' || !guildId || !channelId) return undefined;
+
+ return `https://discord.com/channels/${guildId}/${threadId || channelId}/${address.messageId}`;
+ }
+
+ return undefined;
+};
diff --git a/src/features/AgentChannel/WakeRecords/useRefreshOnReturn.test.ts b/src/features/AgentChannel/WakeRecords/useRefreshOnReturn.test.ts
new file mode 100644
index 00000000000..0a3deb526d6
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/useRefreshOnReturn.test.ts
@@ -0,0 +1,31 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useRefreshOnReturn } from './useRefreshOnReturn';
+
+describe('useRefreshOnReturn', () => {
+ it('does not refresh on first mount: the first fetch is already running', () => {
+ const refresh = vi.fn();
+ renderHook(() => useRefreshOnReturn(true, refresh));
+
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
+ it('refreshes each time the panel is shown again', () => {
+ const refresh = vi.fn();
+ const { rerender } = renderHook(({ active }) => useRefreshOnReturn(active, refresh), {
+ initialProps: { active: true },
+ });
+
+ rerender({ active: false });
+ expect(refresh).not.toHaveBeenCalled();
+
+ rerender({ active: true });
+ expect(refresh).toHaveBeenCalledTimes(1);
+
+ rerender({ active: true });
+ rerender({ active: false });
+ rerender({ active: true });
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/features/AgentChannel/WakeRecords/useRefreshOnReturn.ts b/src/features/AgentChannel/WakeRecords/useRefreshOnReturn.ts
new file mode 100644
index 00000000000..44bdba0b62d
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/useRefreshOnReturn.ts
@@ -0,0 +1,17 @@
+import { useEffect, useRef } from 'react';
+
+/**
+ * Calls `refresh` each time `active` turns true again after the first time. The records panel
+ * stays mounted while hidden, so without this, messages the bot judged meanwhile (the owner was on
+ * another tab testing it) would not appear when they come back.
+ */
+export const useRefreshOnReturn = (active: boolean, refresh: () => void) => {
+ const refreshRef = useRef(refresh);
+ refreshRef.current = refresh;
+ const wasActive = useRef(active);
+
+ useEffect(() => {
+ if (active && !wasActive.current) refreshRef.current();
+ wasActive.current = active;
+ }, [active]);
+};
diff --git a/src/features/AgentChannel/WakeRecords/useWakeRecords.test.ts b/src/features/AgentChannel/WakeRecords/useWakeRecords.test.ts
new file mode 100644
index 00000000000..affbee9f97a
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/useWakeRecords.test.ts
@@ -0,0 +1,37 @@
+import type { BotWakeDecisionPage } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { withUserLabel } from './useWakeRecords';
+
+vi.mock('@/services/agentBotProvider', () => ({ agentBotProviderService: {} }));
+
+const item = (id: string, userLabel: any = null) =>
+ ({ id, outcome: 'wake', userLabel }) as BotWakeDecisionPage['items'][number];
+
+describe('withUserLabel', () => {
+ const pages = [
+ { items: [item('a'), item('b')], nextCursor: { createdAt: 'x', id: 'b' } },
+ { items: [item('c', { label: 'correct' })] },
+ ] as BotWakeDecisionPage[];
+
+ it('sets the mark on the one decision across pages and leaves the rest', () => {
+ const mark = { createdAt: new Date(), label: 'false_wake' as const, note: undefined };
+
+ const next = withUserLabel(pages, 'c', mark)!;
+
+ expect(next[1].items[0].userLabel).toBe(mark);
+ expect(next[0].items.map((i) => i.userLabel)).toEqual([null, null]);
+ expect(next[0].nextCursor).toEqual(pages[0].nextCursor);
+ });
+
+ it('puts the previous mark back on rollback', () => {
+ const marked = withUserLabel(pages, 'c', null)!;
+
+ expect(marked[1].items[0].userLabel).toBeNull();
+ expect(pages[1].items[0].userLabel).toEqual({ label: 'correct' });
+ });
+
+ it('leaves an unloaded list alone', () => {
+ expect(withUserLabel(undefined, 'a', null)).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentChannel/WakeRecords/useWakeRecords.ts b/src/features/AgentChannel/WakeRecords/useWakeRecords.ts
new file mode 100644
index 00000000000..cc313cc732a
--- /dev/null
+++ b/src/features/AgentChannel/WakeRecords/useWakeRecords.ts
@@ -0,0 +1,118 @@
+import type {
+ BotWakeDecisionItem,
+ BotWakeDecisionPage,
+ BotWakeUserLabel,
+ SignalDecisionOutcome,
+} from '@lobechat/types';
+import { useCallback } from 'react';
+import useSWRInfinite from 'swr/infinite';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { botWakeKeys } from '@/libs/swr/keys';
+import { agentBotProviderService } from '@/services/agentBotProvider';
+
+export const WAKE_RECORDS_PAGE_SIZE = 20;
+
+export interface WakeRecordFilters {
+ followupOnly: boolean;
+ outcome?: SignalDecisionOutcome;
+ unmarkedOnly: boolean;
+}
+
+type DecisionsKey = ReturnType<typeof botWakeKeys.decisions>;
+
+/** The page list with `decisionId`'s mark replaced; `undefined` pages stay as they are. */
+export const withUserLabel = (
+ pages: BotWakeDecisionPage[] | undefined,
+ decisionId: string,
+ userLabel: BotWakeDecisionItem['userLabel'],
+): BotWakeDecisionPage[] | undefined =>
+ pages?.map((page) => ({
+ ...page,
+ items: page.items.map((item) => (item.id === decisionId ? { ...item, userLabel } : item)),
+ }));
+
+/** Last-30-days counts for one bot. */
+export const useWakeSummary = (botId: string) =>
+ useClientDataSWR(botWakeKeys.summary(botId), () => agentBotProviderService.getWakeSummary(botId));
+
+/**
+ * One bot's decisions, a page at a time. Pages live in this hook's own SWR cache, which a global
+ * key-filter `mutate` cannot reach (SWR skips `$inf$` keys), so marks go through `markDecision`.
+ */
+export const useWakeDecisions = (botId: string, filters: WakeRecordFilters) => {
+ const workspaceId = useActiveWorkspaceId();
+ const { followupOnly, outcome, unmarkedOnly } = filters;
+
+ const getKey = useCallback(
+ (_index: number, previous: BotWakeDecisionPage | null): DecisionsKey | null => {
+ if (previous && !previous.nextCursor) return null;
+
+ return botWakeKeys.decisions(
+ workspaceId,
+ botId,
+ { followupOnly, outcome, unmarkedOnly },
+ previous?.nextCursor,
+ );
+ },
+ [botId, followupOnly, outcome, unmarkedOnly, workspaceId],
+ );
+
+ const swr = useSWRInfinite(
+ getKey,
+ ([, , id, keyOutcome, keyFollowup, keyUnmarked, cursorAt, cursorId]) =>
+ agentBotProviderService.listWakeDecisions({
+ botId: id as string,
+ cursor: cursorAt ? { createdAt: cursorAt as string, id: cursorId as string } : undefined,
+ followupOnly: (keyFollowup as boolean) || undefined,
+ limit: WAKE_RECORDS_PAGE_SIZE,
+ outcome: (keyOutcome as SignalDecisionOutcome | null) ?? undefined,
+ unmarkedOnly: (keyUnmarked as boolean) || undefined,
+ }),
+ { revalidateFirstPage: false, revalidateOnFocus: false },
+ );
+
+ const { data: pages, mutate: mutatePages } = swr;
+
+ /**
+ * Shows the mark at once and saves it; `null` takes the mark back. A failed save puts the
+ * previous mark back and rethrows, so the caller can say so. The summary refreshes after a save.
+ */
+ const markDecision = useCallback(
+ async (decisionId: string, label: BotWakeUserLabel | null) => {
+ const previous = pages
+ ?.flatMap((page) => page.items)
+ .find((item) => item.id === decisionId)?.userLabel;
+
+ await mutatePages(
+ (current) =>
+ withUserLabel(
+ current,
+ decisionId,
+ label ? { createdAt: new Date(), label, note: undefined } : null,
+ ),
+ {
+ revalidate: false,
+ },
+ );
+
+ try {
+ const saved = await agentBotProviderService.labelWakeDecision({ botId, decisionId, label });
+ await mutatePages((current) => withUserLabel(current, decisionId, saved), {
+ revalidate: false,
+ });
+ } catch (error) {
+ await mutatePages((current) => withUserLabel(current, decisionId, previous ?? null), {
+ revalidate: false,
+ });
+ throw error;
+ }
+
+ void mutate(botWakeKeys.summary(botId));
+ },
+ [botId, mutatePages, pages],
+ );
+
+ return { ...swr, markDecision };
+};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 3023de7e686..44781106e33 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -900,6 +900,30 @@ export const agentSignalKeys = {
]),
};
+// ---- bot wake records (one bot's judged messages; never persisted) ----
+export const botWakeKeys = {
+ decisions: def(
+ 'botWake:decisions',
+ // Keyed by context: a bot id is only visible in the workspace it lives in.
+ (
+ workspaceId: string | null,
+ botId: string,
+ filters: { followupOnly: boolean; outcome?: string; unmarkedOnly: boolean },
+ cursor: { createdAt: string; id: string } | undefined,
+ ) => [
+ 'botWake:decisions',
+ workspaceId,
+ botId,
+ filters.outcome ?? null,
+ filters.followupOnly,
+ filters.unmarkedOnly,
+ cursor?.createdAt ?? null,
+ cursor?.id ?? null,
+ ],
+ ),
+ summary: def('botWake:summary', (botId: string) => ['botWake:summary', botId]),
+};
+
// ---- misc UI singletons -------------------------------------------------
export const ollamaKeys = {
downloadModel: def('ollama:downloadModel', (model: string) => ['ollama:downloadModel', model]),
diff --git a/src/services/agentBotProvider.ts b/src/services/agentBotProvider.ts
index 3bdf060ad54..d84fc5d4014 100644
--- a/src/services/agentBotProvider.ts
+++ b/src/services/agentBotProvider.ts
@@ -1,3 +1,5 @@
+import type { BotWakeDecisionPage, BotWakeSummary, BotWakeUserMark } from '@lobechat/types';
+
import { lambdaClient } from '@/libs/trpc/client';
import type { BotRuntimeStatusSnapshot } from '../types/botRuntimeStatus';
@@ -77,6 +79,23 @@ class AgentBotProviderService {
return lambdaClient.agentBotProvider.testConnection.mutate(params);
};
+ /** One bot's wake decisions, newest first; pass the previous page's `nextCursor` for more. */
+ listWakeDecisions = async (
+ params: Parameters<typeof lambdaClient.agentBotWake.listWakeDecisions.query>[0],
+ ): Promise<BotWakeDecisionPage> => {
+ return lambdaClient.agentBotWake.listWakeDecisions.query(params);
+ };
+
+ getWakeSummary = async (botId: string): Promise<BotWakeSummary> => {
+ return lambdaClient.agentBotWake.getWakeSummary.query({ botId });
+ };
+
+ labelWakeDecision = async (
+ params: Parameters<typeof lambdaClient.agentBotWake.labelWakeDecision.mutate>[0],
+ ): Promise<BotWakeUserMark> => {
+ return lambdaClient.agentBotWake.labelWakeDecision.mutate(params);
+ };
+
lineFetchBotInfo = async (channelAccessToken: string) => {
return lambdaClient.agentBotProvider.lineFetchBotInfo.mutate({ channelAccessToken });
};