Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { render, screen } from '@testing-library/react';
import type React from 'react';
import { describe, expect, it } from 'vitest';
import { InlineAppLinkChip, isInAppPath } 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 to a screen of the app is an inline box', () => {
it('counts only root-relative paths as screens of the app', () => {
expect(isInAppPath('/devices/new')).toBe(true);
expect(isInAppPath('//evil.example/x')).toBe(false);
expect(isInAppPath('https://openframe.ai/devices')).toBe(false);
expect(isInAppPath('#section')).toBe(false);
expect(isInAppPath(undefined)).toBe(false);
});

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 @@ -30,6 +30,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, isInAppPath } from './inline-app-link-chip';
import { remarkCardLinks } from './remark-card-links';
import { remarkMentionChips } from './remark-mention-chips';
import { remarkStripCitations } from './remark-strip-citations';
Expand Down Expand Up @@ -463,6 +464,15 @@ 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 to a screen of the app (`/devices/new`) is drawn as an inline box, the skin of the host's entity
// mentions, still routed through the host's `NavLinkAnchor` (`inline-app-link-chip.tsx`).
if (typeof href === 'string' && isInAppPath(href)) {
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
return (
<InlineAppLinkChip href={href} anchor={NavLinkAnchor}>
{children}
</InlineAppLinkChip>
);
}
if (typeof href === 'string' && NavLinkAnchor && !href.startsWith('#')) {
return (
<NavLinkAnchor href={href} className={linkClassName} {...rest}>
Expand Down
59 changes: 58 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,26 @@ function dispatchSlashCommandAction(
* 2. Ask: small `MessageSquare` icon-button on the right → fires
* `onDiscuss(ref)` to drill into THIS row via `entityIdFilter`.
*/
/** 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')}>{'\u00a0'}</span>
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
</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 +925,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 +2105,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,43 @@
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 { ChatVideoToggleButton, useChatVideoToggle, WATCH_VIDEO_LABEL } from '../chat-video-toggle';

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

function Footer({ video, reserve }: { video: ChatRef | null; reserve?: boolean }) {
const { action } = useChatVideoToggle(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(<ChatVideoToggleButton 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,11 @@
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 { ChatCollapsibleVideo, HIDE_VIDEO_LABEL, WATCH_VIDEO_LABEL } from '../chat-video-toggle';
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 +39,44 @@ 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(ChatCollapsibleVideo);
});

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(ChatCollapsibleVideo);
}
});

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 === ChatCollapsibleVideo).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();
expect(container.innerHTML).toBe(before);
});
});
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
'use client';

/**
* A chat video opens from its card, never on its own.
*
* The player used to be drawn the moment its card resolved: a 16:9 box (plus
* its tab row) appeared under a card whose skeleton was one row tall, and an
* answer with three recordings grew by three players while it was being read
* (CU-17tkuw61kfy). Now the card shows a "Watch video" action in the row it
* already draws, so the answer keeps its height when it loads, and the player
* opens below the card only when the reader asks for it. A height change the
* reader asked for is not a layout shift.
*
* Two shapes, one state:
* - `useChatVideoToggle` for a card with a footer row (the action goes in the
* row, the player below the card);
* - `ChatCollapsibleVideo` for a video with no card of its own (a
* `[card://video:<id>]` marker): the same action on a row of its own.
*
* The action's space never changes. A card type whose records can carry a video
* (`video` on its registry entry) draws the action in its skeleton
* (`ChatVideoToggleButton loading`), and a record of that type with no video
* keeps the slot, unseen (`useChatVideoToggle(null, { reserve: true })`), so the
* row is the same height loading, loaded with a video and loaded without one.
*/

import type React from 'react';
import { type ReactNode, useState } from 'react';
import { PlayIcon } from '../../icons-v2-generated/media-playback/play-icon';
import { Button } from '../../ui/button';
import type { ChatRef } from '../chat-ref.types';
import { CARD_FOOTER_ACTION_CLASS, FooterActionSkeleton } from '../source-action-button';
import { ChatVideoEntityCard } from './chat-video-entity-card';

export const WATCH_VIDEO_LABEL = 'Watch video';
export const HIDE_VIDEO_LABEL = 'Hide video';

export function ChatVideoToggleButton({
open = false,
onToggle,
title,
loading,
}: {
open?: boolean;
onToggle?: () => void;
title?: string;
/** The action's loading form, drawn in the skeleton of a card that can carry a video. */
loading?: boolean;
}): React.ReactElement {
if (loading) return <FooterActionSkeleton label={WATCH_VIDEO_LABEL} className={CARD_FOOTER_ACTION_CLASS} />;
const label = open ? HIDE_VIDEO_LABEL : WATCH_VIDEO_LABEL;
return (
<Button
variant="transparent"
size="small"
leftIcon={<PlayIcon className="!h-3 !w-3" />}
onClick={(e: React.MouseEvent) => {
// The card around it is a link: the action must not follow it.
e.preventDefault();
e.stopPropagation();
onToggle?.();
}}
aria-expanded={open}
aria-label={title ? `${label}: ${title}` : label}
className={CARD_FOOTER_ACTION_CLASS}
>
{label}
</Button>
);
}

/**
* The action for a card's footer row, and the player to draw below the card (null while closed). With no video,
* `reserve` keeps the action's slot, unseen and unreachable, for a card type whose records can carry one.
*/
export function useChatVideoToggle(
video: ChatRef | null,
{ reserve = false }: { reserve?: boolean } = {},
): { action: ReactNode; player: ReactNode } {
const [open, setOpen] = useState(false);
if (!video) {
return {
action: reserve ? (
<span aria-hidden inert className="invisible">
<ChatVideoToggleButton />
</span>
) : null,
player: null,
};
}
return {
action: <ChatVideoToggleButton open={open} onToggle={() => setOpen(o => !o)} title={video.title} />,
player: open ? <ChatVideoEntityCard chatRef={video} /> : null,
};
}

/** A video with no card of its own: the action on its own row, the player below it once opened. */
export function ChatCollapsibleVideo({ chatRef }: { chatRef: ChatRef }): React.ReactElement {
const { action, player } = useChatVideoToggle(chatRef);
return (
<div className="grid min-w-0 grid-cols-1 gap-3">
<div className="flex items-center gap-2 pl-0.5">
{action}
<span className="min-w-0 truncate text-ods-text-secondary text-h6">{chatRef.title}</span>
</div>
{player}
</div>
);
}
Loading
Loading