Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,17 @@ describe('ChatMessageEnhanced — in-app screen links', () => {
expect(windowOpen).not.toHaveBeenCalled();
});

it("draws a link that stays in the app as the inline box, by the runtime's own new-tab rule", () => {
renderAnswer(ANSWER);
// The box is the anchor around the lib's InlineChip (`InlineAppLinkChip`), routed by the same host anchor.
for (const anchor of screen.getAllByRole('link')) expect(anchor).toHaveClass('no-underline');
});

it('keeps a link the runtime sends to a new tab a plain link, not a box', () => {
renderAnswer(ANSWER.replace(/\]\(\//g, `](${ORIGIN}/`));
expect(screen.getByRole('link', { name: 'Devices → Add Device' })).not.toHaveClass('no-underline');
});

it('opens the same link written absolute in a new tab, even on the page origin', () => {
renderAnswer(ANSWER.replace(/\]\(\//g, `](${ORIGIN}/`));
const anchor = screen.getByRole('link', { name: 'Devices → Add Device' });
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { render, screen } from '@testing-library/react';
import type React from 'react';
import { describe, expect, it } from 'vitest';
import { InlineAppLinkChip } from '../inline-app-link-chip';

function HostAnchor({ href, className, children }: { href: string; className?: string; children?: React.ReactNode }) {
return (
<a href={href} className={className} data-testid="host-anchor">
{children}
</a>
);
}

describe('a link that stays in the app is an inline box', () => {
it('draws the label in the boxed chip, through the host anchor', () => {
render(
<InlineAppLinkChip href="/devices/new" anchor={HostAnchor}>
Devices → Add Device
</InlineAppLinkChip>,
);
const link = screen.getByRole('link', { name: /Devices → Add Device/ });
expect(link).toHaveAttribute('href', '/devices/new');
expect(link).toHaveAttribute('data-testid', 'host-anchor');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import React, { forwardRef, memo, type ReactNode, useEffect, useMemo, useRef } from 'react';
import { createCardMarkerScanner } from '../../chat-protocol/card-marker';
import { useChatRuntime } from '../../contexts/chat-runtime-context';
import Link from '../../embed-shims/next-link';
import { cn } from '../../utils/cn';
import { isToday } from '../../utils/date-utils';
Expand Down Expand Up @@ -30,6 +31,7 @@ import { ContextCompactionDisplay } from './context-compaction-display';
import { BlockCard, type BlockCardProps } from './entity-cards/block-card';
import { ErrorMessageDisplay } from './error-message-display';
import { EscalationOfferMessage } from './escalation-offer-message';
import { InlineAppLinkChip } from './inline-app-link-chip';
import { remarkCardLinks } from './remark-card-links';
import { remarkMentionChips } from './remark-mention-chips';
import { remarkStripCitations } from './remark-strip-citations';
Expand All @@ -41,6 +43,7 @@ import { TicketEventMessage } from './ticket-event-message';
import { ToolExecutionDisplay } from './tool-execution-display';
import type { AskSegment, MessageSegment, MessageContent, ChatMessageEnhancedProps } from './types';
import { CHAT_APPEARANCE } from './types/chat.types';
import { computeIsNewTab } from './utils/nav-anchor-props';

/** Inline `@marker:id` mention token in the message body (sibling of the
* `[card://]` grammar) — used to filter out items rendered inline from the
Expand Down Expand Up @@ -406,6 +409,9 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
const renderingPlanRef = useRef(renderingPlan);
renderingPlanRef.current = renderingPlan;

// The runtime decides whether a link stays in this app (`computeIsNewTab`); null outside a chat runtime, where
// every link stays a plain link.
const chatRuntime = useChatRuntime();
const cardComponentOverrides = useMemo(() => {
if (!hasMarkerSupport && !hasMentionSupport) return undefined;
return {
Expand Down Expand Up @@ -463,6 +469,23 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
// flamingo hero-demo with mock content), fall back to a plain
// `<a href>`. No cross-origin sniffing here — the OSS-lib does
// not own routing decisions; the host does.
// A link that stays in this app is drawn as an inline box, the skin of the host's entity mentions, still
// routed through the host's `NavLinkAnchor`. Whether it stays is the runtime's ONE new-tab rule
// (`computeIsNewTab`, the decision the chat's cards and source chips make): a link it keeps in this window
// is a place in the app; one it sends to a new tab (another site, a hub page from an embedded chat, a
// `mailto:`) stays a plain link.
if (
typeof href === 'string' &&
!href.startsWith('#') &&
chatRuntime &&
!computeIsNewTab(chatRuntime, href, null)
) {
return (
<InlineAppLinkChip href={href} anchor={NavLinkAnchor}>
{children}
</InlineAppLinkChip>
);
}
if (typeof href === 'string' && NavLinkAnchor && !href.startsWith('#')) {
return (
<NavLinkAnchor href={href} className={linkClassName} {...rest}>
Expand All @@ -481,7 +504,7 @@ const ChatMessageEnhanced = forwardRef<HTMLDivElement, ChatMessageEnhancedProps>
// streaming turn (booleans + host-stable fn/component identities, both
// enforced by this file's `memo` comparator). The rendering plan is
// read through a ref above precisely so it does NOT appear here.
}, [hasMarkerSupport, hasMentionSupport, renderMention, NavLinkAnchor]);
}, [hasMarkerSupport, hasMentionSupport, renderMention, NavLinkAnchor, chatRuntime]);

/**
* Body of a markdown-bearing segment (`text` / `guide`).
Expand Down
62 changes: 61 additions & 1 deletion openframe-frontend-core/src/components/chat/embeddable-chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ import { ActionsMenuDropdown, type ActionsMenuItem } from '../ui/actions-menu';
import { Button } from '../ui/button';
import { Drawer, DrawerContent } from '../ui/drawer';
import { HoverDropdown, type HoverDropdownItem } from '../ui/hover-dropdown';
import { TextHold } from '../ui/layout-hold';
import { LoadingItems } from '../ui/loading-scope';
import { CollisionBoundaryContext, PortalContainerContext } from '../ui/portal-container';
import { SKELETON_SURFACE_CLASS } from '../ui/skeleton-surface';
import { SquareAvatar } from '../ui/square-avatar';
import { ChatAppearanceContext } from './chat-appearance-context';
import { ChatArchivePage } from './chat-archive-page';
Expand Down Expand Up @@ -705,6 +707,29 @@ function dispatchSlashCommandAction(
* 2. Ask: small `MessageSquare` icon-button on the right → fires
* `onDiscuss(ref)` to drill into THIS row via `entityIdFilter`.
*/
/** A no-break space: one line of the chip's text, so a bar that holds it is exactly one text line tall. */
const ONE_TEXT_LINE = '\u00a0';

/** How many chips the strip's loading form draws: the count real answers' strips showed (measured). On a phone,
* where a strip holds one chip a row, it draws one. */
const SOURCE_CHIP_SKELETON_COUNT = 2;

/**
* A source chip's loading form, built like the chip (`wrapChip` around `chipBody`): the chip's frame, its icon,
* its title as a bar one text line tall (so the chip is the loaded chip's height), and the Ask slot beside it.
*/
function SourceChipSkeleton({ className }: { className?: string }) {
return (
<span aria-hidden className={cn('pointer-events-none inline-flex shrink-0 items-center', className)}>
<span className={chatChipClass({ tone: 'secondary' })}>
<span className={cn(SKELETON_SURFACE_CLASS, 'inline-block h-3.5 w-3.5 rounded-sm')} />
<span className={cn(SKELETON_SURFACE_CLASS, 'w-28 rounded-sm')}>{ONE_TEXT_LINE}</span>
</span>
<span className={cn(SKELETON_SURFACE_CLASS, '-mr-1 ml-1 inline-block h-5 w-5 rounded-sm')} />
</span>
);
}

function SourceChip({
src,
baseRoute,
Expand Down Expand Up @@ -903,16 +928,37 @@ function SourceChips({
chipBasePlatform,
onClose,
onDiscuss,
loading,
}: {
cited: ChatSource[];
uncited: ChatSource[];
baseRoute: string;
chipBasePlatform?: string;
onClose: () => void;
onDiscuss?: (ref: ChatRef) => void;
/** The answer is still being written: the strip's frame, heading and a row of chips in their loading form, so
* the strip does not appear under the answer when it finishes. */
loading?: boolean;
}) {
const [expanded, setExpanded] = useState(false);

if (loading) {
return (
<div aria-hidden className="mt-2 flex flex-col gap-1.5 border-t border-ods-border pt-2">
<span className="uppercase text-ods-text-muted text-h6">
<TextHold>Sources</TextHold>
</span>
{/* One row at every width: a chip that does not fit is cut, never wrapped (a strip's chips fit one row in
the answers measured, and a wrapped skeleton shrinks when the answer ends). */}
<div className="flex flex-nowrap gap-1.5 overflow-hidden">
{Array.from({ length: SOURCE_CHIP_SKELETON_COUNT }, (_, i) => (
<SourceChipSkeleton key={i} className={i > 0 ? 'max-md:hidden' : undefined} />
))}
</div>
</div>
);
}

if (cited.length === 0) {
const fallback = uncited.slice(0, FALLBACK_TOP_RETRIEVED);
if (fallback.length === 0) return null;
Expand Down Expand Up @@ -2062,7 +2108,21 @@ function EmbeddableChatInner({
// the THREAD, so testing it alone pulls the strips off every earlier
// answer too — a reader scrolled up watches finished citations blink out
// for the duration of an unrelated turn.
if (chatLoading && index === messages.length - 1) return null;
// Its strip is drawn in its loading form meanwhile, so the strip is already there when the answer ends.
if (chatLoading && index === messages.length - 1) {
return (
<div className="pb-2">
<SourceChips
loading
cited={[]}
uncited={[]}
baseRoute={resolvedBaseRoute}
chipBasePlatform={chipBasePlatform}
onClose={handleNavigationClose}
/>
</div>
);
}
const { cited, uncited } = splitCitedSources(message.sources, flattenAssistantContent(message.content));
if (cited.length === 0 && uncited.length === 0) return null;
return (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import type { ChatRef } from '../../chat-ref.types';
import { SourceActionButton } from '../../source-action-button';
import { CHAT_CARD_DISCLOSURES, ChatCardDisclosureButton, useChatCardDisclosure } from '../chat-card-disclosure';

const WATCH_VIDEO_LABEL = CHAT_CARD_DISCLOSURES.VIDEO.label;

const ref = { type: 'webinar', id: 'w1', title: 'A webinar' } as ChatRef;

function Footer({ video, reserve }: { video: ChatRef | null; reserve?: boolean }) {
const { action } = useChatCardDisclosure('VIDEO', video, { reserve });
return <div data-testid="row">{action}</div>;
}

describe('the card footer keeps its actions in place while loading', () => {
it('draws "Watch video" in its loading form: the label held as a skeleton bar, not a reachable button', () => {
render(<ChatCardDisclosureButton kind="VIDEO" loading />);
expect(screen.getByText(WATCH_VIDEO_LABEL)).toHaveAttribute('aria-hidden', 'true');
expect(screen.queryByRole('button')).toBeNull();
});

it('keeps the slot, unseen, for a record of a video type that has no video', () => {
render(<Footer video={null} reserve />);
// The action is laid out (its space is kept) but cannot be reached or read.
expect(screen.getByText(WATCH_VIDEO_LABEL)).toBeTruthy();
expect(screen.queryByRole('button')).toBeNull();
});

it('draws nothing for a type that cannot carry a video', () => {
render(<Footer video={null} />);
expect(screen.getByTestId('row')).toBeEmptyDOMElement();
});

it('draws the live action when the record has a video', () => {
render(<Footer video={ref} reserve />);
expect(screen.getByRole('button', { name: `${WATCH_VIDEO_LABEL}: A webinar` })).toBeTruthy();
});

it('draws Ask in its loading form with the same label width', () => {
render(<SourceActionButton chatRef={ref} onDiscuss={() => undefined} density="card" loading />);
expect(screen.queryByRole('button')).toBeNull();
expect(screen.getByText('Ask')).toHaveAttribute('aria-hidden', 'true');
});
});
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { render, screen } from '@testing-library/react';
import { fireEvent, render, screen } from '@testing-library/react';
import { isValidElement, type ReactElement, type ReactNode } from 'react';
import { afterEach, describe, expect, it } from 'vitest';
import { setEmbedAuthAdapter } from '../../../../utils/embed-authed-fetch';
import { ExternalMediaNotice } from '../../../ui/markdown/external-media-notice';
import type { ChatRef } from '../../chat-ref.types';
import type { BlockCardProps } from '../block-card';
import { ChatVideoEntityCard } from '../chat-video-entity-card';
import { CHAT_CARD_DISCLOSURES, ChatCardDisclosureRow } from '../chat-card-disclosure';

const WATCH_VIDEO_LABEL = CHAT_CARD_DISCLOSURES.VIDEO.label;
const HIDE_VIDEO_LABEL = CHAT_CARD_DISCLOSURES.VIDEO.openLabel;
import { renderChatInlineEntityCard } from '../dispatch';

/** `[card://video:mp4-<base64url(url)>]`: the id the hub mints for an embedded video, and one a reply can mint too. */
Expand Down Expand Up @@ -39,20 +42,47 @@ describe('video marker — a player from outside the app is not drawn', () => {
it('mounts a video from the app itself (the gateway a native shell sanctions)', () => {
setEmbedAuthAdapter({ allowedOrigins: ['https://gateway.example'] });
const block = blockOf(mp4Ref('https://gateway.example/media/v.mp4'));
expect(isValidElement(block) && block.type).toBe(ChatVideoEntityCard);
expect(isValidElement(block) && block.type).toBe(ChatCardDisclosureRow);
});

it('plays Mux and YouTube markers: their ids only ever reach those fixed hosts', () => {
for (const id of ['mux-a1B2c3D4e5F6g7H8i9', 'dQw4w9WgXcQ']) {
const block = blockOf({ type: 'video', id } as ChatRef);
expect(isValidElement(block) && block.type, id).toBe(ChatVideoEntityCard);
expect(isValidElement(block) && block.type, id).toBe(ChatCardDisclosureRow);
}
});

it('does not draw a player for a plain-http mp4 at all', () => {
const card = renderChatInlineEntityCard(mp4Ref('http://attacker.example/v.mp4'));
const { children } = isValidElement(card) ? (card.props as { children?: ReactNode }) : {};
expect(isValidElement(children) && children.type === ChatVideoEntityCard).toBe(false);
expect(isValidElement(children) && children.type === ChatCardDisclosureRow).toBe(false);
expect(isValidElement(children) && children.type === ExternalMediaNotice).toBe(false);
});
});

/**
* The player opens from its card, never on its own: drawn when the answer loads,
* every recording grew the answer by a 16:9 box while it was being read
* (CU-17tkuw61kfy).
*/
describe('video marker — collapsed until the reader opens it', () => {
it('draws one action row and no player, then the player once opened, and closes again', () => {
const block = blockOf({ type: 'video', id: 'mux-a1B2c3D4e5F6g7H8i9', title: 'Onboarding walkthrough' } as ChatRef);
const { container } = render(<>{block}</>);
const open = screen.getByRole('button', { name: `${WATCH_VIDEO_LABEL}: Onboarding walkthrough` });
expect(open.getAttribute('aria-expanded')).toBe('false');
const before = container.innerHTML;

fireEvent.click(open);
const close = screen.getByRole('button', { name: `${HIDE_VIDEO_LABEL}: Onboarding walkthrough` });
expect(close.getAttribute('aria-expanded')).toBe('true');
expect(container.innerHTML).not.toBe(before);

fireEvent.click(close);
expect(screen.getByRole('button', { name: `${WATCH_VIDEO_LABEL}: Onboarding walkthrough` })).toBeTruthy();
// The player stays mounted while the panel closes, so it is not cut mid-animation; it unmounts at the end.
expect(container.innerHTML).not.toBe(before);
fireEvent.transitionEnd(screen.getByTestId('chat-card-disclosure-panel'));
expect(container.innerHTML).toBe(before);
});
});
Loading
Loading