🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(verify): paginate report list with infinite scroll + server-side search (#16783)
Arvin Xu2711655cab3a
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex 82aaa463a8c..fd296301ed6 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -118,6 +118,17 @@ const updateRunInputSchema = verifyRunIdInputSchema.extend({}),});+// Cursor-paginated report list. `cursor` is the opaque token from the previous+// page's `nextCursor`; `q` filters by title (server-side, so it hits the whole+// history, not just the loaded page).+const listReportSummariesInputSchema = z+ .object({+ cursor: z.string().optional(),+ limit: z.number().int().min(1).max(100).optional(),+ q: z.string().optional(),+ })+ .optional();+const uploadEvidenceInputSchema = z.object({capturedBy: evidenceCapturedBySchema.optional(),@@ -498,34 +509,42 @@ export const verifyRouter = router({listRuns: verifyProcedure.query(async ({ ctx }) => ctx.runModel.query()),- listReportSummaries: verifyProcedure.query(async ({ ctx }) => {- const runs = await ctx.runModel.query();- const reports = await Promise.all(runs.map((run) => ctx.reportModel.findByRun(run.id)));-- return runs.map((run, index) => {- const report = reports[index];+ listReportSummaries: verifyProcedure+ .input(listReportSummariesInputSchema)+ .query(async ({ ctx, input }) => {+ const { items: runs, nextCursor } = await ctx.runModel.queryPage({+ cursor: input?.cursor,+ limit: input?.limit,+ q: input?.q,+ });+ const reports = await Promise.all(runs.map((run) => ctx.reportModel.findByRun(run.id)));++ const items = runs.map((run, index) => {+ const report = reports[index];++ return {+ report: report+ ? {+ createdAt: report.createdAt,+ failedChecks: report.failedChecks,+ generatedAt: report.generatedAt,+ id: report.id,+ overallConfidence: report.overallConfidence,+ passedChecks: report.passedChecks,+ reviewedByUser: report.reviewedByUser,+ summary: report.summary,+ totalChecks: report.totalChecks,+ uncertainChecks: report.uncertainChecks,+ verdict: report.verdict,+ verifyRunId: report.verifyRunId,+ }+ : null,+ run,+ };+ });- return {- report: report- ? {- createdAt: report.createdAt,- failedChecks: report.failedChecks,- generatedAt: report.generatedAt,- id: report.id,- overallConfidence: report.overallConfidence,- passedChecks: report.passedChecks,- reviewedByUser: report.reviewedByUser,- summary: report.summary,- totalChecks: report.totalChecks,- uncertainChecks: report.uncertainChecks,- verdict: report.verdict,- verifyRunId: report.verifyRunId,- }- : null,- run,- };- });- }),+ return { items, nextCursor };+ }),listResultsByRun: verifyProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {const run = await resolveVerifyRun(ctx, input.verifyRunId);diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex c56a936bd21..5e38a50d2bf 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -154,9 +154,13 @@"workspace.expand": "Show report list","workspace.listEmpty": "Reports appear here after a checker run finishes or a report is ingested.","workspace.listEmptyTitle": "No reports yet",+ "workspace.loadError": "Something went wrong while loading your reports.",+ "workspace.loadErrorTitle": "Couldn’t load reports",+ "workspace.loadMoreError": "Couldn’t load more reports","workspace.renameEmpty": "Report title cannot be empty","workspace.renameError": "Failed to rename report","workspace.renameSuccess": "Report renamed",+ "workspace.retry": "Retry","workspace.search": "Search reports","workspace.searchEmptyPrefix": "No reports match “","workspace.searchEmptySuffix": "”.",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex f75ea91d4d1..e9f2f653cbb 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -154,9 +154,13 @@"workspace.expand": "显示报告列表","workspace.listEmpty": "检查器运行完成或导入报告后,报告会显示在这里。","workspace.listEmptyTitle": "暂无验证报告",+ "workspace.loadError": "加载报告时出错了。",+ "workspace.loadErrorTitle": "报告加载失败",+ "workspace.loadMoreError": "加载更多失败","workspace.renameEmpty": "报告标题不能为空","workspace.renameError": "报告重命名失败","workspace.renameSuccess": "报告已重命名",+ "workspace.retry": "重试","workspace.search": "搜索报告","workspace.searchEmptyPrefix": "没有报告匹配「","workspace.searchEmptySuffix": "」。",diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 812dd44728b..9bd37da449d 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -1,5 +1,5 @@import type { VerifyCheckItem, VerifyRunSource, VerifyRunStatus } from '@lobechat/types';-import { and, desc, eq, isNull } from 'drizzle-orm';+import { and, desc, eq, ilike, isNull, lt, or, sql } from 'drizzle-orm';import { agentOperations } from '../schemas/agentOperations';import type { NewVerifyRun, VerifyRunItem } from '../schemas/verify';@@ -23,6 +23,25 @@ export interface VerifyRunState {verifyStatus: VerifyRunStatus | null;}+/**+ * Opaque list cursor = `${createdAt ISO}__${id}`. Both parts are metacharacter-+ * free (ISO timestamp + uuid), so a plain `__` delimiter round-trips safely.+ */+const encodeCursor = (createdAt: Date, id: string): string => `${createdAt.toISOString()}__${id}`;++const decodeCursor = (cursor?: string): { createdAt: Date; id: string } | null => {+ if (!cursor) return null;+ const idx = cursor.lastIndexOf('__');+ if (idx <= 0) return null;+ const createdAt = new Date(cursor.slice(0, idx));+ const id = cursor.slice(idx + 2);+ if (Number.isNaN(createdAt.getTime()) || !id) return null;+ return { createdAt, id };+};++/** Escape LIKE/ILIKE metacharacters (`\ % _`) so user input matches literally. */+const escapeLike = (value: string): string => value.replaceAll(/[\\%_]/g, (c) => `\\${c}`);+const toState = (run: VerifyRunItem | null | undefined): VerifyRunState | null =>run? {@@ -112,6 +131,67 @@ export class VerifyRunModel {});};+ /**+ * Cursor-paginated page of verification sessions, newest first, optionally+ * filtered by a title search. Ordered by `(createdAt, id)` descending and+ * paged on that composite key so rows sharing a `createdAt` (e.g. a batch+ * ingest) can't be dropped or duplicated at a page boundary — a plain+ * `createdAt`-only cursor would.+ *+ * `createdAt` is compared/ordered at **millisecond** precision+ * (`date_trunc('milliseconds', …)`) to match the cursor, which round-trips+ * through a JS `Date` / ISO string and so only carries milliseconds. The DB+ * column is `timestamptz` and can hold microseconds; comparing the raw column+ * against the truncated cursor would make same-millisecond rows match neither+ * the `eq` tiebreaker nor the `lt` bound, silently dropping them. Truncating+ * both sides keeps the keyset lossless.+ *+ * Fetches `limit + 1` to detect a further page without a second COUNT query:+ * `nextCursor` is `null` on the last page, otherwise the encoded cursor of the+ * last returned row.+ */+ queryPage = async ({+ cursor,+ limit = 30,+ q,+ }: { cursor?: string; limit?: number; q?: string } = {}): Promise<{+ items: VerifyRunItem[];+ nextCursor: string | null;+ }> => {+ const conditions = [this.ownership()];++ // Millisecond-truncated createdAt — the precision the cursor round-trips at.+ const createdAtMs = sql`date_trunc('milliseconds', ${verifyRuns.createdAt})`;++ const decoded = decodeCursor(cursor);+ if (decoded) {+ // (createdAt, id) < (cursor.createdAt, cursor.id) in descending order.+ conditions.push(+ or(+ lt(createdAtMs, decoded.createdAt),+ and(eq(createdAtMs, decoded.createdAt), lt(verifyRuns.id, decoded.id)),+ )!,+ );+ }++ const search = q?.trim();+ // Escape LIKE metacharacters so a user typing `%`/`_` searches literally.+ if (search) conditions.push(ilike(verifyRuns.title, `%${escapeLike(search)}%`));++ const rows = await this.db.query.verifyRuns.findMany({+ limit: limit + 1,+ orderBy: [desc(createdAtMs), desc(verifyRuns.id)],+ where: and(...conditions),+ });++ const hasMore = rows.length > limit;+ const items = hasMore ? rows.slice(0, limit) : rows;+ const last = items.at(-1);+ const nextCursor = hasMore && last ? encodeCursor(last.createdAt, last.id) : null;++ return { items, nextCursor };+ };+/** The verification session bound to an Agent Run, or undefined when none yet. */findByOperation = async (operationId: string) => {return this.db.query.verifyRuns.findFirst({diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 0cb9d636486..15cb05d4d8b 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -180,9 +180,13 @@ export default {'workspace.listEmpty':'Reports appear here after a checker run finishes or a report is ingested.','workspace.listEmptyTitle': 'No reports yet',+ 'workspace.loadError': 'Something went wrong while loading your reports.',+ 'workspace.loadErrorTitle': 'Couldn’t load reports',+ 'workspace.loadMoreError': 'Couldn’t load more reports','workspace.renameEmpty': 'Report title cannot be empty','workspace.renameError': 'Failed to rename report','workspace.renameSuccess': 'Report renamed',+ 'workspace.retry': 'Retry','workspace.search': 'Search reports','workspace.searchEmptyPrefix': 'No reports match “','workspace.searchEmptySuffix': '”.',diff --git a/src/features/Verify/Workspace/ReportListPanel.tsx b/src/features/Verify/Workspace/ReportListPanel.tsxindex 59f1372f605..0a7761849de 100644--- a/src/features/Verify/Workspace/ReportListPanel.tsx+++ b/src/features/Verify/Workspace/ReportListPanel.tsx@@ -29,8 +29,9 @@ import {Pencil,Search,Trash2,+ TriangleAlert,} from 'lucide-react';-import { memo, useMemo, useRef, useState } from 'react';+import { memo, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate, useParams } from 'react-router';@@ -43,7 +44,7 @@ import { verifyService } from '@/services/verify';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';-import { useVerifyReportSummaries } from '../hooks';+import { useVerifyReportSummariesInfinite } from '../hooks';const PANEL_MIN = 260;const PANEL_MAX = 420;@@ -221,6 +222,19 @@ const styles = createStaticStyles(({ css }) => ({color: ${cssVar.colorText};}`,+ loadMoreError: css`+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ align-items: center;+ justify-content: center;++ padding-block: 10px;+ padding-inline: 12px;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,}));type Glyph = 'ok' | 'bad' | 'unsure' | 'running';@@ -416,6 +430,7 @@ const ReportListItem = memo<{<NavItemactive={active}description={description}+ style={mutating ? { opacity: 0.62, pointerEvents: 'none' } : undefined}title={title}titleColor={cssVar.colorText}actions={@@ -440,7 +455,6 @@ const ReportListItem = memo<{style={{ color: meta.color }}/>}- style={mutating ? { opacity: 0.62, pointerEvents: 'none' } : undefined}onClick={() => navigate(`/verify/${item.run.id}`)}/>);@@ -452,10 +466,17 @@ const ReportListPanel = memo(() => {const { t } = useTranslation('verify');const { runId } = useParams<{ runId: string }>();const { md = true } = useResponsive();- const { data, isLoading, mutate: refreshReports } = useVerifyReportSummaries();- const reports = useMemo(() => data ?? [], [data]);const [query, setQuery] = useState('');+ const [debouncedQuery, setDebouncedQuery] = useState('');+ // Debounce the server-side search so each keystroke doesn't fire a query.+ useEffect(() => {+ const id = setTimeout(() => setDebouncedQuery(query.trim()), 300);+ return () => clearTimeout(id);+ }, [query]);++ const { items, error, hasMore, isLoadingInitial, isLoadingMore, loadMore, reload } =+ useVerifyReportSummariesInfinite(debouncedQuery);const [showPanel, panelWidth, updateSystemStatus] = useGlobalStore((s) => [systemStatusSelectors.showVerifyReportPanel(s),@@ -465,12 +486,6 @@ const ReportListPanel = memo(() => {const [tmpWidth, setTmpWidth] = useState(panelWidth);if (tmpWidth !== panelWidth) setTmpWidth(panelWidth);- const filtered = useMemo(() => {- const q = query.trim().toLowerCase();- if (!q) return reports;- return reports.filter((r) => (r.run.title || '').toLowerCase().includes(q));- }, [reports, query]);-const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {if (!size) return;const w = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;@@ -479,6 +494,22 @@ const ReportListPanel = memo(() => {updateSystemStatus({ verifyReportPanelWidth: w });};+ // Infinite scroll: load the next page when a sentinel near the list's end+ // scrolls into view (rootMargin pre-fetches before the user hits the bottom).+ const sentinelRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const el = sentinelRef.current;+ if (!el || !hasMore) return;+ const io = new IntersectionObserver(+ (entries) => {+ if (entries[0]?.isIntersecting && hasMore && !isLoadingMore) loadMore();+ },+ { rootMargin: '200px' },+ );+ io.observe(el);+ return () => io.disconnect();+ }, [hasMore, isLoadingMore, loadMore]);+return (<DraggablePanelclassName={styles.panel}@@ -520,14 +551,27 @@ const ReportListPanel = memo(() => {</div><Flexbox flex={1} style={{ minHeight: 0, overflowX: 'hidden', overflowY: 'auto' }}>- {isLoading && !data ? (+ {error && items.length === 0 ? (+ // A failed fetch must read as an error with a retry — not masquerade+ // as an empty "no reports" page.+ <Center className={styles.emptyState} gap={12}>+ <Empty+ description={t('workspace.loadError')}+ icon={TriangleAlert}+ title={t('workspace.loadErrorTitle')}+ />+ <button className={styles.clearBtn} type={'button'} onClick={() => reload()}>+ {t('workspace.retry')}+ </button>+ </Center>+ ) : isLoadingInitial ? (<SkeletonList rows={6} style={{ paddingBlock: 6, paddingInline: 8 }} />- ) : filtered.length === 0 ? (- query.trim() ? (+ ) : items.length === 0 ? (+ debouncedQuery ? (<div className={styles.empty}><span className={styles.emptyMsg}>{t('workspace.searchEmptyPrefix')}- <b className={styles.queryHl}>{query.trim()}</b>+ <b className={styles.queryHl}>{debouncedQuery}</b>{t('workspace.searchEmptySuffix')}</span><button className={styles.clearBtn} type={'button'} onClick={() => setQuery('')}>@@ -545,14 +589,29 @@ const ReportListPanel = memo(() => {)) : (<div className={styles.list}>- {filtered.map((item) => (+ {items.map((item) => (<ReportListItemactive={item.run.id === runId}item={item}key={item.run.id}- onReportsChanged={refreshReports}+ onReportsChanged={reload}/>))}+ {/* Sentinel drives infinite scroll; keep it mounted so the observer+ can re-fire after each page appends. */}+ <div aria-hidden ref={sentinelRef} style={{ height: 1 }} />+ {isLoadingMore ? (+ <SkeletonList rows={2} style={{ paddingBlock: 6, paddingInline: 8 }} />+ ) : error ? (+ // A later page failed (page 1 already rendered above): offer an+ // inline retry instead of a silently stuck bottom skeleton.+ <div className={styles.loadMoreError}>+ <span>{t('workspace.loadMoreError')}</span>+ <button className={styles.clearBtn} type={'button'} onClick={() => reload()}>+ {t('workspace.retry')}+ </button>+ </div>+ ) : null}</div>)}</Flexbox>diff --git a/src/features/Verify/hooks.ts b/src/features/Verify/hooks.tsindex c962a5e7ceb..b5054f01603 100644--- a/src/features/Verify/hooks.ts+++ b/src/features/Verify/hooks.ts@@ -1,8 +1,15 @@+import { useCallback, useEffect } from 'react';+import useSWRInfinite from 'swr/infinite';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useClientDataSWR } from '@/libs/swr';import { verifyKeys } from '@/libs/swr/keys';import { documentService } from '@/services/document';+import type { VerifyReportSummaryPage } from '@/services/verify';import { verifyService } from '@/services/verify';+const VERIFY_REPORT_PAGE_SIZE = 30;+/** Plan + rollup status for one Agent Run. Pass null operationId to skip. */export const useVerifyState = (operationId: string | null) =>useClientDataSWR(operationId ? verifyKeys.state(operationId) : null, () =>@@ -21,12 +28,73 @@ export const useVerifyReportBundle = (verifyRunId: string | null) =>verifyService.getReportBundle(verifyRunId!),);-/** Current user's recent verification sessions with report rollup fields. */-export const useVerifyReportSummaries = (enabled = true) =>- useClientDataSWR(enabled ? verifyKeys.reportSummaries() : null, () =>- verifyService.listReportSummaries(),+/**+ * Cursor-paginated, infinite-scrolling report summaries. `q` drives a+ * server-side title search (spanning the whole history, not just loaded pages);+ * changing it collapses back to the first page.+ */+export const useVerifyReportSummariesInfinite = (q: string) => {+ const workspaceId = useActiveWorkspaceId();++ const getKey = useCallback(+ (_index: number, previous: VerifyReportSummaryPage | null) => {+ // Stop paging once the previous page reported no further cursor.+ if (previous && previous.nextCursor === null) return null;+ return verifyKeys.reportSummaries(workspaceId, q, previous?.nextCursor ?? undefined);+ },+ [q, workspaceId],+ );++ const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite(+ getKey,+ ([, , query, cursor]: readonly [string, string, string, string]) =>+ verifyService.listReportSummaries({+ cursor: cursor || undefined,+ limit: VERIFY_REPORT_PAGE_SIZE,+ q: query || undefined,+ }),+ { revalidateFirstPage: false },);+ // A new search term starts a fresh key series; collapse size back to 1 so we+ // don't cascade-fetch as many pages as the previous query had loaded.+ useEffect(() => {+ setSize(1);+ }, [q, setSize]);++ const loadMore = useCallback(() => {+ void setSize((s) => s + 1);+ }, [setSize]);+ const reload = useCallback(() => {+ void mutate();+ }, [mutate]);++ // SWR leaves a failed/pending page's slot `undefined`, so guard the holes.+ const items = data?.flatMap((page) => page?.items ?? []) ?? [];+ const lastLoadedPage = data?.findLast(Boolean);+ const reachedEnd = lastLoadedPage ? lastLoadedPage.nextCursor === null : false;++ // A subsequent page is genuinely in flight only when it hasn't errored — an+ // errored page also leaves its slot undefined, but must not read as loading.+ const isLoadingMore =+ !error && (isLoading || (size > 0 && !!data && typeof data[size - 1] === 'undefined'));++ // Pause the sentinel while an error is showing so it can't hot-loop the failed+ // page; the panel offers a manual retry (`reload`) instead.+ const hasMore = !reachedEnd && !error;++ return {+ error,+ hasMore,+ isLoadingInitial: isLoading,+ isLoadingMore,+ isValidating,+ items,+ loadMore,+ reload,+ };+};+/** Model / token / latency for an LLM verifier judgment. Pass null to skip. */export const useVerifierTracing = (tracingId: string | null | undefined) =>useClientDataSWR(tracingId ? verifyKeys.tracing(tracingId) : null, () =>diff --git a/src/features/Verify/index.ts b/src/features/Verify/index.tsindex 0a16df7a996..9baa705a3de 100644--- a/src/features/Verify/index.ts+++ b/src/features/Verify/index.ts@@ -1,5 +1,5 @@export { default as CheckerDock } from './CheckerDock';-export { useVerifyReportSummaries, useVerifyResults, useVerifyState } from './hooks';+export { useVerifyReportSummariesInfinite, useVerifyResults, useVerifyState } from './hooks';export { default as ReportViewer } from './ReportViewer';export { default as RunResult } from './RunResult';export { countResults, isDraftUnconfirmed, phaseFromStatus } from './utils';diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 0c295755c42..a6e0fdeffe2 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -672,7 +672,15 @@ export const verifyKeys = {'verify:reportBundle',verifyRunId,]),- reportSummaries: def('verify:reportSummaries', () => ['verify:reportSummaries']),+ reportSummaries: def(+ 'verify:reportSummaries',+ (workspaceId?: string | null, q?: string, cursor?: string) => [+ 'verify:reportSummaries',+ workspaceId ?? '',+ q ?? '',+ cursor ?? '',+ ],+ ),results: def('verify:results', (operationId: string) => ['verify:results', operationId]),rubric: def('verify:rubric', (rubricId: string) => ['verify:rubric', rubricId]),rubricCriteria: def('verify:rubricCriteria', (rubricId: string) => [diff --git a/src/services/verify.ts b/src/services/verify.tsindex 0d9512dc920..9ff0e7000ad 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -104,6 +104,13 @@ export interface VerifyReportSummary {run: VerifyRunItem;}+/** One cursor-paginated page of report summaries. */+export interface VerifyReportSummaryPage {+ items: VerifyReportSummary[];+ /** Opaque token for the next page, or `null` when this is the last page. */+ nextCursor: string | null;+}+export interface GenerateDraftPlanInput {context?: string;enableAiGeneration?: boolean;@@ -162,9 +169,17 @@ export class VerifyService {verifyRunId,}) as Promise<VerifyReportBundle | null>;- /** Current user's recent verification sessions with report rollup fields. */- listReportSummaries = (): Promise<VerifyReportSummary[]> =>- lambdaClient.verify.listReportSummaries.query() as Promise<VerifyReportSummary[]>;+ /**+ * One cursor-paginated page of the current user's verification sessions with+ * report rollup fields. `cursor` comes from the previous page's `nextCursor`;+ * `q` filters by title on the server so search spans the whole history.+ */+ listReportSummaries = (params?: {+ cursor?: string;+ limit?: number;+ q?: string;+ }): Promise<VerifyReportSummaryPage> =>+ lambdaClient.verify.listReportSummaries.query(params) as Promise<VerifyReportSummaryPage>;deleteRun = (verifyRunId: string): Promise<unknown> =>lambdaClient.verify.deleteRun.mutate({ verifyRunId });