🤯 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
♻️ refactor(verify): persist settled verify cards through @lobechat/replica (#20846)
Arvin Xu788dd02b5070
diff --git a/apps/server/src/services/verify/__tests__/repairService.test.ts b/apps/server/src/services/verify/__tests__/repairService.test.tsindex c73925bb0ed..083f96b4f3a 100644--- a/apps/server/src/services/verify/__tests__/repairService.test.ts+++ b/apps/server/src/services/verify/__tests__/repairService.test.ts@@ -7,6 +7,7 @@ const m = vi.hoisted(() => ({findVerifyMessage: vi.fn(),listResults: vi.fn(),markRepairing: vi.fn(),+ recordAutoRepair: vi.fn(),rounds: vi.fn(),run: vi.fn(),settleFailedRepair: vi.fn(),@@ -20,7 +21,11 @@ vi.mock('@/database/models/message', () => ({}));vi.mock('@/database/models/verifyRun', () => ({VerifyRunModel: vi.fn(function () {- return { findByOperation: m.run, listByAcceptance: m.rounds };+ return {+ findByOperation: m.run,+ listByAcceptance: m.rounds,+ recordAutoRepair: m.recordAutoRepair,+ };}),}));vi.mock('@/database/models/verifyCheckResult', () => ({@@ -134,4 +139,38 @@ describe('VerifyRepairService.triggerAutoRepair', () => {await new VerifyRepairService({} as any, 'user').triggerAutoRepair('op-3', spawner),).toEqual({ repairOperationId: 'repair-op' });});++ describe('records the auto-repair decision', () => {+ const trigger = (spawner?: any) =>+ new VerifyRepairService({} as any, 'user').triggerAutoRepair('op-3', spawner);++ beforeEach(() => m.listResults.mockResolvedValue([gateFailure('gif-check')]));++ it('marks a spawned repair', async () => {+ await trigger(vi.fn().mockResolvedValue({ repairOperationId: 'repair-op' }));+ expect(m.recordAutoRepair).toHaveBeenCalledWith('round-3', 'spawned');+ });++ it('declines when the spawner returns nothing (repair cap reached or spawn failed)', async () => {+ expect(await trigger(vi.fn().mockResolvedValue(null))).toBeNull();+ expect(m.recordAutoRepair).toHaveBeenCalledWith('round-3', 'declined');+ });++ it('declines without a spawner', async () => {+ expect(await trigger()).toBeNull();+ expect(m.recordAutoRepair).toHaveBeenCalledWith('round-3', 'declined');+ });++ it('declines a superseded round', async () => {+ m.rounds.mockResolvedValue([round, { id: 'round-4', roundIndex: 4, status: 'verifying' }]);+ expect(await trigger(vi.fn())).toBeNull();+ expect(m.recordAutoRepair).toHaveBeenCalledWith('round-3', 'declined');+ });++ it('records nothing when no auto-repair check failed', async () => {+ m.listResults.mockResolvedValue([{ checkItemId: 'gif-check', status: 'passed' }]);+ await trigger(vi.fn());+ expect(m.recordAutoRepair).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/verify/repairService.ts b/apps/server/src/services/verify/repairService.tsindex 66ecfcc512f..b5181b33e61 100644--- a/apps/server/src/services/verify/repairService.ts+++ b/apps/server/src/services/verify/repairService.ts@@ -349,6 +349,16 @@ export class VerifyRepairService {);}+ /**+ * Mark a failed round's auto-repair as declined, so readers (the persisted+ * verify card) can treat its `failed` status as final rather than transient.+ */+ private async declineRepair(operationId: string): Promise<null> {+ const run = await this.runModel.findByOperation(operationId);+ if (run) await this.runModel.recordAutoRepair(run.id, 'declined');+ return null;+ }+/*** Trigger one round of auto-repair. Returns the repair operation id, or null* when there's nothing to repair or no spawner is available in this context.@@ -361,11 +371,11 @@ export class VerifyRepairService {if (failures.length === 0) return null;if (await this.isSuperseded(operationId)) {log('op %s round is superseded within its acceptance, not repairing', operationId);- return null;+ return this.declineRepair(operationId);}if (!spawner) {log('auto-repair eligible for op %s but no spawner available', operationId);- return null;+ return this.declineRepair(operationId);}const failedItemIds = failures.map((f) => f.item.id);@@ -388,11 +398,13 @@ export class VerifyRepairService {operationId,verifyMessageId: verifyMessage?.id,});- if (!spawned) return null;+ // Cap reached, or the spawn failed: the failure stands as this round's verdict.+ if (!spawned) return this.declineRepair(operationId);// Link the repair operation onto each failed result and flip the rollup.const run = await this.runModel.findByOperation(operationId);if (run) {+ await this.runModel.recordAutoRepair(run.id, 'spawned');for (const { item } of failures) {await this.resultModel.updateByCheckItem(run.id, item.id, {repairOperationId: spawned.repairOperationId,diff --git a/packages/database/src/models/__tests__/userMemories.test.ts b/packages/database/src/models/__tests__/userMemories.test.tsindex accb6b1d8c8..770536235f5 100644--- a/packages/database/src/models/__tests__/userMemories.test.ts+++ b/packages/database/src/models/__tests__/userMemories.test.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { LayersEnum, MemorySourceType, MergeStrategyEnum, TypesEnum } from '@lobechat/types';-import { eq } from 'drizzle-orm';+import { eq, sql } from 'drizzle-orm';import { nanoid } from 'nanoid';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -37,16 +37,13 @@ const userMemoryModel = new UserMemoryModel(serverDB, userId);* @returns Normalized random vector*/function generateRandomEmbedding(dimensions: number = 1024): number[] {- const vector = new Array(dimensions).fill(0).map(() => Math.random() * 2 - 1); // Random values between -1 and 1+ const vector = Array.from({ length: dimensions }, () => Math.random() * 2 - 1); // Random values between -1 and 1// Normalize the vectorconst magnitude = Math.sqrt(vector.reduce((sum, val) => sum + val * val, 0));return vector.map((val) => val / magnitude);}-const mockEmbedding = generateRandomEmbedding();-const mockEmbedding2 = generateRandomEmbedding();-function createAxisVector(dimensions: number = 1024, index: number = 0): number[] {return Array.from({ length: dimensions }, (_, i) => (i === index ? 1 : 0));}@@ -1249,7 +1246,10 @@ describe('UserMemoryModel', () => {const created = await userMemoryModel.create(generateRandomCreateUserMemoryExperienceParams(),);-+ // Backdate both stamps: create (DB now()) and update (JS clock) can share a millisecond.+ await serverDB.execute(+ sql`UPDATE user_memories SET created_at = created_at - interval '1 minute', updated_at = created_at - interval '1 minute' WHERE id = ${created.id}`,+ );await userMemoryModel.update(created.id, {memoryCategory: 'updated-category',summary: 'Updated summary',@@ -1263,7 +1263,7 @@ describe('UserMemoryModel', () => {expect(updated?.memoryCategory).toBe('updated-category');expect(updated?.summary).toBe('Updated summary');expect(updated?.title).toBe('Updated title');- expect(updated?.updatedAt.getTime()).toBeGreaterThan(created.createdAt.getTime());+ expect(updated?.updatedAt.getTime()).toBeGreaterThan(updated!.createdAt.getTime());});it('ignores updates for memories owned by other users', async () => {diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.tsindex 4129b0939b4..135aff146a9 100644--- a/packages/database/src/models/__tests__/verifyRun.test.ts+++ b/packages/database/src/models/__tests__/verifyRun.test.ts@@ -442,3 +442,32 @@ describe('VerifyRunModel.listByAcceptances', () => {expect(runs.every((run) => run.acceptanceId === mine)).toBe(true);});});++describe('VerifyRunModel.recordAutoRepair', () => {+ it('exposes the decision on the run state without clobbering other metadata', async () => {+ const operationId = `op-${randomUUID()}`;+ const runId = await buildRun(operationId);+ const model = new VerifyRunModel(serverDB, userId);+ await model.setMetadata(runId, { maxRepairRounds: 2 });++ expect((await model.getStateByOperation(operationId))?.verifyAutoRepair).toBeNull();++ await model.recordAutoRepair(runId, 'declined');++ expect((await model.getStateByOperation(operationId))?.verifyAutoRepair).toBe('declined');+ expect((await model.findById(runId))?.metadata).toMatchObject({+ autoRepair: 'declined',+ maxRepairRounds: 2,+ });+ });++ it('never writes another user’s run', async () => {+ const operationId = `op-${randomUUID()}`;+ const runId = await buildRun(operationId);++ await new VerifyRunModel(serverDB, otherUserId).recordAutoRepair(runId, 'declined');++ const state = await new VerifyRunModel(serverDB, userId).getStateByOperation(operationId);+ expect(state?.verifyAutoRepair).toBeNull();+ });+});diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 3c58b5b5a06..b59afb3964d 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -25,7 +25,12 @@ import { VerifyCriterionModel } from './verifyCriterion';* / verifyStatus) so the router response and every UI / CLI consumer stay* unchanged while the storage moves from agent_operations to verify_runs.*/+/** What auto-repair decided for a failed round (`verify_runs.metadata.autoRepair`). */+export type VerifyAutoRepairOutcome = 'declined' | 'spawned';+export interface VerifyRunState {+ /** `declined` makes a failed round with `auto_repair` checks final. */+ verifyAutoRepair: VerifyAutoRepairOutcome | null;verifyPlan: VerifyCheckItem[] | null;verifyPlanConfirmedAt: Date | null;/** The session id — exposed so a builder holding only its operationId can@@ -54,6 +59,8 @@ const decodeCursor = (cursor?: string): { createdAt: Date; id: string } | null =const toState = (run: VerifyRunItem | null | undefined): VerifyRunState | null =>run? {+ verifyAutoRepair:+ (run.metadata as { autoRepair?: VerifyAutoRepairOutcome } | null)?.autoRepair ?? null,verifyPlan: (run.plan ?? null) as VerifyCheckItem[] | null,verifyPlanConfirmedAt: run.planConfirmedAt ?? null,verifyRunId: run.id,@@ -592,6 +599,16 @@ export class VerifyRunModel {return claimed.length > 0;};+ /** Record the auto-repair decision without clobbering the rest of `metadata`. */+ recordAutoRepair = async (runId: string, outcome: VerifyAutoRepairOutcome): Promise<void> => {+ await this.db+ .update(verifyRuns)+ .set({+ metadata: sql`coalesce(${verifyRuns.metadata}, '{}'::jsonb) || jsonb_build_object('autoRepair', ${outcome}::text)`,+ })+ .where(and(eq(verifyRuns.id, runId), this.ownership()));+ };+setMetadata = async (runId: string, metadata: Record<string, unknown>): Promise<void> => {await this.db.update(verifyRuns)diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.tsindex 2d80c8ed18b..50f3fe7bcc0 100644--- a/src/features/Acceptance/hooks.ts+++ b/src/features/Acceptance/hooks.ts@@ -13,7 +13,7 @@ import type {AcceptanceListQuery,} from '@/services/verify';import { verifyService } from '@/services/verify';-import { useVerifyStore } from '@/store/verify';+import { useVerifyStore, verifySelectors } from '@/store/verify';const ACCEPTANCE_PAGE_SIZE = 30;const VERIFY_REPORT_SWR_CONFIG = {@@ -47,17 +47,29 @@ export const getAcceptanceBySubjectRefreshInterval = (acceptance: unknown) => {return status && TERMINAL_ACCEPTANCE_STATUSES.has(status) ? 0 : 5000;};+/**+ * One Agent Run's verify card, read from the verify store's replica of+ * `verifyRunMap`: a settled run paints from IndexedDB on reload, then refreshes.+ */+const useVerifyRun = (operationId: string | null) => {+ const useFetchVerifyRun = useVerifyStore((s) => s.useFetchVerifyRun);+ const run = useVerifyStore(verifySelectors.verifyRun(operationId));+ const sync = useFetchVerifyRun(operationId);++ return { mutate: sync.revalidate, run };+};+/** Plan + rollup status for one Agent Run. Pass null operationId to skip. */-export const useVerifyState = (operationId: string | null) =>- useClientDataSWR(operationId ? verifyKeys.state(operationId) : null, () =>- verifyService.getVerifyState(operationId!),- );+export const useVerifyState = (operationId: string | null) => {+ const { mutate, run } = useVerifyRun(operationId);+ return { data: run?.state, mutate };+};/** Per-item check results for one Agent Run. Pass null operationId to skip. */-export const useVerifyResults = (operationId: string | null) =>- useClientDataSWR(operationId ? verifyKeys.results(operationId) : null, () =>- verifyService.listResults(operationId!),- );+export const useVerifyResults = (operationId: string | null) => {+ const { mutate, run } = useVerifyRun(operationId);+ return { data: run?.results, mutate };+};/** Full standalone report bundle (run + report + results + evidence) by verifyRunId. */export const useVerifyReportBundle = (verifyRunId: string | null) =>diff --git a/src/features/Portal/VerifyResult/useMoreMenu.ts b/src/features/Portal/VerifyResult/useMoreMenu.tsindex 362efa09821..0edc3183bc1 100644--- a/src/features/Portal/VerifyResult/useMoreMenu.ts+++ b/src/features/Portal/VerifyResult/useMoreMenu.ts@@ -1,8 +1,7 @@import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';-import { mutate as globalMutate } from '@/libs/swr';-import { verifyKeys } from '@/libs/swr/keys';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';+import { useVerifyStore } from '@/store/verify';export const useVerifyResultMoreMenu = (): PortalMoreMenuConfig | undefined => {const operationId = useChatStore(chatPortalSelectors.verifyResultOperationId);@@ -13,11 +12,7 @@ export const useVerifyResultMoreMenu = (): PortalMoreMenuConfig | undefined => {return {// The plan item id — the handle `lh verify` commands and evidence take.copyId: checkItemId,- // Title reads the plan (state), the badge and body read the results.- refresh: () =>- Promise.all([- globalMutate(verifyKeys.state(operationId)),- globalMutate(verifyKeys.results(operationId)),- ]),+ // Title reads the plan (state), the badge and body read the results — one replica entry.+ refresh: () => useVerifyStore.getState().refreshVerifyRun(operationId),};};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 725ff0876bb..773a37ea7bf 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -800,7 +800,6 @@ export const verifyKeys = {'verify:reportBundle',verifyRunId,]),- results: def('verify:results', (operationId: string) => ['verify:results', operationId]),rubric: def('verify:rubric', (rubricId: string) => ['verify:rubric', rubricId]),/** The acceptance round an old `/verify/:runId` link redirects to. */runAcceptanceRound: def('verify:runAcceptanceRound', (verifyRunId: string) => [@@ -812,7 +811,6 @@ export const verifyKeys = {rubricId,]),rubrics: def('verify:rubrics', () => ['verify:rubrics']),- state: def('verify:state', (operationId: string) => ['verify:state', operationId]),tracing: def('verify:tracing', (tracingId: string) => ['verify:tracing', tracingId]),};diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex ff1da0837b7..2144d4ef9e6 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -14,6 +14,8 @@ const preHydrateMessagesMock = vi.hoisted(() => vi.fn(async () => true));const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);const preHydrateBuiltinAgentMock = vi.hoisted(() => vi.fn(async () => true));const preHydrateDeviceListMock = vi.hoisted(() => vi.fn(async () => true));+const preHydrateVerifyRunsMock = vi.hoisted(() => vi.fn(async (_ids: string[]) => {}));+const chatState = vi.hoisted(() => ({ dbMessagesMap: {} as Record<string, unknown[]> }));vi.mock('@lobechat/builtin-agents', () => ({BUILTIN_AGENT_SLUGS: { inbox: 'inbox' },@@ -39,6 +41,7 @@ vi.mock('@/store/agent/selectors', () => ({vi.mock('@/store/chat', () => ({useChatStore: {getState: () => ({+ dbMessagesMap: chatState.dbMessagesMap,preHydrateMessages: preHydrateMessagesMock,preHydrateTopicList: preHydrateTopicListMock,}),@@ -49,6 +52,10 @@ vi.mock('@/store/device', () => ({useDeviceStore: { getState: () => ({ preHydrateDeviceList: preHydrateDeviceListMock }) },}));+vi.mock('@/store/verify', () => ({+ useVerifyStore: { getState: () => ({ preHydrateVerifyRuns: preHydrateVerifyRunsMock }) },+}));+const loaderArgs = (aid?: string) => ({ params: aid ? { aid } : {} }) as never;describe('agent chat topic list loader', () => {@@ -147,7 +154,10 @@ describe('agent chat topic list loader', () => {describe('agent chat transcript pre-hydrate', () => {beforeEach(() => {- preHydrateMessagesMock.mockClear();+ chatState.dbMessagesMap = {};+ preHydrateMessagesMock.mockReset();+ preHydrateMessagesMock.mockResolvedValue(true);+ preHydrateVerifyRunsMock.mockReset();});it("seeds the topic's persisted transcript into the chat store before the route commits", async () => {@@ -160,6 +170,36 @@ describe('agent chat transcript pre-hydrate', () => {});});+ it('seeds the verify cards of the seeded transcript before the route commits', async () => {+ const order: string[] = [];+ preHydrateMessagesMock.mockImplementation(async () => {+ order.push('messages');+ chatState.dbMessagesMap = {+ main_agt_1_tpc_1: [+ { content: 'hi', id: 'msg_1', role: 'user' },+ { id: 'msg_2', metadata: { verifyOperationId: 'op_1' }, role: 'verify' },+ { id: 'msg_3', metadata: {}, role: 'verify' },+ ],+ };+ return true;+ });+ preHydrateVerifyRunsMock.mockImplementation(async () => {+ order.push('verify');+ });++ await preHydrateMessagesForRoute('agt_1', 'tpc_1');++ expect(preHydrateVerifyRunsMock).toHaveBeenCalledWith(['op_1']);+ expect(order).toEqual(['messages', 'verify']);+ });++ it('never rejects the route when the verify cards cannot be read', async () => {+ preHydrateVerifyRunsMock.mockRejectedValueOnce(new Error('storage exploded'));++ await expect(preHydrateMessagesForRoute('agt_1', 'tpc_1')).resolves.toBeUndefined();+ expect(preHydrateMessagesMock).toHaveBeenCalled();+ });+it('skips a route without a topic', async () => {await preHydrateMessagesForRoute('agt_1');diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex 6efb07f2bc7..9702dd6926d 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -6,7 +6,9 @@ import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaintimport { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useDeviceStore } from '@/store/device';+import { useVerifyStore } from '@/store/verify';const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));@@ -58,10 +60,23 @@ export const preHydrateMessagesForRoute = async (const agentId = resolveRouteAgentId(routeAgentId);if (!agentId || !topicId) return;- await settleWithin(- useChatStore.getState().preHydrateMessages({ agentId, scope: 'main', topicId }),- PRE_PAINT_HYDRATE_TIMEOUT,- );+ const context = { agentId, scope: 'main' as const, topicId };+ const seed = async () => {+ await useChatStore.getState().preHydrateMessages(context);++ // Verify cards render from their own replica: seed the cards of the seeded+ // transcript before the route commits, so a settled card paints in the same+ // frame as its message instead of after its own mount-time storage read.+ const messages = useChatStore.getState().dbMessagesMap[messageMapKey(context)] ?? [];+ const verifyOperationIds = messages.flatMap((message) =>+ message.role === 'verify' && message.metadata?.verifyOperationId+ ? [message.metadata.verifyOperationId]+ : [],+ );+ await useVerifyStore.getState().preHydrateVerifyRuns(verifyOperationIds);+ };++ await settleWithin(seed(), PRE_PAINT_HYDRATE_TIMEOUT);};/**diff --git a/src/services/verify.ts b/src/services/verify.tsindex ae6680bb3bd..e47aec11d3c 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -18,6 +18,7 @@ import type {} from '@lobechat/types';import type { VerifyStatus } from '@/database/models/agentOperation';+import type { VerifyAutoRepairOutcome } from '@/database/models/verifyRun';import type {VerifyCheckResultItem,VerifyCriterionItem,@@ -120,6 +121,8 @@ export interface VerifyCriterionDraft {}export interface VerifyStateResponse {+ /** The server's auto-repair decision for a failed round; absent until it decided. */+ verifyAutoRepair?: VerifyAutoRepairOutcome | null;verifyPlan: VerifyCheckItem[] | null;verifyPlanConfirmedAt: Date | null;verifyStatus: VerifyStatus | null;diff --git a/src/store/verify/action.ts b/src/store/verify/action.tsindex 3e2f6e5b94b..dd92b7412b1 100644--- a/src/store/verify/action.ts+++ b/src/store/verify/action.ts@@ -17,6 +17,9 @@ import {acceptanceBundleResource,acceptanceBySubjectKey,acceptanceBySubjectResource,+ toPersistedVerifyRun,+ verifyRunResource,+ type VerifyRunSnapshot,} from './projection';export type Action = Pick<ActionImpl, keyof ActionImpl>;@@ -27,6 +30,7 @@ type Setter = StoreSetter<Store>;/** `acceptanceBundleMap` / `acceptanceBySubjectMap` are plain `Record<key, value>` views. */const acceptanceBundleLens = recordLens<Store, AcceptanceBundle>('acceptanceBundleMap');const acceptanceBySubjectLens = recordLens<Store, AcceptanceBySubject>('acceptanceBySubjectMap');+const verifyRunLens = recordLens<Store, VerifyRunSnapshot>('verifyRunMap');/*** The verify store owns the write-back loop for the delivery-check config@@ -41,6 +45,8 @@ export class ActionImpl {readonly #bundle;/** The subject-attachment replica, behind `acceptanceBySubjectMap`. */readonly #bySubject;+ /** The Agent Run verify card replica, behind `verifyRunMap[operationId]`. */+ readonly #run;/** Pending writes coalesced per id and flushed together on a debounce. */#pendingCriteria = new Map<string, VerifyCriterionEdit>();@@ -84,6 +90,22 @@ export class ActionImpl {stateKey: 'acceptanceBySubjectReplica',view: acceptanceBySubjectLens,});+ this.#run = createReplicaSlice(verifyRunResource, {+ actionPrefix: 'verifyRun',+ fetcher: async (operationId) => {+ const [state, results] = await Promise.all([+ verifyService.getVerifyState(operationId),+ verifyService.listResults(operationId),+ ]);+ return { results, state };+ },+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'verifyRunReplica',+ toPersisted: toPersistedVerifyRun,+ view: verifyRunLens,+ });}/** Re-read one acceptance bundle (after a review, merge, delete or status sweep). */@@ -99,6 +121,24 @@ export class ActionImpl {await this.#bySubject.revalidate(acceptanceBySubjectKey({ subjectId, subjectType }));};+ /**+ * Seed the persisted verify cards of a transcript before its messages mount+ * (route pre-paint), so a settled card paints in the same frame as the+ * message it belongs to instead of a few frames later.+ */+ preHydrateVerifyRuns = async (operationIds: string[]): Promise<void> => {+ if (operationIds.length === 0) return;+ const scope = verifyRunResource.scope.get();+ // The slot may still hold the previous identity's rows; drop them before seeding.+ this.#run.ensureScope(scope);+ await Promise.all(operationIds.map((operationId) => this.#run.hydrate(operationId, scope)));+ };++ /** Re-read one Agent Run's verify card (after a plan action or a manual refresh). */+ refreshVerifyRun = async (operationId: string): Promise<void> => {+ await this.#run.revalidate(operationId);+ };+/*** Fetch orchestration only; the caller reads the bundle through* `acceptanceBundleMap` (`verifySelectors.acceptanceBundle`). `refreshInterval`@@ -143,6 +183,17 @@ export class ActionImpl {revalidateOnReconnect: true,});+ /**+ * Fetch orchestration only; the caller reads the card through `verifyRunMap`+ * (`verifySelectors.verifyRun`). A persisted settled run paints first and is+ * revalidated in the background.+ */+ useFetchVerifyRun = (operationId?: string | null): ReplicaSyncResult =>+ this.#run.useSync(operationId || null, {+ revalidateOnFocus: true,+ revalidateOnReconnect: true,+ });+#persist = async (): Promise<void> => {const criteria = [...this.#pendingCriteria.entries()];const instructions = [...this.#pendingInstructions.entries()];diff --git a/src/store/verify/initialState.ts b/src/store/verify/initialState.tsindex 871a0239df8..84b401df124 100644--- a/src/store/verify/initialState.ts+++ b/src/store/verify/initialState.ts@@ -3,6 +3,8 @@ import type { VerifierType, VerifyOnFailStrategy, VerifyRubricConfig } from '@loimport { createReplicaState, type ReplicaState } from '@/libs/replica';import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';+import type { VerifyRunSnapshot } from './projection';+/** The criterion fields the portal can edit. */export interface VerifyCriterionEdit {description?: string;@@ -42,6 +44,10 @@ export interface State {* in-flight delivery-standard rename pending a debounced save.*/rubricTitleEdits: Record<string, string>;+ /** Replica view of the Agent Run verify cards, one entry per operation id. */+ verifyRunMap: Record<string, VerifyRunSnapshot>;+ /** Replica bookkeeping of `verifyRunMap`. */+ verifyRunReplica: ReplicaState<VerifyRunSnapshot>;}export const initialState: State = {@@ -53,4 +59,6 @@ export const initialState: State = {instructionEdits: {},rubricConfigEdits: {},rubricTitleEdits: {},+ verifyRunMap: {},+ verifyRunReplica: createReplicaState(),};diff --git a/src/store/verify/projection.ts b/src/store/verify/projection.tsindex 80de1f1eff0..99c2ed26922 100644--- a/src/store/verify/projection.ts+++ b/src/store/verify/projection.ts@@ -1,7 +1,9 @@import type { AcceptanceSubjectType } from '@lobechat/types';+import type { VerifyCheckResultItem } from '@/database/schemas/verify';+import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';import { defineReplica } from '@/libs/replica';-import type { AcceptanceBundle, AcceptanceBySubject } from '@/services/verify';+import type { AcceptanceBundle, AcceptanceBySubject, VerifyStateResponse } from '@/services/verify';/*** The Acceptance aggregate of one acceptance id (`acceptanceBundleMap[id]`):@@ -45,3 +47,94 @@ export const acceptanceBySubjectResource = defineReplica<storage: 'indexedDB',version: 1,});++/** The plan + rollup status and per-item results of one Agent Run's verify round. */+export interface VerifyRunSnapshot {+ results: VerifyCheckResultItem[];+ /** `null` when the run has no verify state on the server. */+ state: VerifyStateResponse | null;+}++const SETTLED_VERIFY_STATUSES = new Set(['delivered', 'errored', 'failed', 'passed']);++/** Mirrors the server's repair gate: an `errored` check is infra, not a delivery fault. */+const isFailedResult = (result: VerifyCheckResultItem | undefined): boolean =>+ !!result &&+ result.status !== 'errored' &&+ (result.status === 'failed' || result.verdict === 'failed' || result.verdict === 'uncertain');++/**+ * A `failed` run with a failed required `auto_repair` check is about to flip to+ * `repairing` (the server spawns the repair right after settling the verdict),+ * so that verdict is not final yet — unless the server recorded that it+ * declined the repair (cap reached, superseded round, no spawner, spawn failed).+ */+const awaitsAutoRepair = ({ results, state }: VerifyRunSnapshot): boolean => {+ if (state?.verifyAutoRepair === 'declined') return false;+ const byItem = new Map(results.map((result) => [result.checkItemId, result]));+ return (state?.verifyPlan ?? []).some(+ (item) =>+ item.required !== false &&+ item.onFail === 'auto_repair' &&+ isFailedResult(byItem.get(item.id)),+ );+};++const UNFINISHED_RESULT_STATUSES = new Set(['pending', 'running']);++/**+ * State and results are two requests with no shared snapshot: a check that+ * finishes between them can pair the terminal status with its pre-commit+ * pending row (or no row). Only a snapshot where every required check has a+ * finished result is consistent enough to replay.+ */+const hasFinishedRequiredResults = ({ results, state }: VerifyRunSnapshot): boolean => {+ const byItem = new Map(results.map((result) => [result.checkItemId, result]));+ return (state?.verifyPlan ?? [])+ .filter((item) => item.required !== false)+ .every((item) => {+ const result = byItem.get(item.id);+ return !!result && !UNFINISHED_RESULT_STATUSES.has(result.status);+ });+};++/** A run whose verdict no longer moves — the only kind worth replaying after a reload. */+export const isSettledVerifyRun = (run: VerifyRunSnapshot | undefined): boolean => {+ const status = run?.state?.verifyStatus;+ if (!run || !status || !SETTLED_VERIFY_STATUSES.has(status)) return false;+ if (!hasFinishedRequiredResults(run)) return false;+ return status !== 'failed' || !awaitsAutoRepair(run);+};++const VERIFY_RUN_NAME = 'verifyRun';+const VERIFY_RUN_VERSION = 1;++/**+ * Persist settled runs only. A planned / verifying / repairing run, or a failed+ * run whose auto-repair is still to come, maps to `null`: the engine then drops+ * any earlier row and keeps the key out of its index (so filtered runs never+ * count toward `persist.maxEntries`). A reload cannot replay a stale spinner or+ * a premature verdict.+ */+export const toPersistedVerifyRun = (run: VerifyRunSnapshot): VerifyRunSnapshot | null =>+ isSettledVerifyRun(run) ? run : null;++/**+ * The verify card of one Agent Run (`verifyRunMap[operationId]`), read by the+ * chat thread's Verify message, the verify result portal and the task run+ * detail. State and results live in one entry so a persisted card never pairs+ * a verdict with results from another moment.+ *+ * Settled runs persist to IndexedDB, so a reload paints the last verdict in+ * the first frame and revalidates in the background; LRU-capped because every+ * verified run in history would otherwise keep its row.+ */+export const verifyRunResource = defineReplica<string, VerifyRunSnapshot>({+ key: (operationId) => operationId,+ name: VERIFY_RUN_NAME,+ persist: { maxEntries: 100 },+ storage: new IndexedDBQueryProjectionStorage<VerifyRunSnapshot>({+ namespace: `replica:${VERIFY_RUN_NAME}:v${VERIFY_RUN_VERSION}`,+ }),+ version: VERIFY_RUN_VERSION,+});diff --git a/src/store/verify/selectors.ts b/src/store/verify/selectors.tsindex a5de33ee5cd..b6d419fe0ec 100644--- a/src/store/verify/selectors.ts+++ b/src/store/verify/selectors.ts@@ -24,6 +24,9 @@ const rubricConfigEdit = (rubricId?: string) => (s: Store) =>const rubricTitleEdit = (rubricId?: string) => (s: Store) =>rubricId ? s.rubricTitleEdits[rubricId] : undefined;+const verifyRun = (operationId?: string | null) => (s: Store) =>+ operationId ? s.verifyRunMap[operationId] : undefined;+export const verifySelectors = {acceptanceBundle,acceptanceBySubject,@@ -31,4 +34,5 @@ export const verifySelectors = {instructionEdit,rubricConfigEdit,rubricTitleEdit,+ verifyRun,};diff --git a/src/store/verify/verifyRun.replica.test.ts b/src/store/verify/verifyRun.replica.test.tsnew file mode 100644index 00000000000..25a687cc3b8--- /dev/null+++ b/src/store/verify/verifyRun.replica.test.ts@@ -0,0 +1,245 @@+/**+ * @vitest-environment happy-dom+ *+ * The Agent Run verify card (`verifyRunMap`) is a replica persisted to+ * IndexedDB for settled runs only: a reload paints the last verdict before the+ * network answers, while a run that is still moving never lands in storage.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useVerifyResults, useVerifyState } from '@/features/Acceptance/hooks';+import { cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { verifyService } from '@/services/verify';++import { useVerifyStore } from './index';+import { initialState } from './initialState';+import { verifyRunResource, type VerifyRunSnapshot } from './projection';++const OP = 'op-1';++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const run = (verifyStatus: string, resultStatus = 'passed'): VerifyRunSnapshot =>+ ({+ results: [{ checkItemId: 'item-1', id: 'result-1', status: resultStatus }],+ state: {+ verifyPlan: [{ id: 'item-1', title: 'Renders the card' }],+ verifyPlanConfirmedAt: null,+ verifyStatus,+ },+ }) as unknown as VerifyRunSnapshot;++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const storage = verifyRunResource.storage!;++describe('verify run replica', () => {+ let scope = '';+ let stateSpy: ReturnType<typeof vi.spyOn>;+ let resultsSpy: ReturnType<typeof vi.spyOn>;++ const stored = async () => (await storage.get({ queryKey: OP, scope }))?.data;+ const persist = (data: VerifyRunSnapshot) =>+ storage.set({ queryKey: OP, scope }, { data, updatedAt: 1 });+ const serve = (data: VerifyRunSnapshot) => {+ stateSpy.mockResolvedValue(data.state as never);+ resultsSpy.mockResolvedValue(data.results as never);+ };++ beforeEach(() => {+ scope = `verify-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ stateSpy = vi.spyOn(verifyService, 'getVerifyState');+ resultsSpy = vi.spyOn(verifyService, 'listResults');+ act(() => useVerifyStore.setState(initialState, false));+ });++ afterEach(async () => {+ cleanup();+ await storage.remove({ queryKey: OP, scope });+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope });+ vi.restoreAllMocks();+ });++ it('paints a persisted settled run before the network answers, then refreshes it', async () => {+ await persist(run('failed', 'failed'));+ let release!: (value: unknown) => void;+ stateSpy.mockImplementation(() => new Promise((resolve) => (release = resolve)) as never);+ resultsSpy.mockResolvedValue(run('passed').results as never);++ const { result } = renderHook(+ () => ({ results: useVerifyResults(OP).data, state: useVerifyState(OP).data }),+ { wrapper },+ );++ // The card has its last verdict on the first painted frame after reload.+ await waitFor(() => expect(result.current.state?.verifyStatus).toBe('failed'));+ expect(result.current.results?.[0]?.status).toBe('failed');++ // The background revalidation then replaces it with the server's answer.+ await act(async () => release(run('passed').state));+ await waitFor(() => expect(result.current.state?.verifyStatus).toBe('passed'));+ expect(result.current.results?.[0]?.status).toBe('passed');+ });++ it('pre-hydrates a persisted run into the view before any card mounts', async () => {+ await persist(run('passed'));++ await useVerifyStore.getState().preHydrateVerifyRuns([OP, 'op-missing']);++ expect(useVerifyStore.getState().verifyRunMap[OP]?.state?.verifyStatus).toBe('passed');+ expect(useVerifyStore.getState().verifyRunMap['op-missing']).toBeUndefined();+ });++ it('persists a settled run fetched from the server', async () => {+ serve(run('passed'));++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(() => expect(useVerifyStore.getState().verifyRunMap[OP]).toBeDefined());+ await waitFor(async () => expect((await stored())?.state?.verifyStatus).toBe('passed'));+ });++ it('keeps a run that is still verifying memory-only', async () => {+ serve(run('verifying', 'running'));++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().verifyRunMap[OP]?.state?.verifyStatus).toBe('verifying'),+ );+ // Give the write queue a turn: nothing may land for an unsettled run.+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(await stored()).toBeUndefined();+ });++ it('keeps a failed run that is about to auto-repair memory-only', async () => {+ const autoRepair = run('failed', 'failed');+ autoRepair.state!.verifyPlan = [+ { id: 'item-1', onFail: 'auto_repair', required: true, title: 'Renders the card' },+ ] as never;+ serve(autoRepair);++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().verifyRunMap[OP]?.state?.verifyStatus).toBe('failed'),+ );+ // The server flips this run to `repairing` next: its verdict must not replay.+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(await stored()).toBeUndefined();+ });++ it('persists a failed auto-repair run once the server declined the repair', async () => {+ const declined = run('failed', 'failed');+ declined.state!.verifyPlan = [+ { id: 'item-1', onFail: 'auto_repair', required: true, title: 'Renders the card' },+ ] as never;+ // Repair cap reached / superseded / no spawner: the failure is the final verdict.+ declined.state!.verifyAutoRepair = 'declined';+ serve(declined);++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(async () => expect((await stored())?.state?.verifyStatus).toBe('failed'));+ });++ it('does not persist a settled status paired with results that are still pending', async () => {+ // State and results are two requests: a check can finish between them, so+ // the terminal status may arrive with the pre-commit pending rows.+ const torn = run('passed', 'pending');+ torn.state!.verifyPlan = [{ id: 'item-1', required: true, title: 'Renders the card' }] as never;+ serve(torn);++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().verifyRunMap[OP]?.state?.verifyStatus).toBe('passed'),+ );+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(await stored()).toBeUndefined();+ });++ it('does not persist a settled status missing a required result', async () => {+ const missing = run('failed', 'failed');+ missing.state!.verifyPlan = [+ { id: 'item-1', onFail: 'manual', required: true, title: 'Renders the card' },+ { id: 'item-2', onFail: 'manual', required: true, title: 'Not reported yet' },+ ] as never;+ serve(missing);++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().verifyRunMap[OP]?.state?.verifyStatus).toBe('failed'),+ );+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(await stored()).toBeUndefined();+ });++ it('keeps an unsettled run out of the replica index', async () => {+ serve(run('verifying', 'running'));++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().verifyRunMap[OP]?.state?.verifyStatus).toBe('verifying'),+ );+ await new Promise((resolve) => setTimeout(resolve, 50));+ // A ghost index key would count toward `persist.maxEntries` and evict real rows.+ const index = (await storage.get({ queryKey: REPLICA_INDEX_KEY, scope }))?.data as unknown;+ expect((index as string[] | undefined) ?? []).not.toContain(OP);+ });++ it('persists a failed run whose failed checks are manual', async () => {+ const manual = run('failed', 'failed');+ manual.state!.verifyPlan = [+ { id: 'item-1', onFail: 'manual', required: true, title: 'Renders the card' },+ ] as never;+ serve(manual);++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(async () => expect((await stored())?.state?.verifyStatus).toBe('failed'));+ });++ it('drops the persisted row of a settled run that starts repairing', async () => {+ await persist(run('failed', 'failed'));+ serve(run('repairing', 'failed'));++ renderHook(() => useVerifyStore.getState().useFetchVerifyRun(OP), { wrapper });++ await waitFor(() =>+ expect(useVerifyStore.getState().verifyRunMap[OP]?.state?.verifyStatus).toBe('repairing'),+ );+ await waitFor(async () => expect(await stored()).toBeUndefined());+ });++ it('does not fetch without an operation id', () => {+ stateSpy.mockImplementation(pending);+ renderHook(() => useVerifyState(null), { wrapper });+ expect(stateSpy).not.toHaveBeenCalled();+ });+});