Skip to content
Merged
24 changes: 24 additions & 0 deletions openframe-frontend-core/src/chat-protocol/app-screen-link.ts
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* The link an answer makes to a screen of the app the chat runs in: a markdown link whose TITLE says so,
* `[Devices → Add Device](/devices/new "app-screen")`. One definition for both sides of the seam: the hub tells the
* model to write exactly this (`appScreenLinkMarkdown` in its instruction), and the chat draws exactly this as an
* inline box (`isAppScreenLink`). Nothing is inferred from the path: a link without the title is a plain link.
*
* A title, not a new URL scheme, so an answer read by a chat that predates this still shows a working link.
*/

/** The markdown link title that marks a link to a screen of the app. */
export const APP_SCREEN_LINK_TITLE = 'app-screen';

/** The markdown for a link to a screen of the app: the label as the reader sees the screen, the screen's path. */
export function appScreenLinkMarkdown(label: string, path: string): string {
return `[${label}](${path} "${APP_SCREEN_LINK_TITLE}")`;
}

/**
* True for a link the answer marked as a screen of the app. The path must also be a path of this app (root-relative,
* never `//host`): the title states the intent, the path is still checked before the app routes to it.
*/
export function isAppScreenLink(href: string | undefined, title: string | undefined): boolean {
return title === APP_SCREEN_LINK_TITLE && typeof href === 'string' && href.startsWith('/') && !href.startsWith('//');
}
3 changes: 3 additions & 0 deletions openframe-frontend-core/src/chat-protocol/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,7 @@ export { isRecord, unwrapEnvelope } from './wire-narrow';
// The `[card://<type>:<id>]` grammar — the renderer's and the server's one
// definition, so a reference the hub emits is one the client expands.
export * from './card-marker';
// The link an answer makes to a screen of the app (`[label](/path "app-screen")`): what the hub tells the model to
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
// write and what the chat draws as an inline box.
export * from './app-screen-link';
export { escapeThinkingTags } from './leading-frames';
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { render, screen } from '@testing-library/react';
import type React from 'react';
import { describe, expect, it } from 'vitest';
import { appScreenLinkMarkdown, isAppScreenLink } from '../../../chat-protocol/app-screen-link';
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 to a screen of the app is an inline box', () => {
it('counts only links the answer marked as a screen of the app, never a guess from the path', () => {
expect(isAppScreenLink('/devices/new', 'app-screen')).toBe(true);
expect(isAppScreenLink('/devices/new', undefined)).toBe(false);
expect(isAppScreenLink('/devices/new', 'Devices')).toBe(false);
expect(isAppScreenLink('//evil.example/x', 'app-screen')).toBe(false);
expect(isAppScreenLink('https://openframe.ai/devices', 'app-screen')).toBe(false);
expect(isAppScreenLink(undefined, 'app-screen')).toBe(false);
});

it('writes the marked link the hub tells the model to write', () => {
expect(appScreenLinkMarkdown('Devices → Add Device', '/devices/new')).toBe(
'[Devices → Add Device](/devices/new "app-screen")',
);
});

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
@@ -1,6 +1,7 @@
'use client';

import React, { forwardRef, memo, type ReactNode, useEffect, useMemo, useRef } from 'react';
import { isAppScreenLink } from '../../chat-protocol/app-screen-link';
import { createCardMarkerScanner } from '../../chat-protocol/card-marker';
import Link from '../../embed-shims/next-link';
import { cn } from '../../utils/cn';
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 Down Expand Up @@ -463,6 +465,16 @@ 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 the answer MARKED as a screen of the app (`[label](/path "app-screen")`, `isAppScreenLink`) is
// drawn as an inline box, the skin of the host's entity mentions, still routed through the host's
// `NavLinkAnchor`. Nothing is inferred from the path: an unmarked link stays a plain link.
if (typeof href === 'string' && isAppScreenLink(href, rest.title)) {
return (
<InlineAppLinkChip href={href} anchor={NavLinkAnchor}>
{children}
</InlineAppLinkChip>
);
}
if (typeof href === 'string' && NavLinkAnchor && !href.startsWith('#')) {
return (
<NavLinkAnchor href={href} className={linkClassName} {...rest}>
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 variant="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