🤯 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): move reports, tracing, rubrics, goal criteria and plan skills onto @lobechat/replica (#22748)
Arvin Xu195092f8f2c8
diff --git a/src/features/Acceptance/Report/ReportViewer.tsx b/src/features/Acceptance/Report/ReportViewer.tsxindex d8d038f5dd9..e9693d91ad4 100644--- a/src/features/Acceptance/Report/ReportViewer.tsx+++ b/src/features/Acceptance/Report/ReportViewer.tsx@@ -1181,7 +1181,7 @@ const ReportViewer = memo<ReportViewerProps>(({ runId: explicitRunId }) => {);}if (isLoading) return <Loading debugId="verify-report-viewer" />;- if (error) {+ if (error && data === undefined) {return (<ReportPageStatedescription={t('report.error.description')}diff --git a/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx b/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsxindex eaccbcd6779..ca4f824649b 100644--- a/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx+++ b/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx@@ -7,13 +7,12 @@ import AsyncError from '@/components/AsyncError';import Loading from '@/components/Loading/CircleLoading';import {unreadableVersions,+ usePlanSkill,useSkillVersion,} from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';import { getLanguage } from '@/features/AgentSkillDetail/ContentViewer';import FileTree from '@/features/FileTree';import { skillFileTree } from '@/features/SkillViewer/skillFileTree';-import { useClientDataSWR } from '@/libs/swr';-import { userSkillService } from '@/services/userSkill';import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';const SKILL_INDEX = 'SKILL.md';@@ -59,9 +58,7 @@ interface SkillDirectoryProps {const SkillDirectory = memo<SkillDirectoryProps>(({ fallbackContent, filesOpen, revision, skillId }) => {const [selectedFile, setSelectedFile] = useState(SKILL_INDEX);- const { data: skill, isLoading } = useClientDataSWR(['goal-gate-plan-skill', skillId], () =>- userSkillService.get(skillId),- );+ const { data: skill, isLoading } = usePlanSkill(skillId);const {data: shipped,error,diff --git a/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts b/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.tsindex 36801dd7235..d9572407434 100644--- a/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts+++ b/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts@@ -12,13 +12,10 @@ const skill = vi.hoisted(() => ({versions: {} as Record<number, { files?: unknown[] }>,}));-vi.mock('@/libs/swr', () => ({- useClientDataSWR: (key: unknown) => ({ data: key ? skill.current : undefined }),-}));vi.mock('@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions', () => ({+ usePlanSkill: (skillId: string | undefined) => ({ data: skillId ? skill.current : undefined }),useSkillVersion: (_skillId: string, version: number) => ({ data: skill.versions[version] }),}));-vi.mock('@/services/userSkill', () => ({ userSkillService: { get: vi.fn() } }));const file = (path: string) => ({ content: '', path });diff --git a/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts b/src/features/Acceptance/Viewer/Gate/usePlanFiles.tsindex 2e5ef9f1583..06799eaf2f9 100644--- a/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts+++ b/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts@@ -1,8 +1,9 @@import { useState } from 'react';-import { useSkillVersion } from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';-import { useClientDataSWR } from '@/libs/swr';-import { userSkillService } from '@/services/userSkill';+import {+ usePlanSkill,+ useSkillVersion,+} from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';/*** The plan skill's directory under review. A plan that ships scripts or@@ -11,9 +12,7 @@ import { userSkillService } from '@/services/userSkill';* Shares the directory's requests, so it costs no second fetch.*/export const usePlanFiles = (skillId: string | undefined, revision: number) => {- const { data: skill } = useClientDataSWR(skillId ? ['goal-gate-plan-skill', skillId] : null, () =>- userSkillService.get(skillId!),- );+ const { data: skill } = usePlanSkill(skillId);const { data: shipped } = useSkillVersion(skillId, revision);// What sits beside `SKILL.md` in the reviewed version (not `SKILL.md` itself).const extraFiles = (shipped?.files ?? skill?.files ?? []).length;diff --git a/src/features/Acceptance/hooks.test.ts b/src/features/Acceptance/hooks.test.tsindex 5d88bccd969..1e8ffc7929b 100644--- a/src/features/Acceptance/hooks.test.ts+++ b/src/features/Acceptance/hooks.test.ts@@ -11,8 +11,6 @@ import {getAcceptanceBySubjectRefreshInterval,useAcceptanceBySubject,useAcceptanceList,- useRubrics,- useVerifyReportBundle,} from './hooks';const createSWRWrapper = (cache: Cache) =>@@ -25,21 +23,6 @@ describe('Verify data hooks', () => {vi.restoreAllMocks();});- it('reuses a cached report bundle without revalidating after a remount', async () => {- const getReportBundle = vi.spyOn(verifyService, 'getReportBundle').mockResolvedValue(null);- const wrapper = createSWRWrapper(new Map());-- const firstMount = renderHook(() => useVerifyReportBundle('run-1'), { wrapper });- await waitFor(() => expect(getReportBundle).toHaveBeenCalledTimes(1));- firstMount.unmount();-- const secondMount = renderHook(() => useVerifyReportBundle('run-1'), { wrapper });- await act(() => new Promise((resolve) => setTimeout(resolve, 20)));-- expect(secondMount.result.current.data).toBeNull();- expect(getReportBundle).toHaveBeenCalledTimes(1);- });-it('loads an acceptance by its task subject identifier', async () => {const getAcceptanceBySubject = vi.spyOn(verifyService, 'getAcceptanceBySubject')@@ -113,13 +96,4 @@ describe('Verify data hooks', () => {expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'accepted' })).toBe(0);expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'closed' })).toBe(0);});-- it('does not request rubrics while rubric authoring is inactive', async () => {- const listRubrics = vi.spyOn(verifyService, 'listRubrics').mockResolvedValue([]);-- renderHook(() => useRubrics(false), { wrapper: createSWRWrapper(new Map()) });- await act(() => new Promise((resolve) => setTimeout(resolve, 20)));-- expect(listRubrics).not.toHaveBeenCalled();- });});diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.tsindex f1059d40de2..d5099e7f661 100644--- a/src/features/Acceptance/hooks.ts+++ b/src/features/Acceptance/hooks.ts@@ -1,16 +1,18 @@import type { CreatableAcceptanceSubjectType } from '@lobechat/types';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import type { ReplicaSyncResult } from '@/libs/replica';import { useClientDataSWR } from '@/libs/swr';import { verifyKeys } from '@/libs/swr/keys';-import { documentService } from '@/services/document';import type {AcceptanceBySubject,AcceptanceListFilter,AcceptanceListItem,AcceptanceListQuery,+ VerifyReportBundle,} from '@/services/verify';import { verifyService } from '@/services/verify';+import { useDocumentStore } from '@/store/document';import { useVerifyStore, verifySelectors } from '@/store/verify';import type { AcceptanceListParams, AcceptancePageParams } from '@/store/verify/projection';@@ -60,13 +62,45 @@ export const useVerifyResults = (operationId: string | null) => {return { data: run?.results, mutate };};-/** Full standalone report bundle (run + report + results + evidence) by verifyRunId. */-export const useVerifyReportBundle = (verifyRunId: string | null) =>- useClientDataSWR(- verifyRunId ? verifyKeys.reportBundle(verifyRunId) : null,- () => verifyService.getReportBundle(verifyRunId!),- VERIFY_REPORT_SWR_CONFIG,- );+/**+ * What a replica-backed read hands the views that used to read an SWR response:+ * `data` is the store entry (`undefined` until hydrated or fetched), `mutate`+ * re-runs the network sync.+ */+export interface VerifyReplicaRead<T> {+ data: T | undefined;+ error: unknown;+ /** Nothing to show yet, and no failure either. */+ isLoading: boolean;+ isValidating: boolean;+ mutate: () => Promise<unknown>;+}++const toReplicaRead = <T>(+ data: T | undefined,+ sync: ReplicaSyncResult,+ enabled: boolean,+): VerifyReplicaRead<T> => ({+ data,+ error: sync.error,+ isLoading: enabled && data === undefined && sync.error == null,+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+});++/**+ * Full standalone report bundle (run + report + results + evidence) by+ * verifyRunId. `data` is `null` once the server answered there is no such run;+ * a finished report paints from IndexedDB on reload, then refreshes.+ */+export const useVerifyReportBundle = (+ verifyRunId: string | null,+): VerifyReplicaRead<VerifyReportBundle | null> => {+ const useFetchVerifyReportBundle = useVerifyStore((s) => s.useFetchVerifyReportBundle);+ const data = useVerifyStore(verifySelectors.verifyReportBundle(verifyRunId));+ const sync = useFetchVerifyReportBundle(verifyRunId);+ return toReplicaRead(data, sync, !!verifyRunId);+};export { useAcceptanceBundle } from './Viewer/useAcceptanceBundle';@@ -243,33 +277,43 @@ export const useAcceptanceListInfinite = (};/** 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, () =>- verifyService.getVerifierTracing(tracingId!),- );--/** The criterion's original judging rule, stored in its instruction document. */-export const useVerifyInstruction = (documentId: string | null | undefined) =>- useClientDataSWR(documentId ? verifyKeys.instruction(documentId) : null, () =>- documentService.getDocumentById(documentId!),- );+export const useVerifierTracing = (tracingId: string | null | undefined) => {+ const useFetchVerifierTracing = useVerifyStore((s) => s.useFetchVerifierTracing);+ const data = useVerifyStore(verifySelectors.verifierTracing(tracingId));+ const sync = useFetchVerifierTracing(tracingId);+ return toReplicaRead(data, sync, !!tracingId);+};-/** A rubric and its run-policy config (e.g. maxRepairRounds). Pass null to skip. */-export const useRubric = (rubricId: string | null | undefined) =>- useClientDataSWR(rubricId ? verifyKeys.rubric(rubricId) : null, () =>- verifyService.getRubric(rubricId!),- );+/**+ * The criterion's original judging rule, stored in its instruction document.+ * Shares the document detail replica, so it paints from the same persisted row+ * as every other view of that document.+ */+export const useVerifyInstruction = (documentId: string | null | undefined) => {+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);+ return useFetchDocumentDetail(documentId || undefined);+};/** The workspace's reusable rubric templates (delivery-standard groups). */-export const useRubrics = (enabled = true) =>- useClientDataSWR(enabled ? verifyKeys.rubrics() : null, () => verifyService.listRubrics());--/** The workspace's reusable atomic criteria. */-export const useCriteria = () =>- useClientDataSWR(verifyKeys.criteria(), () => verifyService.listCriteria());+export const useRubrics = (enabled = true) => {+ const useFetchVerifyRubrics = useVerifyStore((s) => s.useFetchVerifyRubrics);+ const data = useVerifyStore(verifySelectors.verifyRubrics);+ const sync = useFetchVerifyRubrics(enabled);+ return toReplicaRead(data, sync, enabled);+};/** The criteria a rubric groups, in rubric order. Pass null to skip. */-export const useRubricCriteria = (rubricId: string | null | undefined) =>- useClientDataSWR(rubricId ? verifyKeys.rubricCriteria(rubricId) : null, () =>- verifyService.getRubricCriteria(rubricId!),- );+export const useRubricCriteria = (rubricId: string | null | undefined) => {+ const useFetchVerifyRubricCriteria = useVerifyStore((s) => s.useFetchVerifyRubricCriteria);+ const data = useVerifyStore(verifySelectors.verifyRubricCriteria(rubricId));+ const sync = useFetchVerifyRubricCriteria(rubricId);+ return toReplicaRead(data, sync, !!rubricId);+};++/** The persisted criteria a Goal is accepted against, in its order. Empty ids skip. */+export const useGoalCriteria = (criteriaIds: string[]) => {+ const useFetchGoalCriteria = useVerifyStore((s) => s.useFetchGoalCriteria);+ const data = useVerifyStore(verifySelectors.goalCriteria(criteriaIds));+ const sync = useFetchGoalCriteria(criteriaIds);+ return toReplicaRead(data, sync, criteriaIds.length > 0);+};diff --git a/src/features/AgentGoals/GoalAcceptanceCriteria.tsx b/src/features/AgentGoals/GoalAcceptanceCriteria.tsxindex a889ddb53a2..d078b32a542 100644--- a/src/features/AgentGoals/GoalAcceptanceCriteria.tsx+++ b/src/features/AgentGoals/GoalAcceptanceCriteria.tsx@@ -16,8 +16,8 @@ import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import { openCriterionEditModal } from '@/features/Acceptance';+import { useGoalCriteria } from '@/features/Acceptance/hooks';import { usePermission } from '@/hooks/usePermission';-import { useClientDataSWR } from '@/libs/swr';import { goalService } from '@/services/goal';import type { GoalCriterionWithInstruction } from '@/services/verify';import { verifyService } from '@/services/verify';@@ -55,10 +55,7 @@ const GoalAcceptanceCriteria = memo<{ criteriaIds: string[]; goalId: string }>(const { allowed: canEdit } = usePermission('create_content');const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);- const { data: criteria, mutate } = useClientDataSWR(- criteriaIds.length > 0 ? ['goal-acceptance-criteria', goalId, criteriaIds.join(',')] : null,- () => verifyService.getCriteria(criteriaIds),- );+ const { data: criteria, mutate } = useGoalCriteria(criteriaIds);const rebind = useCallback(async (nextIds: string[]) => {diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsxindex 4ce6e7b7610..4bd6a65b4b6 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx@@ -1,12 +1,19 @@'use client';-import { createContext, memo, type PropsWithChildren, use, useMemo, useState } from 'react';--import { useClientDataSWR } from '@/libs/swr';-import { userSkillService } from '@/services/userSkill';+import {+ createContext,+ memo,+ type PropsWithChildren,+ use,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import type { GoalGraphView } from '../goalGraphViewModel';import type { BatchModel, BatchRound } from '../Graph/batchModel';+import { usePlanSkill } from './skillVersions';/*** The plan version a reader picked in the panel's header, shared with its body.@@ -44,11 +51,17 @@ export interface PlanVersion {*/export const usePlanVersions = (graph: GoalGraphView, model: BatchModel) => {const planSkill = model.planSkill;- // Keyed by the round count, so a revision the panel is open on loads its version.- const { data: skill, isLoading } = useClientDataSWR(- planSkill ? ['goal-plan-skill', planSkill.id, model.rounds.length] : null,- () => userSkillService.get(planSkill!.id),- );+ const planSkillId = planSkill?.id;+ const { data: skill, isLoading, mutate } = usePlanSkill(planSkillId);+ // A new round can rewrite the plan: re-read the skill once the round count+ // moves, so a revision the panel is open on loads its version.+ const roundCount = model.rounds.length;+ const lastRoundCount = useRef(roundCount);+ useEffect(() => {+ if (lastRoundCount.current === roundCount) return;+ lastRoundCount.current = roundCount;+ if (planSkillId) void mutate();+ }, [mutate, planSkillId, roundCount]);const kept = [...(skill?.versions ?? [])].sort((a, b) => a.version - b.version);const versions: PlanVersion[] = kept.length? kept.map((version) => ({ revision: version.version }))diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.tsindex 08bf6750190..3f0f9f0c7a4 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import { unreadableVersions } from './skillVersions';-vi.mock('@/services/userSkill', () => ({ userSkillService: {} }));+vi.mock('@/store/verify', () => ({ useVerifyStore: vi.fn(), verifySelectors: {} }));describe('unreadableVersions', () => {const error = new Error('storage down');diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.tsindex 46a77c1ba32..404508858cb 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts@@ -1,17 +1,45 @@-import { useClientDataSWR } from '@/libs/swr';-import { userSkillService } from '@/services/userSkill';+import { useMemo } from 'react';++import { useVerifyStore, verifySelectors } from '@/store/verify';/*** One version of a skill as it shipped — its `SKILL.md` and the files beside* it — read from its archive on demand. A version never changes, so it is- * fetched once and shared by every view that reads it.+ * persisted once, painted from IndexedDB on a reload and shared by every view+ * that reads it. `data` is `null` once the server answered it has no such version.*/-export const useSkillVersion = (skillId: string | undefined, version: number | undefined) =>- useClientDataSWR(- skillId && version ? ['user-skill-version', skillId, version] : null,- () => userSkillService.getVersion(skillId!, version!),- { revalidateOnFocus: false, revalidateOnReconnect: false },+export const useSkillVersion = (skillId: string | undefined, version: number | undefined) => {+ const params = useMemo(+ () => (skillId && version ? { skillId, version } : null),+ [skillId, version],);+ const useFetchSkillVersion = useVerifyStore((s) => s.useFetchSkillVersion);+ const data = useVerifyStore(verifySelectors.skillVersion(params));+ const sync = useFetchSkillVersion(params);+ return {+ data,+ error: sync.error,+ isLoading: !!params && data === undefined && sync.error == null,+ mutate: sync.revalidate,+ };+};++/**+ * A plan skill from the user's library with every version it kept, shared by+ * the gate's directory, its file toggle and the batch plan's version list.+ * Paints from IndexedDB on a reload; `data` is `null` once the skill is gone.+ */+export const usePlanSkill = (skillId: string | undefined) => {+ const useFetchPlanSkill = useVerifyStore((s) => s.useFetchPlanSkill);+ const data = useVerifyStore(verifySelectors.planSkill(skillId));+ const sync = useFetchPlanSkill(skillId);+ return {+ data,+ error: sync.error,+ isLoading: !!skillId && data === undefined && sync.error == null,+ mutate: sync.revalidate,+ };+};/*** The versions that failed to read and have nothing to show. Pending ones arediff --git a/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts b/src/features/AgentGoals/ProcessControl/useGoalResultData.test.tsindex 4a6414ef0f0..25df4ebd0c0 100644--- a/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts+++ b/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts@@ -12,7 +12,8 @@ const mocks = vi.hoisted(() => ({getCriteria: vi.fn(),}));-vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+vi.mock('@/business/client/hooks/useActiveWorkspaceId', async (importOriginal) => ({+ ...(await importOriginal<object>()),useActiveWorkspaceId: () => undefined,}));vi.mock('@/services/verify', () => ({diff --git a/src/features/AgentGoals/ProcessControl/useGoalResultData.ts b/src/features/AgentGoals/ProcessControl/useGoalResultData.tsindex 645ab065bba..d4112d7fbba 100644--- a/src/features/AgentGoals/ProcessControl/useGoalResultData.ts+++ b/src/features/AgentGoals/ProcessControl/useGoalResultData.ts@@ -1,5 +1,7 @@-import { useClientDataSWR } from '@/libs/swr';-import { verifyService } from '@/services/verify';+import { useEffect, useRef } from 'react';++import { useGoalCriteria } from '@/features/Acceptance/hooks';+import { useVerifyStore, verifySelectors } from '@/store/verify';import type { GoalGraphView } from './goalGraphViewModel';import {@@ -11,10 +13,10 @@ import {} from './goalResultState';/**- * Keyed by the graph's view of the acceptance as well as its id. A rework keeps- * the same acceptance id, so an id-only key held the rejected round until a- * reload; the polled graph moving the acceptance (or its Task node) on is what- * re-reads the bundle.+ * The graph's view of the acceptance, and a reason to re-read the bundle when+ * it moves. A rework keeps the same acceptance id, so reading by id alone held+ * the rejected round until a reload; the polled graph moving the acceptance (or+ * its Task node) on is what re-reads the bundle.** The Goal's own status is part of that state too. A rework ends by putting the* Goal back on `achieved` — the moment the graph poll stops — and the snapshot@@ -23,8 +25,10 @@ import {* sign-off strip kept reading 修改中 until the page was reloaded; the Goal* moving on is its own reason to re-read the latest round.*/-export const goalResultAcceptanceKey = (acceptanceId: string, graphState: string) =>- ['goal-result-acceptance', acceptanceId, graphState] as const;+export const goalResultGraphState = (graph: GoalGraphView) => {+ const acceptanceView = findGoalAcceptanceView(graph);+ return `${graph.goal.status}:${acceptanceView?.acceptance?.status}:${acceptanceView?.node.status}`;+};/*** What the result page reads beyond the graph: the Goal-level acceptance@@ -38,20 +42,27 @@ export const useGoalResultData = (graph: GoalGraphView) => {const acceptanceId = acceptanceView?.acceptance?.id;const criteriaIds = graph.goal.config?.acceptance?.criteriaIds ?? [];- const graphState = `${graph.goal.status}:${acceptanceView?.acceptance?.status}:${acceptanceView?.node.status}`;- const bundle = useClientDataSWR(- acceptanceId ? goalResultAcceptanceKey(acceptanceId, graphState) : null,- () => verifyService.getAcceptanceBundle(acceptanceId!),- // Keep the page on the last bundle while the next state loads, instead of- // dropping back to skeletons every time the graph moves.- { keepPreviousData: true },- );- const criteria = useClientDataSWR(- criteriaIds.length > 0- ? ['goal-acceptance-criteria', graph.goal.id, criteriaIds.join(',')]- : null,- () => verifyService.getCriteria(criteriaIds),- );+ const graphState = goalResultGraphState(graph);+ // The same replica entry the Acceptance viewer reads: a reload paints the+ // last bundle from IndexedDB, and the page stays on it while the next state loads.+ const useFetchAcceptanceBundle = useVerifyStore((s) => s.useFetchAcceptanceBundle);+ const bundleData = useVerifyStore(verifySelectors.acceptanceBundle(acceptanceId));+ const bundleSync = useFetchAcceptanceBundle(acceptanceId);+ const criteria = useGoalCriteria(criteriaIds);++ // Re-read the bundle once the graph moves the acceptance on (see above). The+ // first state is covered by the sync's own mount request.+ const lastGraphState = useRef<string>(undefined);+ const { revalidate } = bundleSync;+ useEffect(() => {+ const previous = lastGraphState.current;+ lastGraphState.current = acceptanceId ? `${acceptanceId}|${graphState}` : undefined;+ if (!acceptanceId || previous === undefined || previous === lastGraphState.current) return;+ if (!previous.startsWith(`${acceptanceId}|`)) return;+ void revalidate();+ }, [acceptanceId, graphState, revalidate]);++ const bundle = { data: bundleData, error: bundleSync.error };const outcomes: CriterionOutcome[] = buildCriterionOutcomes({checks: (bundle.data?.checks ?? []) as unknown as CheckLike[],@@ -62,7 +73,9 @@ export const useGoalResultData = (graph: GoalGraphView) => {// A failed read must not pass for a result: empty checks would render every// criterion as unjudged and a missing bundle would hide the sign-off.- const error = bundle.error ?? criteria.error;+ // A failed background refresh keeps the result already on screen.+ const error =+ (bundle.data ? undefined : bundle.error) ?? (criteria.data ? undefined : criteria.error);return {acceptanceId,@@ -71,11 +84,11 @@ export const useGoalResultData = (graph: GoalGraphView) => {canReview: bundle.data?.canReview ?? false,error,isLoading:- (!!acceptanceId && bundle.isLoading && !bundle.data) ||+ (!!acceptanceId && !bundle.data && bundle.error == null) ||(criteriaIds.length > 0 && criteria.isLoading),- mutateAcceptance: bundle.mutate,+ mutateAcceptance: bundleSync.revalidate,outcomes,- retry: () => Promise.all([bundle.mutate(), criteria.mutate()]),+ retry: () => Promise.all([bundleSync.revalidate(), criteria.mutate()]),};};diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsxindex 908cfee081a..ec860be1567 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx@@ -147,7 +147,7 @@ const TaskVerifyConfig = memo(() => {});const savedCount = verify?.verifyCriteriaIds?.length ?? 0;- const { data: rubrics } = useRubrics();+ const { data: rubrics, mutate: refreshRubrics } = useRubrics();// ---- local working state ----const [requirement, setRequirement] = useState(verify?.requirement ?? '');@@ -483,11 +483,13 @@ const TaskVerifyConfig = memo(() => {rubric.id,templateCriterionIds.map((criterionId) => ({ criterionId })),);+ // The template list is persisted: list the new template now, not after a reload.+ void refreshRubrics();toast.success(t('verifyConfig.saveAsTemplateSuccess'));} catch (e) {console.error('[TaskVerifyConfig] save as template failed:', e);}- }, [drafts, verify?.verifyCriteriaIds, requirement, t]);+ }, [drafts, verify?.verifyCriteriaIds, refreshRubrics, requirement, t]);const rubricOptions = useMemo(() => (rubrics ?? []).map((r) => ({ label: r.title, value: r.id })),diff --git a/src/features/Portal/VerifyReport/useMoreMenu.test.ts b/src/features/Portal/VerifyReport/useMoreMenu.test.tsindex 1b4a3a49d6f..ee08d1a25fe 100644--- a/src/features/Portal/VerifyReport/useMoreMenu.test.ts+++ b/src/features/Portal/VerifyReport/useMoreMenu.test.ts@@ -10,8 +10,10 @@ const mocks = vi.hoisted(() => ({vi.mock('@/components/RenameModal', () => ({ openRenameModal: vi.fn() }));vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: mocks.allowed }) }));-vi.mock('@/libs/swr', () => ({ mutate: vi.fn() }));-vi.mock('@/services/verify', () => ({ verifyService: { updateRunTitle: vi.fn() } }));+vi.mock('@/store/verify', () => ({+ useVerifyStore: (selector: (s: unknown) => unknown) =>+ selector({ refreshVerifyReportBundle: vi.fn(), renameVerifyReportRun: vi.fn() }),+}));vi.mock('./useReportUrl', () => ({useVerifyReportUrl: () => ({reportUrl: 'https://app.lobehub.com/acceptance/acc_1?r=2',diff --git a/src/features/Portal/VerifyReport/useMoreMenu.ts b/src/features/Portal/VerifyReport/useMoreMenu.tsindex 5b06418ee07..b366de62935 100644--- a/src/features/Portal/VerifyReport/useMoreMenu.ts+++ b/src/features/Portal/VerifyReport/useMoreMenu.ts@@ -5,22 +5,22 @@ import { openRenameModal } from '@/components/RenameModal';import { useVerifyReportBundle } from '@/features/Acceptance/hooks';import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';import { usePermission } from '@/hooks/usePermission';-import { mutate as globalMutate } from '@/libs/swr';-import { verifyKeys } from '@/libs/swr/keys';-import { verifyService } from '@/services/verify';+import { useVerifyStore } from '@/store/verify';import { useVerifyReportUrl } from './useReportUrl';export const useVerifyReportMoreMenu = (): PortalMoreMenuConfig | undefined => {const { t } = useTranslation('verify');const { reportUrl, runId } = useVerifyReportUrl();- // Same SWR key as the title and body, so this shares their request.+ // Same replica entry as the title and body, so this shares their request.const { data } = useVerifyReportBundle(runId ?? null);+ const refreshVerifyReportBundle = useVerifyStore((s) => s.refreshVerifyReportBundle);+ const renameVerifyReportRun = useVerifyStore((s) => s.renameVerifyReportRun);const { allowed: canEdit } = usePermission('edit_own_content');if (!runId) return;- const refresh = () => globalMutate(verifyKeys.reportBundle(runId));+ const refresh = () => refreshVerifyReportBundle(runId);return {copyId: runId,@@ -35,8 +35,7 @@ export const useVerifyReportMoreMenu = (): PortalMoreMenuConfig | undefined => {defaultValue: data.run.title ?? '',onSave: async (next) => {try {- await verifyService.updateRunTitle(runId, next);- await refresh();+ await renameVerifyReportRun(runId, next);toast.success(t('workspace.renameSuccess'));} catch (error) {console.error('[verify-report:rename]', error);diff --git a/src/features/Portal/VerifyReport/useReportUrl.ts b/src/features/Portal/VerifyReport/useReportUrl.tsindex fbb20268b4a..26a253ddebd 100644--- a/src/features/Portal/VerifyReport/useReportUrl.ts+++ b/src/features/Portal/VerifyReport/useReportUrl.ts@@ -12,7 +12,7 @@ import { chatPortalSelectors } from '@/store/chat/selectors';export const useVerifyReportUrl = () => {const appOrigin = useAcceptanceOrigin();const runId = useChatStore(chatPortalSelectors.verifyReportRunId);- // Same SWR key as the portal's title and body, so this shares their request.+ // Same replica entry as the portal's title and body, so this shares their request.const { data } = useVerifyReportBundle(runId ?? null);const roundPath = buildAcceptanceRoundPath(data?.run);// Copied and opened outside the app, so it stays on the public route: thediff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.tsindex 6c7a32259e4..a62dc87ced5 100644--- a/src/libs/swr/keys.frozen.test.ts+++ b/src/libs/swr/keys.frozen.test.ts@@ -168,14 +168,7 @@ const LEGACY_SWR_KEYS = ['userMemoryKeys.retrieve','userMemoryKeys.tags','verifyKeys.acceptancePurgePreview',- 'verifyKeys.criteria',- 'verifyKeys.instruction',- 'verifyKeys.reportBundle',- 'verifyKeys.rubric',- 'verifyKeys.rubricCriteria',- 'verifyKeys.rubrics','verifyKeys.runAcceptanceRound',- 'verifyKeys.tracing','videoKeys.generationStatus','workKeys.conversation','workKeys.versions',diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 4f96779b4b4..92e1e5158e3 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -632,27 +632,11 @@ export const verifyKeys = {'verify:acceptancePurgePreview',acceptanceId,]),- criteria: def('verify:criteria', () => ['verify:criteria']),- instruction: def('verify:instruction', (documentId: string) => [- 'verify:instruction',- documentId,- ]),- reportBundle: def('verify:reportBundle', (verifyRunId: string) => [- 'verify:reportBundle',- verifyRunId,- ]),- 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) => ['verify:runAcceptanceRound',verifyRunId,]),- rubricCriteria: def('verify:rubricCriteria', (rubricId: string) => [- 'verify:rubricCriteria',- rubricId,- ]),- rubrics: def('verify:rubrics', () => ['verify:rubrics']),- tracing: def('verify:tracing', (tracingId: string) => ['verify:tracing', tracingId]),};// ---- inbox / notifications ----------------------------------------------diff --git a/src/store/verify/action.ts b/src/store/verify/action.tsindex c07deacbe31..a8bc1a99542 100644--- a/src/store/verify/action.ts+++ b/src/store/verify/action.ts@@ -1,6 +1,7 @@import type {AcceptanceCommentList,CreatableAcceptanceSubjectType,+ UserSkillVersionDetail,VerifyRubricConfig,} from '@lobechat/types';import { debounce } from 'es-toolkit/compat';@@ -8,17 +9,27 @@ import isEqual from 'fast-deep-equal';import { type StateCreator } from 'zustand';import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@/const/index';+import type { VerifyCriterionItem, VerifyRubricItem } from '@/database/schemas/verify';import {createReplicaSlice,linkReplicaEntity,recordLens,type ReplicaPageResult,type ReplicaSyncResult,+ revalidateReplica,} from '@/libs/replica';import { acceptanceCommentService } from '@/services/acceptanceComment';import { documentService } from '@/services/document';-import type { AcceptanceBundle, AcceptanceBySubject, AcceptanceListItem } from '@/services/verify';+import { type UserSkillDetail, userSkillService } from '@/services/userSkill';+import type {+ AcceptanceBundle,+ AcceptanceBySubject,+ AcceptanceListItem,+ GoalCriterionWithInstruction,+ VerifyReportBundle,+} from '@/services/verify';import { verifyService } from '@/services/verify';+import { documentDetailResource } from '@/store/document/slices/document/projection';import { type StoreSetter } from '@/store/types';import { flattenActions } from '@/store/utils/flattenActions';import { isTrpcErrorCode } from '@/utils/trpcError';@@ -37,7 +48,20 @@ import {acceptancePageKey,type AcceptancePageParams,acceptancePageResource,+ goalCriteriaResource,+ planSkillResource,+ type SkillVersionParams,+ skillVersionResource,+ toPersistedLookup,+ toPersistedReportBundle,toPersistedVerifyRun,+ type VerifierTracing,+ verifierTracingResource,+ VERIFY_RUBRIC_LIST_KEY,+ type VerifyLookup,+ verifyReportBundleResource,+ verifyRubricCriteriaResource,+ verifyRubricListResource,verifyRunResource,type VerifyRunSnapshot,} from './projection';@@ -65,6 +89,20 @@ export const ACCEPTANCE_PAGE_SIZE = 30;*/const ACCEPTANCE_LIST_DEDUPE_MS = 10_000;+/**+ * Several views read one entry at once (the report page with the portal title,+ * menu and link; the gate directory with its file toggle), and the app's SWR+ * hook does not dedupe: collapse their mount requests into one. A manual,+ * write-driven or polled `revalidate` still goes out.+ */+const SHARED_READ_DEDUPE = 10_000;++/** The read was denied or the record is gone: the cached copy must stop rendering. */+const isTerminalReadError = (error: unknown) =>+ isTrpcErrorCode(error, 'NOT_FOUND') ||+ isTrpcErrorCode(error, 'FORBIDDEN') ||+ isTrpcErrorCode(error, 'UNAUTHORIZED');+/*** The verify store owns the write-back loop for the delivery-check config* portal: every control writes through `updateCriterion` / `updateInstruction`,@@ -88,6 +126,20 @@ export class ActionImpl {readonly #listEntity;/** Each acceptance's discussion, behind `acceptanceCommentMap[acceptanceId]`. */readonly #comments;+ /** Standalone verify reports, behind `verifyReportBundleMap[verifyRunId]`. */+ readonly #report;+ /** LLM verifier tracings, behind `verifierTracingMap[tracingId]`. */+ readonly #tracing;+ /** Rubric templates, behind `verifyRubricListMap.all`. */+ readonly #rubrics;+ /** The criteria of one rubric, behind `verifyRubricCriteriaMap[rubricId]`. */+ readonly #rubricCriteria;+ /** A Goal's acceptance criteria, behind `goalCriteriaMap[ids]`. */+ readonly #goalCriteria;+ /** Plan skills under review, behind `planSkillMap[skillId]`. */+ readonly #planSkill;+ /** Shipped skill versions, behind `skillVersionMap['<id>@<version>']`. */+ readonly #skillVersion;/** Pending writes coalesced per id and flushed together on a debounce. */#pendingCriteria = new Map<string, VerifyCriterionEdit>();@@ -175,6 +227,79 @@ export class ActionImpl {stateKey: 'acceptanceCommentReplica',view: acceptanceCommentLens,});+ this.#report = createReplicaSlice(verifyReportBundleResource, {+ actionPrefix: 'verifyReportBundle',+ fetcher: async (verifyRunId) => ({+ value: await verifyService.getReportBundle(verifyRunId),+ }),+ get,+ // A 5s poll of an in-flight run that returns the same report keeps its+ // reference, so the page does not re-render on every tick.+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'verifyReportBundleReplica',+ toPersisted: toPersistedReportBundle,+ view: recordLens<Store, VerifyLookup<VerifyReportBundle>>('verifyReportBundleMap'),+ });+ this.#tracing = createReplicaSlice(verifierTracingResource, {+ actionPrefix: 'verifierTracing',+ fetcher: async (tracingId) => ({ value: await verifyService.getVerifierTracing(tracingId) }),+ get,+ set,+ stateKey: 'verifierTracingReplica',+ toPersisted: toPersistedLookup,+ view: recordLens<Store, VerifyLookup<VerifierTracing>>('verifierTracingMap'),+ });+ this.#rubrics = createReplicaSlice(verifyRubricListResource, {+ actionPrefix: 'verifyRubricList',+ fetcher: () => verifyService.listRubrics(),+ get,+ set,+ stateKey: 'verifyRubricListReplica',+ view: recordLens<Store, VerifyRubricItem[]>('verifyRubricListMap'),+ });+ this.#rubricCriteria = createReplicaSlice(verifyRubricCriteriaResource, {+ actionPrefix: 'verifyRubricCriteria',+ fetcher: (rubricId) => verifyService.getRubricCriteria(rubricId),+ get,+ set,+ stateKey: 'verifyRubricCriteriaReplica',+ view: recordLens<Store, VerifyCriterionItem[]>('verifyRubricCriteriaMap'),+ });+ this.#goalCriteria = createReplicaSlice(goalCriteriaResource, {+ actionPrefix: 'goalCriteria',+ fetcher: (criteriaIds) => verifyService.getCriteria(criteriaIds),+ get,+ set,+ stateKey: 'goalCriteriaReplica',+ view: recordLens<Store, GoalCriterionWithInstruction[]>('goalCriteriaMap'),+ });+ this.#planSkill = createReplicaSlice(planSkillResource, {+ actionPrefix: 'planSkill',+ effects: {+ onError: (error, _skillId, { key, scope }) => {+ if (key && isTerminalReadError(error)) this.#planSkill.remove(key, scope);+ },+ },+ fetcher: async (skillId) => ({ value: (await userSkillService.get(skillId)) ?? null }),+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'planSkillReplica',+ toPersisted: toPersistedLookup,+ view: recordLens<Store, VerifyLookup<UserSkillDetail>>('planSkillMap'),+ });+ this.#skillVersion = createReplicaSlice(skillVersionResource, {+ actionPrefix: 'skillVersion',+ fetcher: async ({ skillId, version }) => ({+ value: await userSkillService.getVersion(skillId, version),+ }),+ get,+ set,+ stateKey: 'skillVersionReplica',+ toPersisted: toPersistedLookup,+ view: recordLens<Store, VerifyLookup<UserSkillVersionDetail>>('skillVersionMap'),+ });}/** One scroll page of the list panel: `cursor` undefined = the head (newest first). */@@ -299,6 +424,37 @@ export class ActionImpl {await Promise.all(operationIds.map((operationId) => this.#run.hydrate(operationId, scope)));};+ /** Re-read one standalone verify report (after a rename or a manual refresh). */+ refreshVerifyReportBundle = async (verifyRunId: string): Promise<void> => {+ await this.#report.revalidate(verifyRunId);+ };++ /** Re-read the rubric templates (after one is saved). */+ refreshVerifyRubrics = async (): Promise<void> => {+ await this.#rubrics.revalidate(VERIFY_RUBRIC_LIST_KEY);+ };++ /** Re-read one plan skill (the batch moved on to another round). */+ refreshPlanSkill = async (skillId: string): Promise<void> => {+ await this.#planSkill.revalidate(skillId);+ };++ /**+ * Rename a verify run: the new title shows on the report at once and the+ * confirmed one lands in the replica (and its persisted row); a rejected+ * rename rolls back to the confirmed title.+ */+ renameVerifyReportRun = async (verifyRunId: string, title: string): Promise<void> => {+ await this.#report.optimistic(+ verifyRunId,+ (entry) =>+ entry.value ? { value: { ...entry.value, run: { ...entry.value.run, title } } } : entry,+ () => verifyService.updateRunTitle(verifyRunId, title),+ );+ // The confirmed title is already on the replica; pick up any other server change.+ void this.#report.revalidate(verifyRunId);+ };+/** 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);@@ -359,6 +515,64 @@ export class ActionImpl {revalidateOnReconnect: true,});+ /**+ * Fetch orchestration only; the caller reads the report through+ * `verifyReportBundleMap`. A finished report paints from IndexedDB on reload;+ * the report page drives the poll of a run that is still moving.+ */+ useFetchVerifyReportBundle = (verifyRunId?: string | null): ReplicaSyncResult =>+ this.#report.useSync(verifyRunId || null, {+ dedupingInterval: SHARED_READ_DEDUPE,+ onError: (error, { key, scope }) => {+ if (key && isTerminalReadError(error)) this.#report.remove(key, scope);+ },+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ });++ /** Fetch orchestration only; the caller reads `verifierTracingMap`. A tracing never changes. */+ useFetchVerifierTracing = (tracingId?: string | null): ReplicaSyncResult =>+ this.#tracing.useSync(tracingId || null, {+ dedupingInterval: SHARED_READ_DEDUPE,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ });++ /** Fetch orchestration only; the caller reads `verifyRubricListMap.all`. */+ useFetchVerifyRubrics = (enabled = true): ReplicaSyncResult =>+ this.#rubrics.useSync({}, { dedupingInterval: SHARED_READ_DEDUPE, enabled });++ /** Fetch orchestration only; the caller reads `verifyRubricCriteriaMap[rubricId]`. */+ useFetchVerifyRubricCriteria = (rubricId?: string | null): ReplicaSyncResult =>+ this.#rubricCriteria.useSync(rubricId || null, { dedupingInterval: SHARED_READ_DEDUPE });++ /** Fetch orchestration only; the caller reads `goalCriteriaMap[goalCriteriaKey(ids)]`. */+ useFetchGoalCriteria = (criteriaIds: string[]): ReplicaSyncResult =>+ this.#goalCriteria.useSync(criteriaIds.length > 0 ? criteriaIds : null, {+ dedupingInterval: SHARED_READ_DEDUPE,+ });++ /** Re-read a Goal's criteria set (after one of its criteria is edited). */+ refreshGoalCriteria = async (criteriaIds: string[]): Promise<void> => {+ if (criteriaIds.length === 0) return;+ await this.#goalCriteria.revalidate(goalCriteriaResource.key(criteriaIds));+ };++ /** Fetch orchestration only; the caller reads `planSkillMap[skillId]`. */+ useFetchPlanSkill = (skillId?: string | null): ReplicaSyncResult =>+ this.#planSkill.useSync(skillId || null, { dedupingInterval: SHARED_READ_DEDUPE });++ /**+ * Fetch orchestration only; the caller reads `skillVersionMap`. A shipped+ * version never changes, so it is not re-read on focus or reconnect.+ */+ useFetchSkillVersion = (params: SkillVersionParams | null): ReplicaSyncResult =>+ this.#skillVersion.useSync(params, {+ dedupingInterval: SHARED_READ_DEDUPE,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ });+#persist = async (): Promise<void> => {const criteria = [...this.#pendingCriteria.entries()];const instructions = [...this.#pendingInstructions.entries()];@@ -391,6 +605,18 @@ export class ActionImpl {}),),]);++ // The edited rows are read elsewhere from persisted replicas: re-read the+ // mounted ones so a reload does not paint the pre-edit copy.+ const refreshes: Promise<unknown>[] = [];+ for (const [id] of instructions) refreshes.push(revalidateReplica(documentDetailResource, id));+ if (criteria.length > 0)+ refreshes.push(+ revalidateReplica(verifyRubricCriteriaResource),+ revalidateReplica(goalCriteriaResource),+ );+ if (rubricTitles.length > 0) refreshes.push(this.refreshVerifyRubrics());+ await Promise.allSettled(refreshes);};/** Edit one or more fields of a criterion (optimistic + debounced persist). */diff --git a/src/store/verify/initialState.ts b/src/store/verify/initialState.tsindex d1609fb99aa..e2ef51e94b2 100644--- a/src/store/verify/initialState.ts+++ b/src/store/verify/initialState.ts@@ -1,14 +1,28 @@import type {AcceptanceCommentList,+ UserSkillVersionDetail,VerifierType,VerifyOnFailStrategy,VerifyRubricConfig,} from '@lobechat/types';+import type { VerifyCriterionItem, VerifyRubricItem } from '@/database/schemas/verify';import { createReplicaState, type ReplicaState } from '@/libs/replica';-import type { AcceptanceBundle, AcceptanceBySubject, AcceptanceListItem } from '@/services/verify';+import type { UserSkillDetail } from '@/services/userSkill';+import type {+ AcceptanceBundle,+ AcceptanceBySubject,+ AcceptanceListItem,+ GoalCriterionWithInstruction,+ VerifyReportBundle,+} from '@/services/verify';-import type { AcceptancePageData, VerifyRunSnapshot } from './projection';+import type {+ AcceptancePageData,+ VerifierTracing,+ VerifyLookup,+ VerifyRunSnapshot,+} from './projection';/** The criterion fields the portal can edit. */export interface VerifyCriterionEdit {@@ -46,11 +60,19 @@ export interface State {* debounced-persisted to the backend.*/criterionEdits: Record<string, VerifyCriterionEdit>;+ /** Replica view of a Goal's acceptance criteria, keyed by the joined criteria ids. */+ goalCriteriaMap: Record<string, GoalCriterionWithInstruction[]>;+ /** Replica bookkeeping of `goalCriteriaMap`. */+ goalCriteriaReplica: ReplicaState<GoalCriterionWithInstruction[]>;/*** Per-instruction edit overlay, keyed by the instruction document id. Holds* the latest rubric text pending a debounced document save.*/instructionEdits: Record<string, string>;+ /** Replica view of the plan skills under review, keyed by skill id. */+ planSkillMap: Record<string, VerifyLookup<UserSkillDetail>>;+ /** Replica bookkeeping of `planSkillMap`. */+ planSkillReplica: ReplicaState<VerifyLookup<UserSkillDetail>>;/*** Per-rubric run-policy edit overlay, keyed by `verify_rubrics.id`. Holds the* in-flight config edits (e.g. maxRepairRounds) pending a debounced save.@@ -61,6 +83,26 @@ export interface State {* in-flight delivery-standard rename pending a debounced save.*/rubricTitleEdits: Record<string, string>;+ /** Replica view of shipped skill versions, keyed `<skillId>@<version>`. */+ skillVersionMap: Record<string, VerifyLookup<UserSkillVersionDetail>>;+ /** Replica bookkeeping of `skillVersionMap`. */+ skillVersionReplica: ReplicaState<VerifyLookup<UserSkillVersionDetail>>;+ /** Replica view of LLM verifier tracings, keyed by tracing id. */+ verifierTracingMap: Record<string, VerifyLookup<VerifierTracing>>;+ /** Replica bookkeeping of `verifierTracingMap`. */+ verifierTracingReplica: ReplicaState<VerifyLookup<VerifierTracing>>;+ /** Replica view of standalone verify reports, keyed by verify run id. */+ verifyReportBundleMap: Record<string, VerifyLookup<VerifyReportBundle>>;+ /** Replica bookkeeping of `verifyReportBundleMap`. */+ verifyReportBundleReplica: ReplicaState<VerifyLookup<VerifyReportBundle>>;+ /** Replica view of the criteria each rubric groups, keyed by rubric id. */+ verifyRubricCriteriaMap: Record<string, VerifyCriterionItem[]>;+ /** Replica bookkeeping of `verifyRubricCriteriaMap`. */+ verifyRubricCriteriaReplica: ReplicaState<VerifyCriterionItem[]>;+ /** Replica view of the rubric templates (`verifyRubricListMap.all`). */+ verifyRubricListMap: Record<string, VerifyRubricItem[]>;+ /** Replica bookkeeping of `verifyRubricListMap`. */+ verifyRubricListReplica: ReplicaState<VerifyRubricItem[]>;/** Replica view of the Agent Run verify cards, one entry per operation id. */verifyRunMap: Record<string, VerifyRunSnapshot>;/** Replica bookkeeping of `verifyRunMap`. */@@ -79,9 +121,23 @@ export const initialState: State = {acceptancePageMap: {},acceptancePageReplica: createReplicaState(),criterionEdits: {},+ goalCriteriaMap: {},+ goalCriteriaReplica: createReplicaState(),instructionEdits: {},+ planSkillMap: {},+ planSkillReplica: createReplicaState(),rubricConfigEdits: {},rubricTitleEdits: {},+ skillVersionMap: {},+ skillVersionReplica: createReplicaState(),+ verifierTracingMap: {},+ verifierTracingReplica: createReplicaState(),+ verifyReportBundleMap: {},+ verifyReportBundleReplica: createReplicaState(),+ verifyRubricCriteriaMap: {},+ verifyRubricCriteriaReplica: createReplicaState(),+ verifyRubricListMap: {},+ verifyRubricListReplica: createReplicaState(),verifyRunMap: {},verifyRunReplica: createReplicaState(),};diff --git a/src/store/verify/projection.ts b/src/store/verify/projection.tsindex 5c9cf539e6f..1e9efa6346d 100644--- a/src/store/verify/projection.ts+++ b/src/store/verify/projection.ts@@ -1,6 +1,14 @@-import type { AcceptanceCommentList, CreatableAcceptanceSubjectType } from '@lobechat/types';+import type {+ AcceptanceCommentList,+ CreatableAcceptanceSubjectType,+ UserSkillVersionDetail,+} from '@lobechat/types';-import type { VerifyCheckResultItem } from '@/database/schemas/verify';+import type {+ VerifyCheckResultItem,+ VerifyCriterionItem,+ VerifyRubricItem,+} from '@/database/schemas/verify';import {AppIndexedDBStorage,arrayEntity,@@ -9,15 +17,24 @@ import {type ReplicaEntityAdapter,type ReplicaPagedData,} from '@/libs/replica';+import type { UserSkillDetail } from '@/services/userSkill';import type {AcceptanceBundle,AcceptanceBySubject,AcceptanceListFilter,AcceptanceListItem,AcceptanceListQuery,+ GoalCriterionWithInstruction,+ VerifyReportBundle,+ verifyService,VerifyStateResponse,} from '@/services/verify';+/** Model / token / latency the verifier's LLM call recorded. */+export type VerifierTracing = NonNullable<+ Awaited<ReturnType<typeof verifyService.getVerifierTracing>>+>;+/*** The Acceptance aggregate of one acceptance id (`acceptanceBundleMap[id]`):* the live review surface read by the Acceptance viewer, the task acceptance@@ -255,3 +272,126 @@ export const acceptanceCommentResource = defineReplica<string, AcceptanceCommentstorage: 'indexedDB',version: 1,});++/**+ * A replica value for a read the server may answer with "not found".+ *+ * Wrapped on purpose: a replica value can never be `null` (the engine reads it+ * as "keep the current value"), but a page must tell "the server has no such+ * record" (`value: null`, settles on its not-found state) apart from "nothing+ * read yet" (no entry). The `null` answer is never persisted (see+ * {@link toPersistedLookup}): it is a page state, and a reload must ask again.+ */+export interface VerifyLookup<T> {+ value: T | null;+}++export const toPersistedLookup = <T>(entry: VerifyLookup<T>): VerifyLookup<T> | null =>+ entry.value === null ? null : entry;++const TERMINAL_REPORT_STATUSES = new Set(['delivered', 'errored', 'failed', 'passed']);++/**+ * Persist finished reports only. A run that is still planned / verifying /+ * repairing is a live status, so a reload must not paint it from an old+ * snapshot; it maps to `null` and the engine drops any earlier row.+ */+export const toPersistedReportBundle = (+ entry: VerifyLookup<VerifyReportBundle>,+): VerifyLookup<VerifyReportBundle> | null =>+ entry.value?.run.status && TERMINAL_REPORT_STATUSES.has(entry.value.run.status) ? entry : null;++/**+ * The standalone verify report of one run (`verifyReportBundleMap[verifyRunId]`):+ * the report page and the verify report portal (title, menu, link). Carries+ * evidence, so the persisted set is LRU-capped.+ */+export const verifyReportBundleResource = defineReplica<string, VerifyLookup<VerifyReportBundle>>({+ key: (verifyRunId) => verifyRunId,+ name: 'verifyReportBundle',+ persist: { maxEntries: 30 },+ storage: 'indexedDB',+ version: 1,+});++/** Model / token / latency of one LLM verifier judgment, keyed by tracing id. */+export const verifierTracingResource = defineReplica<string, VerifyLookup<VerifierTracing>>({+ key: (tracingId) => tracingId,+ name: 'verifierTracing',+ persist: { maxEntries: 100 },+ storage: 'indexedDB',+ version: 1,+});++/** The rubric list is not paged: every template sits in this single entry. */+export const VERIFY_RUBRIC_LIST_KEY = 'all';++/** The workspace's reusable rubric templates (`verifyRubricListMap.all`). */+export const verifyRubricListResource = defineReplica<Record<string, never>, VerifyRubricItem[]>({+ key: () => VERIFY_RUBRIC_LIST_KEY,+ name: 'verifyRubricList',+ storage: 'indexedDB',+ version: 1,+});++/** The criteria one rubric groups, in rubric order, keyed by rubric id. */+export const verifyRubricCriteriaResource = defineReplica<string, VerifyCriterionItem[]>({+ key: (rubricId) => rubricId,+ name: 'verifyRubricCriteria',+ persist: { maxEntries: 50 },+ storage: 'indexedDB',+ version: 1,+});++/** One entry key per criteria set: the request depends on the ids alone. */+export const goalCriteriaKey = (criteriaIds: string[]) => criteriaIds.join(',');++/**+ * The persisted criteria a Goal is accepted against, with their judge+ * instructions, keyed by the ordered id list (`goalCriteriaMap`). Shared by the+ * Goal's acceptance-standard section and its result / sign-off pages.+ */+export const goalCriteriaResource = defineReplica<string[], GoalCriterionWithInstruction[]>({+ key: goalCriteriaKey,+ name: 'verifyGoalCriteria',+ persist: { maxEntries: 50 },+ storage: 'indexedDB',+ version: 1,+});++/**+ * A plan skill from the user's library with every version it kept, keyed by+ * skill id (`planSkillMap`): the gate's skill directory and the batch plan's+ * version list. Ships the skill's files, so the persisted set is capped.+ */+export const planSkillResource = defineReplica<string, VerifyLookup<UserSkillDetail>>({+ key: (skillId) => skillId,+ name: 'planSkill',+ persist: { maxEntries: 20 },+ storage: 'indexedDB',+ version: 1,+});++/** One shipped version of a skill. */+export interface SkillVersionParams {+ skillId: string;+ version: number;+}++export const skillVersionKey = ({ skillId, version }: SkillVersionParams) =>+ `${skillId}@${version}`;++/**+ * One version of a skill as it shipped (`skillVersionMap['<id>@<version>']`).+ * A version never changes once written, so the persisted copy is exact.+ */+export const skillVersionResource = defineReplica<+ SkillVersionParams,+ VerifyLookup<UserSkillVersionDetail>+>({+ key: skillVersionKey,+ name: 'skillVersion',+ persist: { maxEntries: 50 },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/verify/selectors.ts b/src/store/verify/selectors.tsindex b91783da50f..e84a7da43b9 100644--- a/src/store/verify/selectors.ts+++ b/src/store/verify/selectors.ts@@ -7,6 +7,10 @@ import {type AcceptanceListParams,acceptancePageKey,type AcceptancePageParams,+ goalCriteriaKey,+ skillVersionKey,+ type SkillVersionParams,+ VERIFY_RUBRIC_LIST_KEY,} from './projection';const EMPTY_EDIT: VerifyCriterionEdit = {};@@ -54,6 +58,60 @@ const rubricTitleEdit = (rubricId?: string) => (s: Store) =>const verifyRun = (operationId?: string | null) => (s: Store) =>operationId ? s.verifyRunMap[operationId] : undefined;+/**+ * A list restored from IndexedDB is not a server answer: an empty snapshot+ * (or one from before the last edit) must read as "still loading", not as+ * "nothing here", until this session's request confirms it.+ */+const confirmedList =+ <T>(+ pick: (s: Store) => { entries: Record<string, { source: string }> },+ map: (s: Store) => Record<string, T[]>,+ key: string | undefined,+ ) =>+ (s: Store): T[] | undefined => {+ if (!key) return undefined;+ const list = map(s)[key];+ if (!list) return undefined;+ if (list.length === 0 && pick(s).entries[key]?.source !== 'server') return undefined;+ return list;+ };++/** The verify report; `null` once the server answered there is none. */+const verifyReportBundle = (verifyRunId?: string | null) => (s: Store) =>+ verifyRunId ? s.verifyReportBundleMap[verifyRunId]?.value : undefined;++const verifierTracing = (tracingId?: string | null) => (s: Store) =>+ tracingId ? s.verifierTracingMap[tracingId]?.value : undefined;++const verifyRubrics = confirmedList(+ (s) => s.verifyRubricListReplica,+ (s) => s.verifyRubricListMap,+ VERIFY_RUBRIC_LIST_KEY,+);++const verifyRubricCriteria = (rubricId?: string | null) =>+ confirmedList(+ (s) => s.verifyRubricCriteriaReplica,+ (s) => s.verifyRubricCriteriaMap,+ rubricId || undefined,+ );++const goalCriteria = (criteriaIds: string[]) =>+ confirmedList(+ (s) => s.goalCriteriaReplica,+ (s) => s.goalCriteriaMap,+ criteriaIds.length > 0 ? goalCriteriaKey(criteriaIds) : undefined,+ );++/** The plan skill; `null` once the server answered it is gone. */+const planSkill = (skillId?: string | null) => (s: Store) =>+ skillId ? s.planSkillMap[skillId]?.value : undefined;++/** One shipped skill version; `null` once the server answered it has none. */+const skillVersion = (params: SkillVersionParams | null) => (s: Store) =>+ params ? s.skillVersionMap[skillVersionKey(params)]?.value : undefined;+export const verifySelectors = {acceptanceBundle,acceptanceBySubject,@@ -61,11 +119,18 @@ export const verifySelectors = {acceptanceList,acceptancePage,criterionEdit,+ goalCriteria,instructionEdit,isAcceptanceCommentsConfirmed,isAcceptanceListConfirmed,isAcceptancePageConfirmed,+ planSkill,rubricConfigEdit,rubricTitleEdit,+ skillVersion,+ verifierTracing,+ verifyReportBundle,+ verifyRubricCriteria,+ verifyRubrics,verifyRun,};diff --git a/src/store/verify/verifyReads.replica.test.ts b/src/store/verify/verifyReads.replica.test.tsnew file mode 100644index 00000000000..89a35fb4843--- /dev/null+++ b/src/store/verify/verifyReads.replica.test.ts@@ -0,0 +1,363 @@+/**+ * @vitest-environment happy-dom+ *+ * The verify report, verifier tracing, rubric templates, rubric / Goal criteria+ * and the plan skill under review are replicas persisted to IndexedDB: a reload+ * paints the last confirmed copy before the network answers, then refreshes.+ *+ * Rows are seeded through the storage namespace (`replica:<name>:v1`) and read+ * through the public hooks only, so these assertions run against the SWR+ * implementation they replaced as well.+ */+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 {+ useGoalCriteria,+ useRubricCriteria,+ useRubrics,+ useVerifierTracing,+ useVerifyReportBundle,+} from '@/features/Acceptance/hooks';+import {+ usePlanSkill,+ useSkillVersion,+} from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';+import { AppIndexedDBStorage, cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { userSkillService } from '@/services/userSkill';+import { verifyService } from '@/services/verify';++import { useVerifyStore } from './index';+import { initialState } from './initialState';++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { provider: () => new Map(), shouldRetryOnError: false } },+ createElement(MutateBridge),+ children,+ );++const storageOf = (name: string) =>+ new AppIndexedDBStorage<unknown>({ namespace: `replica:${name}:v1` });++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, reject, resolve };+};++const report = (title: string, status = 'passed') =>+ ({+ isOwner: true,+ report: null,+ results: [],+ run: { id: 'run-1', status, title },+ }) as never;++const rubric = (id: string, title: string) => ({ id, title }) as never;+const criterion = (id: string, title: string) => ({ id, title }) as never;++describe('verify read replicas', () => {+ let scope = '';+ const seeded: { name: string; queryKey: string; scope: string }[] = [];++ const persist = async (name: string, queryKey: string, data: unknown, at = scope) => {+ seeded.push({ name, queryKey, scope: at });+ await storageOf(name).set({ queryKey, scope: at }, { data, updatedAt: 1 });+ };+ const stored = async (name: string, queryKey: string) => {+ seeded.push({ name, queryKey, scope });+ return (await storageOf(name).get({ queryKey, scope }))?.data;+ };++ beforeEach(() => {+ scope = `verify-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useVerifyStore.setState(initialState, false));+ });++ afterEach(async () => {+ cleanup();+ for (const row of seeded.splice(0)) {+ const storage = storageOf(row.name);+ await storage.remove({ queryKey: row.queryKey, scope: row.scope });+ await storage.remove({ queryKey: REPLICA_INDEX_KEY, scope: row.scope });+ }+ vi.restoreAllMocks();+ });++ describe('verify report', () => {+ it('paints a persisted finished report before the network answers, then refreshes it', async () => {+ await persist('verifyReportBundle', 'run-1', { value: report('Saved title') });+ const next = deferred<unknown>();+ vi.spyOn(verifyService, 'getReportBundle').mockImplementation(() => next.promise as never);++ const { result } = renderHook(() => useVerifyReportBundle('run-1'), { wrapper });++ await waitFor(() => expect(result.current.data?.run.title).toBe('Saved title'));+ expect(result.current.isLoading).toBe(false);++ await act(async () => next.resolve(report('Fresh title')));+ await waitFor(() => expect(result.current.data?.run.title).toBe('Fresh title'));+ });++ it('persists a finished report but keeps a running one memory-only', async () => {+ const getReportBundle = vi.spyOn(verifyService, 'getReportBundle');+ getReportBundle.mockResolvedValueOnce(report('Done'));+ renderHook(() => useVerifyReportBundle('run-1'), { wrapper });+ await waitFor(async () =>+ expect(await stored('verifyReportBundle', 'run-1')).toMatchObject({+ value: { run: { title: 'Done' } },+ }),+ );+ cleanup();++ getReportBundle.mockResolvedValueOnce(report('Still going', 'verifying'));+ act(() => useVerifyStore.setState(initialState, false));+ const { result } = renderHook(() => useVerifyReportBundle('run-2'), { wrapper });+ await waitFor(() => expect(result.current.data?.run.status).toBe('verifying'));+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(await stored('verifyReportBundle', 'run-2')).toBeUndefined();+ });++ it('settles a missing run on not found without persisting the answer', async () => {+ vi.spyOn(verifyService, 'getReportBundle').mockResolvedValue(null);++ const { result } = renderHook(() => useVerifyReportBundle('run-gone'), { wrapper });++ await waitFor(() => expect(result.current.data).toBeNull());+ expect(result.current.isLoading).toBe(false);+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(await stored('verifyReportBundle', 'run-gone')).toBeUndefined();+ });++ it('sends one request for the page, title, menu and link reading the same report', async () => {+ const getReportBundle = vi+ .spyOn(verifyService, 'getReportBundle')+ .mockResolvedValue(report('Shared'));++ const { result } = renderHook(+ () => [+ useVerifyReportBundle('run-1'),+ useVerifyReportBundle('run-1'),+ useVerifyReportBundle('run-1'),+ useVerifyReportBundle('run-1'),+ ],+ { wrapper },+ );++ await waitFor(() => expect(result.current[3].data?.run.title).toBe('Shared'));+ expect(getReportBundle).toHaveBeenCalledTimes(1);+ });++ it('keeps the last report on screen when a refresh fails', async () => {+ await persist('verifyReportBundle', 'run-1', { value: report('Saved title') });+ vi.spyOn(verifyService, 'getReportBundle').mockRejectedValue(new Error('network down'));++ const { result } = renderHook(() => useVerifyReportBundle('run-1'), { wrapper });++ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));+ expect(result.current.data?.run.title).toBe('Saved title');+ });++ it('does not show the previous identity its report after a switch', async () => {+ const previous = scope;+ await persist('verifyReportBundle', 'run-1', { value: report('Theirs') }, previous);+ vi.spyOn(verifyService, 'getReportBundle').mockImplementation(pending);++ const { rerender, result } = renderHook(() => useVerifyReportBundle('run-1'), { wrapper });+ await waitFor(() => expect(result.current.data?.run.title).toBe('Theirs'));++ scope = `verify-user-${randomUUID()}:personal`;+ rerender();++ await waitFor(() => expect(result.current.data).toBeUndefined());+ expect(result.current.isLoading).toBe(true);+ });++ it('renames the run on the report and in its persisted row, and rolls back a rejected rename', async () => {+ const getReportBundle = vi+ .spyOn(verifyService, 'getReportBundle')+ .mockResolvedValue(report('Old'));+ renderHook(() => useVerifyReportBundle('run-1'), { wrapper });+ await waitFor(() =>+ expect(useVerifyStore.getState().verifyReportBundleMap['run-1']?.value?.run.title).toBe(+ 'Old',+ ),+ );++ const write = deferred<unknown>();+ vi.spyOn(verifyService, 'updateRunTitle').mockImplementation(() => write.promise as never);+ getReportBundle.mockResolvedValue(report('New'));+ let renaming!: Promise<void>;+ act(() => {+ renaming = useVerifyStore.getState().renameVerifyReportRun('run-1', 'New');+ });+ // Optimistic: the new title is on the report before the server answers.+ expect(useVerifyStore.getState().verifyReportBundleMap['run-1']?.value?.run.title).toBe(+ 'New',+ );+ await act(async () => {+ write.resolve(undefined);+ await renaming;+ });+ await waitFor(async () =>+ expect(await stored('verifyReportBundle', 'run-1')).toMatchObject({+ value: { run: { title: 'New' } },+ }),+ );++ vi.spyOn(verifyService, 'updateRunTitle').mockRejectedValue(new Error('denied'));+ await act(async () => {+ await expect(+ useVerifyStore.getState().renameVerifyReportRun('run-1', 'Rejected'),+ ).rejects.toThrow('denied');+ });+ expect(useVerifyStore.getState().verifyReportBundleMap['run-1']?.value?.run.title).toBe(+ 'New',+ );+ });+ });++ describe('verifier tracing', () => {+ it('paints a persisted tracing before the network answers', async () => {+ await persist('verifierTracing', 'trace-1', {+ value: { inputTokens: 10, model: 'gpt-x', outputTokens: 5 },+ });+ vi.spyOn(verifyService, 'getVerifierTracing').mockImplementation(pending);++ const { result } = renderHook(() => useVerifierTracing('trace-1'), { wrapper });++ await waitFor(() => expect(result.current.data?.model).toBe('gpt-x'));+ });+ });++ describe('rubric templates', () => {+ it('paints the persisted templates before the network answers, then refreshes them', async () => {+ await persist('verifyRubricList', 'all', [rubric('r1', 'Saved')]);+ const next = deferred<unknown>();+ vi.spyOn(verifyService, 'listRubrics').mockImplementation(() => next.promise as never);++ const { result } = renderHook(() => useRubrics(), { wrapper });++ await waitFor(() => expect(result.current.data?.[0]?.title).toBe('Saved'));+ await act(async () => next.resolve([rubric('r1', 'Fresh')]));+ await waitFor(() => expect(result.current.data?.[0]?.title).toBe('Fresh'));+ });++ it('reads a restored empty list as loading until the server confirms it', async () => {+ await persist('verifyRubricList', 'all', []);+ const next = deferred<unknown>();+ vi.spyOn(verifyService, 'listRubrics').mockImplementation(() => next.promise as never);++ const { result } = renderHook(() => useRubrics(), { wrapper });++ await waitFor(() => expect(useVerifyStore.getState().verifyRubricListMap.all).toEqual([]));+ expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(true);++ await act(async () => next.resolve([]));+ await waitFor(() => expect(result.current.data).toEqual([]));+ expect(result.current.isLoading).toBe(false);+ });++ it('does not request templates while rubric authoring is inactive', async () => {+ const listRubrics = vi.spyOn(verifyService, 'listRubrics').mockResolvedValue([]);++ renderHook(() => useRubrics(false), { wrapper });+ await act(() => new Promise((resolve) => setTimeout(resolve, 20)));++ expect(listRubrics).not.toHaveBeenCalled();+ });+ });++ describe('rubric and Goal criteria', () => {+ it('paints the persisted criteria of a rubric before the network answers', async () => {+ await persist('verifyRubricCriteria', 'r1', [criterion('c1', 'Saved')]);+ vi.spyOn(verifyService, 'getRubricCriteria').mockImplementation(pending);++ const { result } = renderHook(() => useRubricCriteria('r1'), { wrapper });++ await waitFor(() => expect(result.current.data?.[0]?.title).toBe('Saved'));+ });++ it('paints a Goal criteria set before the network answers, then refreshes it', async () => {+ await persist('verifyGoalCriteria', 'c1,c2', [+ criterion('c1', 'Saved 1'),+ criterion('c2', 'Saved 2'),+ ]);+ const next = deferred<unknown>();+ const getCriteria = vi+ .spyOn(verifyService, 'getCriteria')+ .mockImplementation(() => next.promise as never);+ const ids = ['c1', 'c2'];++ const { result } = renderHook(() => [useGoalCriteria(ids), useGoalCriteria(ids)], {+ wrapper,+ });++ await waitFor(() => expect(result.current[0].data?.[1]?.title).toBe('Saved 2'));+ await act(async () => next.resolve([criterion('c1', 'Fresh 1'), criterion('c2', 'Fresh 2')]));+ await waitFor(() => expect(result.current[1].data?.[0]?.title).toBe('Fresh 1'));+ // The criteria section and the result page share one request.+ expect(getCriteria).toHaveBeenCalledTimes(1);+ expect(getCriteria).toHaveBeenCalledWith(ids);+ });+ });++ describe('plan skill', () => {+ it('paints the persisted plan skill and its shipped version before the network answers', async () => {+ await persist('planSkill', 'skill-1', {+ value: { files: [{ content: '', path: 'scripts/a.sh' }], id: 'skill-1', versions: [] },+ });+ await persist('skillVersion', 'skill-1@2', { value: { content: '# v2', files: [] } });+ vi.spyOn(userSkillService, 'get').mockImplementation(pending);+ vi.spyOn(userSkillService, 'getVersion').mockImplementation(pending);++ const { result } = renderHook(+ () => ({ skill: usePlanSkill('skill-1'), version: useSkillVersion('skill-1', 2) }),+ { wrapper },+ );++ await waitFor(() => expect(result.current.skill.data?.files).toHaveLength(1));+ await waitFor(() => expect(result.current.version.data?.content).toBe('# v2'));+ expect(result.current.skill.isLoading).toBe(false);+ expect(result.current.version.isLoading).toBe(false);+ });++ it('sends one request for the gate directory and its file toggle', async () => {+ const get = vi+ .spyOn(userSkillService, 'get')+ .mockResolvedValue({ files: [], id: 'skill-1', versions: [] } as never);++ const { result } = renderHook(() => [usePlanSkill('skill-1'), usePlanSkill('skill-1')], {+ wrapper,+ });++ await waitFor(() => expect(result.current[1].data).toBeDefined());+ expect(get).toHaveBeenCalledTimes(1);+ });+ });+});