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.

💄 style(channel): paginate wake records and keep connection actions on the Connect tab (#22081)

Arvin Xu659c1a08c9fb
diff --git a/apps/server/src/routers/lambda/agentBotWake.test.ts b/apps/server/src/routers/lambda/agentBotWake.test.ts
index 1165d9a25f6..d2bbff3fc21 100644
--- a/apps/server/src/routers/lambda/agentBotWake.test.ts
+++ b/apps/server/src/routers/lambda/agentBotWake.test.ts
@@ -152,6 +152,19 @@ describe('agentBotWakeRouter', () => {
);
});
+ it('reads a numbered page and passes its total through', async () => {
+ mockListByScope.mockResolvedValue({ items: [], total: 42 });
+
+ const page = await agentBotWakeRouter
+ .createCaller(ctx)
+ .listWakeDecisions({ botId: BOT_ID, limit: 20, offset: 40 });
+
+ expect(mockListByScope).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 20, offset: 40 }),
+ );
+ expect(page.total).toBe(42);
+ });
+
it('splits current labels into the agent’s silence and the owner’s mark', async () => {
mockListByScope.mockResolvedValue({
items: [
diff --git a/apps/server/src/routers/lambda/agentBotWake.ts b/apps/server/src/routers/lambda/agentBotWake.ts
index dbe5fd13c29..9f1c4ff8e72 100644
--- a/apps/server/src/routers/lambda/agentBotWake.ts
+++ b/apps/server/src/routers/lambda/agentBotWake.ts
@@ -71,7 +71,8 @@ const cursorSchema = z.object({
export const agentBotWakeRouter = router({
/**
- * One bot's wake decisions, newest first, from the last {@link SCOPE_READ_DEFAULT_DAYS} days:
+ * One bot's wake decisions, newest first, from the last {@link SCOPE_READ_DEFAULT_DAYS} days, a
+ * numbered page (`offset`) or a keyset page (`cursor`) at a time, with the filtered `total`:
* 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.
*/
@@ -82,6 +83,7 @@ export const agentBotWakeRouter = router({
cursor: cursorSchema.optional(),
followupOnly: z.boolean().optional(),
limit: z.number().int().min(1).max(SCOPE_READ_MAX_LIMIT).optional(),
+ offset: z.number().int().min(0).optional(),
outcome: z.enum(SIGNAL_DECISION_OUTCOMES).optional(),
unmarkedOnly: z.boolean().optional(),
}),
@@ -95,6 +97,7 @@ export const agentBotWakeRouter = router({
finalReasons: input.followupOnly ? BOT_WAKE_FOLLOWUP_REASONS : undefined,
labeled: input.unmarkedOnly ? { by: BOT_WAKE_USER_LABEL_SOURCE, has: false } : undefined,
limit: input.limit,
+ offset: input.offset,
outcome: input.outcome,
scopeKey,
});
@@ -115,6 +118,7 @@ export const agentBotWakeRouter = router({
};
}),
nextCursor: page.nextCursor,
+ total: page.total,
};
}),
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 0a75ca82040..e35a98dba07 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -462,7 +462,6 @@
"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",
@@ -472,7 +471,6 @@
"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",
@@ -519,6 +517,7 @@
"channel.records.summary.marked": "Marked by you",
"channel.records.summary.skip": "Skipped",
"channel.records.summary.wake": "Woke",
+ "channel.records.total": "{{count}} records",
"channel.refreshStatus": "Refresh status",
"channel.removeChannel": "Remove IM Bot",
"channel.removeFailed": "Failed to remove bot",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 6f9c6c2f4ce..34266eb574a 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -462,7 +462,6 @@
"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": "只看未标记",
@@ -472,7 +471,6 @@
"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": "不该唤醒",
@@ -519,6 +517,7 @@
"channel.records.summary.marked": "你已标记",
"channel.records.summary.skip": "未唤醒",
"channel.records.summary.wake": "已唤醒",
+ "channel.records.total": "共 {{count}} 条",
"channel.refreshStatus": "刷新状态",
"channel.removeChannel": "移除 IM 机器人",
"channel.removeFailed": "移除 Bot 失败",
diff --git a/packages/database/src/models/__tests__/signalDecision.scope.test.ts b/packages/database/src/models/__tests__/signalDecision.scope.test.ts
index c973476586f..312aafce317 100644
--- a/packages/database/src/models/__tests__/signalDecision.scope.test.ts
+++ b/packages/database/src/models/__tests__/signalDecision.scope.test.ts
@@ -126,6 +126,22 @@ describe('SignalDecisionModel scope reads', () => {
expect(third.nextCursor).toBeUndefined();
});
+ it('pages by offset and counts every match, not just the page', async () => {
+ for (let i = 0; i < 5; i++) await seed(`m${i}`, { minutesAgo: 10 - i });
+ await seed('elsewhere', { scope: 'discord:app-2' });
+ const model = new SignalDecisionModel(serverDB, userId);
+
+ const second = await model.listByScope({ limit: 2, offset: 2, scopeKey });
+ const last = await model.listByScope({ limit: 2, offset: 4, scopeKey });
+
+ expect(second.items.map((i) => i.text)).toEqual(['text of m2', 'text of m1']);
+ expect(second.total).toBe(5);
+ expect(last.items.map((i) => i.text)).toEqual(['text of m0']);
+ expect(last.total).toBe(5);
+ // The count follows the filters.
+ expect((await model.listByScope({ outcome: 'skip', scopeKey })).total).toBe(0);
+ });
+
it('keeps rows that share a millisecond apart through the cursor', async () => {
const a = await seed('same-a');
const b = await seed('same-b');
diff --git a/packages/database/src/models/signalDecision.ts b/packages/database/src/models/signalDecision.ts
index 769719f782f..b199943c2a5 100644
--- a/packages/database/src/models/signalDecision.ts
+++ b/packages/database/src/models/signalDecision.ts
@@ -57,6 +57,8 @@ export interface ListDecisionsByScopeParams {
labeled?: { by: string; has: boolean };
/** 1..{@link SCOPE_READ_MAX_LIMIT}; defaults to 20. */
limit?: number;
+ /** Rows to skip, for numbered pages; applied after the cursor when both are given. */
+ offset?: number;
outcome?: SignalDecisionOutcome;
scopeKey: string;
/** Lower bound on `created_at`; defaults to {@link SCOPE_READ_DEFAULT_DAYS} days ago. */
@@ -92,6 +94,8 @@ export interface ScopeDecisionListItem {
export interface ScopeDecisionPage {
items: ScopeDecisionListItem[];
nextCursor?: ScopeDecisionCursor;
+ /** Decisions matching the filters in the window, ignoring the cursor and offset. */
+ total: number;
}
export interface SummarizeDecisionsByScopeParams {
@@ -257,8 +261,9 @@ export class SignalDecisionModel {
/**
* 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.
+ * label, and how many match the filters. Every predicate starts from
+ * `(user_id, scope_key, created_at)`, so the read and the count stay 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);
@@ -273,10 +278,6 @@ export class SignalDecisionModel {
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})`;
@@ -286,27 +287,41 @@ export class SignalDecisionModel {
: sql`${latest} = ${SIGNAL_DECISION_LABEL_CLEARED}`,
);
}
+ const matching = and(...conditions);
+ const paged = params.cursor
+ ? and(
+ matching,
+ sql`(${signalDecisions.createdAt}, ${signalDecisions.id}) < (${params.cursor.createdAt}::timestamptz, ${params.cursor.id}::uuid)`,
+ )
+ : matching;
- 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 [rows, [{ total }]] = await Promise.all([
+ 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(paged)
+ .orderBy(desc(signalDecisions.createdAt), desc(signalDecisions.id))
+ .limit(limit + 1)
+ .offset(Math.max(params.offset ?? 0, 0)),
+ this.db
+ .select({ total: sql<number>`count(*)::int` })
+ .from(signalDecisions)
+ .where(matching),
+ ]);
const page = rows.slice(0, limit);
const labels = await this.currentLabels(page.map((row) => row.id));
@@ -327,6 +342,7 @@ export class SignalDecisionModel {
})),
nextCursor:
rows.length > limit && last ? { createdAt: last.createdAtIso, id: last.id } : undefined,
+ total,
};
};
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 8bf4610988c..6f0b33940d3 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -734,12 +734,11 @@ export default {
'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.total': '{{count}} records',
'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 4c700f5dbf3..6ea34f98201 100644
--- a/packages/types/src/signal.ts
+++ b/packages/types/src/signal.ts
@@ -174,6 +174,8 @@ export interface BotWakeDecisionPage {
items: BotWakeDecisionItem[];
/** Keyset position of the next page; absent on the last one. */
nextCursor?: { createdAt: string; id: string };
+ /** Decisions matching the filters in the window, across all pages. */
+ total: number;
}
/** Counts of one bot's wake decisions over the last `days` days. */
diff --git a/src/features/AgentChannel/PlatformDetail/Footer.tsx b/src/features/AgentChannel/PlatformDetail/Footer.tsx
index 12458b7168d..c951b26b3f9 100644
--- a/src/features/AgentChannel/PlatformDetail/Footer.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Footer.tsx
@@ -43,7 +43,7 @@ const styles = stylex.create({
},
resultDetail: {
color: cssVar.colorTextTertiary,
- fontFamily: 'monospace',
+ fontFamily: cssVar.fontFamilyCode,
fontSize: 12,
wordBreak: 'break-all',
},
@@ -56,7 +56,7 @@ const styles = stylex.create({
color: cssVar.colorTextSecondary,
flexGrow: 1,
flexShrink: 1,
- fontFamily: 'monospace',
+ fontFamily: cssVar.fontFamilyCode,
fontSize: 13,
height: cssVar.controlHeight,
lineHeight: cssVar.controlHeight,
@@ -271,6 +271,8 @@ FooterNotices.displayName = 'ChannelFooterNotices';
interface FooterActionsProps {
connecting: boolean;
+ /** Remove and Test connection act on the connection, so they live on the Connect tab only. */
+ connectionActions?: boolean;
disabled?: boolean;
form: FormInstance<ChannelFormValues>;
hasConfig: boolean;
@@ -293,6 +295,7 @@ export const FooterActions = memo<FooterActionsProps>(
({
platformDef,
form,
+ connectionActions = true,
hasConfig,
hideSave,
isDirty,
@@ -318,51 +321,56 @@ export const FooterActions = memo<FooterActionsProps>(
? `${origin}/api/agent/webhooks/${platformId}/${applicationId}`
: `${origin}/api/agent/webhooks/${platformId}`;
+ const showConnectionActions = connectionActions && hasConfig;
+ const showActionBar = showConnectionActions || isDirty || !hideSave;
+
return (
<div {...stylex.props(styles.bottom)}>
- <div {...stylex.props(styles.actionBar)}>
- {hasConfig ? (
- <Button
- danger
- disabled={disabled || saving || connecting}
- icon={<Trash2 size={16} />}
- onClick={onDelete}
- >
- {t('channel.removeChannel')}
- </Button>
- ) : (
- <div />
- )}
- <Flexbox horizontal gap={12}>
- {hasConfig && (
- <Button
- disabled={writeDisabled || saving || connecting}
- icon={<RefreshCw size={16} />}
- loading={testing}
- onClick={onTestConnection}
- >
- {t('channel.testConnection')}
- </Button>
- )}
- {isDirty && (
- <Button disabled={writeDisabled || saving || connecting} onClick={onDiscard}>
- {t('channel.discard')}
- </Button>
- )}
- {!hideSave && (
+ {showActionBar && (
+ <div {...stylex.props(styles.actionBar)}>
+ {showConnectionActions ? (
<Button
- disabled={writeDisabled}
- loading={saving || connecting}
- type="primary"
- onClick={onSave}
+ danger
+ disabled={disabled || saving || connecting}
+ icon={<Trash2 size={16} />}
+ onClick={onDelete}
>
- {connecting
- ? t('channel.connecting')
- : t(hasConfig ? 'channel.save' : 'channel.saveAndConnect')}
+ {t('channel.removeChannel')}
</Button>
+ ) : (
+ <div />
)}
- </Flexbox>
- </div>
+ <Flexbox horizontal gap={12}>
+ {showConnectionActions && (
+ <Button
+ disabled={writeDisabled || saving || connecting}
+ icon={<RefreshCw size={16} />}
+ loading={testing}
+ onClick={onTestConnection}
+ >
+ {t('channel.testConnection')}
+ </Button>
+ )}
+ {isDirty && (
+ <Button disabled={writeDisabled || saving || connecting} onClick={onDiscard}>
+ {t('channel.discard')}
+ </Button>
+ )}
+ {!hideSave && (
+ <Button
+ disabled={writeDisabled}
+ loading={saving || connecting}
+ type="primary"
+ onClick={onSave}
+ >
+ {connecting
+ ? t('channel.connecting')
+ : t(hasConfig ? 'channel.save' : 'channel.saveAndConnect')}
+ </Button>
+ )}
+ </Flexbox>
+ </div>
+ )}
{hasConfig && showWebhookUrl && (
<Flexbox gap={8}>
diff --git a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
index c59f4a32feb..8336b4763d5 100644
--- a/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.save.test.tsx
@@ -231,14 +231,22 @@ describe('PlatformDetail saving', () => {
expect(mocks.updateBotProvider.mock.calls[0][2].settings.replyStyle).toBe('Short and casual.');
});
- it('leaves the bottom bar to Remove and Test connection for a saved bot', () => {
+ it('keeps Remove and Test connection on the Connect tab, off the settings tabs', () => {
render(<PlatformDetail agentId="agt" currentConfig={config} platformDef={platformDef} />, {
wrapper: MemoryRouter,
});
-
- expect(
- screen.getByRole('button', { name: new RegExp(en['channel.removeChannel']) }),
- ).toBeVisible();
+ const remove = () =>
+ screen.queryByRole('button', { name: new RegExp(en['channel.removeChannel']) });
+ const test = () =>
+ screen.queryByRole('button', { name: new RegExp(en['channel.testConnection']) });
+
+ // A saved bot opens on a settings tab.
+ expect(remove()).toBeNull();
+ expect(test()).toBeNull();
+
+ openTab(en['channel.tab.connect']);
+ expect(remove()).toBeVisible();
+ expect(test()).toBeVisible();
expect(screen.queryByRole('button', { name: en['channel.save'] })).toBeNull();
expect(screen.queryByRole('button', { name: en['channel.saveAndConnect'] })).toBeNull();
});
diff --git a/src/features/AgentChannel/PlatformDetail/index.tsx b/src/features/AgentChannel/PlatformDetail/index.tsx
index abd42846e75..b0de693a09c 100644
--- a/src/features/AgentChannel/PlatformDetail/index.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.tsx
@@ -1066,6 +1066,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
/>
<FooterActions
connecting={connecting}
+ connectionActions={activeTab === 'connect'}
disabled={readOnly}
form={form}
hasConfig={!!currentConfig}
diff --git a/src/features/AgentChannel/WakeRecords/RecordTable.tsx b/src/features/AgentChannel/WakeRecords/RecordTable.tsx
index 3edec152dfe..c120a9785b2 100644
--- a/src/features/AgentChannel/WakeRecords/RecordTable.tsx
+++ b/src/features/AgentChannel/WakeRecords/RecordTable.tsx
@@ -52,14 +52,21 @@ const styles = stylex.create({
interface RecordTableProps {
disabled?: boolean;
items: BotWakeDecisionItem[];
+ loading?: boolean;
onMark: (decisionId: string, label: BotWakeUserLabel | null) => Promise<void>;
+ pagination: {
+ current: number;
+ onChange: (page: number) => void;
+ pageSize: number;
+ total: number;
+ };
}
/**
* 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) => {
+export const RecordTable = ({ disabled, items, loading, onMark, pagination }: 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.
@@ -209,9 +216,15 @@ export const RecordTable = ({ disabled, items, onMark }: RecordTableProps) => {
<Table<BotWakeDecisionItem>
columns={columns}
dataSource={items}
- pagination={false}
+ loading={loading}
rowKey={'id'}
size={'small'}
+ pagination={{
+ ...pagination,
+ showSizeChanger: false,
+ showTotal: (total) => t('channel.records.total', { count: total }),
+ 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/index.tsx b/src/features/AgentChannel/WakeRecords/index.tsx
index 2a54891c48b..777befb56f7 100644
--- a/src/features/AgentChannel/WakeRecords/index.tsx
+++ b/src/features/AgentChannel/WakeRecords/index.tsx
@@ -16,7 +16,13 @@ import { botWakeKeys } from '@/libs/swr/keys';
import { RecordTable } from './RecordTable';
import { Summary } from './Summary';
import { useRefreshOnReturn } from './useRefreshOnReturn';
-import { useWakeDecisions, type WakeRecordFilters } from './useWakeRecords';
+import {
+ pageLoadFailed,
+ recordsEmpty,
+ useWakeDecisions,
+ WAKE_RECORDS_PAGE_SIZE,
+ type WakeRecordFilters,
+} from './useWakeRecords';
/** Matches `SCOPE_READ_DEFAULT_DAYS` on the server; the summary reports it too. */
const WINDOW_DAYS = 30;
@@ -63,11 +69,21 @@ interface WakeRecordsProps {
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);
+ const [filters, setFiltersState] = useState<WakeRecordFilters>(NO_FILTERS);
+ const [page, setPage] = useState(1);
+ const { data, error, isLoading, isValidating, markDecision, mutate } = useWakeDecisions(
+ botId,
+ filters,
+ page,
+ );
+
+ // Another filter is another list: start it from its first page.
+ const setFilters = useCallback((update: (prev: WakeRecordFilters) => WakeRecordFilters) => {
+ setFiltersState(update);
+ setPage(1);
+ }, []);
- // New decisions arrive while the owner is elsewhere (testing the bot): refetch the loaded pages
+ // New decisions arrive while the owner is elsewhere (testing the bot): refetch the open page
// and the summary on coming back, and on demand.
const refresh = useCallback(() => {
void mutate();
@@ -75,12 +91,9 @@ export const WakeRecords = ({ active = true, botId, disabled }: WakeRecordsProps
}, [botId, mutate]);
useRefreshOnReturn(active, refresh);
- const items = data?.flatMap((page) => page.items) ?? [];
+ const items = data?.items ?? [];
+ const total = data?.total ?? 0;
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}>
@@ -135,15 +148,17 @@ export const WakeRecords = ({ active = true, botId, disabled }: WakeRecordsProps
<AsyncBoundary
data={data}
error={error}
- isEmpty={items.length === 0}
- isLoading={isLoading}
+ // A page past the end (its last rows marked away) is not an empty list: the pager stays.
+ isEmpty={recordsEmpty({ error, total })}
+ // A page turn keeps the previous page on screen; only the first load is a skeleton.
+ isLoading={isLoading && !data}
loading={<ListSkeleton />}
empty={
filtered ? (
<Empty
title={t('channel.records.emptyFiltered.title')}
action={
- <Button onClick={() => setFilters(NO_FILTERS)}>
+ <Button onClick={() => setFilters(() => NO_FILTERS)}>
{t('channel.records.emptyFiltered.clear')}
</Button>
}
@@ -158,22 +173,22 @@ export const WakeRecords = ({ active = true, botId, disabled }: WakeRecordsProps
}
onRetry={() => void mutate()}
>
- <RecordTable disabled={disabled} items={items} onMark={markDecision} />
- {loadMoreFailed ? (
+ {pageLoadFailed({ data, error, isLoading }) && (
<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>
- )
)}
+ <RecordTable
+ disabled={disabled}
+ items={items}
+ // The previous page, while the one asked for loads.
+ loading={isLoading}
+ pagination={{
+ current: page,
+ onChange: setPage,
+ pageSize: WAKE_RECORDS_PAGE_SIZE,
+ total,
+ }}
+ onMark={markDecision}
+ />
</AsyncBoundary>
</Flexbox>
);
diff --git a/src/features/AgentChannel/WakeRecords/useWakeRecords.test.ts b/src/features/AgentChannel/WakeRecords/useWakeRecords.test.ts
index affbee9f97a..d9beb103ad8 100644
--- a/src/features/AgentChannel/WakeRecords/useWakeRecords.test.ts
+++ b/src/features/AgentChannel/WakeRecords/useWakeRecords.test.ts
@@ -1,7 +1,7 @@
import type { BotWakeDecisionPage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
-import { withUserLabel } from './useWakeRecords';
+import { pageLoadFailed, recordsEmpty, withUserLabel } from './useWakeRecords';
vi.mock('@/services/agentBotProvider', () => ({ agentBotProviderService: {} }));
@@ -9,29 +9,57 @@ 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[];
+ const page = {
+ items: [item('a'), item('b', { label: 'correct' })],
+ total: 42,
+ } as BotWakeDecisionPage;
- it('sets the mark on the one decision across pages and leaves the rest', () => {
+ it('sets the mark on the one decision and leaves the rest and the total', () => {
const mark = { createdAt: new Date(), label: 'false_wake' as const, note: undefined };
- const next = withUserLabel(pages, 'c', mark)!;
+ const next = withUserLabel(page, 'a', 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);
+ expect(next.items[0].userLabel).toBe(mark);
+ expect(next.items[1].userLabel).toEqual({ label: 'correct' });
+ expect(next.total).toBe(42);
});
- it('puts the previous mark back on rollback', () => {
- const marked = withUserLabel(pages, 'c', null)!;
+ it('puts the previous mark back on rollback without touching the original', () => {
+ const cleared = withUserLabel(page, 'b', null)!;
- expect(marked[1].items[0].userLabel).toBeNull();
- expect(pages[1].items[0].userLabel).toEqual({ label: 'correct' });
+ expect(cleared.items[1].userLabel).toBeNull();
+ expect(page.items[1].userLabel).toEqual({ label: 'correct' });
});
- it('leaves an unloaded list alone', () => {
+ it('leaves an unloaded page alone', () => {
expect(withUserLabel(undefined, 'a', null)).toBeUndefined();
});
});
+
+describe('pageLoadFailed', () => {
+ const shown = { items: [], total: 42 };
+
+ it('reports a failed page turn while the previous page is still shown', () => {
+ expect(pageLoadFailed({ data: shown, error: new Error('boom'), isLoading: false })).toBe(true);
+ });
+
+ it('stays quiet while the page loads, when it loaded, and before anything loaded', () => {
+ expect(pageLoadFailed({ data: shown, error: new Error('boom'), isLoading: true })).toBe(false);
+ expect(pageLoadFailed({ data: shown, error: undefined, isLoading: false })).toBe(false);
+ // The first load's failure is the boundary's full error state, not this inline one.
+ expect(pageLoadFailed({ data: undefined, error: new Error('boom'), isLoading: false })).toBe(
+ false,
+ );
+ });
+});
+
+describe('recordsEmpty', () => {
+ it('is the empty state only when nothing matches and nothing failed', () => {
+ expect(recordsEmpty({ error: undefined, total: 0 })).toBe(true);
+ expect(recordsEmpty({ error: undefined, total: 3 })).toBe(false);
+ });
+
+ it('does not read a failed filter load over a kept empty page as "no records"', () => {
+ expect(recordsEmpty({ error: new Error('boom'), total: 0 })).toBe(false);
+ });
+});
diff --git a/src/features/AgentChannel/WakeRecords/useWakeRecords.ts b/src/features/AgentChannel/WakeRecords/useWakeRecords.ts
index cc313cc732a..3a0c0417da1 100644
--- a/src/features/AgentChannel/WakeRecords/useWakeRecords.ts
+++ b/src/features/AgentChannel/WakeRecords/useWakeRecords.ts
@@ -5,9 +5,7 @@ import type {
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';
@@ -20,60 +18,64 @@ export interface WakeRecordFilters {
unmarkedOnly: boolean;
}
-type DecisionsKey = ReturnType<typeof botWakeKeys.decisions>;
-
-/** The page list with `decisionId`'s mark replaced; `undefined` pages stay as they are. */
+/** The page with `decisionId`'s mark replaced; an unloaded page stays as it is. */
export const withUserLabel = (
- pages: BotWakeDecisionPage[] | undefined,
+ page: BotWakeDecisionPage | undefined,
decisionId: string,
userLabel: BotWakeDecisionItem['userLabel'],
-): BotWakeDecisionPage[] | undefined =>
- pages?.map((page) => ({
+): BotWakeDecisionPage | undefined =>
+ page && {
...page,
items: page.items.map((item) => (item.id === decisionId ? { ...item, userLabel } : item)),
- }));
+ };
+
+/**
+ * The page asked for failed while another one is still on screen. `keepPreviousData` keeps the
+ * old rows in `data`, so without this the failure would pass for the new page's rows.
+ */
+export const pageLoadFailed = ({
+ data,
+ error,
+ isLoading,
+}: {
+ data: unknown;
+ error: unknown;
+ isLoading: boolean;
+}): boolean => data !== undefined && !!error && !isLoading;
+
+/**
+ * Nothing matches, and that is the answer, not a failure: an empty page kept on screen by
+ * `keepPreviousData` while the next filter's request failed is an error to show, not "no records".
+ */
+export const recordsEmpty = ({ error, total }: { error: unknown; total: number }): boolean =>
+ total === 0 && !error;
/** 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`.
+ * One numbered page (1-based) of a bot's decisions, with the filtered total. The previous page stays
+ * on screen while the next one loads, so the table does not collapse on every page turn.
*/
-export const useWakeDecisions = (botId: string, filters: WakeRecordFilters) => {
- const workspaceId = useActiveWorkspaceId();
+export const useWakeDecisions = (botId: string, filters: WakeRecordFilters, page: number) => {
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]) =>
+ const swr = useClientDataSWR<BotWakeDecisionPage>(
+ botWakeKeys.decisions(botId, { followupOnly, outcome, unmarkedOnly }, page),
+ () =>
agentBotProviderService.listWakeDecisions({
- botId: id as string,
- cursor: cursorAt ? { createdAt: cursorAt as string, id: cursorId as string } : undefined,
- followupOnly: (keyFollowup as boolean) || undefined,
+ botId,
+ followupOnly: followupOnly || undefined,
limit: WAKE_RECORDS_PAGE_SIZE,
- outcome: (keyOutcome as SignalDecisionOutcome | null) ?? undefined,
- unmarkedOnly: (keyUnmarked as boolean) || undefined,
+ offset: (page - 1) * WAKE_RECORDS_PAGE_SIZE,
+ outcome,
+ unmarkedOnly: unmarkedOnly || undefined,
}),
- { revalidateFirstPage: false, revalidateOnFocus: false },
+ { keepPreviousData: true, revalidateOnFocus: false },
);
- const { data: pages, mutate: mutatePages } = swr;
+ const { data, mutate: mutatePage } = swr;
/**
* Shows the mark at once and saves it; `null` takes the mark back. A failed save puts the
@@ -81,29 +83,25 @@ export const useWakeDecisions = (botId: string, filters: WakeRecordFilters) => {
*/
const markDecision = useCallback(
async (decisionId: string, label: BotWakeUserLabel | null) => {
- const previous = pages
- ?.flatMap((page) => page.items)
- .find((item) => item.id === decisionId)?.userLabel;
+ const previous = data?.items.find((item) => item.id === decisionId)?.userLabel;
- await mutatePages(
+ await mutatePage(
(current) =>
withUserLabel(
current,
decisionId,
label ? { createdAt: new Date(), label, note: undefined } : null,
),
- {
- revalidate: false,
- },
+ { revalidate: false },
);
try {
const saved = await agentBotProviderService.labelWakeDecision({ botId, decisionId, label });
- await mutatePages((current) => withUserLabel(current, decisionId, saved), {
+ await mutatePage((current) => withUserLabel(current, decisionId, saved), {
revalidate: false,
});
} catch (error) {
- await mutatePages((current) => withUserLabel(current, decisionId, previous ?? null), {
+ await mutatePage((current) => withUserLabel(current, decisionId, previous ?? null), {
revalidate: false,
});
throw error;
@@ -111,7 +109,7 @@ export const useWakeDecisions = (botId: string, filters: WakeRecordFilters) => {
void mutate(botWakeKeys.summary(botId));
},
- [botId, mutatePages, pages],
+ [botId, data, mutatePage],
);
return { ...swr, markDecision };
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 9a1908c1627..e0519c372d3 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -906,21 +906,17 @@ export const agentSignalKeys = {
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,
+ page: number,
) => [
'botWake:decisions',
- workspaceId,
botId,
filters.outcome ?? null,
filters.followupOnly,
filters.unmarkedOnly,
- cursor?.createdAt ?? null,
- cursor?.id ?? null,
+ page,
],
),
summary: def('botWake:summary', (botId: string) => ['botWake:summary', botId]),