Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

31.4 KB
Raw Blame
/**
 * @vitest-environment happy-dom
 */
import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
import { fireEvent, render } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { EntityLinkHostProvider, type EntityLinkPortalScope } from '../host';
import Render from './index';
import { InternalEntityPreview } from './InternalEntityPreview';

const mockConst = vi.hoisted(() => ({
  isDesktop: false,
}));

vi.mock('@lobechat/const', async (importOriginal) => ({
  ...((await importOriginal()) as Record<string, unknown>),
  get isDesktop() {
    return mockConst.isDesktop;
  },
}));

vi.mock('@lobehub/ui', async (importOriginal) => {
  const actual = await importOriginal<Record<string, unknown>>();
  const factories: ((original: typeof importOriginal) => unknown)[] = [
    async (importOriginal) => ({
      ...((await importOriginal()) as Record<string, unknown>),
      ActionIcon: ({ icon: _icon, onClick, title, ...rest }: any) => (
        <button {...rest} aria-label={title} type="button" onClick={onClick} />
      ),
    }),
    async (importOriginal) => ({
      ...(await importOriginal<object>()),
      // Keep content mounted after dismissal to model the popover's exit animation.
      Popover: ({ children, content, onOpenChange }: any) => (
        <div onMouseEnter={() => onOpenChange?.(true)} onMouseLeave={() => onOpenChange?.(false)}>
          {children}
          {content}
        </div>
      ),
    }),
  ];
  const merged: Record<string, unknown> = { ...actual };
  for (const factory of factories) {
    const part = (await factory(importOriginal)) as Record<string, unknown>;
    for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
  }
  return merged;
});

// `enableMessageLinkIcon` is read via useUserStore(selector). We drive the
// selector's return value through this module-level flag so each case can flip
// the "Link Icon" setting on/off without a real store.
let mockShowIcon = true;
const mockOpenInBrowserTab = vi.fn();
const mockNavigate = vi.fn();
const mockOpenAcceptance = vi.fn();
const mockOpenAgentDetail = vi.fn();
const mockOpenDocument = vi.fn();
const mockOpenGoal = vi.fn();
const mockOpenTaskDetail = vi.fn();
const mockOpenVerifyReport = vi.fn();

vi.mock('@/business/client/hooks/useWorkspaces', () => ({
  useWorkspaces: () => [{ id: 'ws-1', slug: 'lobe-team' }],
}));

vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
  useWorkspaceAwareNavigate: () => mockNavigate,
}));

// What the entity preview replica holds for this case (null = unresolved).
let mockEntityPreview: {
  acceptance?: { exceptions: number; passed: number; rounds: number; total: number };
  description?: string;
  title?: string;
} | null = null;

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.
vi.mock('@/store/agentDocument', () => ({
  agentDocumentActions: { fetchDocumentList: vi.fn(), useFetchDocumentList: vi.fn() },
  agentDocumentSelectors: {
    getDocumentList: (agentId?: string) => () =>
      agentId ? [{ documentId: 'docs_doc1', id: 'agent-document-1' }] : undefined,
  },
  useAgentDocumentStore: (selector: (state: unknown) => unknown) => selector({}),
}));

vi.mock('@/store/agent', () => ({
  useAgentStore: (selector: (state: unknown) => unknown) => selector({ activeAgentId: 'agt_1' }),
}));

vi.mock('@/store/chat', () => ({
  useChatStore: (selector: (state: unknown) => unknown) =>
    selector({
      openAcceptance: mockOpenAcceptance,
      openAgentDetail: mockOpenAgentDetail,
      openDocument: mockOpenDocument,
      openGoal: mockOpenGoal,
      openTaskDetail: mockOpenTaskDetail,
      openVerifyReport: mockOpenVerifyReport,
    }),
}));

vi.mock('@/store/user', () => ({
  useUserStore: (selector: (s: unknown) => unknown) => selector(undefined),
}));

vi.mock('@/store/user/selectors', () => ({
  userGeneralSettingsSelectors: {
    enableMessageLinkIcon: () => mockShowIcon,
  },
}));

const mockOpenTrustedExternalUrl = vi.fn();

vi.mock('@/utils/openTrustedExternalUrl', () => ({
  openTrustedExternalUrl: (url: string) => mockOpenTrustedExternalUrl(url),
}));

let mockAppOrigin = 'https://app.lobehub.com';

vi.mock('@/hooks/useAppOrigin', () => ({
  useAppOrigin: () => mockAppOrigin,
}));

vi.mock('@/store/global', () => ({
  useGlobalStore: (selector: (s: unknown) => unknown) =>
    selector({ openInBrowserTab: mockOpenInBrowserTab }),
}));

const renderLink = (properties: Record<string, unknown>) =>
  render(
    <Render id="msg-1" node={{ properties }} tagName="lobeLink" type="element">
      {null}
    </Render>,
  );

/** The same link inside a host that declares what it can open in a panel. */
const renderLinkInHost = (properties: Record<string, unknown>, portal: EntityLinkPortalScope) =>
  render(
    <EntityLinkHostProvider portal={portal}>
      <Render id="msg-1" node={{ properties }} tagName="lobeLink" type="element">
        {null}
      </Render>
    </EntityLinkHostProvider>,
  );

/** Hover the link's preview trigger (the Popover mock), not the outer action wrapper. */
const hoverPreview = (container: HTMLElement) =>
  fireEvent.mouseEnter(container.querySelector('a')!.parentElement!);

/** The open-in-browser action inside the hover preview card. */
const previewBrowserAction = (container: HTMLElement) =>
  container.querySelector<HTMLElement>('a ~ * button[aria-label="report.actions.openInBrowser"]');

afterEach(() => {
  mockShowIcon = true;
  mockConst.isDesktop = false;
  mockEntityPreview = null;
  mockAppOrigin = 'https://app.lobehub.com';
  vi.restoreAllMocks();
});

beforeEach(() => {
  vi.clearAllMocks();
});

describe('Link Render — message link icon toggle', () => {
  describe('when enableMessageLinkIcon is ON (default)', () => {
    it('renders a generic link with a leading favicon icon', () => {
      mockShowIcon = true;
      const { container } = renderLink({
        linkDomain: 'thecoffee.club',
        linkHref: 'https://thecoffee.club',
        linkKind: 'generic',
        linkLabel: 'https://thecoffee.club',
      });
      const anchor = container.querySelector('a')!;
      expect(anchor).toBeTruthy();
      expect(anchor.getAttribute('href')).toBe('https://thecoffee.club');
      // icon span + favicon <img> present before the label
      expect(anchor.querySelector('span')).toBeTruthy();
      expect(anchor.querySelector('img')).toBeTruthy();
      expect(anchor.textContent).toContain('https://thecoffee.club');
    });

    it('renders a github link with an icon (svg)', () => {
      mockShowIcon = true;
      const { container } = renderLink({
        linkHref: 'https://github.com/lobehub/lobehub',
        linkKind: 'github',
        linkLabel: 'lobehub/lobehub',
      });
      const anchor = container.querySelector('a')!;
      expect(anchor.querySelector('span')).toBeTruthy();
      expect(anchor.querySelector('svg')).toBeTruthy();
    });
  });

  describe('when enableMessageLinkIcon is OFF', () => {
    it('renders a generic link as a plain anchor with NO icon', () => {
      mockShowIcon = false;
      const { container } = renderLink({
        linkDomain: 'thecoffee.club',
        linkHref: 'https://thecoffee.club',
        linkKind: 'generic',
        linkLabel: 'https://thecoffee.club',
      });
      const anchor = container.querySelector('a')!;
      expect(anchor).toBeTruthy();
      expect(anchor.getAttribute('href')).toBe('https://thecoffee.club');
      // no icon span, no favicon img — copies cleanly into email/other apps
      expect(anchor.querySelector('span')).toBeNull();
      expect(anchor.querySelector('img')).toBeNull();
      expect(anchor.textContent).toBe('https://thecoffee.club');
    });

    it('drops the icon for every link kind (github / linear / email)', () => {
      mockShowIcon = false;
      for (const properties of [
        {
          linkHref: 'https://github.com/lobehub/lobehub',
          linkKind: 'github',
          linkLabel: 'lobehub/lobehub',
        },
        { linkHref: 'https://linear.app/x/issue/ABC-1', linkKind: 'linear', linkLabel: 'ABC-1' },
        { linkHref: 'mailto:[email protected]', linkKind: 'email', linkLabel: '[email protected]' },
      ]) {
        const { container } = renderLink(properties);
        const anchor = container.querySelector('a')!;
        expect(anchor.querySelector('span')).toBeNull();
        expect(anchor.querySelector('svg')).toBeNull();
        expect(anchor.querySelector('img')).toBeNull();
      }
    });
  });
});

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',
      title: 'Workspace publishing',
    };
    const { container, getByText } = render(
      <InternalEntityPreview
        fallbackTitle="Acceptance"
        reference={{
          acceptanceId: 'acceptance-1',
          pathname: '/acceptance/acceptance-1',
          type: 'acceptance',
        }}
      >
        <span>Preview trigger</span>
      </InternalEntityPreview>,
    );
    fireEvent.mouseEnter(container.firstElementChild!);
    expect(getByText('Publish external workspace resources')).toBeInTheDocument();

    fireEvent.mouseLeave(container.firstElementChild!);
    expect(getByText('Publish external workspace resources')).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!);
    expect(getByText('Updated requirement')).toBeInTheDocument();
    expect(getByText('Updated acceptance')).toBeInTheDocument();
  });

  it('opens an acceptance in the browser from its preview, not the side panel', () => {
    // A click on the link itself opens the side panel; the preview offers the
    // full page as an explicit alternative, as an absolute URL so the desktop
    // system browser can resolve it.
    mockEntityPreview = { title: 'Workspace publishing' };
    const { container } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });
    hoverPreview(container);

    fireEvent.click(previewBrowserAction(container)!);

    expect(mockOpenTrustedExternalUrl).toHaveBeenCalledWith(
      'https://app.lobehub.com/acceptance/acceptance-1',
    );
    expect(mockOpenAcceptance).not.toHaveBeenCalled();
  });

  it('opens the app, not the gateway apex, from the desktop cloud preview', () => {
    // Desktop in cloud mode reports `https://lobehub.com` as its origin, where
    // `/acceptance/<id>` is the marketing site's page rather than the report.
    mockAppOrigin = 'https://lobehub.com';
    mockEntityPreview = { title: 'Workspace publishing' };
    const { container } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });
    hoverPreview(container);

    fireEvent.click(previewBrowserAction(container)!);

    expect(mockOpenTrustedExternalUrl).toHaveBeenCalledWith(
      'https://app.lobehub.com/acceptance/acceptance-1',
    );
  });

  it('offers no browser action without an app origin to resolve against', () => {
    mockAppOrigin = '';
    const { container, queryByRole } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });
    fireEvent.mouseEnter(container.firstElementChild!);

    expect(queryByRole('button', { name: 'report.actions.openInBrowser' })).toBeNull();
  });

  it('keeps the browser action off previews of other entities', () => {
    const { container, queryByRole } = renderLink({
      linkHref: '/task/T-198',
      linkKind: 'generic',
      linkLabel: 'Task',
    });
    fireEvent.mouseEnter(container.firstElementChild!);

    expect(queryByRole('button', { name: 'report.actions.openInBrowser' })).toBeNull();
  });

  it('opens an acceptance in the browser from beside the link, without hovering', () => {
    // The side panel a click opens can sit under another surface (a session
    // overlay), so the browser page is one click away right next to the link.
    const { container } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });

    const action = container.querySelector<HTMLElement>('[data-acceptance-browser]')!;
    expect(action).toHaveAttribute('aria-label', 'report.actions.openInBrowser');
    // Outside the anchor: the desktop preload claims clicks via closest('a').
    expect(action.closest('a')).toBeNull();

    fireEvent.click(action);

    expect(mockOpenTrustedExternalUrl).toHaveBeenCalledWith(
      'https://app.lobehub.com/acceptance/acceptance-1',
    );
    expect(mockOpenAcceptance).not.toHaveBeenCalled();
  });

  it('keeps a workspace-qualified acceptance link scoped when opening it in the browser', () => {
    const { container } = renderLink({
      linkHref: '/lobe-team/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });

    fireEvent.click(container.querySelector('[data-acceptance-browser]')!);

    expect(mockOpenTrustedExternalUrl).toHaveBeenCalledWith(
      'https://app.lobehub.com/lobe-team/acceptance/acceptance-1',
    );
  });

  it('offers no inline browser action without an origin or on other entities', () => {
    for (const linkHref of ['/task/T-198', '/verify/run-1']) {
      const { container } = renderLink({ linkHref, linkKind: 'generic', linkLabel: 'Entity' });
      expect(container.querySelector('[data-acceptance-browser]')).toBeNull();
    }

    mockAppOrigin = '';
    const { container } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });
    expect(container.querySelector('[data-acceptance-browser]')).toBeNull();
  });

  it('keeps the inline browser action off mobile, where a tap beside the link would misfire', () => {
    vi.stubGlobal('__MOBILE__', true);

    try {
      const { container } = renderLink({
        linkHref: '/acceptance/acceptance-1',
        linkKind: 'generic',
        linkLabel: 'Acceptance',
      });

      expect(container.querySelector('[data-acceptance-browser]')).toBeNull();
    } finally {
      vi.unstubAllGlobals();
    }
  });

  it('replaces a pasted URL label with the resolved entity title', () => {
    // A raw acceptance URL says nothing about what it points to; once the
    // entity resolves, the link reads as its title.
    mockEntityPreview = { title: 'Gateway 消息队列重建' };

    const { container } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: '/acceptance/acceptance-1',
    });

    const anchor = container.querySelector('a')!;
    expect(anchor.textContent).toBe('Gateway 消息队列重建');
    expect(anchor.getAttribute('href')).toBe('/acceptance/acceptance-1');
  });

  it('keeps the pasted URL while the title has not resolved', () => {
    mockEntityPreview = null;

    const { container } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: '/acceptance/acceptance-1',
    });

    expect(container.querySelector('a')!.textContent).toBe('/acceptance/acceptance-1');
  });

  it('never replaces authored link text with the entity title', () => {
    mockEntityPreview = { title: 'Resolved title' };

    const { container } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });

    expect(container.querySelector('a')!.textContent).toBe('Acceptance');
  });

  it('keeps a URL-shaped authored label — bare means label === href, not "looks like a URL"', () => {
    mockEntityPreview = { title: 'Resolved title' };

    const { container } = renderLink({
      linkHref: '/task/T-198',
      linkKind: 'generic',
      linkLabel: 'https://docs.example',
    });

    expect(container.querySelector('a')!.textContent).toBe('https://docs.example');
  });

  it('does not resolve titles for workspace-qualified links', () => {
    // The ambient client reads the ACTIVE scope; /lobe-team/task/T-198 may
    // name a different entity there, so the URL stays.
    mockEntityPreview = { title: 'Wrong-scope title' };

    const { container } = renderLink({
      linkHref: '/lobe-team/task/T-198',
      linkKind: 'generic',
      linkLabel: '/lobe-team/task/T-198',
    });

    expect(container.querySelector('a')!.textContent).toBe('/lobe-team/task/T-198');
  });

  it('opens acceptance links in the conversation portal', () => {
    const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => undefined);

    const { getByRole } = renderLink({
      linkHref: '/acceptance/acceptance-1',
      linkKind: 'generic',
      linkLabel: 'Acceptance',
    });

    fireEvent.click(getByRole('link', { name: 'Acceptance' }));

    expect(mockOpenAcceptance).toHaveBeenCalledWith('acceptance-1');
    expect(assign).not.toHaveBeenCalled();
    expect(mockNavigate).not.toHaveBeenCalled();
  });

  it('opens official document links in the conversation portal', () => {
    const { getByRole } = renderLink({
      linkHref: '/agent/agt_1/docs/doc1',
      linkKind: 'generic',
      linkLabel: 'Research notes',
    });

    fireEvent.click(getByRole('link', { name: 'Research notes' }));

    expect(mockOpenDocument).toHaveBeenCalledWith('docs_doc1', 'agent-document-1');
    expect(getByRole('link', { name: 'Research notes' })).toHaveAttribute(
      'href',
      '/agent/agt_1/docs/doc1',
    );
    expect(mockNavigate).not.toHaveBeenCalled();
  });

  it('opens page links as the standalone page on mobile instead of the portal modal', () => {
    vi.stubGlobal('__MOBILE__', true);

    try {
      const { getByRole } = renderLink({
        linkHref: '/page/doc1',
        linkKind: 'generic',
        linkLabel: 'Meeting notes',
      });

      fireEvent.click(getByRole('link', { name: 'Meeting notes' }));

      expect(mockNavigate).toHaveBeenCalledWith('/page/doc1');
      expect(mockOpenDocument).not.toHaveBeenCalled();
    } finally {
      vi.unstubAllGlobals();
    }
  });

  it('opens tasks and agents in their portal views', () => {
    const task = renderLink({
      linkHref: '/task/T-198',
      linkKind: 'generic',
      linkLabel: 'T-198',
    });
    fireEvent.click(task.getByRole('link', { name: 'T-198' }));
    expect(mockOpenTaskDetail).toHaveBeenCalledWith('T-198');
    task.unmount();

    const agent = renderLink({
      linkHref: '/agent/agt_1',
      linkKind: 'generic',
      linkLabel: 'Research agent',
    });
    fireEvent.click(agent.getByRole('link', { name: 'Research agent' }));
    expect(mockOpenAgentDetail).toHaveBeenCalledWith('agt_1');
  });

  it('shows a goal the CLI printed by its title and goal icon, and opens it beside the chat', () => {
    // `lh goal create` prints the goal URL; agents paste it bare or label it with
    // the id. Either way the link should read as the goal, not its id.
    mockEntityPreview = { title: 'Vent 真信号修复' };

    const { container, getByRole } = renderLink({
      linkHref: '/goal/goal_abc',
      linkKind: 'generic',
      linkLabel: 'goal_abc',
    });

    const anchor = container.querySelector('a')!;
    expect(anchor.textContent).toBe('Vent 真信号修复');
    // The goal's own icon, not a status or progress glyph.
    expect(anchor.querySelector('svg.lucide-target')).not.toBeNull();

    fireEvent.click(getByRole('link', { name: 'Vent 真信号修复' }));
    expect(mockOpenGoal).toHaveBeenCalledWith('goal_abc');
    expect(mockNavigate).not.toHaveBeenCalled();
  });

  it('keeps authored text on a goal link', () => {
    mockEntityPreview = { title: 'Resolved goal title' };

    const { container } = renderLink({
      linkHref: '/agent/agt_1/goal/goal_abc',
      linkKind: 'generic',
      linkLabel: '接续 goal',
    });

    expect(container.querySelector('a')!.textContent).toBe('接续 goal');
  });

  it('hard-navigates personal verify pages into the Workbench runtime', () => {
    const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => undefined);

    const { getByRole } = renderLink({
      linkHref: '/verify/run-1',
      linkKind: 'generic',
      linkLabel: 'Verify report',
    });

    fireEvent.click(getByRole('link', { name: 'Verify report' }));

    expect(assign).toHaveBeenCalledWith('/verify/run-1');
    expect(mockNavigate).not.toHaveBeenCalled();
    expect(mockOpenVerifyReport).not.toHaveBeenCalled();
  });

  it('opens a verify link for the active workspace in the report portal', () => {
    const { getByRole } = renderLink({
      linkHref: '/lobe-team/verify/run-1',
      linkKind: 'generic',
      linkLabel: 'LobeHub Verify',
    });

    fireEvent.click(getByRole('link', { name: 'LobeHub Verify' }));

    expect(mockOpenVerifyReport).toHaveBeenCalledWith('run-1');
    expect(mockNavigate).not.toHaveBeenCalled();
  });

  it('preserves modifier-click browser behavior on web', () => {
    const { getByRole } = renderLink({
      linkHref: '/task/T-198',
      linkKind: 'generic',
      linkLabel: 'T-198',
    });

    fireEvent.click(getByRole('link', { name: 'T-198' }), { metaKey: true });

    expect(mockOpenTaskDetail).not.toHaveBeenCalled();
  });

  it('takes over modifier-clicks on desktop, which has no new tab to open', () => {
    mockConst.isDesktop = true;

    const { getByRole } = renderLink({
      linkHref: '/task/T-198',
      linkKind: 'generic',
      linkLabel: 'T-198',
    });

    fireEvent.click(getByRole('link', { name: 'T-198' }), { metaKey: true });

    expect(mockOpenTaskDetail).toHaveBeenCalledWith('T-198');
  });
});

// The desktop preload intercepts every anchor click in the capture phase and, unless
// the renderer has claimed the link, stops propagation before React's onClick runs.
// Dropping this attribute would silently send internal links to the system browser.
describe('Link Render — desktop preload contract', () => {
  it('marks internal entity links as renderer-handled', () => {
    const { getByRole } = renderLink({
      linkHref: '/verify/run-1',
      linkKind: 'generic',
      linkLabel: 'Verify report',
    });

    expect(getByRole('link', { name: 'Verify report' })).toHaveAttribute(
      RENDERER_HANDLED_LINK_ATTR,
      'true',
    );
  });

  it('leaves external links unclaimed so the preload opens them in the system browser', () => {
    const { container } = renderLink({
      linkDomain: 'github.com',
      linkHref: 'https://github.com/lobehub/lobehub',
      linkKind: 'github',
      linkLabel: 'lobehub/lobehub',
    });

    expect(container.querySelector('a')).not.toHaveAttribute(RENDERER_HANDLED_LINK_ATTR);
  });
});

describe('Link Render — open an external link in the side browser', () => {
  const renderExternal = () =>
    renderLink({
      linkDomain: 'localhost',
      linkHref: 'http://localhost:3022/observability/context',
      linkKind: 'generic',
      linkLabel: 'http://localhost:3022/observability/context',
    });

  it('offers the side-browser action on desktop', () => {
    mockConst.isDesktop = true;

    const { container } = renderExternal();
    const action = container.querySelector('[data-side-browser]')!;
    expect(action).toBeTruthy();

    fireEvent.click(action);

    expect(mockOpenInBrowserTab).toHaveBeenCalledWith(
      'http://localhost:3022/observability/context',
    );
  });

  it("opens the page in the host's side browser when the host has one", () => {
    mockConst.isDesktop = true;
    const openInHostBrowser = vi.fn();

    const { container } = render(
      <EntityLinkHostProvider portal={['acceptance']} onOpenSideBrowser={openInHostBrowser}>
        <Render
          id="msg-1"
          tagName="lobeLink"
          type="element"
          node={{
            properties: {
              linkDomain: 'localhost',
              linkHref: 'http://localhost:3022/observability/context',
              linkKind: 'generic',
              linkLabel: 'http://localhost:3022/observability/context',
            },
          }}
        >
          {null}
        </Render>
      </EntityLinkHostProvider>,
    );
    fireEvent.click(container.querySelector('[data-side-browser]')!);

    expect(openInHostBrowser).toHaveBeenCalledWith('http://localhost:3022/observability/context');
    // The working sidebar is not on this page; a request left for it would pop it open later.
    expect(mockOpenInBrowserTab).not.toHaveBeenCalled();
  });

  it('keeps the action OUTSIDE the anchor, or the preload would swallow its click', () => {
    mockConst.isDesktop = true;

    const { container } = renderExternal();

    // The preload intercepts clicks via closest('a') in the capture phase, so an
    // action nested inside the link would never reach React.
    expect(container.querySelector('a [data-side-browser]')).toBeNull();
    expect(container.querySelector('[data-side-browser]')!.closest('a')).toBeNull();
  });

  it('leaves the anchor itself untouched, so a plain click still opens the system browser', () => {
    mockConst.isDesktop = true;

    const { container } = renderExternal();
    const anchor = container.querySelector('a')!;

    expect(anchor).not.toHaveAttribute(RENDERER_HANDLED_LINK_ATTR);
    expect(anchor).toHaveAttribute('target', '_blank');

    fireEvent.click(anchor);
    expect(mockOpenInBrowserTab).not.toHaveBeenCalled();
  });

  it('hides the action on web', () => {
    mockConst.isDesktop = false;
    const web = renderExternal();
    expect(web.container.querySelector('[data-side-browser]')).toBeNull();
  });

  it('hides the action for non-web links (mailto) and for portal-bound internal links', () => {
    mockConst.isDesktop = true;

    const email = renderLink({
      linkHref: 'mailto:[email protected]',
      linkKind: 'email',
      linkLabel: '[email protected]',
    });
    expect(email.container.querySelector('[data-side-browser]')).toBeNull();
    email.unmount();

    const internal = renderLink({
      linkHref: '/verify/run-1',
      linkKind: 'generic',
      linkLabel: 'Verify report',
    });
    expect(internal.container.querySelector('[data-side-browser]')).toBeNull();
  });

  it('navigates non-entity app routes without leaving the SPA', () => {
    const { getByRole } = renderLink({
      linkHref: '/settings/profile',
      linkKind: 'generic',
      linkLabel: 'Profile settings',
    });

    fireEvent.click(getByRole('link', { name: 'Profile settings' }));

    expect(mockNavigate).toHaveBeenCalledWith('/settings/profile');
  });

  it('preserves workspace prefixes for workspace-qualified SPA routes', () => {
    const { getByRole } = renderLink({
      linkHref: '/lobe-team/tasks',
      linkKind: 'generic',
      linkLabel: 'Workspace tasks',
    });

    fireEvent.click(getByRole('link', { name: 'Workspace tasks' }));

    expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/tasks', { escape: true });
  });

  it('opens a task from another workspace beside the chat, scoped to that workspace', () => {
    const { getByRole } = renderLink({
      linkHref: '/lobe-team/task/T-198',
      linkKind: 'generic',
      linkLabel: 'Workspace task',
    });

    fireEvent.click(getByRole('link', { name: 'Workspace task' }));

    expect(mockOpenTaskDetail).toHaveBeenCalledWith('T-198', { id: 'ws-1', slug: 'lobe-team' });
    expect(mockNavigate).not.toHaveBeenCalled();
  });

  it('still navigates other workspace-qualified entities into their workspace', () => {
    const { getByRole } = renderLink({
      linkHref: '/lobe-team/agent/agt_9',
      linkKind: 'generic',
      linkLabel: 'Workspace agent',
    });

    fireEvent.click(getByRole('link', { name: 'Workspace agent' }));

    expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/agent/agt_9', { escape: true });
    expect(mockOpenAgentDetail).not.toHaveBeenCalled();
  });

  it('preserves a different agent context for agent-scoped document links', () => {
    const { getByRole } = renderLink({
      linkHref: '/agent/agt_other/docs/docs_1',
      linkKind: 'generic',
      linkLabel: 'Another agent document',
    });

    fireEvent.click(getByRole('link', { name: 'Another agent document' }));

    expect(mockNavigate).toHaveBeenCalledWith('/agent/agt_other/docs/docs_1', { escape: true });
    expect(mockOpenDocument).not.toHaveBeenCalled();
  });
});

describe('Link Render — host portal scope', () => {
  it('navigates instead of opening a detail when the host has no panel', () => {
    const { getByRole } = renderLinkInHost(
      { linkHref: '/acceptance/acceptance-1', linkKind: 'generic', linkLabel: 'Acceptance' },
      false,
    );

    fireEvent.click(getByRole('link', { name: 'Acceptance' }));

    // A full-screen reader covers the page: a panel opened behind it would be
    // invisible, so the entity's own route is the only destination that works.
    expect(mockNavigate).toHaveBeenCalledWith('/acceptance/acceptance-1');
    expect(mockOpenAcceptance).not.toHaveBeenCalled();
  });

  it('closes the covering reader and opens the acceptance panel on desktop', () => {
    // Electron registers no standalone `/acceptance` route, so the navigation
    // fallback would land on a dead destination.
    mockConst.isDesktop = true;
    const onDismiss = vi.fn();
    const { getByRole } = render(
      <EntityLinkHostProvider portal={false} onDismiss={onDismiss}>
        <Render
          id="msg-1"
          tagName="lobeLink"
          type="element"
          node={{
            properties: {
              linkHref: '/acceptance/acceptance-1',
              linkKind: 'generic',
              linkLabel: 'Acceptance',
            },
          }}
        >
          {null}
        </Render>
      </EntityLinkHostProvider>,
    );

    fireEvent.click(getByRole('link', { name: 'Acceptance' }));

    expect(onDismiss).toHaveBeenCalledOnce();
    expect(mockOpenAcceptance).toHaveBeenCalledWith('acceptance-1');
    expect(mockNavigate).not.toHaveBeenCalled();
  });

  it('navigates entity kinds the host cannot present', () => {
    const { getByRole } = renderLinkInHost(
      { linkHref: '/task/T-198', linkKind: 'generic', linkLabel: 'T-198' },
      ['acceptance'],
    );

    fireEvent.click(getByRole('link', { name: 'T-198' }));

    expect(mockNavigate).toHaveBeenCalledWith('/task/T-198');
    expect(mockOpenTaskDetail).not.toHaveBeenCalled();
  });

  it('navigates a task from another workspace when the host has no panel', () => {
    const { getByRole } = renderLinkInHost(
      { linkHref: '/lobe-team/task/T-198', linkKind: 'generic', linkLabel: 'Workspace task' },
      false,
    );

    fireEvent.click(getByRole('link', { name: 'Workspace task' }));

    expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/task/T-198', { escape: true });
    expect(mockOpenTaskDetail).not.toHaveBeenCalled();
  });

  it('still opens the kinds the host can present', () => {
    const { getByRole } = renderLinkInHost(
      { linkHref: '/acceptance/acceptance-1', linkKind: 'generic', linkLabel: 'Acceptance' },
      ['acceptance'],
    );

    fireEvent.click(getByRole('link', { name: 'Acceptance' }));

    expect(mockOpenAcceptance).toHaveBeenCalledWith('acceptance-1');
    expect(mockNavigate).not.toHaveBeenCalled();
  });
});