Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
perf(web): prioritize landing workspace startup and load Home on demand (#1042)
Gustavo Ye6aa5c1896950
diff --git a/DESIGN.md b/DESIGN.mdindex 78b71046f..24e86d15a 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -268,7 +268,7 @@ Words are part of the interface. They should sound like the brand: **warm, sharp## Interactive landing workspace- Keep the interactive second screen separate from the existing product story. Use native community views with local data; preview navigation and actions must not mutate a real account.-- Reserve the workspace frame before loading. Mount its isolated document immediately after the homepage load event; show a responsive workspace skeleton until that document reports readiness. Readiness must not depend on animation callbacks in the hidden iframe.+- Reserve the workspace frame before loading. Mount its isolated document immediately after the hero mounts, its paper font/canvas settles, and its own images settle, without waiting for the full homepage load event; show a responsive workspace skeleton until that document reports readiness. Readiness must not depend on animation callbacks in the hidden iframe.- Compact preview typography must preserve fixed-pixel rail, avatar, and Inbox geometry. Grouped messages and reply previews align with the first message's avatar column.- Mobile landing bot profiles retain the Bot log companion but hide its footer row to give the notebook body more space. Desktop retains the full notebook.- Bot logs use local fixed Thoughts and Marks. Preview Thoughts are static. Scroll-to-tail affects only the notebook scroller, never the surrounding landing page.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dd4b7e78f..c8b97833e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -511,6 +511,9 @@ importers:remark-gfm:specifier: ^4.0.1version: 4.0.1+ remark-math:+ specifier: 6.0.0+ version: 6.0.0remark-parse:specifier: ^11.0.0version: 11.0.0diff --git a/src/web/package.json b/src/web/package.jsonindex 7c342c86a..f7ffe69d1 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -123,6 +123,7 @@"rehype-slug": "^6.0.0","remark-breaks": "^4.0.0","remark-gfm": "^4.0.1",+ "remark-math": "6.0.0","remark-parse": "^11.0.0","resend": "6.33.0","shadcn": "^4.21.5",diff --git a/src/web/src/components/community/messages/emoji-picker-interactive.tsx b/src/web/src/components/community/messages/emoji-picker-interactive.tsxnew file mode 100644index 000000000..8ac8e1601--- /dev/null+++ b/src/web/src/components/community/messages/emoji-picker-interactive.tsx@@ -0,0 +1,22 @@+"use client"++import { useTheme } from "next-themes"+import EmojiMartPicker from "@emoji-mart/react"+import emojiMartData from "@emoji-mart/data"++// emoji-mart picker β themed to match light/dark. Uses the native set so it+// renders system emoji without fetching an external SVG sprite (the twitter/twemoji+// set shows "#" placeholders when the CDN sprite can't load).+export default function EmojiPicker({ onPick }: { onPick: (emoji: string) => void }) {+ const { resolvedTheme } = useTheme()+ return (+ <EmojiMartPicker+ data={emojiMartData}+ theme={resolvedTheme === "dark" ? "dark" : "light"}+ set="native"+ previewPosition="none"+ skinTonePosition="none"+ onEmojiSelect={(e: { native: string }) => onPick(e.native)}+ />+ )+}diff --git a/src/web/src/components/community/messages/emoji-picker.dom.test.tsx b/src/web/src/components/community/messages/emoji-picker.dom.test.tsxnew file mode 100644index 000000000..368bb9239--- /dev/null+++ b/src/web/src/components/community/messages/emoji-picker.dom.test.tsx@@ -0,0 +1,45 @@+import { act, render, screen, waitFor } from "@/test/react-dom-harness"+import { describe, expect, it, vi } from "vitest"+import { EmojiPickerPopover } from "./emoji-picker"+import { CommunityPreviewNavigation } from "../shell/community-preview-navigation"++const mocks = vi.hoisted(() => ({ picker: vi.fn(), loadData: vi.fn() }))+vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }))+vi.mock("@emoji-mart/react", () => ({ default: (props: { onEmojiSelect: (value: { native: string }) => void }) => {+ mocks.picker(props)+ return <button onClick={() => props.onEmojiSelect({ native: "π" })}>Choose emoji</button>+} }))+vi.mock("@emoji-mart/data", () => {+ mocks.loadData()+ return { default: { emojis: { tada: { skins: [{ native: "π" }] } } } }+})++describe("demo emoji affordance", () => {+ it("retains the original trigger without mounting a picker in preview", () => {+ const pick = vi.fn()+ render(<CommunityPreviewNavigation value={true}><EmojiPickerPopover onPick={pick}><button className="hover:bg-accent">Emoji preview</button></EmojiPickerPopover></CommunityPreviewNavigation>)+ const trigger = screen.getByRole("button", { name: "Emoji preview" })+ expect(trigger).toHaveClass("hover:bg-accent")+ act(() => trigger.click())+ expect(trigger).not.toHaveAttribute("aria-expanded")+ expect(pick).not.toHaveBeenCalled()+ })+})++describe("native emoji picker", () => {+ it("keeps full native data, theme and selection behavior", async () => {+ const pick = vi.fn()+ const open = vi.fn()+ render(<EmojiPickerPopover onPick={pick} onOpenChange={open}><button>Emoji</button></EmojiPickerPopover>)+ expect(screen.getByRole("button", { name: "Emoji" })).toBeVisible()+ act(() => screen.getByRole("button", { name: "Emoji" }).click())+ expect(open).toHaveBeenLastCalledWith(true)+ await waitFor(() => expect(screen.getByRole("button", { name: "Choose emoji" })).toBeVisible())+ const props = mocks.picker.mock.lastCall![0]+ expect(props).toMatchObject({ theme: "dark", set: "native", previewPosition: "none", skinTonePosition: "none" })+ expect(props.data).toEqual({ emojis: { tada: { skins: [{ native: "π" }] } } })+ act(() => screen.getByRole("button", { name: "Choose emoji" }).click())+ expect(pick).toHaveBeenCalledWith("π")+ expect(open).toHaveBeenLastCalledWith(false)+ })+})diff --git a/src/web/src/components/community/messages/emoji-picker.tsx b/src/web/src/components/community/messages/emoji-picker.tsxindex 02fb92771..119d7ecc5 100644--- a/src/web/src/components/community/messages/emoji-picker.tsx+++ b/src/web/src/components/community/messages/emoji-picker.tsx@@ -1,47 +1,30 @@"use client"-import { useAtom, useCreateAtom } from "@tanstack/react-store";--import type React from "react"-import { useTheme } from "next-themes"-import EmojiMartPicker from "@emoji-mart/react"-import emojiMartData from "@emoji-mart/data"+import { lazy, Suspense, type ReactNode, type ReactElement } from "react"+import { useAtom, useCreateAtom } from "@tanstack/react-store"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"+import { useCommunityPreviewNavigation } from "@/components/community/shell/community-preview-navigation"-// emoji-mart picker β themed to match light/dark. Uses the native set so it-// renders system emoji without fetching an external SVG sprite (the twitter/twemoji-// set shows "#" placeholders when the CDN sprite can't load).-function EmojiPicker({ onPick }: { onPick: (emoji: string) => void }) {- const { resolvedTheme } = useTheme()- return (- <EmojiMartPicker- data={emojiMartData}- theme={resolvedTheme === "dark" ? "dark" : "light"}- set="native"- previewPosition="none"- skinTonePosition="none"- onEmojiSelect={(e: { native: string }) => onPick(e.native)}- />- )-}+const EmojiPicker = lazy(() => import("./emoji-picker-interactive"))-// emoji picker in a shadcn Popover β trigger is the passed child, picker portals out-export function EmojiPickerPopover({- children, onPick, side = "top", align = "end", onOpenChange,-}: {- children: React.ReactNode+export function EmojiPickerPopover(props: {+ children: ReactNodeonPick: (emoji: string) => voidside?: "top" | "bottom" | "left" | "right"align?: "start" | "center" | "end"onOpenChange?: (open: boolean) => void}) {+ const preview = useCommunityPreviewNavigation()const [open, setOpen] = useAtom(useCreateAtom(false))- const setBoth = (o: boolean) => { setOpen(o); onOpenChange?.(o) }+ const setBoth = (value: boolean) => { setOpen(value); props.onOpenChange?.(value) }+ if (preview) return <>{props.children}</>return (<Popover open={open} onOpenChange={setBoth}>- <PopoverTrigger render={children as React.ReactElement} />- <PopoverContent side={side} align={align} className="w-auto border-none bg-transparent p-0 shadow-none">- <EmojiPicker onPick={(e) => { onPick(e); setBoth(false) }} />+ <PopoverTrigger render={props.children as ReactElement} />+ <PopoverContent side={props.side ?? "top"} align={props.align ?? "end"} className="w-auto border-none bg-transparent p-0 shadow-none">+ <Suspense fallback={<div role="status" className="rounded-md bg-popover p-3 text-sm text-muted-foreground">Loading emojiβ¦</div>}>+ <EmojiPicker onPick={(emoji) => { props.onPick(emoji); setBoth(false) }} />+ </Suspense></PopoverContent></Popover>)diff --git a/src/web/src/components/community/messages/message-body-full.tsx b/src/web/src/components/community/messages/message-body-full.tsxnew file mode 100644index 000000000..44e2e48d9--- /dev/null+++ b/src/web/src/components/community/messages/message-body-full.tsx@@ -0,0 +1,4 @@+import { mermaid, cjk, math } from "@/lib/streamdown-plugins"++const fullMessagePlugins = { mermaid, cjk, math }+export default fullMessagePluginsdiff --git a/src/web/src/components/community/messages/message-body-preview.dom.test.tsx b/src/web/src/components/community/messages/message-body-preview.dom.test.tsxnew file mode 100644index 000000000..b7223544a--- /dev/null+++ b/src/web/src/components/community/messages/message-body-preview.dom.test.tsx@@ -0,0 +1,34 @@+import { describe, it, expect } from "vitest"+import { renderCommunity as render } from "@/test/community-owner-harness"+import { waitFor } from "@/test/react-dom-harness"+import { CommunityPreviewNavigation } from "../shell/community-preview-navigation"+import { MessageBody } from "./message-body"++describe("demo message rendering", () => {+ it("keeps diagram and formula syntax as text while retaining ordinary Markdown", async () => {+ const view = render(<CommunityPreviewNavigation value={true}><MessageBody text={"**Hello** $x^2$\n\n```mermaid\ngraph TD; A-->B\n```"} /></CommunityPreviewNavigation>)+ await waitFor(() => expect(view.container.querySelector('[data-streamdown="strong"]')?.textContent).toBe("Hello"))+ expect(view.container.textContent).toContain("$x^2$")+ expect(view.container.textContent).toContain("graph TD; A-->B")+ expect(view.container.querySelector(".katex, svg[aria-roledescription]")).toBeNull()+ })++ it("preserves ordinary text nodes while native plugins load", async () => {+ const view = render(<MessageBody text={"**Keep selected text**\n\n$x^2$"} />)+ const text = view.container.querySelector('[data-streamdown="strong"]')!+ expect(text.textContent).toBe("Keep selected text")+ await waitFor(() => expect(view.container.querySelector(".katex")).not.toBeNull())+ expect(text.isConnected).toBe(true)+ expect(view.container.querySelector('[data-streamdown="strong"]')).toBe(text)+ })++ it("keeps native plain text visible while plugins load", () => {+ const view = render(<MessageBody text="Immediate plain message" />)+ expect(view.container.textContent).toContain("Immediate plain message")+ })++ it("keeps real chat formula rendering", async () => {+ const view = render(<MessageBody text={"$x^2$"} />)+ await waitFor(() => expect(view.container.querySelector(".katex")).not.toBeNull())+ })+})diff --git a/src/web/src/components/community/messages/message-body-view.tsx b/src/web/src/components/community/messages/message-body-view.tsxnew file mode 100644index 000000000..1c7983575--- /dev/null+++ b/src/web/src/components/community/messages/message-body-view.tsx@@ -0,0 +1,152 @@+import { useMemo, type ComponentProps } from "react"+import { Streamdown } from "streamdown"+import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from "rehype-sanitize"+import { harden } from "rehype-harden"+import type { PluggableList } from "unified"+import { chatSyntaxHandlers } from "@/lib/community/chat-syntax-plugin"+import { CHAT_REMARK_PLUGINS } from "@/lib/community/chat-markdown"+import {+ extractInviteTokens,+ MD_ALLOWED_TAGS,+ MD_LITERAL_TAGS,+ buildMdComponents,+} from "./message-markdown"+import { CommunityInviteCard } from "../social/community-invite-card"+import type { MessagePerspective } from "@/components/community/messages/message-presentation-types"+import type { OpenProfile } from "@/components/community/social/profile-types"++// The sanitize schema Streamdown builds internally when `allowedTags` is+// left at its default merge path (verified against Streamdown 2.5.0's+// compiled source): `defaultSchema` + `protocols.href` gains `"tel"` ++// `attributes.code` gains `"metastring"` (for the shiki code-highlighting+// metastring), THEN `MD_ALLOWED_TAGS`'s tag names/attributes are merged in.+// Reproduced here because dropping `rehype-raw` (below) requires supplying a+// custom `rehypePlugins` array, and Streamdown's `allowedTags`-merge-into-+// sanitize-schema auto-fire is gated by strict reference equality against+// Streamdown's own default `rehypePlugins` array β a gate any custom array+// breaks on purpose, so `allowedTags`/`MD_ALLOWED_TAGS` are NOT passed as a+// `<Streamdown>` prop below; this schema stands in for that merge instead.+const SANITIZE_SCHEMA: SanitizeSchema = {+ ...defaultSchema,+ protocols: {+ ...defaultSchema.protocols,+ href: [...(defaultSchema.protocols?.href ?? []), "tel"],+ },+ attributes: {+ ...defaultSchema.attributes,+ code: [...(defaultSchema.attributes?.code ?? []), "metastring"],+ },+ tagNames: [...(defaultSchema.tagNames ?? []), ...Object.keys(MD_ALLOWED_TAGS)],+}+for (const [tag, attrs] of Object.entries(MD_ALLOWED_TAGS)) {+ SANITIZE_SCHEMA.attributes = { ...SANITIZE_SCHEMA.attributes, [tag]: attrs }+}++// The exact `rehype-harden` config Streamdown ships as its own default β+// verified against the compiled source. This is the layer that+// unconditionally blocks `javascript:`/`data:`/`vbscript:`/`file:` links+// regardless of any other configuration (see debt record #9's finding β+// `linkSafety={{ enabled: false }}` below does NOT gate this; it only+// toggles the AI-content confirm-before-navigating modal).+const HARDEN_CONFIG = {+ allowedImagePrefixes: ["*"],+ allowedLinkPrefixes: ["*"],+ allowedProtocols: ["*"],+ defaultOrigin: undefined,+ allowDataImages: true,+}++// Hand-rolled replacement for Streamdown's default `rehypePlugins` pipeline+// (`[rehype-raw, [rehype-sanitize, schema], [rehype-harden, config]]`,+// verified against the compiled source) with `rehype-raw` dropped β chat-+// only syntax (spoiler/mention/channelRef) is now parsed as real mdast+// nodes by `chatSyntaxPlugin` (see the `remarkPlugins`/`remarkRehypeOptions`+// props below), never spliced into the message string as HTML tags, so+// there is nothing left for `rehype-raw` to parse. With `rehype-raw` gone,+// Streamdown's own remark-side fallback (any literal `html`-type mdast node+// β i.e. raw HTML the user typed, like `<b>bold</b>` β becomes a plain-text+// node) makes user-typed HTML render as literal text automatically.+const REHYPE_PLUGINS: PluggableList = [+ [rehypeSanitize, SANITIZE_SCHEMA],+ [harden, HARDEN_CONFIG],+]++// Message body renderer. Standard markdown (bold/italic/strike/code/codeblock/quote)+// plus GFM constructs (tables, task lists, autolinks, strikethrough) render via+// `remarkGfm` in the remarkPlugins array below β it MUST be listed explicitly+// because passing a custom `remarkPlugins` replaces Streamdown's default array+// (which bundles remark-gfm), so without it GFM silently stops parsing. This+// matches agent-chat, which gets GFM from Streamdown's untouched defaults. The+// table tags GFM emits are already permitted by rehype-sanitize's defaultSchema+// (`table/thead/tbody/tr/td/th`); table controls are wired via `controls.table`+// below. The shared+// mermaid/math/cjk plugins give parity with the agent bubble (diagrams, KaTeX+// math, CJK spacing) and operate on different constructs than the chat-only+// syntax (spoilers, @mentions, @everyone, #channels) that `chatSyntaxPlugin`+// parses directly into mdast nodes and maps to pill components β no custom+// markdown parser, no HTML-string splicing.+//+// Community invite URLs (`/c/invite/<token>`) render inline: the+// URL stays as a plain auto-linked <a> in the message body, and a rich join+// card renders BELOW it. Both surfaces coexist so users can still copy/share+// the raw link even when the card is present.+export function MessageBodyView({+ text,+ plugins,+ onOpenProfile,+ perspective = "neutral",+}: {+ text: string+ plugins: ComponentProps<typeof Streamdown>["plugins"]+ onOpenProfile?: OpenProfile+ perspective?: MessagePerspective+}) {+ const inviteTokens = useMemo(() => extractInviteTokens(text), [text])+ const components = useMemo(+ () => buildMdComponents(onOpenProfile),+ [onOpenProfile],+ )+ return (+ <div+ data-community-message-body+ className="markdown markdown-chat flex flex-col gap-2 wrap-anywhere select-text text-[15px] leading-snug text-foreground"+ >+ <Streamdown+ className="message-markdown-blocks flex flex-col gap-2 space-y-0"+ mode="static"+ parseIncompleteMarkdown={false}+ plugins={plugins}+ remarkPlugins={CHAT_REMARK_PLUGINS}+ remarkRehypeOptions={{ handlers: chatSyntaxHandlers }}+ rehypePlugins={REHYPE_PLUGINS}+ // Deliberately skips the AI-content confirm-before-navigating modal+ // β that feature exists for LLM-generated content where a model+ // could be prompt-injected into emitting a malicious-looking link;+ // community chat links are typed by the human sender, so a plain+ // hyperlink click is the expected behavior. Protocol/XSS filtering+ // is unconditional via `rehype-harden` above, unaffected by this+ // flag either way.+ linkSafety={{ enabled: false }}+ controls={{+ code: { copy: true, download: false },+ table: { copy: true, download: false, fullscreen: true },+ }}+ literalTagContent={MD_LITERAL_TAGS}+ components={components}+ >+ {text}+ </Streamdown>+ {inviteTokens.length > 0 && (+ <div className="flex flex-col gap-2">+ {inviteTokens.map((token) => (+ <CommunityInviteCard+ key={token}+ token={token}+ perspective={perspective}+ />+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/src/web/src/components/community/messages/message-body.dom.test.ts b/src/web/src/components/community/messages/message-body.dom.test.tsindex f26db2108..23510867f 100644--- a/src/web/src/components/community/messages/message-body.dom.test.ts+++ b/src/web/src/components/community/messages/message-body.dom.test.ts@@ -5,7 +5,12 @@ import { renderCommunity as render } from "@/test/community-owner-harness"import { readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"-import { MessageBody } from "./message-body"+import fullMessagePlugins from "./message-body-full"+import { MessageBodyView } from "./message-body-view"++function MessageBody(props: Omit<React.ComponentProps<typeof MessageBodyView>, "plugins">) {+ return React.createElement(MessageBodyView, { ...props, plugins: fullMessagePlugins })+}const componentDirectory = dirname(fileURLToPath(import.meta.url))diff --git a/src/web/src/components/community/messages/message-body.tsx b/src/web/src/components/community/messages/message-body.tsxindex fccda2b69..583dd670f 100644--- a/src/web/src/components/community/messages/message-body.tsx+++ b/src/web/src/components/community/messages/message-body.tsx@@ -1,158 +1,43 @@-import { memo, useMemo } from "react"-import { Streamdown } from "streamdown"-import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from "rehype-sanitize"-import { harden } from "rehype-harden"-import type { PluggableList } from "unified"-import { mermaid, cjk, math } from "@/lib/streamdown-plugins"-import { chatSyntaxHandlers } from "@/lib/community/chat-syntax-plugin"-import { CHAT_REMARK_PLUGINS } from "@/lib/community/chat-markdown"-import {- extractInviteTokens,- MD_ALLOWED_TAGS,- MD_LITERAL_TAGS,- buildMdComponents,-} from "./message-markdown"-import { CommunityInviteCard } from "../social/community-invite-card"-import type { MessagePerspective } from "@/components/community/messages/message-presentation-types"-import type { OpenProfile } from "@/components/community/social/profile-types"+"use client"-// The sanitize schema Streamdown builds internally when `allowedTags` is-// left at its default merge path (verified against Streamdown 2.5.0's-// compiled source): `defaultSchema` + `protocols.href` gains `"tel"` +-// `attributes.code` gains `"metastring"` (for the shiki code-highlighting-// metastring), THEN `MD_ALLOWED_TAGS`'s tag names/attributes are merged in.-// Reproduced here because dropping `rehype-raw` (below) requires supplying a-// custom `rehypePlugins` array, and Streamdown's `allowedTags`-merge-into--// sanitize-schema auto-fire is gated by strict reference equality against-// Streamdown's own default `rehypePlugins` array β a gate any custom array-// breaks on purpose, so `allowedTags`/`MD_ALLOWED_TAGS` are NOT passed as a-// `<Streamdown>` prop below; this schema stands in for that merge instead.-const SANITIZE_SCHEMA: SanitizeSchema = {- ...defaultSchema,- protocols: {- ...defaultSchema.protocols,- href: [...(defaultSchema.protocols?.href ?? []), "tel"],- },- attributes: {- ...defaultSchema.attributes,- code: [...(defaultSchema.attributes?.code ?? []), "metastring"],- },- tagNames: [...(defaultSchema.tagNames ?? []), ...Object.keys(MD_ALLOWED_TAGS)],-}-for (const [tag, attrs] of Object.entries(MD_ALLOWED_TAGS)) {- SANITIZE_SCHEMA.attributes = { ...SANITIZE_SCHEMA.attributes, [tag]: attrs }-}--// The exact `rehype-harden` config Streamdown ships as its own default β-// verified against the compiled source. This is the layer that-// unconditionally blocks `javascript:`/`data:`/`vbscript:`/`file:` links-// regardless of any other configuration (see debt record #9's finding β-// `linkSafety={{ enabled: false }}` below does NOT gate this; it only-// toggles the AI-content confirm-before-navigating modal).-const HARDEN_CONFIG = {- allowedImagePrefixes: ["*"],- allowedLinkPrefixes: ["*"],- allowedProtocols: ["*"],- defaultOrigin: undefined,- allowDataImages: true,-}+import { memo, useEffect, useState } from "react"+import { cjk } from "@streamdown/cjk"+import { useCommunityPreviewNavigation } from "@/components/community/shell/community-preview-navigation"+import type { OpenProfile } from "../social/profile-types"+import type { MessagePerspective } from "./message-presentation-types"+import { MessageBodyView } from "./message-body-view"-// Hand-rolled replacement for Streamdown's default `rehypePlugins` pipeline-// (`[rehype-raw, [rehype-sanitize, schema], [rehype-harden, config]]`,-// verified against the compiled source) with `rehype-raw` dropped β chat--// only syntax (spoiler/mention/channelRef) is now parsed as real mdast-// nodes by `chatSyntaxPlugin` (see the `remarkPlugins`/`remarkRehypeOptions`-// props below), never spliced into the message string as HTML tags, so-// there is nothing left for `rehype-raw` to parse. With `rehype-raw` gone,-// Streamdown's own remark-side fallback (any literal `html`-type mdast node-// β i.e. raw HTML the user typed, like `<b>bold</b>` β becomes a plain-text-// node) makes user-typed HTML render as literal text automatically.-const REHYPE_PLUGINS: PluggableList = [- [rehypeSanitize, SANITIZE_SCHEMA],- [harden, HARDEN_CONFIG],-]--// Message body renderer. Standard markdown (bold/italic/strike/code/codeblock/quote)-// plus GFM constructs (tables, task lists, autolinks, strikethrough) render via-// `remarkGfm` in the remarkPlugins array below β it MUST be listed explicitly-// because passing a custom `remarkPlugins` replaces Streamdown's default array-// (which bundles remark-gfm), so without it GFM silently stops parsing. This-// matches agent-chat, which gets GFM from Streamdown's untouched defaults. The-// table tags GFM emits are already permitted by rehype-sanitize's defaultSchema-// (`table/thead/tbody/tr/td/th`); table controls are wired via `controls.table`-// below. The shared-// mermaid/math/cjk plugins give parity with the agent bubble (diagrams, KaTeX-// math, CJK spacing) and operate on different constructs than the chat-only-// syntax (spoilers, @mentions, @everyone, #channels) that `chatSyntaxPlugin`-// parses directly into mdast nodes and maps to pill components β no custom-// markdown parser, no HTML-string splicing.-//-// Community invite URLs (`/c/invite/<token>`) render inline: the-// URL stays as a plain auto-linked <a> in the message body, and a rich join-// card renders BELOW it. Both surfaces coexist so users can still copy/share-// the raw link even when the card is present.-function MessageBodyImpl({- text,- onOpenProfile,- perspective = "neutral",-}: {+type MessageBodyProps = {text: stringonOpenProfile?: OpenProfileperspective?: MessagePerspective-}) {- const inviteTokens = useMemo(() => extractInviteTokens(text), [text])- const components = useMemo(- () => buildMdComponents(onOpenProfile),- [onOpenProfile],- )- return (- <div- data-community-message-body- className="markdown markdown-chat flex flex-col gap-2 wrap-anywhere select-text text-[15px] leading-snug text-foreground"- >- <Streamdown- className="message-markdown-blocks flex flex-col gap-2 space-y-0"- mode="static"- parseIncompleteMarkdown={false}- plugins={{ mermaid, cjk, math }}- remarkPlugins={CHAT_REMARK_PLUGINS}- remarkRehypeOptions={{ handlers: chatSyntaxHandlers }}- rehypePlugins={REHYPE_PLUGINS}- // Deliberately skips the AI-content confirm-before-navigating modal- // β that feature exists for LLM-generated content where a model- // could be prompt-injected into emitting a malicious-looking link;- // community chat links are typed by the human sender, so a plain- // hyperlink click is the expected behavior. Protocol/XSS filtering- // is unconditional via `rehype-harden` above, unaffected by this- // flag either way.- linkSafety={{ enabled: false }}- controls={{- code: { copy: true, download: false },- table: { copy: true, download: false, fullscreen: true },- }}- literalTagContent={MD_LITERAL_TAGS}- components={components}- >- {text}- </Streamdown>- {inviteTokens.length > 0 && (- <div className="flex flex-col gap-2">- {inviteTokens.map((token) => (- <CommunityInviteCard- key={token}- token={token}- perspective={perspective}- />- ))}- </div>- )}- </div>- )}-// Memoized: the message body is pure in (text, onOpenProfile). Once the row's-// `onOpenProfile` is reference-stable (see message-list callback stabilization),-// re-rendering the parent Message no longer re-runs Streamdown's markdown parse-// + its per-Block subtree β the largest single cost in the switch re-render-// storm (Streamdown/Block were top react-scan offenders).-export const MessageBody = memo(MessageBodyImpl)+type FullPlugins = typeof import("./message-body-full")["default"]+const previewPlugins = { cjk }+let fullPlugins: FullPlugins | null = null+let loadingPlugins: Promise<FullPlugins> | null = null++function loadFullPlugins() {+ return loadingPlugins ??= import("./message-body-full").then((module) => {+ fullPlugins = module.default+ return fullPlugins+ })+}++export const MessageBody = memo(function MessageBody(props: MessageBodyProps) {+ const preview = useCommunityPreviewNavigation()+ const [plugins, setPlugins] = useState(() => fullPlugins)+ const [loadError, setLoadError] = useState<unknown>(null)+ useEffect(() => {+ if (preview || plugins) return+ let active = true+ void loadFullPlugins().then(+ (loaded) => { if (active) setPlugins(loaded) },+ (error: unknown) => { if (active) setLoadError(error) },+ )+ return () => { active = false }+ }, [preview, plugins])+ if (loadError) throw loadError+ return <MessageBodyView {...props} plugins={preview ? previewPlugins : plugins ?? previewPlugins} />+})diff --git a/src/web/src/components/community/messages/message-list-row.tsx b/src/web/src/components/community/messages/message-list-row.tsxindex adfc497eb..4600f2ade 100644--- a/src/web/src/components/community/messages/message-list-row.tsx+++ b/src/web/src/components/community/messages/message-list-row.tsx@@ -57,7 +57,7 @@ export function renderMessageListRow(}return (<div className="flow-root" style={{ paddingBlock: `${item.paddingTop ?? MESSAGE_ROW_VERTICAL_PADDING_PX}px ${item.paddingBottom ?? MESSAGE_ROW_VERTICAL_PADDING_PX}px` }} data-message-row-key={item.key}>- <div data-msg-id={item.m.id} data-testid={tid.message(item.m.id)}>+ <div className="flow-root" data-msg-id={item.m.id} data-testid={tid.message(item.m.id)}><MessageRowm={item.m}hoverCapable={props.hoverCapable}diff --git a/src/web/src/components/community/messages/message-list-view.dom.test.ts b/src/web/src/components/community/messages/message-list-view.dom.test.tsindex 11ca40ff8..f5a10d016 100644--- a/src/web/src/components/community/messages/message-list-view.dom.test.ts+++ b/src/web/src/components/community/messages/message-list-view.dom.test.ts@@ -1,6 +1,6 @@import React from "react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { fireEvent, render } from "@/test/react-dom-harness"+import { fireEvent, render, waitFor } from "@/test/react-dom-harness"import { MessageListSkeleton, renderMessageListView as renderView } from "./message-list-view"import { ComposerAccessoryRail } from "./composer-accessory-rail"import { MessageShareDialog } from "./message-share-dialog"@@ -251,7 +251,7 @@ describe("renderMessageListView", () => {expect(content()).not.toHaveClass("pb-4", "sm:pb-6")})- it("wires selection actions through the footer slot and closes the share dialog", () => {+ it("wires selection actions through the footer slot and closes the share dialog", async () => {const exitSelect = vi.fn()const setShareOpen = vi.fn()const closeShare = vi.fn()@@ -284,6 +284,7 @@ describe("renderMessageListView", () => {expect(exitSelect).toHaveBeenCalledOnce()share.click()expect(setShareOpen).toHaveBeenCalledWith(true)+ await waitFor(() => expect(mockedShareDialog).toHaveBeenCalled())expect(mockedShareDialog).toHaveBeenCalledWith(expect.objectContaining({m: state.selectedMessages,open: true,diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsxindex 98d26a7d9..c97f8c9f8 100644--- a/src/web/src/components/community/messages/message-list-view.tsx+++ b/src/web/src/components/community/messages/message-list-view.tsx@@ -6,10 +6,12 @@ import { tid } from "@/lib/community/testids"import { CONVERSATION_TAIL_SPACE_PX } from "@/lib/community/conversation-layout"import { renderMessageListHero } from "./message-list-row"import { ComposerAccessoryRail, MessageSelectionFooter } from "./composer-accessory-rail"-import { MessageShareDialog } from "./message-share-dialog"+import dynamic from "next/dynamic"import type { MessageListController } from "./message-list-controller"import type { ResolvedMessageListProps } from "./message-list-types"+const MessageShareDialog = dynamic(() => import("./message-share-dialog").then((module) => module.MessageShareDialog), { loading: () => null })+export function renderMessageListView(props: ResolvedMessageListProps,controller: MessageListController,diff --git a/src/web/src/components/home/deferred-landing-media.dom.test.tsx b/src/web/src/components/home/deferred-landing-media.dom.test.tsxindex 2b0d433b5..f4f9bf454 100644--- a/src/web/src/components/home/deferred-landing-media.dom.test.tsx+++ b/src/web/src/components/home/deferred-landing-media.dom.test.tsx@@ -2,7 +2,7 @@ import React, { lazy } from "react"import { renderToString } from "react-dom/server"import { act, fireEvent, render, screen } from "@/test/react-dom-harness"import { afterEach, describe, expect, it, vi } from "vitest"-import { DeferredLandingMedia } from "./deferred-landing-media"+import { DeferredLandingMedia, DeferredShellMotion } from "./deferred-landing-media"const props = { poster: "/landing/posters/server.webp", darkPoster: "/landing/posters/server-dark.webp", width: 1120, height: 660 }afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })@@ -87,3 +87,11 @@ describe("deferred landing media", () => {error.mockRestore()})})+++it("keeps the below-workspace product poster below hero and interactive Shell priority", () => {+ const html = renderToString(<DeferredShellMotion scene="server" />)+ expect(html).toContain('loading="lazy"')+ expect(html).not.toContain('fetchPriority="high"')+ expect(html).not.toContain('loading="eager"')+})diff --git a/src/web/src/components/home/deferred-landing-media.tsx b/src/web/src/components/home/deferred-landing-media.tsxindex fea353fcf..a87d666bd 100644--- a/src/web/src/components/home/deferred-landing-media.tsx+++ b/src/web/src/components/home/deferred-landing-media.tsx@@ -72,7 +72,7 @@ export function DeferredLandingMedia({ poster, darkPoster, width, height, childr}export function DeferredShellMotion(props: ComponentProps<typeof LandingShellMotion>) {- return <DeferredLandingMedia poster={`/landing/posters/${props.scene}.webp`} darkPoster={`/landing/posters/${props.scene}-dark.webp`} width={1120} height={660} priority={props.scene === "server"}><Shell {...props} /></DeferredLandingMedia>+ return <DeferredLandingMedia poster={`/landing/posters/${props.scene}.webp`} darkPoster={`/landing/posters/${props.scene}-dark.webp`} width={1120} height={660}><Shell {...props} /></DeferredLandingMedia>}export function DeferredMobileChatMotion(props: { beat: number }) {diff --git a/src/web/src/components/home/hero-brand.dom.test.tsx b/src/web/src/components/home/hero-brand.dom.test.tsxindex 5b918de05..72e90b383 100644--- a/src/web/src/components/home/hero-brand.dom.test.tsx+++ b/src/web/src/components/home/hero-brand.dom.test.tsx@@ -4,11 +4,11 @@ import { fireEvent, render, screen } from "@/test/react-dom-harness";vi.mock("@gsap/react", () => ({ useGSAP: vi.fn() }));vi.mock("gsap", () => ({ default: { registerPlugin: vi.fn() } }));-vi.mock("@/components/typewriter-visual", () => ({ TypewriterVisual: () => null }));+vi.mock("@/components/typewriter-visual", () => ({ TypewriterVisual: ({ onPaperSettled }: { onPaperSettled?: () => void }) => <button onClick={onPaperSettled}>Finish paper</button> }));import { HeroSection } from "./hero-section";-afterEach(() => vi.unstubAllGlobals());+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });it("reveals the home-logo faces over the combined hero brand and restores them on leave", () => {vi.stubGlobal("matchMedia", (query: string) => ({@@ -28,3 +28,42 @@ it("reveals the home-logo faces over the combined hero brand and restores them ofireEvent.focus(brand);expect(logo.getAttribute("data-state")).toBe("reveal");});+++it("signals hero readiness after only its own images settle", () => {+ vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false);+ const ready = vi.fn();+ render(<><img src="below-hero.png" alt="Outside hero" /><HeroSection isLoggedIn={false} onReady={ready} backgroundDecoration={<><img src="hero-a.png" alt="Hero A" /><img src="hero-b.png" alt="Hero B" /></>} /></>);+ fireEvent.click(screen.getByRole("button", { name: "Finish paper" }));+ expect(ready).not.toHaveBeenCalled();+ fireEvent.load(screen.getByAltText("Outside hero"));+ expect(ready).not.toHaveBeenCalled();+ fireEvent.load(screen.getByAltText("Hero A"));+ expect(ready).not.toHaveBeenCalled();+ fireEvent.load(screen.getByAltText("Hero B"));+ expect(ready).toHaveBeenCalledTimes(1);+});++it("does not wait for window load when hero images are cached", () => {+ vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(true);+ const ready = vi.fn();+ render(<HeroSection isLoggedIn={false} onReady={ready} backgroundDecoration={<img src="cached-hero.png" alt="Cached hero" />} />);+ expect(ready).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Finish paper" }));+ expect(ready).toHaveBeenCalledTimes(1);+});++it("releases the scheduler on a failed hero image and removes pending handlers on unmount", () => {+ vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false);+ const ready = vi.fn();+ const view = render(<HeroSection isLoggedIn={false} onReady={ready} backgroundDecoration={<img src="hero.png" alt="Hero" />} />);+ fireEvent.click(screen.getByRole("button", { name: "Finish paper" }));+ const image = screen.getByAltText("Hero");+ fireEvent.error(image);+ expect(ready).toHaveBeenCalledTimes(1);+ fireEvent.load(image);+ expect(ready).toHaveBeenCalledTimes(1);+ view.unmount();+ fireEvent.load(image);+ expect(ready).toHaveBeenCalledTimes(1);+});diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsxindex a333e724f..c33849aab 100644--- a/src/web/src/components/home/hero-section.tsx+++ b/src/web/src/components/home/hero-section.tsx@@ -3,7 +3,7 @@/* eslint-disable @next/next/no-html-link-for-pages -- Product entrances require a new document to unload public tracking. */import { useAtom, useCreateAtom } from "@tanstack/react-store";-import { type CSSProperties, type ReactNode } from "react";+import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";import Link from "next/link";import { TypewriterVisual } from "@/components/typewriter-visual";import { trackLandingCtaClicked } from "@/lib/analytics";@@ -35,6 +35,7 @@ export function HeroSection({backgroundDecoration,desktopSplit = false,nextSectionId,+ onReady,}: {isLoggedIn: boolean;kicker?: string;@@ -55,7 +56,31 @@ export function HeroSection({backgroundDecoration?: ReactNode;desktopSplit?: boolean;nextSectionId?: string;+ onReady?: () => void;}) {+ const [paperSettled, setPaperSettled] = useState(false);+ const handlePaperSettled = useCallback(() => setPaperSettled(true), []);+ const heroRef = useRef<HTMLElement>(null);+ useEffect(() => {+ if (!onReady || !paperSettled || !heroRef.current) return;+ const pending = new Set(Array.from(heroRef.current.querySelectorAll("img")).filter((image) => !image.complete));+ const images = [...pending];+ const finish = (event: Event) => {+ if (!pending.delete(event.currentTarget as HTMLImageElement)) return;+ if (pending.size === 0) onReady();+ };+ for (const image of images) {+ image.addEventListener("load", finish, { once: true });+ image.addEventListener("error", finish, { once: true });+ }+ if (pending.size === 0) onReady();+ return () => {+ for (const image of images) {+ image.removeEventListener("load", finish);+ image.removeEventListener("error", finish);+ }+ };+ }, [onReady, paperSettled]);const [copied, setCopied] = useAtom(useCreateAtom(false));const ctaSizingClassName = largeCtas? "px-3 py-3 text-[clamp(0.6875rem,3vw,1rem)] whitespace-nowrap sm:px-8"@@ -63,6 +88,7 @@ export function HeroSection({return (<section+ ref={heroRef}data-testid={testId}className={`hero-section relative flex h-screen items-center justify-center overflow-hidden${desktopSplit ? " hero-section-split" : ""}${nextSectionId ? " hero-section-scrollable" : ""}`}style={{ backgroundColor: "var(--landing-bg)" }}@@ -145,6 +171,7 @@ export function HeroSection({{/* Full Typewriter */}<div data-static-paper={staticPaper || undefined} className={`hero-artwork absolute inset-0 ${typewriterClassName ?? ""}`}><TypewriterVisual+ onPaperSettled={onReady ? handlePaperSettled : undefined}animateEntrance={!staticPaper}entranceDelay={1.2}className="absolute! inset-0"diff --git a/src/web/src/components/home/landing-interactive-demo.dom.test.tsx b/src/web/src/components/home/landing-interactive-demo.dom.test.tsxindex 84ff159c8..5d9765e9f 100644--- a/src/web/src/components/home/landing-interactive-demo.dom.test.tsx+++ b/src/web/src/components/home/landing-interactive-demo.dom.test.tsx@@ -5,13 +5,15 @@ import { LandingInteractiveDemo } from "./landing-interactive-demo"afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers() })describe("background workspace loading", () => {- it("waits for the homepage load, then keeps the loader until its own frame is ready", () => {+ it("starts after the hero while the rest of the homepage is still loading, then validates frame readiness", () => {vi.spyOn(document, "readyState", "get").mockReturnValue("loading")- render(<LandingInteractiveDemo />)+ const view = render(<LandingInteractiveDemo heroReady={false} />)expect(screen.queryByTitle("Alook workspace")).toBeNull()expect(screen.getByRole("status")).toHaveAttribute("aria-label", "Loading Alook workspace")expect(document.querySelectorAll('[data-slot="skeleton"]').length).toBeGreaterThan(10)act(() => window.dispatchEvent(new Event("load")))+ expect(screen.queryByTitle("Alook workspace")).toBeNull()+ view.rerender(<LandingInteractiveDemo heroReady />)const frame = screen.getByTitle("Alook workspace") as HTMLIFrameElementexpect(frame).toHaveAttribute("src", "/demo")expect(screen.getByRole("status")).toBeVisible()@@ -24,19 +26,19 @@ describe("background workspace loading", () => {expect(frame).toHaveAttribute("aria-hidden", "false")})- it("removes the pending load listener when unmounted", () => {+ it("removes the readiness listener when unmounted", () => {vi.spyOn(document, "readyState", "get").mockReturnValue("loading")const remove = vi.spyOn(window, "removeEventListener")- const view = render(<LandingInteractiveDemo />)+ const view = render(<LandingInteractiveDemo heroReady={false} />)view.unmount()- expect(remove).toHaveBeenCalledWith("load", expect.any(Function))+ expect(remove).toHaveBeenCalledWith("message", expect.any(Function))})- it("starts immediately when the homepage has already loaded", () => {- vi.spyOn(document, "readyState", "get").mockReturnValue("complete")+ it("starts immediately when the hero is ready without waiting for idle or homepage load", () => {+ vi.spyOn(document, "readyState", "get").mockReturnValue("loading")const idle = vi.fn()vi.stubGlobal("requestIdleCallback", idle)- render(<LandingInteractiveDemo />)+ render(<LandingInteractiveDemo heroReady />)expect(screen.getByTitle("Alook workspace")).toHaveAttribute("src", "/demo")expect(idle).not.toHaveBeenCalled()})diff --git a/src/web/src/components/home/landing-interactive-demo.tsx b/src/web/src/components/home/landing-interactive-demo.tsxindex 43bbf0e12..9aaaa04a1 100644--- a/src/web/src/components/home/landing-interactive-demo.tsx+++ b/src/web/src/components/home/landing-interactive-demo.tsx@@ -4,16 +4,9 @@ import { useEffect, useRef, useState } from "react"import { LandingWorkspaceSkeleton } from "./landing-workspace-skeleton"import styles from "./landing-interactive-shell.module.css"-export function LandingInteractiveDemo() {- const [started, setStarted] = useState(false)+export function LandingInteractiveDemo({ heroReady }: { heroReady: boolean }) {const [ready, setReady] = useState(false)const frame = useRef<HTMLIFrameElement>(null)- useEffect(() => {- const start = () => setStarted(true)- if (document.readyState === "complete") start()- else window.addEventListener("load", start, { once: true })- return () => window.removeEventListener("load", start)- }, [])useEffect(() => {const receive = (event: MessageEvent) => {if (event.origin === window.location.origin && event.source === frame.current?.contentWindow && event.data?.type === "alook-demo-ready") setReady(true)@@ -24,7 +17,7 @@ export function LandingInteractiveDemo() {return <section id="workspace" className={styles.section} aria-label="Explore Alook" data-testid="landing-interactive-section"><div className={styles.frame} aria-busy={!ready}>{!ready && <LandingWorkspaceSkeleton />}- {started && <iframe ref={frame} src="/demo" title="Alook workspace" className={styles.workspace} aria-hidden={!ready} tabIndex={ready ? undefined : -1} style={{ opacity: ready ? 1 : 0 }} />}+ {heroReady && <iframe ref={frame} src="/demo" title="Alook workspace" className={styles.workspace} aria-hidden={!ready} tabIndex={ready ? undefined : -1} style={{ opacity: ready ? 1 : 0 }} />}</div></section>}diff --git a/src/web/src/components/home/landing-interactive-shell.dom.test.tsx b/src/web/src/components/home/landing-interactive-shell.dom.test.tsxindex 940ab2d03..327d8a131 100644--- a/src/web/src/components/home/landing-interactive-shell.dom.test.tsx+++ b/src/web/src/components/home/landing-interactive-shell.dom.test.tsx@@ -120,10 +120,10 @@ describe("interactive landing workspace", () => {await setupUser().click(screen.getByRole("button", { name: "Profile" }))expect(screen.queryByRole("region", { name: "Running bots" })).toBeNull()})- it("opens Friends, My Bots and Machines as populated pages", () => {+ it("opens Friends, My Bots and Machines as populated pages", async () => {render(<LandingInteractiveShell />)fireEvent.click(screen.getAllByRole("link", { name: "Home" })[0])- expect(screen.getByPlaceholderText("Search friends")).toBeVisible()+ expect(await screen.findByPlaceholderText("Search friends")).toBeVisible()expect(screen.getByRole("link", { name: "Alli" })).toHaveTextContent(/^Alli$/)fireEvent.click(screen.getByRole("link", { name: "My Bots" }))expect(screen.getByRole("heading", { name: "My Bots" })).toBeVisible()diff --git a/src/web/src/components/home/landing-interactive-shell.tsx b/src/web/src/components/home/landing-interactive-shell.tsxindex 1740ee44c..30ea219e7 100644--- a/src/web/src/components/home/landing-interactive-shell.tsx+++ b/src/web/src/components/home/landing-interactive-shell.tsx@@ -1,6 +1,7 @@"use client"import { useEffect, useRef, useState } from "react"+import dynamic from "next/dynamic"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { createCommunityDbRegistry } from "@/lib/community-db/collections"import { CommunityDbProvider } from "@/lib/community-db/projections"@@ -31,9 +32,12 @@ import type { Marked, Mention, UnreadServer } from "@/lib/community/models/inboximport type { NotifLevel } from "@alook/shared"import { DEMO_CHANNELS, DEMO_DMS, DEMO_MESSAGES, DEMO_PROFILES, DEMO_SERVERS, DEMO_UNREADS, DEMO_MENTIONS } from "./landing-interactive-shell-data"import { LandingBotLog } from "./landing-bot-log"-import { WorkspaceHome } from "./landing-workspace-home"import styles from "./landing-interactive-shell.module.css"+const WorkspaceHome = dynamic(() => import("./landing-workspace-home").then((module) => module.WorkspaceHome), {+ loading: () => <p role="status" className="p-6 text-sm text-muted-foreground">Loading Homeβ¦</p>,+})+export default function LandingInteractiveShell() {useEffect(() => {window.parent.postMessage({ type: "alook-demo-ready" }, window.location.origin)diff --git a/src/web/src/components/home/landing-page.tsx b/src/web/src/components/home/landing-page.tsxindex e25a88c99..dffe20e96 100644--- a/src/web/src/components/home/landing-page.tsx+++ b/src/web/src/components/home/landing-page.tsx@@ -1,7 +1,7 @@"use client"import Image from "next/image"-import { useEffect, useRef, type PointerEvent as ReactPointerEvent } from "react"+import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"import { LANDING_HUMAN_AVATARS } from "./landing-human-avatars"import { GeneratedAvatar } from "@/components/avatar"import { ProviderLogo } from "@/components/provider-logo"@@ -207,6 +207,8 @@ function IdentityProof() {}export function LandingPage({ isLoggedIn }: { isLoggedIn: boolean }) {+ const [heroReady, setHeroReady] = useState(false)+ const handleHeroReady = useCallback(() => setHeroReady(true), [])return (<main className={`landing ${styles.page}`}><MarketingNav@@ -221,6 +223,7 @@ export function LandingPage({ isLoggedIn }: { isLoggedIn: boolean }) {containerTestId={tid.landingHeaderContainer}/><HeroSection+ onReady={handleHeroReady}staticPaperdesktopSplitnextSectionId="workspace"@@ -250,7 +253,7 @@ export function LandingPage({ isLoggedIn }: { isLoggedIn: boolean }) {backgroundDecoration={<HeroAvatarSwarm />}/>- <LandingInteractiveDemo />+ <LandingInteractiveDemo heroReady={heroReady} /><section id="product" tabIndex={-1} className={styles.productSection} data-testid="landing-product-proof"><div className={styles.productLayout} data-testid={tid.landingMainContainer}>diff --git a/src/web/src/components/home/marketing-nav.dom.test.tsx b/src/web/src/components/home/marketing-nav.dom.test.tsxnew file mode 100644index 000000000..e58033900--- /dev/null+++ b/src/web/src/components/home/marketing-nav.dom.test.tsx@@ -0,0 +1,33 @@+import React, { type ComponentProps } from "react";+import { afterEach, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@/test/react-dom-harness";++vi.mock("next/link", () => ({+ default: ({ prefetch, ...props }: ComponentProps<"a"> & { prefetch?: boolean }) =>+ <a {...props} data-prefetch={prefetch === false ? "disabled" : "auto"} />,+}));+vi.mock("@/lib/analytics", () => ({ trackLandingCtaClicked: vi.fn(), trackGithubOutboundClicked: vi.fn() }));++import { MarketingNav } from "./marketing-nav";++afterEach(() => vi.restoreAllMocks());++it("defers route prefetch until the homepage navigation is revealed, without changing link destinations", () => {+ let bottom = 100;+ const { container } = render(<><section className="hero-section" /><MarketingNav isLoggedIn={false} revealAfterHero collapseLinksOnMobile /></>);+ vi.spyOn(container.querySelector(".hero-section")!, "getBoundingClientRect").mockImplementation(() => ({ bottom }) as DOMRect);+ fireEvent.scroll(window);+ for (const link of container.querySelectorAll("[data-prefetch]")) expect(link).toHaveAttribute("data-prefetch", "disabled");+ expect(screen.getAllByRole("link", { name: "Pricing" })[0]).toHaveAttribute("href", "/pricing");+ bottom = -1;+ fireEvent.scroll(window);+ for (const link of container.querySelectorAll("[data-prefetch]")) expect(link).toHaveAttribute("data-prefetch", "auto");+ bottom = 100;+ fireEvent.scroll(window);+ for (const link of container.querySelectorAll("[data-prefetch]")) expect(link).toHaveAttribute("data-prefetch", "disabled");+});++it("preserves default prefetch outside the homepage reveal behavior", () => {+ const { container } = render(<MarketingNav isLoggedIn={false} />);+ for (const link of container.querySelectorAll("[data-prefetch]")) expect(link).toHaveAttribute("data-prefetch", "auto");+});diff --git a/src/web/src/components/home/marketing-nav.tsx b/src/web/src/components/home/marketing-nav.tsxindex f36f4b8e3..d55fe6c49 100644--- a/src/web/src/components/home/marketing-nav.tsx+++ b/src/web/src/components/home/marketing-nav.tsx@@ -37,6 +37,7 @@ export function MarketingNav({containerTestId?: string;}) {const [revealed, setRevealed] = useAtom(useCreateAtom(false));+ const prefetch = revealAfterHero && !revealed ? false : undefined;useEffect(() => {if (!revealAfterHero) return;@@ -64,7 +65,7 @@ export function MarketingNav({className={`${containerClassName ?? "mx-auto w-full max-w-5xl px-6"} flex items-center justify-between py-2`}data-testid={containerTestId}>- <Link href={homeHref} className="flex items-center gap-1">+ <Link prefetch={prefetch} href={homeHref} className="flex items-center gap-1"><Image src="/alook.svg" alt="Alook" width={22} height={22} /><spanclassName="text-lg tracking-tight"@@ -85,11 +86,12 @@ export function MarketingNav({return link.usesDocumentNavigation ? (<a key={link.href} href={link.href} className={className} style={MARKETING_SITE_LINK_STYLE}>{link.label}</a>) : (- <Link key={link.href} href={link.href} className={className} style={MARKETING_SITE_LINK_STYLE}>{link.label}</Link>+ <Link prefetch={prefetch} key={link.href} href={link.href} className={className} style={MARKETING_SITE_LINK_STYLE}>{link.label}</Link>);})}{showTemplates && (<Link+ prefetch={prefetch}href="/templates"className="hidden sm:block px-3 py-2 text-xs uppercase tracking-widest transition-opacity duration-150 hover:opacity-70"style={{@@ -159,9 +161,9 @@ export function MarketingNav({{MARKETING_SITE_LINKS.map((link) => link.usesDocumentNavigation ? (<a key={link.href} href={link.href} className={`marketing-mobile-site-link block ${MARKETING_SITE_LINK_CLASS_NAME}`} style={MARKETING_SITE_LINK_STYLE}>{link.label}</a>) : (- <Link key={link.href} href={link.href} className={`marketing-mobile-site-link block ${MARKETING_SITE_LINK_CLASS_NAME}`} style={MARKETING_SITE_LINK_STYLE}>{link.label}</Link>+ <Link prefetch={prefetch} key={link.href} href={link.href} className={`marketing-mobile-site-link block ${MARKETING_SITE_LINK_CLASS_NAME}`} style={MARKETING_SITE_LINK_STYLE}>{link.label}</Link>))}- {showTemplates && <Link href="/templates" className="block px-3 py-2 text-xs uppercase tracking-widest">Templates</Link>}+ {showTemplates && <Link prefetch={prefetch} href="/templates" className="block px-3 py-2 text-xs uppercase tracking-widest">Templates</Link>}<GithubOutboundLink surface="public_nav" target="_blank" rel="noopener noreferrer" className="block px-3 py-2 text-xs uppercase tracking-widest">GitHub</GithubOutboundLink><a href="https://discord.alook.ai" target="_blank" rel="noopener noreferrer" className="block px-3 py-2 text-xs uppercase tracking-widest">Discord</a><a href="https://x.com/alook_ai" target="_blank" rel="noopener noreferrer" className="block px-3 py-2 text-xs uppercase tracking-widest">X</a>diff --git a/src/web/src/components/typewriter-city-art.tsx b/src/web/src/components/typewriter-city-art.tsxindex 762bab541..e9415b234 100644--- a/src/web/src/components/typewriter-city-art.tsx+++ b/src/web/src/components/typewriter-city-art.tsx@@ -5,9 +5,10 @@ import { useEffect, useRef } from "react";import { TYPEWRITER_CITY_ART } from "./typewriter-city-art-data";import styles from "./typewriter-city-art.module.css";-export function TypewriterCityArt() {+export function TypewriterCityArt({ onSettled }: { onSettled?: () => void }) {const frameRef = useRef<HTMLDivElement>(null);const canvasRef = useRef<HTMLCanvasElement>(null);+ const [settled, setSettled] = useAtom(useCreateAtom(false));const [ready, setReady] = useAtom(useCreateAtom(false));useEffect(() => {@@ -29,27 +30,29 @@ export function TypewriterCityArt() {smaller.width = image.width / 2;smaller.height = image.height / 2;const smallerContext = smaller.getContext("2d");- if (!smallerContext) return;+ if (!smallerContext) { setSettled(true); return; }smallerContext.drawImage(image, 0, 0, smaller.width, smaller.height);image = smaller;}canvas.width = width;canvas.height = Math.round(width * 9 / 16);const output = canvas.getContext("2d");- if (!output) return;+ if (!output) { setSettled(true); return; }output.imageSmoothingQuality = "high";output.drawImage(image, 0, 0, canvas.width, canvas.height);setReady(true);+ setSettled(true);};const scheduleDraw = () => {cancelAnimationFrame(animationFrame);animationFrame = requestAnimationFrame(draw);};- void document.fonts?.load('20px "Alook Jgs5"').then(() => {+ if (!document.fonts) { setSettled(true); return; }+ void document.fonts.load('20px "Alook Jgs5"').then(() => {if (disposed) return;const context = source.getContext("2d");- if (!context) return;+ if (!context) { setSettled(true); return; }context.font = '20px "Alook Jgs5"';context.fillStyle = getComputedStyle(frame).color;context.textBaseline = "top";@@ -60,14 +63,18 @@ export function TypewriterCityArt() {observer = new ResizeObserver(scheduleDraw);observer.observe(frame);window.addEventListener("resize", scheduleDraw);- }).catch(() => {});+ }).catch(() => { if (!disposed) setSettled(true); });return () => {disposed = true;observer?.disconnect();cancelAnimationFrame(animationFrame);window.removeEventListener("resize", scheduleDraw);};- }, [setReady]);+ }, [setReady, setSettled]);++ useEffect(() => {+ if (settled) onSettled?.();+ }, [settled, onSettled]);return (<div ref={frameRef} className={styles.frame} role="img" aria-label="A giant Alook sculpture in an ASCII city, surrounded by buildings, a park, and streets.">diff --git a/src/web/src/components/typewriter-visual.dom.test.tsx b/src/web/src/components/typewriter-visual.dom.test.tsxindex c6958e039..a95a49528 100644--- a/src/web/src/components/typewriter-visual.dom.test.tsx+++ b/src/web/src/components/typewriter-visual.dom.test.tsx@@ -1,14 +1,38 @@import React from "react";import { renderToString } from "react-dom/server";-import { render, screen } from "@/test/react-dom-harness";-import { describe, expect, it, vi } from "vitest";+import { act, render, screen } from "@/test/react-dom-harness";+import { afterEach, describe, expect, it, vi } from "vitest";vi.mock("@gsap/react", () => ({ useGSAP: vi.fn() }));import { TypewriterVisual } from "./typewriter-visual";import { TYPEWRITER_CITY_ART } from "./typewriter-city-art-data";+const originalFonts = Object.getOwnPropertyDescriptor(document, "fonts");+afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ if (originalFonts) Object.defineProperty(document, "fonts", originalFonts);+ else Reflect.deleteProperty(document, "fonts");+});+describe("typewriter paper", () => {+ it("waits for the paper font and committed canvas before releasing the hero", async () => {+ let resolveFont!: () => void;+ const font = new Promise<void>((resolve) => { resolveFont = resolve; });+ Object.defineProperty(document, "fonts", { configurable: true, value: { load: () => font } });+ const drawImage = vi.fn();+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ drawImage, fillText: vi.fn() } as unknown as CanvasRenderingContext2D);+ vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });+ const settled = vi.fn();+ const { container } = render(<TypewriterVisual animateEntrance={false} onPaperSettled={settled} />);+ expect(settled).not.toHaveBeenCalled();+ await act(async () => { resolveFont(); await font; });+ expect(drawImage).toHaveBeenCalled();+ expect(container.querySelector("pre")?.className).toContain("rendered");+ expect(settled).toHaveBeenCalledTimes(1);+ });+it("announces the paper font in server HTML before hydration", () => {const html = renderToString(<TypewriterVisual animateEntrance={false} />);expect(html).toContain('rel="preload"');diff --git a/src/web/src/components/typewriter-visual.tsx b/src/web/src/components/typewriter-visual.tsxindex 19ebabdf6..4a560fec9 100644--- a/src/web/src/components/typewriter-visual.tsx+++ b/src/web/src/components/typewriter-visual.tsx@@ -26,6 +26,7 @@ interface TypewriterVisualProps {paper?: React.ReactNode;blobScale?: number;blobBottom?: string;+ onPaperSettled?: () => void;}export function TypewriterVisual({@@ -35,6 +36,7 @@ export function TypewriterVisual({paper,blobScale = 1,blobBottom,+ onPaperSettled,}: TypewriterVisualProps) {const containerRef = useRef<HTMLDivElement>(null);const handleMouseMove = useCallback(@@ -78,7 +80,7 @@ export function TypewriterVisual({const paperTrack = (<div className="tw-paper-track"><div className={`tw-paper${paper == null ? " tw-paper-city" : ""}`} style={animateEntrance ? undefined : { opacity: 1 }}>- {paper ?? <TypewriterCityArt />}+ {paper ?? <TypewriterCityArt onSettled={onPaperSettled} />}</div></div>);diff --git a/src/web/src/lib/community/chat-markdown.ts b/src/web/src/lib/community/chat-markdown.tsindex c391aa315..aef3600a8 100644--- a/src/web/src/lib/community/chat-markdown.ts+++ b/src/web/src/lib/community/chat-markdown.ts@@ -4,7 +4,8 @@ import remarkGfm from "remark-gfm"import remarkBreaks from "remark-breaks"import type { Root } from "mdast"import { formatHandle, type MentionCandidate, type MentionType } from "@alook/shared"-import { cjk, math } from "../streamdown-remark-plugins"+import { cjk } from "@streamdown/cjk"+import remarkMath from "remark-math"import { chatSyntaxPlugin, type MentionNode } from "./chat-syntax-plugin"export const CHAT_REMARK_PLUGINS: PluggableList = [remarkGfm, chatSyntaxPlugin, remarkBreaks]@@ -14,7 +15,7 @@ const processor = unified().use(cjk.remarkPluginsBefore).use(CHAT_REMARK_PLUGINS).use(cjk.remarkPluginsAfter)- .use([math.remarkPlugin])+ .use(remarkMath, { singleDollarTextMath: true }).freeze()function parsedMentions(content: string): MentionNode[] {diff --git a/src/web/src/lib/streamdown-plugins.test.ts b/src/web/src/lib/streamdown-plugins.test.tsnew file mode 100644index 000000000..8bcae19f8--- /dev/null+++ b/src/web/src/lib/streamdown-plugins.test.ts@@ -0,0 +1,72 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ create: vi.fn(),+ get: vi.fn(),+ render: vi.fn(),+ initialize: vi.fn(),+}))+vi.mock("@streamdown/mermaid", () => ({ createMermaidPlugin: mocks.create }))+vi.mock("./streamdown-remark-plugins", () => ({ cjk: {}, math: {} }))++beforeEach(() => {+ vi.resetModules()+ vi.clearAllMocks()+ mocks.create.mockImplementation(() => ({ getMermaid: mocks.get }))+ mocks.get.mockReturnValue({ render: mocks.render, initialize: mocks.initialize })+ mocks.render.mockResolvedValue({ svg: '<svg aria-label="Diagram" />' })+})++describe("deferred diagram engine", () => {+ it("loads on first render, retains the existing appearance, and reuses the engine", async () => {+ const { mermaid } = await import("./streamdown-plugins")+ const instance = mermaid.getMermaid()+ expect(mocks.create).not.toHaveBeenCalled()+ expect(await instance.render("one", "graph TD; A-->B")).toEqual({ svg: '<svg aria-label="Diagram" />' })+ expect(mocks.create).toHaveBeenCalledWith({ config: expect.objectContaining({+ theme: "base", fontFamily: "ui-sans-serif, system-ui, sans-serif",+ themeVariables: expect.objectContaining({ primaryColor: "#eceae6", primaryTextColor: "#2d2a26" }),+ }) })+ await instance.render("two", "graph TD; C-->D")+ expect(mocks.create).toHaveBeenCalledTimes(1)+ expect(mocks.render).toHaveBeenLastCalledWith("two", "graph TD; C-->D")+ })++ it("preserves initial and updated configuration and forwards rendering errors", async () => {+ const { mermaid } = await import("./streamdown-plugins")+ const instance = mermaid.getMermaid({ theme: "dark" })+ await instance.render("one", "graph TD; A-->B")+ expect(mocks.initialize).toHaveBeenLastCalledWith({ theme: "dark" })+ instance.initialize({ theme: "forest" })+ const error = new Error("invalid diagram")+ mocks.render.mockRejectedValueOnce(error)+ await expect(instance.render("bad", "invalid")).rejects.toBe(error)+ expect(mocks.initialize).toHaveBeenLastCalledWith({ theme: "forest" })+ await expect(instance.render("next", "graph TD; A-->B")).resolves.toHaveProperty("svg")+ })++ it("captures each concurrent render configuration and does not reinitialize repeated renders", async () => {+ const { mermaid } = await import("./streamdown-plugins")+ const seen: string[] = []+ let theme = "default"+ mocks.initialize.mockImplementation((config) => { theme = config.theme })+ mocks.render.mockImplementation(async () => { seen.push(theme); return { svg: "<svg />" } })+ const dark = mermaid.getMermaid({ theme: "dark" }).render("dark", "graph TD; A-->B")+ const forest = mermaid.getMermaid({ theme: "forest" }).render("forest", "graph TD; C-->D")+ await Promise.all([dark, forest])+ expect(seen).toEqual(["dark", "forest"])+ expect(mocks.initialize).toHaveBeenCalledTimes(2)+ await mermaid.getMermaid().render("again", "graph TD; E-->F")+ expect(mocks.initialize).toHaveBeenCalledTimes(2)+ })++ it("allows retry if engine initialization fails", async () => {+ const { mermaid } = await import("./streamdown-plugins")+ const error = new Error("engine unavailable")+ mocks.create.mockImplementationOnce(() => { throw error })+ const instance = mermaid.getMermaid()+ await expect(instance.render("one", "graph TD; A-->B")).rejects.toBe(error)+ await expect(instance.render("two", "graph TD; A-->B")).resolves.toHaveProperty("svg")+ expect(mocks.create).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/web/src/lib/streamdown-plugins.ts b/src/web/src/lib/streamdown-plugins.tsindex 3e0f00a1c..5ad91744c 100644--- a/src/web/src/lib/streamdown-plugins.ts+++ b/src/web/src/lib/streamdown-plugins.ts@@ -1,7 +1,7 @@-import { createMermaidPlugin } from "@streamdown/mermaid";+import type { DiagramPlugin, MermaidConfig, MermaidInstance, MermaidPluginOptions } from "@streamdown/mermaid";export { cjk, math } from "./streamdown-remark-plugins";-export const mermaid = createMermaidPlugin({+const options: MermaidPluginOptions = {config: {theme: "base",themeVariables: {@@ -24,4 +24,43 @@ export const mermaid = createMermaidPlugin({},fontFamily: "ui-sans-serif, system-ui, sans-serif",},-});+};++let engine: Promise<DiagramPlugin> | undefined;+let configuration: MermaidConfig | undefined;+let revision = 0;+let appliedRevision = -1;++const instance: MermaidInstance = {+ initialize(next) {+ configuration = next;+ revision += 1;+ },+ async render(id, source) {+ const renderConfiguration = configuration;+ const renderRevision = revision;+ engine ??= import("@streamdown/mermaid")+ .then(({ createMermaidPlugin }) => createMermaidPlugin(options))+ .catch((error: unknown) => {+ engine = undefined;+ throw error;+ });+ const plugin = await engine;+ const renderer = plugin.getMermaid();+ if (renderConfiguration && appliedRevision !== renderRevision) {+ renderer.initialize(renderConfiguration);+ appliedRevision = renderRevision;+ }+ return renderer.render(id, source);+ },+};++export const mermaid: DiagramPlugin = {+ name: "mermaid",+ type: "diagram",+ language: "mermaid",+ getMermaid(config) {+ if (config) instance.initialize(config);+ return instance;+ },+};