🤯 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(entityLink): move internal link title previews onto @lobechat/replica (#22876)
Arvin Xuae6f6edb386d
diff --git a/src/features/EntityLink/Render/InternalEntityLink.reload.test.tsx b/src/features/EntityLink/Render/InternalEntityLink.reload.test.tsxnew file mode 100644index 00000000000..5ddf76a74db--- /dev/null+++ b/src/features/EntityLink/Render/InternalEntityLink.reload.test.tsx@@ -0,0 +1,159 @@+/**+ * @vitest-environment happy-dom+ *+ * A pasted entity URL is titled from the entity preview replica, so a reload+ * paints the remembered title instead of flashing the raw URL first. Each+ * "reload" re-imports the module graph (fresh stores, fresh SWR cache) over the+ * same localStorage.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const scope = vi.hoisted(() => ({ current: '' }));++vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getCacheScope: () => scope.current,+ isScopeTrusted: () => true,+ useCacheScope: () => scope.current,+}));+vi.mock('@/libs/swr', async (importOriginal) => {+ const swr = await import('swr');+ return {+ ...(await importOriginal<Record<string, unknown>>()),+ mutate: swr.mutate,+ useClientDataSWR: swr.default,+ };+});+vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ // Render the card inline, opened on hover, so its content can be asserted.+ Popover: ({ children, content, onOpenChange }: any) =>+ createElement(+ 'div',+ { 'data-testid': 'trigger', 'onMouseEnter': () => onOpenChange?.(true) },+ children,+ content,+ ),+}));+vi.mock('@/business/client/hooks/useWorkspaces', () => ({ useWorkspaces: () => [] }));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => vi.fn(),+}));+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: unknown) => unknown) => selector({}),+}));+vi.mock('@/store/agentDocument', () => ({+ agentDocumentActions: { fetchDocumentList: vi.fn(), useFetchDocumentList: vi.fn() },+ agentDocumentSelectors: { getDocumentList: () => () => undefined },+ useAgentDocumentStore: (selector: (state: unknown) => unknown) => selector({}),+}));++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++const PATH = '/task/T-198';+const task = (name: string) => ({+ data: { description: 'Rebuild the gateway queue', id: 'task_1', identifier: 'T-198', name },+});++const pending = () => new Promise<never>(() => {});++/** A fresh module graph: what a page reload starts from (localStorage survives). */+const reload = async () => {+ cleanup();+ vi.resetModules();+ const [{ InternalEntityLink }, { taskService }] = await Promise.all([+ import('./InternalEntityLink'),+ import('@/services/task'),+ ]);+ const getDetail = vi.spyOn(taskService, 'getDetail');+ const renderLink = () =>+ render(+ createElement(InternalEntityLink, {+ href: PATH,+ label: PATH,+ reference: { pathname: PATH, taskId: 'T-198', type: 'task' },+ }),+ { wrapper },+ );+ return { getDetail, renderLink };+};++/** Let the server answer reach the persisted copy before the next reload. */+const settle = () =>+ act(async () => {+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));+ });++describe('InternalEntityLink across a reload', { timeout: 60_000 }, () => {+ beforeEach(() => {+ scope.current = `entity-link-user-${randomUUID()}:personal`;+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it('paints the remembered title, not the URL, before the network answers', async () => {+ const first = await reload();+ first.getDetail.mockResolvedValue(task('Gateway queue rebuild') as never);+ const firstView = first.renderLink();+ await waitFor(() =>+ expect(firstView.container.querySelector('a')!.textContent).toBe('Gateway queue rebuild'),+ );+ await settle();++ const second = await reload();+ second.getDetail.mockImplementation(pending);+ const { container } = second.renderLink();+ await settle();++ expect(container.querySelector('a')!.textContent).toBe('Gateway queue rebuild');+ });++ it('replaces the remembered title once the server answers', async () => {+ const first = await reload();+ first.getDetail.mockResolvedValue(task('Old title') as never);+ first.renderLink();+ await settle();++ const second = await reload();+ let answer!: (value: unknown) => void;+ second.getDetail.mockImplementation(+ () =>+ new Promise((resolve) => {+ answer = resolve;+ }) as never,+ );+ const { container } = second.renderLink();+ await settle();+ expect(container.querySelector('a')!.textContent).toBe('Old title');++ await act(async () => {+ answer(task('Renamed title'));+ });+ await waitFor(() => expect(container.querySelector('a')!.textContent).toBe('Renamed title'));+ });++ it('opens the hover card on the remembered preview, without a skeleton', async () => {+ const first = await reload();+ first.getDetail.mockResolvedValue(task('Gateway queue rebuild') as never);+ first.renderLink();+ await settle();++ const second = await reload();+ second.getDetail.mockImplementation(pending);+ const { getByTestId, getByText } = second.renderLink();+ await settle();+ fireEvent.mouseEnter(getByTestId('trigger'));+ await settle();++ expect(getByText('Rebuild the gateway queue')).toBeInTheDocument();+ });+});diff --git a/src/features/EntityLink/Render/InternalEntityLink.tsx b/src/features/EntityLink/Render/InternalEntityLink.tsxindex 2c59d168f17..48f75156f22 100644--- a/src/features/EntityLink/Render/InternalEntityLink.tsx+++ b/src/features/EntityLink/Render/InternalEntityLink.tsx@@ -21,7 +21,6 @@ import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { shouldHardNavigateToWorkbench } from '@/libs/next/workbenchNavigation';-import { useClientDataSWR } from '@/libs/swr';import { useAgentStore } from '@/store/agent';import {agentDocumentActions,@@ -33,12 +32,9 @@ import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';import { useEntityLinkHostDismiss, useEntityLinkPortal } from '../host';import { type InternalLinkReference, isBareLinkLabel, isEntityIdLabel } from '../internalLink';-import {- getPreviewData,- InternalEntityPreview,- internalEntityPreviewKey,-} from './InternalEntityPreview';+import { InternalEntityPreview } from './InternalEntityPreview';import { useAcceptanceBrowserUrl } from './useAcceptanceBrowserUrl';+import { useEntityPreview } from './useEntityPreview';const styles = createStaticStyles(({ css, cssVar }) => ({browser: css`@@ -106,7 +102,6 @@ interface InternalEntityLinkProps {}export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label, reference }) => {- const { t } = useTranslation('chat');const { t: tVerify } = useTranslation('verify');const navigate = useWorkspaceAwareNavigate();const activeAgentId = useAgentStore((s) => s.activeAgentId);@@ -129,8 +124,9 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,s.openVerifyReport,]);// A pasted URL says nothing about what it points to, so resolve the entity's- // own title and show that instead — the same read the hover preview makes,- // under the same key, so the eager fetch also makes the hover card instant.+ // own title and show that instead — the same preview replica the hover card+ // reads, so the eager fetch also makes the card instant, and a reload paints+ // the remembered title instead of flashing the URL first.// Bare links are sparse in real messages, which is why prefetching the full// preview beats a dedicated title read. Cross-workspace links are skipped:// the ambient client resolves against the ACTIVE scope, where a@@ -140,12 +136,8 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,reference.type !== 'route' &&!reference.workspaceSlug &&(isBareLinkLabel(label, href) || isEntityIdLabel(label, reference));- const { data: entity } = useClientDataSWR(- shouldResolveTitle ? internalEntityPreviewKey(reference) : null,- () => getPreviewData(reference, t),- { revalidateOnFocus: false },- );- const displayLabel = (shouldResolveTitle && entity?.title) || label;+ const { title: entityTitle } = useEntityPreview(reference, shouldResolveTitle);+ const displayLabel = (shouldResolveTitle && entityTitle) || label;// A click on the link opens the acceptance in the side panel, which another// surface (a session overlay) can cover; this one-click way out to the full// browser page needs no hover on the preview first. Mobile opens it in adiff --git a/src/features/EntityLink/Render/InternalEntityPreview.tsx b/src/features/EntityLink/Render/InternalEntityPreview.tsxindex e22e3318e88..27ff2f34ef0 100644--- a/src/features/EntityLink/Render/InternalEntityPreview.tsx+++ b/src/features/EntityLink/Render/InternalEntityPreview.tsx@@ -1,6 +1,5 @@'use client';-import type { VerifyCodingScope } from '@lobechat/types';import {ActionIcon,Avatar,@@ -26,16 +25,12 @@ import { useTranslation } from 'react-i18next';import { ArticleSkeleton } from '@/components/Skeleton';import { goalStatusKey } from '@/features/AgentGoals/goalPresentation';-import { useClientDataSWR } from '@/libs/swr';-import { agentService } from '@/services/agent';-import { documentService } from '@/services/document';-import { goalService } from '@/services/goal';-import { taskService } from '@/services/task';-import { verifyService } from '@/services/verify';+import type { EntityPreview } from '@/store/entityPreview';import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';import type { InternalLinkReference } from '../internalLink';import { useAcceptanceBrowserUrl } from './useAcceptanceBrowserUrl';+import { useEntityPreview } from './useEntityPreview';const styles = createStaticStyles(({ css, cssVar }) => ({content: css`@@ -78,15 +73,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-interface PreviewData {- avatar?: string | null;- backgroundColor?: string | null;- description?: string | null;- meta?: string | null;- secondaryMeta?: string | null;- title?: string | null;-}-const getVerifyStatusLabel = (status: string | null | undefined, t: TFunction<'chat'>) => {switch (status) {case 'delivered': {@@ -123,116 +109,63 @@ const getVerifyStatusLabel = (status: string | null | undefined, t: TFunction<'c};/**- * One cache entry per entity, shared between the hover preview and the eager- * title resolution on the link itself — whichever fires first warms the other.+ * The card's status lines. They come from statuses and counts that move on+ * while the entity runs, so a preview restored from an earlier session only+ * shows them once the server has confirmed it; the branch / commit / tested-at+ * line of a verify run is fixed and paints at once.*/-export const internalEntityPreviewKey = (reference: InternalLinkReference) => [- 'internal-entity-preview',- reference.type,- reference.pathname,-];--export const getPreviewData = async (- reference: InternalLinkReference,+export const formatPreviewMeta = (+ preview: EntityPreview | undefined,+ isConfirmed: boolean,t: TFunction<'chat'>,-): Promise<PreviewData | null> => {- switch (reference.type) {- case 'acceptance': {- const bundle = await verifyService.getAcceptanceBundle(reference.acceptanceId);- if (!bundle) return null;+): { meta?: string | null; secondaryMeta?: string | null } => {+ if (!preview) return {};- const passed = bundle.checks.filter((check) => check.state === 'passed').length;- const exceptions = bundle.checks.filter(- (check) => check.state === 'failed' || check.state === 'uncertain',- ).length;+ const { acceptance, goal, verify } = preview;+ const verifyScope = verify+ ? [+ verify.branch,+ verify.commit,+ verify.testedAt ? new Date(verify.testedAt).toLocaleString() : null,+ ]+ .filter(Boolean)+ .join(' · ')+ : null;- return {- description: bundle.acceptance.requirement || bundle.latestReport?.summary,- meta: t('internalLink.preview.acceptanceCounts', {- exceptions,- passed,- total: bundle.checks.length,- }),- secondaryMeta: t('internalLink.preview.acceptanceRounds', {- count: bundle.rounds.length,- }),- title: bundle.subject.title || bundle.subject.id,- };- }- case 'agent': {- return agentService.getAgentConfigById(reference.agentId);- }- case 'document': {- const document = await documentService.getDocumentById(reference.documentId);- return document- ? {- description: document.content,- title: document.title || document.filename,- }- : null;- }- case 'goal': {- const { decisions, goal, nodes } = await goalService.getGraph(reference.goalId);- const tasks = nodes.filter((node) => node.kind === 'task');- const done = tasks.filter((node) =>- ['rejected', 'resolved', 'retired'].includes(node.status),- ).length;- const pending = decisions.filter((decision) => decision.status === 'pending').length;+ if (!isConfirmed) return { secondaryMeta: verifyScope };- return {- description: goal.requirement,- meta: [- pending > 0 ? t('goalList.needsYou', { count: pending }) : t(goalStatusKey(goal.status)),- t('goalList.taskProgress', { done, total: tasks.length }),- ].join(' · '),- title: goal.title,- };- }- case 'task': {- const result = await taskService.getDetail(reference.taskId);- const task = result.data;- return task- ? {- description: task.description || task.instruction,- title: task.name || task.identifier,- }- : null;- }- case 'verify': {- const bundle = await verifyService.getReportBundle(reference.runId);- if (!bundle) return null;+ if (acceptance)+ return {+ meta: t('internalLink.preview.acceptanceCounts', {+ exceptions: acceptance.exceptions,+ passed: acceptance.passed,+ total: acceptance.total,+ }),+ secondaryMeta: t('internalLink.preview.acceptanceRounds', { count: acceptance.rounds }),+ };- const { report, run } = bundle;- const status = report?.verdict ?? run.status;- const counts = report- ? t('internalLink.preview.verifyCounts', {- failed: report.failedChecks ?? 0,- passed: report.passedChecks ?? 0,- uncertain: report.uncertainChecks ?? 0,- })- : null;- // Branch/commit chips only exist on a coding scope (a run with no- // scenario predates the column and is coding); testedAt is shared.- const codingScope =- (run.scenario ?? 'coding') === 'coding' ? (run.context as VerifyCodingScope | null) : null;- const testedAt = (run.context as { testedAt?: string } | null)?.testedAt;- const scope = [- codingScope?.branch,- codingScope?.commit?.slice(0, 10),- testedAt ? new Date(testedAt).toLocaleString() : null,- ].filter(Boolean);+ if (goal)+ return {+ meta: [+ goal.pendingDecisions > 0+ ? t('goalList.needsYou', { count: goal.pendingDecisions })+ : t(goalStatusKey(goal.status)),+ t('goalList.taskProgress', { done: goal.done, total: goal.total }),+ ].join(' · '),+ };- return {- description: report?.summary,- meta: [getVerifyStatusLabel(status, t), counts].filter(Boolean).join(' · '),- secondaryMeta: scope.join(' · '),- title: run.title,- };- }- case 'route': {- return null;- }- }+ if (verify)+ return {+ meta: [+ getVerifyStatusLabel(verify.status, t),+ verify.counts ? t('internalLink.preview.verifyCounts', verify.counts) : null,+ ]+ .filter(Boolean)+ .join(' · '),+ secondaryMeta: verifyScope,+ };++ return {};};interface InternalEntityPreviewProps extends PropsWithChildren {@@ -248,11 +181,18 @@ export const InternalEntityPreview = memo<InternalEntityPreviewProps>(// A click on the link opens the acceptance in the side panel; this is the// explicit way out to a full browser page.const browserUrl = useAcceptanceBrowserUrl(reference);- const { data, isLoading } = useClientDataSWR(- open ? internalEntityPreviewKey(reference) : null,- () => getPreviewData(reference, t),- { revalidateOnFocus: false },- );+ const {+ error,+ isConfirmed,+ isHydrated,+ isValidating,+ preview: data,+ title,+ } = useEntityPreview(reference, open);+ // Skeleton only while nothing at all is known; a remembered preview paints+ // at once and the network confirms it behind it.+ const isLoading = !data && !error && (!isHydrated || isValidating);+ const { meta, secondaryMeta } = formatPreviewMeta(data, isConfirmed, t);const icon =reference.type === 'acceptance'@@ -289,7 +229,7 @@ export const InternalEntityPreview = memo<InternalEntityPreviewProps>()}<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}><span className={styles.type}>{typeLabel}</span>- <span className={styles.title}>{data?.title || fallbackTitle}</span>+ <span className={styles.title}>{title || fallbackTitle}</span></Flexbox>{browserUrl && (<ActionIcon@@ -305,14 +245,14 @@ export const InternalEntityPreview = memo<InternalEntityPreviewProps>({data.description}</Text>)}- {data?.meta && (+ {meta && (<Text fontSize={12} type={'secondary'}>- {data.meta}+ {meta}</Text>)}- {data?.secondaryMeta && (+ {secondaryMeta && (<Text fontSize={12} type={'secondary'}>- {data.secondaryMeta}+ {secondaryMeta}</Text>)}</Flexbox>@@ -320,7 +260,7 @@ export const InternalEntityPreview = memo<InternalEntityPreviewProps>(return (<Popover- // Disabling the SWR key clears data before the exit animation finishes.+ // Keep the closing card as it was through the exit animation.content={<Freeze frozen={!open}>{content}</Freeze>}mouseEnterDelay={0.35}open={open}diff --git a/src/features/EntityLink/Render/index.test.tsx b/src/features/EntityLink/Render/index.test.tsxindex 5ffc915c1de..7487e8ada38 100644--- a/src/features/EntityLink/Render/index.test.tsx+++ b/src/features/EntityLink/Render/index.test.tsx@@ -69,21 +69,23 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({useWorkspaceAwareNavigate: () => mockNavigate,}));-// What the shared preview/title read answers for this case (null = unresolved).+// What the entity preview replica holds for this case (null = unresolved).let mockEntityPreview: {+ acceptance?: { exceptions: number; passed: number; rounds: number; total: number };description?: string;- meta?: string;- secondaryMeta?: string;title?: string;} | null = null;-vi.mock('@/libs/swr', () => ({- useClientDataSWR: (key: unknown) => {- if (key === null) return { data: undefined, mutate: vi.fn() };- if (Array.isArray(key) && key[0] === 'internal-entity-preview')- return { data: mockEntityPreview, mutate: vi.fn() };- return { data: undefined, mutate: vi.fn() };- },+vi.mock('./useEntityPreview', () => ({+ useEntityPreview: () => ({+ error: undefined,+ isConfirmed: true,+ isHydrated: true,+ isValidating: false,+ preview: mockEntityPreview ?? undefined,+ revalidate: vi.fn(),+ title: mockEntityPreview?.title,+ }),}));// The active agent's document-list replica, already loaded.@@ -250,9 +252,8 @@ describe('Link Render — message link icon toggle', () => {describe('Link Render — internal entities', () => {it('preserves preview details during dismissal and refreshes them when reopened', () => {mockEntityPreview = {+ acceptance: { exceptions: 0, passed: 4, rounds: 3, total: 4 },description: 'Publish external workspace resources',- meta: '4/4 passed · 0 exceptions',- secondaryMeta: '3 verification rounds',title: 'Workspace publishing',};const { container, getByText } = render(@@ -272,8 +273,9 @@ describe('Link Render — internal entities', () => {fireEvent.mouseLeave(container.firstElementChild!);expect(getByText('Publish external workspace resources')).toBeInTheDocument();- expect(getByText('4/4 passed · 0 exceptions')).toBeInTheDocument();- expect(getByText('3 verification rounds')).toBeInTheDocument();+ // Counts are formatted at render time (the test i18n echoes the key).+ expect(getByText('internalLink.preview.acceptanceCounts')).toBeInTheDocument();+ expect(getByText('internalLink.preview.acceptanceRounds')).toBeInTheDocument();mockEntityPreview = { description: 'Updated requirement', title: 'Updated acceptance' };fireEvent.mouseEnter(container.firstElementChild!);diff --git a/src/features/EntityLink/Render/useEntityPreview.reload.test.ts b/src/features/EntityLink/Render/useEntityPreview.reload.test.tsnew file mode 100644index 00000000000..80a5c8f08c1--- /dev/null+++ b/src/features/EntityLink/Render/useEntityPreview.reload.test.ts@@ -0,0 +1,200 @@+/**+ * @vitest-environment happy-dom+ *+ * The entity preview replica behind internal links. Each "reload" re-imports+ * the module graph (fresh stores, fresh SWR cache) over the same localStorage.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { SWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { InternalLinkReference } from '../internalLink';++const scope = vi.hoisted(() => ({ current: '' }));++vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getCacheScope: () => scope.current,+ isScopeTrusted: () => true,+ useCacheScope: () => scope.current,+}));+vi.mock('@/libs/swr', async (importOriginal) => {+ const swr = await import('swr');+ return {+ ...(await importOriginal<Record<string, unknown>>()),+ mutate: swr.mutate,+ useClientDataSWR: swr.default,+ };+});++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++const GOAL: InternalLinkReference = { goalId: 'goal_1', pathname: '/goal/goal_1', type: 'goal' };+const graph = (title: string, status = 'running') => ({+ decisions: [],+ goal: { requirement: 'Ship the replica migration', status, title },+ nodes: [+ { kind: 'task', status: 'resolved' },+ { kind: 'task', status: 'running' },+ ],+});++const pending = () => new Promise<never>(() => {});++/** A fresh module graph: what a page reload starts from (localStorage survives). */+const reload = async () => {+ cleanup();+ vi.resetModules();+ const [{ useEntityPreview }, { goalService }, { useGoalStore }] = await Promise.all([+ import('./useEntityPreview'),+ import('@/services/goal'),+ import('@/store/goal'),+ ]);+ const getGraph = vi.spyOn(goalService, 'getGraph');+ const renderPreview = () => renderHook(() => useEntityPreview(GOAL, true), { wrapper });+ /** The link label and its hover card (or the same entity linked twice) on one screen. */+ const renderTwo = () =>+ renderHook(+ () => {+ useEntityPreview(GOAL, true);+ return useEntityPreview(GOAL, true);+ },+ { wrapper },+ );+ return { getGraph, renderPreview, renderTwo, useGoalStore };+};++/** Let the server answer reach the persisted copy before the next reload. */+const settle = () =>+ act(async () => {+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));+ });++/** Persist one server answer in the current scope. */+const remember = async (title: string) => {+ const first = await reload();+ first.getGraph.mockResolvedValue(graph(title) as never);+ const { result } = first.renderPreview();+ await waitFor(() => expect(result.current.title).toBe(title));+ await settle();+};++describe('useEntityPreview across a reload', { timeout: 60_000 }, () => {+ beforeEach(() => {+ scope.current = `entity-preview-user-${randomUUID()}:personal`;+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it('paints the remembered preview before the network answers', async () => {+ await remember('Replica migration');++ const second = await reload();+ second.getGraph.mockImplementation(pending);+ const { result } = second.renderPreview();+ await settle();++ expect(result.current.title).toBe('Replica migration');+ expect(result.current.preview?.description).toBe('Ship the replica migration');+ });++ it('treats remembered statuses as unconfirmed until the server answers', async () => {+ await remember('Replica migration');++ const second = await reload();+ let answer!: (value: unknown) => void;+ second.getGraph.mockImplementation(+ () =>+ new Promise((resolve) => {+ answer = resolve;+ }) as never,+ );+ const { result } = second.renderPreview();+ await settle();+ expect(result.current.isConfirmed).toBe(false);++ await act(async () => {+ answer(graph('Replica migration', 'achieved'));+ });+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));+ expect(result.current.preview?.goal?.status).toBe('achieved');+ });++ it('keeps the remembered preview when the refresh fails', async () => {+ await remember('Replica migration');++ const second = await reload();+ second.getGraph.mockRejectedValue(new Error('offline'));+ const { result } = second.renderPreview();+ await waitFor(() => expect(second.getGraph).toHaveBeenCalled());+ await settle();++ expect(result.current.title).toBe('Replica migration');+ });++ it('does not restore an entity the server no longer has', async () => {+ await remember('Replica migration');++ const second = await reload();+ // `goal.graph` rejects a deleted goal with NOT_FOUND.+ second.getGraph.mockRejectedValue(+ Object.assign(new Error('Goal not found'), { data: { code: 'NOT_FOUND' } }),+ );+ const { result } = second.renderPreview();+ await waitFor(() => expect(result.current.preview).toBeUndefined());+ await settle();++ const third = await reload();+ third.getGraph.mockImplementation(pending);+ const reloaded = third.renderPreview();+ await settle();++ expect(reloaded.result.current.preview).toBeUndefined();+ expect(reloaded.result.current.title).toBeUndefined();+ });++ it('drops the title another surface loaded once the server says the entity is gone', async () => {+ const first = await reload();+ // The goal was opened earlier in the session, so its graph is still in the goal store.+ first.useGoalStore.setState({+ goalGraphById: { goal_1: { goal: { title: 'Stale goal title' } } as never },+ });+ first.getGraph.mockRejectedValue(+ Object.assign(new Error('Goal not found'), { data: { code: 'NOT_FOUND' } }),+ );+ const { result } = first.renderPreview();+ await waitFor(() => expect(first.getGraph).toHaveBeenCalled());+ await settle();++ expect(result.current.title).toBeUndefined();+ });++ it('shows another identity nothing of the previous one', async () => {+ await remember('Replica migration');++ const second = await reload();+ second.getGraph.mockImplementation(pending);+ scope.current = `entity-preview-user-${randomUUID()}:ws-2`;+ const { result } = second.renderPreview();+ await settle();++ expect(result.current.preview).toBeUndefined();+ expect(result.current.title).toBeUndefined();+ });++ it('asks the server once for the same entity mounted twice', async () => {+ const first = await reload();+ first.getGraph.mockResolvedValue(graph('Replica migration') as never);+ first.renderTwo();+ await settle();++ expect(first.getGraph).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/features/EntityLink/Render/useEntityPreview.ts b/src/features/EntityLink/Render/useEntityPreview.tsnew file mode 100644index 00000000000..fd841336391--- /dev/null+++ b/src/features/EntityLink/Render/useEntityPreview.ts@@ -0,0 +1,105 @@+import { cacheScope } from '@/libs/replica';+import { useAgentStore } from '@/store/agent';+import { useDocumentStore } from '@/store/document';+import {+ entityPreviewActions,+ type EntityPreviewParams,+ entityPreviewSelectors,+ useEntityPreviewStore,+} from '@/store/entityPreview';+import { useGoalStore } from '@/store/goal';+import { useTaskStore } from '@/store/task';+import { useVerifyStore } from '@/store/verify';++import type { InternalLinkReference } from '../internalLink';++export const toEntityPreviewParams = (+ reference: InternalLinkReference,+): EntityPreviewParams | null => {+ switch (reference.type) {+ case 'acceptance': {+ return { id: reference.acceptanceId, type: 'acceptance' };+ }+ case 'agent': {+ return { id: reference.agentId, type: 'agent' };+ }+ case 'document': {+ return { id: reference.documentId, type: 'document' };+ }+ case 'goal': {+ return { id: reference.goalId, type: 'goal' };+ }+ case 'task': {+ return { id: reference.taskId, type: 'task' };+ }+ case 'verify': {+ return { id: reference.runId, type: 'verify' };+ }+ case 'route': {+ return null;+ }+ }+};++/**+ * The entity's title from a detail replica another surface already loaded+ * (the task / goal / document open beside the chat, the agent list), so the+ * link can be titled before its own preview arrives.+ */+const useLoadedDetailTitle = (params: EntityPreviewParams | null): string | undefined => {+ const id = params?.id ?? '';+ const type = params?.type;++ const agentTitle = useAgentStore((s) =>+ type === 'agent' ? s.agentMap[id]?.title || undefined : undefined,+ );+ const documentTitle = useDocumentStore((s) => {+ if (type !== 'document') return;+ const document = s.documentDetailMap[id]?.document;+ return document?.title || document?.filename || undefined;+ });+ const goalTitle = useGoalStore((s) =>+ type === 'goal' ? s.goalGraphById[id]?.goal.title || undefined : undefined,+ );+ const taskTitle = useTaskStore((s) => {+ if (type !== 'task') return;+ const task = s.taskDetailMap[s.taskRefIndex[id] ?? id];+ return task?.name || task?.identifier || undefined;+ });+ const verifyTitle = useVerifyStore((s) => {+ if (type === 'acceptance') {+ const subject = s.acceptanceBundleMap[id]?.subject;+ return subject?.title || subject?.id || undefined;+ }+ if (type === 'verify') return s.verifyReportBundleMap[id]?.value?.run.title || undefined;+ });++ return agentTitle ?? documentTitle ?? goalTitle ?? taskTitle ?? verifyTitle;+};++/**+ * The preview of the entity a link points at, from its replica: a reload+ * paints the last-seen preview at once and the network then confirms it.+ */+export const useEntityPreview = (reference: InternalLinkReference, enabled: boolean) => {+ const params = toEntityPreviewParams(reference);+ const sync = entityPreviewActions.useFetchEntityPreview(params, { enabled });+ const preview = useEntityPreviewStore(entityPreviewSelectors.getPreview(params));+ const isConfirmed = useEntityPreviewStore(entityPreviewSelectors.isPreviewConfirmed(params));+ const isMissing = useEntityPreviewStore(+ entityPreviewSelectors.isPreviewMissing(params, cacheScope.use()),+ );+ const loadedTitle = useLoadedDetailTitle(enabled ? params : null);++ return {+ ...sync,+ isConfirmed,+ preview,+ // A preview the server answered this session is the freshest title; a+ // restored one yields to a detail another surface already loaded. Once the+ // server said the entity is gone, no remembered title stands in for it.+ title: isMissing+ ? undefined+ : (isConfirmed ? preview?.title : undefined) || loadedTitle || preview?.title || undefined,+ };+};diff --git a/src/store/entityPreview/action.ts b/src/store/entityPreview/action.tsnew file mode 100644index 00000000000..f5fa849d03e--- /dev/null+++ b/src/store/entityPreview/action.ts@@ -0,0 +1,58 @@+import { type ReplicaSyncResult } from '@/libs/replica';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { type EntityPreviewState, initialState } from './initialState';+import { EntityPreviewPrivateAction } from './privateAction';+import { type EntityPreviewParams } from './projection';+import { useEntityPreviewStore } from './store';++const n = setNamespace('entityPreview');++type Setter = StoreSetter<EntityPreviewState>;++/**+ * A conversation can link the same entity many times, and each link plus its+ * hover card mounts a sync: collapse them into one request per entity.+ */+const ENTITY_PREVIEW_DEDUPING_INTERVAL = 10_000;++export class EntityPreviewActionImpl {+ readonly #private: EntityPreviewPrivateAction;+ readonly #set: Setter;++ constructor(+ set: Setter,+ _get: () => EntityPreviewState,+ privateAction: EntityPreviewPrivateAction,+ ) {+ this.#set = set;+ this.#private = privateAction;+ }++ /**+ * Fetch orchestration for one linked entity's preview. Read it with+ * `entityPreviewSelectors.getPreview`, not from the return value.+ */+ useFetchEntityPreview = (+ params: EntityPreviewParams | null,+ { enabled = true }: { enabled?: boolean } = {},+ ): ReplicaSyncResult =>+ this.#private.previews.useSync(params, {+ dedupingInterval: ENTITY_PREVIEW_DEDUPING_INTERVAL,+ enabled,+ revalidateOnFocus: false,+ });++ reset = (): void => {+ this.#set(initialState, false, n('reset'));+ };+}++const { getState, setState } = useEntityPreviewStore;++export const entityPreviewActions = new EntityPreviewActionImpl(+ setState,+ getState,+ new EntityPreviewPrivateAction(setState, getState),+);diff --git a/src/store/entityPreview/fetchEntityPreview.ts b/src/store/entityPreview/fetchEntityPreview.tsnew file mode 100644index 00000000000..63a9895595d--- /dev/null+++ b/src/store/entityPreview/fetchEntityPreview.ts@@ -0,0 +1,127 @@+import type { VerifyCodingScope } from '@lobechat/types';++import { agentService } from '@/services/agent';+import { documentService } from '@/services/document';+import { goalService } from '@/services/goal';+import { taskService } from '@/services/task';+import { verifyService } from '@/services/verify';+import type { AgentItem } from '@/types/agent';+import { isTrpcErrorCode } from '@/utils/trpcError';++import { clipDescription, type EntityPreview, type EntityPreviewParams } from './projection';++/** Read one linked entity and keep only what its preview paints. */+const readEntityPreview = async ({+ id,+ type,+}: EntityPreviewParams): Promise<EntityPreview | null> => {+ switch (type) {+ case 'acceptance': {+ const bundle = await verifyService.getAcceptanceBundle(id);+ if (!bundle) return null;++ return {+ acceptance: {+ exceptions: bundle.checks.filter(+ (check) => check.state === 'failed' || check.state === 'uncertain',+ ).length,+ passed: bundle.checks.filter((check) => check.state === 'passed').length,+ rounds: bundle.rounds.length,+ total: bundle.checks.length,+ },+ description: clipDescription(bundle.acceptance.requirement || bundle.latestReport?.summary),+ title: bundle.subject.title || bundle.subject.id,+ };+ }+ case 'agent': {+ // The agent row: its config plus the meta (description) the card shows.+ const agent = (await agentService.getAgentConfigById(id)) as Partial<AgentItem> | null;+ if (!agent) return null;++ return {+ avatar: agent.avatar,+ backgroundColor: agent.backgroundColor,+ description: clipDescription(agent.description),+ title: agent.title,+ };+ }+ case 'document': {+ const document = await documentService.getDocumentById(id);+ if (!document) return null;++ return {+ description: clipDescription(document.content),+ title: document.title || document.filename,+ };+ }+ case 'goal': {+ const { decisions, goal, nodes } = await goalService.getGraph(id);+ const tasks = nodes.filter((node) => node.kind === 'task');++ return {+ description: clipDescription(goal.requirement),+ goal: {+ done: tasks.filter((node) => ['rejected', 'resolved', 'retired'].includes(node.status))+ .length,+ pendingDecisions: decisions.filter((decision) => decision.status === 'pending').length,+ status: goal.status,+ total: tasks.length,+ },+ title: goal.title,+ };+ }+ case 'task': {+ const task = (await taskService.getDetail(id)).data;+ if (!task) return null;++ return {+ description: clipDescription(task.description || task.instruction),+ title: task.name || task.identifier,+ };+ }+ case 'verify': {+ const bundle = await verifyService.getReportBundle(id);+ if (!bundle) return null;++ const { report, run } = bundle;+ // Branch/commit chips only exist on a coding scope (a run with no+ // scenario predates the column and is coding); testedAt is shared.+ const codingScope =+ (run.scenario ?? 'coding') === 'coding' ? (run.context as VerifyCodingScope | null) : null;++ return {+ description: clipDescription(report?.summary),+ title: run.title,+ verify: {+ branch: codingScope?.branch,+ commit: codingScope?.commit?.slice(0, 10),+ counts: report+ ? {+ failed: report.failedChecks ?? 0,+ passed: report.passedChecks ?? 0,+ uncertain: report.uncertainChecks ?? 0,+ }+ : undefined,+ status: report?.verdict ?? run.status,+ testedAt: (run.context as { testedAt?: string } | null)?.testedAt,+ },+ };+ }+ }+};++/**+ * {@link readEntityPreview}, answering `null` when the entity is gone or no+ * longer visible to the viewer: some reads (a goal graph) reject instead of+ * resolving to nothing, and either way the remembered preview must go.+ */+export const fetchEntityPreview = async (+ params: EntityPreviewParams,+): Promise<EntityPreview | null> => {+ try {+ return await readEntityPreview(params);+ } catch (error) {+ if (isTrpcErrorCode(error, 'NOT_FOUND') || isTrpcErrorCode(error, 'FORBIDDEN')) return null;+ throw error;+ }+};diff --git a/src/store/entityPreview/index.ts b/src/store/entityPreview/index.tsnew file mode 100644index 00000000000..81305685f4e--- /dev/null+++ b/src/store/entityPreview/index.ts@@ -0,0 +1,5 @@+export { entityPreviewActions } from './action';+export { type EntityPreviewState } from './initialState';+export { type EntityPreview, type EntityPreviewParams, type EntityPreviewType } from './projection';+export { entityPreviewSelectors } from './selectors';+export { useEntityPreviewStore } from './store';diff --git a/src/store/entityPreview/initialState.ts b/src/store/entityPreview/initialState.tsnew file mode 100644index 00000000000..e89e2ff3547--- /dev/null+++ b/src/store/entityPreview/initialState.ts@@ -0,0 +1,22 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';++import type { EntityPreview } from './projection';++export interface EntityPreviewState {+ /** Linked entity previews (`entityPreviewMap[entityPreviewKey(params)]`). */+ entityPreviewMap: Record<string, EntityPreview>;+ /**+ * Entities the server answered as gone (or no longer visible), by entry key,+ * with the cache scope that answer belongs to. Memory only: it stops the link+ * from falling back to a title another surface loaded before.+ */+ entityPreviewMissing: Record<string, string>;+ /** Replica bookkeeping for `entityPreviewMap`. */+ entityPreviewReplica: ReplicaState<EntityPreview>;+}++export const initialState: EntityPreviewState = {+ entityPreviewMap: {},+ entityPreviewMissing: {},+ entityPreviewReplica: createReplicaState(),+};diff --git a/src/store/entityPreview/privateAction.ts b/src/store/entityPreview/privateAction.tsnew file mode 100644index 00000000000..ace403d81ed--- /dev/null+++ b/src/store/entityPreview/privateAction.ts@@ -0,0 +1,47 @@+import isEqual from 'fast-deep-equal';++import { createReplicaSlice, recordLens } from '@/libs/replica';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { fetchEntityPreview } from './fetchEntityPreview';+import { type EntityPreviewState } from './initialState';+import { type EntityPreview, entityPreviewResource } from './projection';++type Setter = StoreSetter<EntityPreviewState>;++const n = setNamespace('entityPreview');++export class EntityPreviewPrivateAction {+ readonly previews;++ constructor(set: Setter, get: () => EntityPreviewState) {+ this.previews = createReplicaSlice(entityPreviewResource, {+ actionPrefix: 'entityPreview',+ effects: {+ onApplied: (_data, _params, { key }) => {+ if (!(key in get().entityPreviewMissing)) return;+ const { [key]: _, ...rest } = get().entityPreviewMissing;+ set({ entityPreviewMissing: rest }, false, n('entityPreviewFound'));+ },+ onMissing: (_params, { key, scope }) => {+ set(+ { entityPreviewMissing: { ...get().entityPreviewMissing, [key]: scope } },+ false,+ n('entityPreviewMissing'),+ );+ },+ },+ fetcher: fetchEntityPreview,+ get,+ // The entity is gone or no longer visible: drop the entry and its+ // persisted row, so a reload stops titling the link with it.+ isMissing: (incoming) => !incoming,+ merge: (incoming, confirmed) =>+ !incoming || isEqual(incoming, confirmed) ? undefined : incoming,+ set,+ stateKey: 'entityPreviewReplica',+ view: recordLens<EntityPreviewState, EntityPreview>('entityPreviewMap'),+ });+ }+}diff --git a/src/store/entityPreview/projection.ts b/src/store/entityPreview/projection.tsnew file mode 100644index 00000000000..e876e29e78c--- /dev/null+++ b/src/store/entityPreview/projection.ts@@ -0,0 +1,66 @@+import type { GoalStatus } from '@lobechat/const/goal';++import { defineReplica } from '@/libs/replica';++/** Entities an internal link can name and preview (every reference type but `route`). */+export type EntityPreviewType = 'acceptance' | 'agent' | 'document' | 'goal' | 'task' | 'verify';++export interface EntityPreviewParams {+ id: string;+ type: EntityPreviewType;+}++/**+ * The compact preview of one linked entity: what the link label and its hover+ * card paint. Counts and statuses are kept raw, so the card formats them in+ * the current language instead of replaying the strings of an older session.+ */+export interface EntityPreview {+ acceptance?: { exceptions: number; passed: number; rounds: number; total: number };+ avatar?: string | null;+ backgroundColor?: string | null;+ description?: string | null;+ goal?: { done: number; pendingDecisions: number; status: GoalStatus; total: number };+ title?: string | null;+ verify?: {+ branch?: string | null;+ commit?: string | null;+ counts?: { failed: number; passed: number; uncertain: number };+ status?: string | null;+ testedAt?: string | null;+ };+}++/** Linked entities whose preview survives a reload, most recently used first. */+export const MAX_PERSISTED_ENTITY_PREVIEWS = 100;++/** The card clamps the description to three lines; longer text is never shown. */+export const ENTITY_PREVIEW_DESCRIPTION_LIMIT = 280;++/**+ * Entry key: `<type>/<id>`. The `/` keeps the SWR sync key clear of the legacy+ * CACHE_TIERS prefixes (`task:`, `agent:`, `document:`), which would persist+ * the response a second time.+ */+export const entityPreviewKey = ({ id, type }: EntityPreviewParams) => `${type}/${id}`;++/**+ * Previews of the entities internal links point at (`entityPreviewMap[key]`).+ * localStorage, not IndexedDB: a mounted link restores its title inside the+ * mount microtask, so a reload paints the title instead of flashing the URL.+ * Entries are compact and LRU-capped to stay well inside the origin quota.+ */+export const entityPreviewResource = defineReplica<+ EntityPreviewParams,+ EntityPreview,+ EntityPreview | null+>({+ key: entityPreviewKey,+ name: 'entityPreview',+ persist: { maxEntries: MAX_PERSISTED_ENTITY_PREVIEWS },+ storage: 'localStorage',+ version: 1,+});++export const clipDescription = (text: string | null | undefined) =>+ text ? text.slice(0, ENTITY_PREVIEW_DESCRIPTION_LIMIT) : text;diff --git a/src/store/entityPreview/selectors.ts b/src/store/entityPreview/selectors.tsnew file mode 100644index 00000000000..fdf063fa616--- /dev/null+++ b/src/store/entityPreview/selectors.ts@@ -0,0 +1,30 @@+import type { EntityPreviewState } from './initialState';+import { type EntityPreview, entityPreviewKey, type EntityPreviewParams } from './projection';++/** One entity's preview, or `undefined` before its first paint (or once it is gone). */+const getPreview =+ (params?: EntityPreviewParams | null) =>+ (s: EntityPreviewState): EntityPreview | undefined =>+ params ? s.entityPreviewMap[entityPreviewKey(params)] : undefined;++/**+ * Whether the server answered this preview in this session. A restored copy+ * still paints the title and description, but its statuses and counts may+ * have moved on since, so they wait for this.+ */+const isPreviewConfirmed =+ (params?: EntityPreviewParams | null) =>+ (s: EntityPreviewState): boolean =>+ !!params && s.entityPreviewReplica.entries[entityPreviewKey(params)]?.source === 'server';++/** Whether the server answered, in this scope, that the entity is gone or not visible. */+const isPreviewMissing =+ (params: EntityPreviewParams | null | undefined, scope: string) =>+ (s: EntityPreviewState): boolean =>+ !!params && s.entityPreviewMissing[entityPreviewKey(params)] === scope;++export const entityPreviewSelectors = {+ getPreview,+ isPreviewConfirmed,+ isPreviewMissing,+};diff --git a/src/store/entityPreview/store.ts b/src/store/entityPreview/store.tsnew file mode 100644index 00000000000..ede25550339--- /dev/null+++ b/src/store/entityPreview/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { type EntityPreviewState, initialState } from './initialState';++const devtools = createDevtools('entityPreview');++export const useEntityPreviewStore = createWithEqualityFn<EntityPreviewState>()(+ devtools(() => initialState),+ shallow,+);++expose('entityPreview', useEntityPreviewStore);