The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Render property listings as browsable transcript cards
Brooklyn Nicholson9b16719e178b
diff --git a/apps/desktop/src/components/assistant-ui/embeds/listing-embed.tsx b/apps/desktop/src/components/assistant-ui/embeds/listing-embed.tsxnew file mode 100644index 00000000000..1b77eaaaf3d--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/embeds/listing-embed.tsx@@ -0,0 +1,260 @@+'use client'++import { useEffect, useState } from 'react'++import { WIDGET_SHELL_CLASS } from '@/components/chat/widget-shell'+import { ImageLightbox } from '@/components/chat/zoomable-image'+import { Codicon } from '@/components/ui/codicon'+import { useImageDownload } from '@/hooks/use-image-download'+import { useI18n } from '@/i18n'+import { ExternalLink } from '@/lib/external-link'+import { type Listing, parseListings, specLine } from '@/lib/listing-embed'+import { cn } from '@/lib/utils'++import type { RichFenceProps } from './types'++/** The conversation's own type scale, so a card reads at the prose's size. */+const TEXT_CLASS = 'text-[length:var(--conversation-text-font-size)]'+const META_CLASS = 'text-[length:var(--conversation-tool-font-size)]'++/**+ * ```listing — a property listing as a native transcript card.+ *+ * The portals can't be framed (no oEmbed, deprecated APIs, X-Frame-Options),+ * so the agent authors the card from what it already gathered and this+ * renderer makes it browsable.+ *+ * It sits on the same shell as every other inline widget+ * (`WIDGET_SHELL_CLASS`: one radius above the composer, mode-derived fill, no+ * border) and uses the conversation's own type scale, so a listing reads as+ * app surface rather than a pasted webpage.+ *+ * Facts ride a quiet meta line; catches get ONE muted line, not a wall of+ * amber badges — a card that shouts every caveat has no hierarchy left for+ * the one that matters.+ */+export default function ListingEmbed({ code, streaming }: RichFenceProps) {+ // Mid-stream the JSON is a prefix and JSON.parse fails, which would flash+ // the raw fence; hold the fallback until the turn settles.+ const listings = streaming ? [] : parseListings(code)++ if (listings.length === 0) {+ // Nothing valid parsed: the boundary's fallback (the plain code block) is+ // the honest render. Throwing lets RichBoundary do it.+ throw new Error('listing: no renderable listings')+ }++ return (+ // Outer breathing room only: `my-*` stands the SET off the prose around+ // it, while `gap-2` owns the space between stacked cards — so two+ // listings stay tight to each other but neither butts into a message.+ // The transcript's own paragraph rhythm, so a card is spaced like any+ // other block; the prose container's first/last-child rules collapse it+ // at a message's edges.+ <span className="my-(--paragraph-gap) flex w-full max-w-128 flex-col gap-2" data-slot="aui_listing-set">+ {listings.map(listing => (+ <ListingCard key={listing.id} listing={listing} />+ ))}+ </span>+ )+}++function ListingCard({ listing }: { listing: Listing }) {+ const specs = specLine(listing)+ // Facts are supporting detail, not headline — one dot-joined meta line+ // beside the specs reads as one thought instead of a badge grid.+ const meta = [specs, ...listing.facts].filter(Boolean).join(' · ')++ return (+ // The shell's fill and radius, but NOT its uniform padding: the photos+ // bleed to the card's rounded edge (clipped by `overflow-hidden`) the way+ // every portal card is built, and only the text carries the shell's inset.+ //+ // `not-prose` is load-bearing. The transcript ancestor is `.aui-md.prose`,+ // and the Typography plugin's `:where(img)` rule adds `2em` of margin to+ // every image inside it — a band of dead card fill above the hero. That+ // selector outranks a `my-0` utility, so the fix is the plugin's own+ // opt-out, which excludes this whole subtree.+ <span className={cn(WIDGET_SHELL_CLASS, 'not-prose block overflow-hidden p-0')} data-slot="aui_listing-card">+ {listing.images.length > 0 && <ListingGallery address={listing.address} images={listing.images} />}++ <span className="block px-3.5 py-3">+ <span className="flex flex-wrap items-baseline justify-between gap-x-3">+ <span className={cn(TEXT_CLASS, 'font-medium text-foreground')}>{listing.address}</span>+ {listing.price && (+ <span className={cn(TEXT_CLASS, 'font-medium tabular-nums text-foreground')}>{listing.price}</span>+ )}+ </span>++ {meta && <span className={cn(META_CLASS, 'mt-0.5 block tabular-nums text-muted-foreground')}>{meta}</span>}++ {listing.note && (+ <span className={cn(TEXT_CLASS, 'mt-1.5 block leading-relaxed text-foreground/80')}>{listing.note}</span>+ )}++ {listing.catches.length > 0 && (+ <span className={cn(META_CLASS, 'mt-2 flex gap-1.5 text-muted-foreground')}>+ <Codicon className="mt-px shrink-0 text-amber-500" name="warning" size="0.75rem" />+ <span className="min-w-0">{listing.catches.join(' · ')}</span>+ </span>+ )}++ {listing.links.length > 0 && (+ <span className={cn(META_CLASS, 'mt-2 flex flex-wrap gap-x-3 gap-y-1')}>+ {listing.links.map(link => (+ <ExternalLink href={link.url} key={link.url}>+ {link.label}+ </ExternalLink>+ ))}+ </span>+ )}+ </span>+ </span>+ )+}++/**+ * The browse surface: a photo MOSAIC, the way the portals themselves show a+ * property — one hero carrying the house plus supporting frames, all visible+ * at once. A single paged hero made you click to learn anything; a grid lets+ * you take in the place in one look and dive only where you want.+ *+ * The tiling adapts to how many photos exist rather than forcing every+ * listing into one shape:+ * 1 photo → a lone 4:3 hero+ * 2 photos → a 3:2 pair, side by side+ * 3+ → hero on the left (2 cols × 2 rows) + two stacked frames right+ *+ * Overflow past the visible tiles folds into a `+N` on the last frame, so the+ * gallery's depth is legible without paying rows for it. Clicking any frame+ * opens the shared lightbox at that photo; ← / → page the whole set there,+ * which is where a big image belongs anyway.+ */+function ListingGallery({ address, images }: { address: string; images: string[] }) {+ const { t } = useI18n()+ const [broken, setBroken] = useState<string[]>([])+ const [openAt, setOpenAt] = useState<number | null>(null)++ // Portal CDNs expire URLs; a dead photo drops out of the mosaic rather than+ // leaving a broken frame in the grid.+ const live = images.filter(src => !broken.includes(src))+ const position = openAt === null ? 0 : Math.min(openAt, live.length - 1)+ const { download, saving } = useImageDownload(live[position])++ // Page the set inside the lightbox — a full-size photo is the right place+ // to go through 40 frames, and the arrow keys are what hands reach for.+ useEffect(() => {+ if (openAt === null || live.length < 2) {+ return+ }++ const onKey = (event: KeyboardEvent) => {+ const delta = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0++ if (delta !== 0) {+ event.preventDefault()+ setOpenAt(prev => ((prev ?? 0) + delta + live.length) % live.length)+ }+ }++ window.addEventListener('keydown', onKey)++ return () => window.removeEventListener('keydown', onKey)+ }, [live.length, openAt])++ if (live.length === 0) {+ return null+ }++ // Tiles the layout shows; anything beyond folds into the `+N` badge.+ const mosaic = live.length >= 3+ const visible = live.slice(0, mosaic ? 3 : live.length)++ return (+ <>+ <span+ className={cn(+ // No radius of its own: the photos bleed to the card's edge and the+ // card's `overflow-hidden` clips the top corners for them.+ 'grid w-full gap-1',+ live.length === 1 && 'aspect-[4/3]',+ live.length === 2 && 'aspect-[3/2] grid-cols-2',+ mosaic && 'aspect-[3/2] grid-cols-3 grid-rows-2'+ )}+ data-slot="aui_listing-gallery"+ >+ {visible.map((src, tile) => (+ <GalleryTile+ address={address}+ // The hero earns its scale only in the 3+ mosaic; with one or two+ // photos every frame is equal.+ className={cn(mosaic && tile === 0 && 'col-span-2 row-span-2')}+ key={src}+ more={tile === visible.length - 1 ? live.length - visible.length : 0}+ onError={() => setBroken(prev => (prev.includes(src) ? prev : [...prev, src]))}+ onOpen={() => setOpenAt(tile)}+ src={src}+ title={t.desktop.openImage}+ />+ ))}+ </span>++ <ImageLightbox+ alt={address}+ copy={t.desktop}+ onClick={download}+ onOpenChange={open => setOpenAt(open ? position : null)}+ open={openAt !== null}+ saving={saving}+ src={live[position]}+ />+ </>+ )+}++function GalleryTile({+ address,+ className,+ more,+ onError,+ onOpen,+ src,+ title+}: {+ address: string+ className?: string+ /** Photos past the visible tiles; rendered as `+N` over this frame. */+ more: number+ onError: () => void+ onOpen: () => void+ src: string+ title: string+}) {+ return (+ <button+ className={cn('relative block size-full cursor-zoom-in overflow-hidden bg-muted/55', className)}+ onClick={onOpen}+ title={title}+ type="button"+ >+ <img+ alt={address}+ className="size-full object-cover transition-opacity hover:opacity-90"+ loading="lazy"+ onError={onError}+ referrerPolicy="no-referrer"+ src={src}+ />+ {more > 0 && (+ <span+ className={cn(+ TEXT_CLASS,+ 'absolute inset-0 grid place-items-center bg-background/55 font-medium tabular-nums text-foreground backdrop-blur-[2px]'+ )}+ >+ +{more}+ </span>+ )}+ </button>+ )+}diff --git a/apps/desktop/src/components/assistant-ui/embeds/registry.tsx b/apps/desktop/src/components/assistant-ui/embeds/registry.tsxindex 2dc7429d923..ed6d861936f 100644--- a/apps/desktop/src/components/assistant-ui/embeds/registry.tsx+++ b/apps/desktop/src/components/assistant-ui/embeds/registry.tsx@@ -9,6 +9,7 @@ import type { RichFenceProps } from './types'// renderer is its own split chunk (mermaid pulls in the mermaid lib, svg pulls// in DOMPurify), loaded only when a block of that language actually appears.const LAZY_FENCE: Record<string, LazyExoticComponent<ComponentType<RichFenceProps>>> = {+ listing: lazy(() => import('./listing-embed')),mermaid: lazy(() => import('./mermaid-embed')),svg: lazy(() => import('./svg-embed'))}diff --git a/apps/desktop/src/lib/listing-embed.test.ts b/apps/desktop/src/lib/listing-embed.test.tsnew file mode 100644index 00000000000..3b1a8de2fcb--- /dev/null+++ b/apps/desktop/src/lib/listing-embed.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest'++import { hostLabel, parseListings, specLine } from './listing-embed'++// Shaped like what the agent actually emits after a portal sweep.+const REAL = JSON.stringify({+ listings: [+ {+ address: '51 Via Los Altos, Tiburon, CA 94920',+ baths: '3.5',+ beds: 3,+ catches: ['No pets', 'Fireplace decorative only'],+ facts: ['0.65 acre', 'Panoramic bay views', '12-mo lease'],+ images: ['https://images.homes.com/a.jpg', 'https://images.homes.com/b.jpg'],+ links: [+ { label: 'homes.com', url: 'https://www.homes.com/property/51-via-los-altos/' },+ { url: 'https://www.redfin.com/CA/Tiburon/51-Via-Los-Altos-94920/home/1244581' }+ ],+ note: 'Bay plus Belvedere Island plus Richmond Bridge.',+ price: '$12,500/mo',+ size: '4,290 sqft'+ }+ ]+})++describe('parseListings', () => {+ it('normalizes a real sweep payload', () => {+ const [listing] = parseListings(REAL)++ expect(listing.address).toBe('51 Via Los Altos, Tiburon, CA 94920')+ expect(listing.beds).toBe(3)+ // String decimals survive: half-baths are real.+ expect(listing.baths).toBe(3.5)+ expect(listing.images).toHaveLength(2)+ expect(listing.facts).toHaveLength(3)+ expect(listing.catches).toHaveLength(2)+ // A bare URL gets the portal host as its label.+ expect(listing.links[1].label).toBe('redfin.com')+ })++ it('accepts a lone object and a bare array', () => {+ expect(parseListings('{"address":"1 Main St"}')).toHaveLength(1)+ expect(parseListings('[{"address":"1 Main St"},{"address":"2 Main St"}]')).toHaveLength(2)+ })++ it('drops entries with no address — a card needs an identity', () => {+ expect(parseListings('[{"price":"$1"},{"address":"1 Main St"}]')).toHaveLength(1)+ })++ it('returns nothing for non-JSON so the plain code block wins', () => {+ expect(parseListings('not json at all')).toEqual([])+ expect(parseListings('{"address":"x"')).toEqual([])+ })++ it('refuses non-http URLs in images and links', () => {+ const [listing] = parseListings(+ JSON.stringify({+ address: 'x',+ images: ['javascript:alert(1)', 'https://ok.example/a.jpg'],+ links: ['data:text/html,hi', 'https://ok.example/listing']+ })+ )++ expect(listing.images).toEqual(['https://ok.example/a.jpg'])+ expect(listing.links.map(link => link.url)).toEqual(['https://ok.example/listing'])+ })++ it('dedupes repeated images and links', () => {+ const [listing] = parseListings(+ JSON.stringify({+ address: 'x',+ images: ['https://a.example/1.jpg', 'https://a.example/1.jpg'],+ links: ['https://a.example/l', 'https://a.example/l']+ })+ )++ expect(listing.images).toHaveLength(1)+ expect(listing.links).toHaveLength(1)+ })++ it('caps a pathological payload', () => {+ const images = Array.from({ length: 500 }, (_, i) => `https://a.example/${i}.jpg`)+ const [listing] = parseListings(JSON.stringify({ address: 'x', images }))++ expect(listing.images.length).toBeLessThanOrEqual(40)+ })++ it('rejects absurd bed counts but keeps the listing', () => {+ const [listing] = parseListings('{"address":"x","beds":9999,"baths":-2}')++ expect(listing.beds).toBeUndefined()+ expect(listing.baths).toBeUndefined()+ expect(listing.address).toBe('x')+ })++ it('takes a single string where a list was expected', () => {+ const [listing] = parseListings('{"address":"x","facts":"private dock"}')++ expect(listing.facts).toEqual(['private dock'])+ })+})++describe('specLine', () => {+ it('joins only the specs that exist', () => {+ const [full] = parseListings('{"address":"x","beds":3,"baths":2,"size":"2,136 sqft"}')+ const [sparse] = parseListings('{"address":"x","beds":3}')++ expect(specLine(full)).toBe('3 bd · 2 ba · 2,136 sqft')+ expect(specLine(sparse)).toBe('3 bd')+ })+})++describe('hostLabel', () => {+ it('strips www so the host reads as the portal name', () => {+ expect(hostLabel('https://www.homes.com/property/x')).toBe('homes.com')+ expect(hostLabel('https://www.har.com/homedetail/y')).toBe('har.com')+ })+})diff --git a/apps/desktop/src/lib/listing-embed.ts b/apps/desktop/src/lib/listing-embed.tsnew file mode 100644index 00000000000..d543f95d4df--- /dev/null+++ b/apps/desktop/src/lib/listing-embed.ts@@ -0,0 +1,257 @@+/**+ * LISTING EMBEDS — property/rental listings as native transcript cards.+ *+ * The rental portals (Zillow, Redfin, Compass, HAR, homes.com) publish no+ * embeddable surface: the public APIs are deprecated or broker-gated, there is+ * no oEmbed endpoint, and every listing page ships `X-Frame-Options`. So a URL+ * cannot be framed and there is nothing to steal at the transport layer.+ *+ * What IS available is the data the agent already gathered to answer the+ * question, plus the portals' own image CDNs (which serve hotlinked `<img>`+ * fine). So the embed is authored, not fetched: the agent emits a ```listing+ * fence holding normalized JSON and it renders as a browsable card — gallery,+ * facts, and the catches that decide a tour.+ *+ * This module is the pure half: parse + validate + normalize. It runs during+ * render, so it stays synchronous and dependency-free, and it treats every+ * field as untrusted model output — bad input degrades to a plain code block+ * rather than a broken card.+ */++/** Cap the gallery so a pathological payload can't mount 400 `<img>` tags. */+const MAX_IMAGES = 40+/** Cap list-shaped fields (facts, catches) for the same reason. */+const MAX_LIST_ITEMS = 12+/** Cap a whole fence — several listings, not a database dump. */+const MAX_LISTINGS = 24+/** Longest single string we'll render; addresses and notes, not essays. */+const MAX_TEXT = 400++export interface ListingLink {+ label: string+ url: string+}++export interface Listing {+ /** Street address / headline. The card's primary identity. */+ address: string+ /** Formatted as given ("$12,500/mo") — the agent knows the market's units. */+ price?: string+ beds?: number+ baths?: number+ /** Interior size, already formatted ("2,136 sqft"). */+ size?: string+ /** Why this one is worth the tour — the agent's own pitch. */+ note?: string+ /** Short amenity/spec chips ("private dock", "12-mo lease"). */+ facts: string[]+ /** Risks worth verifying before touring — the honest half of the card. */+ catches: string[]+ /** Gallery image URLs (https only). */+ images: string[]+ /** Canonical detail-page links; multiple portals mirror one property. */+ links: ListingLink[]+ /** Stable key for React lists. */+ id: string+}++function text(value: unknown): string | undefined {+ if (typeof value !== 'string') {+ return undefined+ }++ const trimmed = value.trim().slice(0, MAX_TEXT)++ return trimmed || undefined+}++/** Beds/baths accept `3` and `"3.5"` — models emit both. Rejects absurd counts. */+function count(value: unknown): number | undefined {+ const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Number(value.trim()) : NaN++ if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 99) {+ return undefined+ }++ // One decimal place: half-baths are real, quarter-baths are not.+ return Math.round(parsed * 10) / 10+}++/** Only absolute http(s) — a card must never smuggle `javascript:` into an href. */+function webUrl(value: unknown): string | undefined {+ const raw = text(value)++ if (!raw) {+ return undefined+ }++ try {+ const url = new URL(raw)++ return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : undefined+ } catch {+ return undefined+ }+}++function stringList(value: unknown, limit = MAX_LIST_ITEMS): string[] {+ if (!Array.isArray(value)) {+ // A single string is a one-item list — models drop the array constantly.+ const single = text(value)++ return single ? [single] : []+ }++ const items: string[] = []++ for (const entry of value) {+ const item = text(entry)++ if (item) {+ items.push(item)+ }++ if (items.length >= limit) {+ break+ }+ }++ return items+}++function urlList(value: unknown, limit = MAX_IMAGES): string[] {+ const urls: string[] = []++ for (const entry of Array.isArray(value) ? value : [value]) {+ const url = webUrl(entry)++ if (url && !urls.includes(url)) {+ urls.push(url)+ }++ if (urls.length >= limit) {+ break+ }+ }++ return urls+}++/** Links accept `["https://…"]` and `[{label, url}]`; the host is a fine+ * default label when the model didn't name the portal. */+function linkList(value: unknown): ListingLink[] {+ const links: ListingLink[] = []++ for (const entry of Array.isArray(value) ? value : [value]) {+ const url = webUrl(typeof entry === 'object' && entry !== null ? (entry as { url?: unknown }).url : entry)++ if (!url || links.some(existing => existing.url === url)) {+ continue+ }++ const label =+ (typeof entry === 'object' && entry !== null+ ? text((entry as { label?: unknown }).label)+ : undefined) ?? hostLabel(url)++ links.push({ label, url })++ if (links.length >= MAX_LIST_ITEMS) {+ break+ }+ }++ return links+}++/** `www.homes.com` → `homes.com`. Bare host reads as the portal's name. */+export function hostLabel(url: string): string {+ try {+ return new URL(url).hostname.replace(/^www\./i, '')+ } catch {+ return 'Listing'+ }+}++function normalizeListing(raw: unknown, index: number): Listing | null {+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {+ return null+ }++ const source = raw as Record<string, unknown>+ // `title` is the common synonym when the property isn't street-addressed.+ const address = text(source.address) ?? text(source.title)++ // A card with no identity is not a card. Everything else is optional, so a+ // sparse listing still renders (and shows what it does have).+ if (!address) {+ return null+ }++ return {+ address,+ baths: count(source.baths),+ beds: count(source.beds),+ catches: stringList(source.catches),+ facts: stringList(source.facts),+ id: text(source.id) ?? `${address}:${index}`,+ images: urlList(source.images ?? source.image),+ links: linkList(source.links ?? source.url),+ note: text(source.note) ?? text(source.why),+ price: text(source.price),+ size: text(source.size) ?? text(source.sqft)+ }+}++/**+ * Parse a ```listing fence. Accepts a single object, a bare array, or+ * `{ listings: [...] }` — all three shapes show up in practice. Returns an+ * empty array on anything unparseable so the caller can fall back to the+ * plain code block.+ */+export function parseListings(code: string): Listing[] {+ let data: unknown++ try {+ data = JSON.parse(code)+ } catch {+ return []+ }++ const entries = Array.isArray(data)+ ? data+ : typeof data === 'object' && data !== null && Array.isArray((data as { listings?: unknown }).listings)+ ? ((data as { listings: unknown[] }).listings)+ : [data]++ const listings: Listing[] = []++ for (const [index, entry] of entries.slice(0, MAX_LISTINGS).entries()) {+ const listing = normalizeListing(entry, index)++ if (listing) {+ listings.push(listing)+ }+ }++ return listings+}++/** The metadata line under the address: "3 bd · 2.5 ba · 2,136 sqft". */+export function specLine(listing: Listing): string {+ const parts: string[] = []++ if (listing.beds !== undefined) {+ parts.push(`${listing.beds} bd`)+ }++ if (listing.baths !== undefined) {+ parts.push(`${listing.baths} ba`)+ }++ if (listing.size) {+ parts.push(listing.size)+ }++ return parts.join(' · ')+}