Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Chat: preview card for a published site in a bot's reply (#6260)

Milind Soni528e787c8135
diff --git a/server/wait-probes.test.ts b/server/wait-probes.test.ts
index 5367c2426a..c056ea9b25 100644
--- a/server/wait-probes.test.ts
+++ b/server/wait-probes.test.ts
@@ -161,6 +161,6 @@ describe("fetchPageText", () => {
expect(Date.now() - started).toBeLessThan(1000);
});
it("counts an answer that is not 2xx as a failed check", async () => {
- expect(await fetchPageText(`http://status.test:${port}/404`, test)).toEqual({ ok: false, refused: false, error: "The page answered 404." });
+ expect(await fetchPageText(`http://status.test:${port}/404`, test)).toEqual({ ok: false, refused: false, error: "The page answered 404.", status: 404 });
});
});
diff --git a/server/wait-probes.ts b/server/wait-probes.ts
index ec2a57495a..baa2aac118 100644
--- a/server/wait-probes.ts
+++ b/server/wait-probes.ts
@@ -177,7 +177,8 @@ export const PAGE_TIMEOUT_MS = 15_000;
export const PAGE_MAX_BYTES = 2 * 1024 * 1024;
export const PAGE_MAX_REDIRECTS = 3;
-type Failure = { ok: false; refused: boolean; error: string };
+/** `status`: the answer's status, when the page answered with an error. */
+type Failure = { ok: false; refused: boolean; error: string; status?: number };
export type PageResult = { ok: true; text: string } | Failure;
/** The 2xx answer a redirect chain ended on: its address, headers and at most `maxBytes` of its body. */
export type PublicPage = { ok: true; url: URL; headers: IncomingHttpHeaders; body: Buffer } | Failure;
@@ -282,7 +283,7 @@ export async function fetchPublicPage(rawUrl: string, options: PageFetchOptions
url = new URL(answer.location, url);
continue;
}
- if (answer.status < 200 || answer.status >= 300) return fail(`The page answered ${answer.status}.`);
+ if (answer.status < 200 || answer.status >= 300) return { ...fail(`The page answered ${answer.status}.`), status: answer.status };
return { ok: true, url, headers: answer.headers, body: answer.body };
}
} catch {
diff --git a/server/web-panel-framing.test.ts b/server/web-panel-framing.test.ts
index 337f0cab28..42fd5b4b82 100644
--- a/server/web-panel-framing.test.ts
+++ b/server/web-panel-framing.test.ts
@@ -79,6 +79,7 @@ describe("checkFraming", () => {
if (req.url === "/deny") res.writeHead(200, { "x-frame-options": "DENY" }).end("no");
else if (req.url === "/hop") res.writeHead(302, { location: "/deny" }).end();
else if (req.url === "/ok") res.writeHead(200).end("yes");
+ else if (req.url === "/team") res.writeHead(401, { "content-type": "text/html" }).end("<title>Login Redirect</title>");
else res.writeHead(404).end();
});
await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
@@ -94,6 +95,10 @@ describe("checkFraming", () => {
expect(await checkFraming(`http://panel.test:${port}/ok`, APP, test)).toBe("allowed");
});
+ it("says a page that answers 401 asks for a login", async () => {
+ expect(await checkFraming(`http://panel.test:${port}/team`, APP, test)).toBe("login");
+ });
+
it("can't tell from a redirect, which may lead to a sign-in page the person's browser never gets", async () => {
expect(await checkFraming(`http://panel.test:${port}/hop`, APP, test)).toBe("unknown");
});
diff --git a/server/web-panel-framing.ts b/server/web-panel-framing.ts
index 5068329b1e..90551da2d0 100644
--- a/server/web-panel-framing.ts
+++ b/server/web-panel-framing.ts
@@ -5,8 +5,8 @@ import type { IncomingHttpHeaders } from "node:http";
import { fetchPublicPage, type PageFetchOptions } from "./wait-probes.ts";
-/** `unknown` whenever this can't be sure. */
-export type Framing = "allowed" | "blocked" | "unknown";
+/** `login`: the page answered 401, so a frame would only show a sign-in. `unknown` whenever this can't be sure. */
+export type Framing = "allowed" | "blocked" | "login" | "unknown";
const SCHEME_SOURCE = /^[a-z][a-z0-9+.-]*:$/;
const HOST_SOURCE = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*)(?::(\d+|\*))?(\/[^?#]*)?$/;
@@ -92,8 +92,10 @@ export function framingOf(headers: IncomingHttpHeaders, pageUrl: string, appOrig
}
/** Never from this computer or a private network. This request carries none of the person's cookies, so a redirect or
- * an error answer may be a sign-in page their browser never gets: those say unknown. */
+ * an error answer may be a sign-in page their browser never gets: those say unknown. A 401 asks every visitor without
+ * a session, a frame included (Netlify's team login and password protection answer 401, 2026-11). */
export async function checkFraming(url: string, appOrigin: string, options: PageFetchOptions = {}): Promise<Framing> {
const page = await fetchPublicPage(url, { maxBytes: 1, maxRedirects: 0, timeoutMs: 8_000, ...options });
- return page.ok ? framingOf(page.headers, page.url.href, appOrigin) : "unknown";
+ if (!page.ok) return page.status === 401 ? "login" : "unknown";
+ return framingOf(page.headers, page.url.href, appOrigin);
}
diff --git a/src/App.tsx b/src/App.tsx
index df6aabf37e..65581f1c1c 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -84,6 +84,7 @@ import { useSessionEnded } from "@/lib/session-ended";
import { PairPage } from "./pair/PairPage";
import { WebPanelPage } from "@/components/WebPanelPage";
import { AppPreviewPanel } from "@/components/published-apps/AppPreviewPanel";
+import { refreshPublishedApps } from "@/lib/own-published-apps";
function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const { state, dispatch } = useStore();
@@ -91,6 +92,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const needsYou = needsYouVersion(state.bots, state.groups, state.notifications);
useTeamPeopleLoader(state.config, needsYou);
useInboxLoader(`${inboxVersion(state.bots) ?? ""}|${needsYou}`);
+ useEffect(() => { refreshPublishedApps(); }, []);
const inboxReady = useInboxReady();
const inboxShown = useInboxPanel().open && inboxReady;
// A Switch AI pick lands once its stopped turn's chat is idle, wherever the person is by then.
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index a67a10d044..32d341320a 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -72,7 +72,7 @@ import { useShowRunCard } from "@/lib/run-card-preferences";
import { useColorUserBubbles } from "@/lib/user-bubble-preference";
import { userBubbleStyle } from "@/lib/user-bubble-tone";
import { ToolActivity } from "./ToolActivity";
-import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { TemplateChatCard } from "./TemplateCard";
+import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { TemplateChatCard } from "./TemplateCard"; import { PublishedSiteCards } from "./published-apps/PublishedSiteCards";
import { ThreadRefText } from "./ThreadRefs"; import { WatchScreenButton } from "./WatchScreenButton";
import { optionsCardRow } from "./OptionsCardRow";
import { MessageBoundary } from "./MessageBoundary";
@@ -785,7 +785,7 @@ const MessagesList = memo(function MessagesList({
{newDay && <DaySeparator at={m.at} today={today} simple={simple} />}
{divider}
{m.automation && <AutomationCaption message={m} line={m.automation} botId={botId} />}{m.inbox && <InboxCaption message={m} />}
- {isLiveReply(m) ? <StreamingReplyContext value>{row}</StreamingReplyContext> : row}{m.inbox?.answers && <InboxAnswers message={m} />}{m.inbox && <InboxCardSlot threadId={threadId} messageId={m.id} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}{m.savedSteps && <SavedStepsChip botId={botId} message={m} />}
+ {isLiveReply(m) ? <StreamingReplyContext value>{row}</StreamingReplyContext> : row}<PublishedSiteCards message={m} />{m.inbox?.answers && <InboxAnswers message={m} />}{m.inbox && <InboxCardSlot threadId={threadId} messageId={m.id} />}{m.setupOffer && <SetupOffer botId={botId} threadId={threadId} message={m} transcript={transcript} />}{m.savedSteps && <SavedStepsChip botId={botId} message={m} />}
</div>
);
})}
diff --git a/src/components/published-apps/PublishedSiteCards.test.ts b/src/components/published-apps/PublishedSiteCards.test.ts
new file mode 100644
index 0000000000..eda12e2d66
--- /dev/null
+++ b/src/components/published-apps/PublishedSiteCards.test.ts
@@ -0,0 +1,223 @@
+// @vitest-environment happy-dom
+import { act, createElement, Fragment } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { PublishedApp } from "../../../shared/published-apps";
+import type { Message } from "@/state/store";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const fixture = vi.hoisted(() => ({
+ state: { computerOpen: false, settingsOpen: false, inspectorOpen: false, activityOpen: false, activeView: "chat" },
+ framing: "allowed",
+ listed: [] as unknown[],
+ api: vi.fn(),
+ opened: [] as string[],
+ dispatched: [] as unknown[],
+ withStore: true,
+}));
+vi.mock("@/state/store", () => ({ useStore: () => ({ state: fixture.state, dispatch: () => {} }) }));
+vi.mock("@/state/store-ref", () => ({ useOptionalStoreRef: () => (fixture.withStore ? { dispatch: (action: unknown) => fixture.dispatched.push(action), state: () => fixture.state } : null) }));
+vi.mock("@/state/api", () => ({ api: fixture.api }));
+vi.mock("@/lib/app-links", () => ({ openExternalLink: async (url: string) => { fixture.opened.push(url); } }));
+
+const { closeAppPreview } = await import("@/lib/app-preview");
+const { rememberPublishedApps, SITE_FRAME_SANDBOX } = await import("@/lib/published-apps");
+const { AppPreviewPanel } = await import("./AppPreviewPanel");
+const { PublishedSiteCards } = await import("./PublishedSiteCards");
+
+const SITE = "https://bright-bakery.netlify.app/";
+const PAGE = "https://abcdefghijklmnopqrstuvwxyz.mausbot.page/";
+const app = (id: string, url: string, title: string, fields: Partial<PublishedApp> = {}): PublishedApp =>
+ ({ id, source: "netlify", title, url, bot: { id: "mira", name: "Mira" }, publishedAt: 1, access: "public", canDelete: true, ...fields });
+const OWN = [
+ app("netlify-mira-bakery", SITE, "Bright Bakery"),
+ app("page-1", PAGE, "Opening hours", { source: "page", access: "link" }),
+ ...["one", "two", "three", "four"].map((name) => app(`netlify-mira-${name}`, `https://${name}.netlify.app/`, name)),
+];
+const reply = (text: string, fields: Partial<Message> = {}) => ({ id: "m1", role: "bot", kind: "text", text, at: 1, ...fields }) as Message;
+const tokens = (value: string | null) => (value ?? "").split(/\s+/).filter(Boolean).sort();
+
+let root: Root;
+let host: HTMLElement;
+beforeEach(() => {
+ fixture.api.mockReset();
+ fixture.api.mockImplementation(async (path: string) => (path.startsWith("/api/published-apps/framing") ? { framing: fixture.framing } : { apps: fixture.listed }));
+ fixture.framing = "allowed";
+ fixture.listed = OWN;
+ fixture.opened.length = 0;
+ fixture.dispatched.length = 0;
+ fixture.withStore = true;
+ rememberPublishedApps(OWN);
+ // happy-dom's observer never reports, so every card counts as on screen.
+ vi.stubGlobal("IntersectionObserver", undefined);
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => { act(() => { closeAppPreview(); root.unmount(); }); host.remove(); vi.useRealTimers(); vi.unstubAllGlobals(); });
+
+const show = (...messages: Message[]) => act(async () => root.render(createElement(Fragment, null, ...messages.map((message) => createElement(PublishedSiteCards, { key: message.id, message })))));
+const cards = () => [...host.querySelectorAll<HTMLElement>("[data-published-site]")];
+const sites = () => cards().map((card) => card.getAttribute("data-published-site"));
+const press = (card: HTMLElement, label: string) => act(() => [...card.querySelectorAll("button")].find((button) => button.textContent === label || button.getAttribute("aria-label") === label)!.click());
+const framingChecks = () => fixture.api.mock.calls.filter(([path]) => String(path).startsWith("/api/published-apps/framing"));
+const listReads = () => fixture.api.mock.calls.filter(([path]) => path === "/api/published-apps");
+
+describe("a published site's card in the chat", () => {
+ it("draws the person's own live site small, in the card picture's sandbox, never inside a button", async () => {
+ await show(reply(`Your bakery site is live: [bright-bakery](${SITE}). Anyone with the link can open it.`));
+ const [card] = cards();
+ expect(sites()).toEqual([SITE]);
+ expect(card!.textContent).toContain("Bright Bakery");
+ expect(card!.textContent).toContain("bright-bakery.netlify.app");
+ const frame = card!.querySelector("iframe")!;
+ expect(frame.getAttribute("src")).toBe(SITE);
+ for (const token of tokens(frame.getAttribute("sandbox"))) expect(tokens(SITE_FRAME_SANDBOX), token).toContain(token);
+ expect(frame.getAttribute("referrerpolicy")).toBe("no-referrer");
+ expect(frame.getAttribute("tabindex")).toBe("-1");
+ expect(frame.closest("button")).toBeNull();
+ expect(card!.querySelector("[data-app-preview-fallback]")).toBeNull();
+
+ press(card!, "Open in browser");
+ expect(fixture.opened).toEqual([SITE]);
+ expect(fixture.dispatched).toEqual([]);
+ });
+
+ it("opens the preview beside the chat from Open, the picture and the address", async () => {
+ const panel = document.createElement("div");
+ document.body.append(panel);
+ const side = createRoot(panel);
+ try {
+ await show(reply(`Here it is: ${SITE}`));
+ for (const open of ["Open", "Preview Bright Bakery"]) {
+ press(cards()[0]!, open);
+ await act(async () => side.render(createElement(AppPreviewPanel)));
+ expect(panel.querySelector("aside")?.getAttribute("data-app-preview"), open).toBe(SITE);
+ expect(panel.querySelector("h2")?.textContent).toBe("Bright Bakery");
+ act(() => closeAppPreview());
+ }
+ act(() => { cards()[0]!.querySelector("a")!.click(); });
+ await act(async () => side.render(createElement(AppPreviewPanel)));
+ expect(panel.querySelector("aside")?.getAttribute("data-app-preview")).toBe(SITE);
+ expect(fixture.dispatched).toContainEqual({ type: "toggleComputer", open: false });
+ expect(fixture.opened).toEqual([]);
+ } finally {
+ act(() => side.unmount());
+ panel.remove();
+ }
+ });
+
+ it("opens in the browser when there is no app around the message to show a preview in", async () => {
+ fixture.withStore = false;
+ await show(reply(`Here it is: ${SITE}`));
+ press(cards()[0]!, "Open");
+ expect(fixture.opened).toEqual([SITE]);
+ });
+
+ it("shows the login line and no frame for a site that asks for a login", async () => {
+ fixture.framing = "login";
+ await show(reply(`Published at ${SITE}`));
+ const card = cards()[0]!;
+ expect(card.querySelector("iframe")).toBeNull();
+ expect(card.querySelector("[data-app-preview-fallback]")?.textContent).toBe("This site asks for a Netlify login. Open it in your browser instead.");
+ expect(card.textContent).toContain("Open in browser");
+
+ act(() => root.unmount());
+ root = createRoot(host);
+ fixture.api.mockClear();
+ rememberPublishedApps([app("netlify-mira-s1", SITE, "Bakery order page", { access: "netlify-team" })]);
+ await show(reply(`Published at ${SITE}menu`));
+ expect(cards()[0]!.querySelector("iframe")).toBeNull();
+ expect(cards()[0]!.textContent).toContain("Bakery order page");
+ expect(cards()[0]!.querySelector("[data-app-preview-fallback]")).not.toBeNull();
+ expect(framingChecks()).toEqual([]);
+ });
+
+ it("draws no card for a Netlify site that is not the person's own, and asks for the list once about it", async () => {
+ const lure = "https://paypa1-account-verify.netlify.app/login";
+ await show(reply(`Please confirm your details at ${lure}`));
+ expect(cards()).toEqual([]);
+ expect(host.querySelector("iframe")).toBeNull();
+ await act(async () => { await Promise.resolve(); });
+ expect(listReads().length).toBeLessThanOrEqual(1);
+ await show(reply(`Please confirm your details at ${lure} now`));
+ expect(cards()).toEqual([]);
+ expect(framingChecks()).toEqual([]);
+ });
+
+ it("draws a card once the list holds a site a bot has just published", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
+ const fresh = "https://fresh-launch.netlify.app/";
+ fixture.listed = [...OWN, app("netlify-mira-fresh", fresh, "Fresh launch")];
+ await show(reply(`It's live: ${fresh}`));
+ expect(cards()).toEqual([]);
+ await act(async () => { await vi.advanceTimersByTimeAsync(16_000); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(listReads()).toHaveLength(1);
+ expect(sites()).toEqual([fresh]);
+ expect(cards()[0]!.textContent).toContain("Fresh launch");
+ });
+
+ it("shows no card for an address that is not https, not a published site, in code, or the app itself", async () => {
+ rememberPublishedApps([...OWN, app("netlify-local", `${window.location.origin}/`, "Local")]);
+ for (const text of ["Published at http://bright-bakery.netlify.app/", "See https://example.com/menu", "Run `curl https://bright-bakery.netlify.app/`",
+ "```\nhttps://bright-bakery.netlify.app/\n```", `Open ${window.location.origin}/`, "https://user:[email protected]/", "No link here."]) {
+ await show(reply(text));
+ expect(cards(), text).toEqual([]);
+ }
+ expect(host.querySelector("iframe")).toBeNull();
+ });
+
+ it("shows nothing on a person's message, a reply still streaming, or a published page's own card", async () => {
+ await show(reply(`Can you change ${SITE}?`, { role: "user" }));
+ expect(cards()).toEqual([]);
+ await show(reply(`Live at ${SITE}`, { id: "live:t1:1" }));
+ expect(cards()).toEqual([]);
+ await show(reply(`Published ${PAGE}`, { publishedPage: { pageId: "abcdefghijklmnopqrstuvwxyz", title: "Opening hours", url: PAGE, state: "live" } as Message["publishedPage"] }));
+ expect(cards()).toEqual([]);
+ });
+
+ it("gives each site one card, in order, and a long list of links three", async () => {
+ await show(reply(`Live: ${SITE} (also [the menu](${SITE}menu).) The page: ${PAGE}`));
+ expect(sites()).toEqual([SITE, PAGE]);
+ await show(reply(["one", "two", "three", "four"].map((name) => `https://${name}.netlify.app/`).join("\n")));
+ expect(sites()).toEqual(["https://one.netlify.app/", "https://two.netlify.app/", "https://three.netlify.app/"]);
+ });
+
+ it("draws a site only on the newest reply that links it", async () => {
+ const older = reply(`First version: ${SITE}`, { id: "m1", at: 1 }), newer = reply(`Updated: ${SITE} and ${PAGE}`, { id: "m2", at: 2 });
+ await show(older, newer);
+ expect(sites()).toEqual([SITE, PAGE]);
+ expect(host.querySelectorAll("iframe")).toHaveLength(2);
+ await show(older);
+ expect(sites()).toEqual([SITE]);
+ });
+
+ it("drops the frame while the card is well off screen, and draws it again when it is back", async () => {
+ const watchers: Array<(entries: Array<{ isIntersecting: boolean }>) => void> = [];
+ vi.stubGlobal("IntersectionObserver", class {
+ constructor(callback: (entries: Array<{ isIntersecting: boolean }>) => void) { watchers.push(callback); }
+ observe() {}
+ disconnect() {}
+ });
+ await show(reply(`Live: ${SITE}`));
+ expect(host.querySelector("iframe")).toBeNull();
+ const see = (isIntersecting: boolean) => act(() => { for (const watch of watchers) watch([{ isIntersecting }]); });
+ see(true);
+ expect(host.querySelector("iframe")?.getAttribute("src")).toBe(SITE);
+ see(false);
+ expect(host.querySelector("iframe")).toBeNull();
+ expect(host.querySelector("[data-app-thumb]")?.getAttribute("data-app-thumb")).toBe("tile");
+ see(true);
+ expect(host.querySelector("iframe")?.getAttribute("src")).toBe(SITE);
+ expect(framingChecks()).toHaveLength(1);
+ });
+
+ it("is full width on a phone and never wider than a reply on a wide screen", async () => {
+ await show(reply(`Live: ${SITE}`));
+ expect(cards()[0]!.className).toContain("w-full");
+ expect(cards()[0]!.className).toContain("max-md:max-w-none");
+ });
+});
diff --git a/src/components/published-apps/PublishedSiteCards.tsx b/src/components/published-apps/PublishedSiteCards.tsx
new file mode 100644
index 0000000000..e7f381c61c
--- /dev/null
+++ b/src/components/published-apps/PublishedSiteCards.tsx
@@ -0,0 +1,95 @@
+import { useEffect, useMemo, useSyncExternalStore } from "react";
+import { ArrowUpRight, Eye } from "lucide-react";
+
+import { openExternalLink } from "@/lib/app-links";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { askAboutSite, useKnownPublishedApps } from "@/lib/own-published-apps";
+import { showAppBesideChat } from "@/lib/page-open";
+import { publishedSiteLinks, type SiteCardLink } from "@/lib/published-site-links";
+import { isLiveReply } from "@/state/live-reply";
+import type { Message } from "@/state/store";
+import { useOptionalStoreRef } from "@/state/store-ref";
+import { ASK_CHIP, ASK_CHIP_IDLE } from "../AskCard";
+import { SiteThumb } from "./SiteThumb";
+
+/** Which shown message links each site, so only the newest of them draws it. */
+const claims = new Map<string, Map<string, number>>();
+const claimListeners = new Set<() => void>();
+let claimsVersion = 0;
+
+function changeClaims(change: () => void): void {
+ change();
+ claimsVersion += 1;
+ for (const listener of claimListeners) listener();
+}
+
+function newestClaim(appId: string): string | undefined {
+ let best: [string, number] | undefined;
+ for (const [messageId, at] of claims.get(appId) ?? []) {
+ if (!best || at > best[1] || (at === best[1] && messageId > best[0])) best = [messageId, at];
+ }
+ return best?.[0];
+}
+
+function useNewestFor(links: readonly SiteCardLink[], messageId: string, at: number): SiteCardLink[] {
+ const sites = links.map((link) => link.appId).join("\n");
+ useEffect(() => {
+ const ids = sites ? sites.split("\n") : [];
+ if (!ids.length) return;
+ changeClaims(() => { for (const id of ids) { if (!claims.has(id)) claims.set(id, new Map()); claims.get(id)!.set(messageId, at); } });
+ return () => changeClaims(() => { for (const id of ids) { claims.get(id)?.delete(messageId); if (claims.get(id)?.size === 0) claims.delete(id); } });
+ }, [sites, messageId, at]);
+ useSyncExternalStore((listener) => { claimListeners.add(listener); return () => { claimListeners.delete(listener); }; }, () => claimsVersion, () => claimsVersion);
+ return links.filter((link) => newestClaim(link.appId) === messageId);
+}
+
+/** One card under a bot's reply for each of the viewer's own published sites it links to (their Published apps list),
+ * on the newest reply that links it: the site drawn small, its name and address, Open (the preview beside the chat,
+ * full screen on a phone) and Open in browser. Any other site stays a plain link. Nothing while the reply streams, and
+ * nothing on a published page's or a template's own card. */
+export function PublishedSiteCards({ message }: { message: Message }) {
+ const apps = useKnownPublishedApps();
+ const done = message.role === "bot" && message.kind === "text" && !message.publishedPage && !message.template && !isLiveReply(message);
+ const text = done ? message.text ?? "" : "";
+ const origin = typeof window === "undefined" ? undefined : window.location?.origin;
+ const { cards, unknown } = useMemo(() => (text && origin ? publishedSiteLinks(text, origin, apps) : { cards: [], unknown: [] }), [text, origin, apps]);
+ useEffect(() => { for (const href of unknown) askAboutSite(href); }, [unknown]);
+ const shown = useNewestFor(cards, message.id, message.at ?? 0);
+ if (shown.length === 0) return null;
+ return (
+ <div data-published-sites="" className="flex w-full flex-col items-start gap-2">
+ {shown.map((link) => <PublishedSiteCard key={link.appId} link={link} />)}
+ </div>
+ );
+}
+
+function PublishedSiteCard({ link }: { link: SiteCardLink }) {
+ const store = useOptionalStoreRef();
+ const host = new URL(link.url).host;
+ const preview = () => {
+ if (store) showAppBesideChat(store.dispatch, link);
+ else void openExternalLink(link.url).catch(() => undefined);
+ };
+ const browser = () => void openExternalLink(link.url).catch(() => undefined);
+ return (
+ <div role="group" aria-label={link.title} data-published-site={link.url} className="w-full max-w-md overflow-hidden rounded-xl border border-hairline/40 bg-panel text-sm max-md:max-w-none">
+ <div className="relative border-b border-hairline/30">
+ <SiteThumb url={link.url} title={link.title} loginOnly={link.loginOnly === true} sayLogin unloadOffScreen />
+ <button type="button" onClick={preview} aria-label={t("publishedApps.card.previewOf", { name: link.title })}
+ className="absolute inset-0 focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus" />
+ </div>
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5 px-3 py-2.5">
+ <div className="min-w-0 flex-1 basis-40">
+ {link.title !== host && <p dir="auto" className="truncate font-medium text-ink" title={link.title}>{link.title}</p>}
+ <a href={link.url} dir="ltr" onClick={(event) => { event.preventDefault(); preview(); }}
+ className={cn("block truncate text-[13px] hover:underline", link.title === host ? "font-medium text-ink" : "text-ink-secondary")}>{host}</a>
+ </div>
+ <div className="flex shrink-0 gap-1.5">
+ <button type="button" onClick={preview} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}><Eye size={14} aria-hidden="true" />{t("chat.page.open")}</button>
+ <button type="button" onClick={browser} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}><ArrowUpRight size={14} aria-hidden="true" />{t("webPanels.page.openInBrowser")}</button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/published-apps/SiteFrame.tsx b/src/components/published-apps/SiteFrame.tsx
index e727017614..e4ea9ad2fb 100644
--- a/src/components/published-apps/SiteFrame.tsx
+++ b/src/components/published-apps/SiteFrame.tsx
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { openExternalLink } from "@/lib/app-links";
import { t } from "@/lib/i18n";
import { showable, SITE_FRAME_ALLOW, SITE_FRAME_SANDBOX } from "@/lib/published-apps";
-import { useFramingRefused } from "./use-framing";
+import { useFramingBlock } from "./use-framing";
const LOAD_TIMEOUT_MS = 10_000;
@@ -11,7 +11,7 @@ const LOAD_TIMEOUT_MS = 10_000;
* never loads, or is not a plain web address), a line saying so and Open in browser. */
export function SiteFrame({ url, title, loginOnly = false, attempt }: { url: string; title: string; loginOnly?: boolean; attempt: number }) {
const canFrame = showable(url, window.location.origin) && !loginOnly;
- const refused = useFramingRefused(canFrame ? url : null, attempt);
+ const block = useFramingBlock(canFrame ? url : null, attempt);
const [timedOut, setTimedOut] = useState(false);
const [loaded, setLoaded] = useState(false);
@@ -22,11 +22,11 @@ export function SiteFrame({ url, title, loginOnly = false, attempt }: { url: str
return () => clearTimeout(timer);
}, [url, attempt]);
- if (!canFrame || refused || (timedOut && !loaded)) {
+ if (!canFrame || block || (timedOut && !loaded)) {
return (
<div data-app-preview-fallback="" className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-6 text-center">
<p className="text-[14px] font-medium text-ink">{t("publishedApps.preview.cantShow")}</p>
- <p className="max-w-sm text-[13px] text-ink-secondary">{t(loginOnly ? "publishedApps.preview.loginBody" : "publishedApps.preview.cantShowBody")}</p>
+ <p className="max-w-sm text-[13px] text-ink-secondary">{t(loginOnly || block === "login" ? "publishedApps.preview.loginBody" : "publishedApps.preview.cantShowBody")}</p>
<button type="button" className="ui-button ui-button-primary" onClick={() => void openExternalLink(url).catch(() => undefined)}>{t("webPanels.page.openInBrowser")}</button>
</div>
);
diff --git a/src/components/published-apps/SiteThumb.tsx b/src/components/published-apps/SiteThumb.tsx
index 0563777cb1..aea2acd46a 100644
--- a/src/components/published-apps/SiteThumb.tsx
+++ b/src/components/published-apps/SiteThumb.tsx
@@ -1,32 +1,46 @@
import { useEffect, useRef, useState } from "react";
+import { t } from "@/lib/i18n";
import { appInitial, showable, SITE_FRAME_ALLOW, SITE_THUMB_SANDBOX } from "@/lib/published-apps";
-import { useFramingRefused } from "./use-framing";
+import { useFramingBlock } from "./use-framing";
const SITE_WIDTH = 1280, SITE_HEIGHT = 800;
const LOAD_TIMEOUT_MS = 12_000;
/** A card's picture: the live site drawn small, loaded only once the card is on screen and never taking a click or
- * the keyboard; until it has loaded, and whenever it can't be shown, a plain tile with the app's initial. */
-export function SiteThumb({ url, title, loginOnly }: { url: string; title: string; loginOnly: boolean }) {
+ * the keyboard; until it has loaded, and whenever it can't be shown, a plain tile with the app's initial. With
+ * `sayLogin`, a site that asks for a login gets that line instead of the initial. With `unloadOffScreen`, the site is
+ * dropped while the card is well off screen and drawn again when it comes back. */
+export function SiteThumb({ url, title, loginOnly, sayLogin = false, unloadOffScreen = false }: { url: string; title: string; loginOnly: boolean; sayLogin?: boolean; unloadOffScreen?: boolean }) {
const box = useRef<HTMLDivElement>(null);
const [onScreen, setOnScreen] = useState(false);
+ const [seen, setSeen] = useState(false);
const [scale, setScale] = useState(0.25);
const [loaded, setLoaded] = useState(false);
const [gaveUp, setGaveUp] = useState(false);
const canFrame = showable(url, window.location.origin) && !loginOnly;
- const refused = useFramingRefused(canFrame && onScreen ? url : null);
+ const block = useFramingBlock(canFrame && seen ? url : null);
+ const refused = block !== null;
useEffect(() => {
const element = box.current;
if (!element) return;
const size = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => setScale(element.clientWidth / SITE_WIDTH));
size?.observe(element);
- if (typeof IntersectionObserver === "undefined") { setOnScreen(true); return () => size?.disconnect(); }
- const seen = new IntersectionObserver((entries) => { if (entries.some((entry) => entry.isIntersecting)) { setOnScreen(true); seen.disconnect(); } }, { rootMargin: "200px" });
- seen.observe(element);
- return () => { size?.disconnect(); seen.disconnect(); };
- }, []);
+ if (typeof IntersectionObserver === "undefined") { setOnScreen(true); setSeen(true); return () => size?.disconnect(); }
+ const watch = new IntersectionObserver((entries) => {
+ if (entries.at(-1)?.isIntersecting) {
+ setOnScreen(true);
+ setSeen(true);
+ if (!unloadOffScreen) watch.disconnect();
+ } else if (unloadOffScreen) {
+ setOnScreen(false);
+ setLoaded(false);
+ }
+ }, { rootMargin: unloadOffScreen ? "600px" : "200px" });
+ watch.observe(element);
+ return () => { size?.disconnect(); watch.disconnect(); };
+ }, [unloadOffScreen]);
const framed = canFrame && onScreen && !refused && !gaveUp;
useEffect(() => {
@@ -35,9 +49,12 @@ export function SiteThumb({ url, title, loginOnly }: { url: string; title: strin
return () => clearTimeout(timer);
}, [framed, loaded]);
+ const login = sayLogin && (loginOnly || block === "login");
return (
- <div ref={box} data-app-thumb={framed && loaded ? "live" : "tile"} className="relative aspect-[16/10] w-full overflow-hidden bg-inset">
- <div aria-hidden="true" className="absolute inset-0 flex items-center justify-center text-[44px] font-semibold text-ink-tertiary">{appInitial(title)}</div>
+ <div ref={box} data-app-thumb={login ? "login" : framed && loaded ? "live" : "tile"} className="relative aspect-[16/10] w-full overflow-hidden bg-inset">
+ {login
+ ? <p data-app-preview-fallback="" className="absolute inset-0 flex items-center justify-center p-4 text-center text-[13px] text-ink-secondary">{t("publishedApps.preview.loginBody")}</p>
+ : <div aria-hidden="true" className="absolute inset-0 flex items-center justify-center text-[44px] font-semibold text-ink-tertiary">{appInitial(title)}</div>}
{framed && (
<iframe
src={url}
diff --git a/src/components/published-apps/preview.security.test.ts b/src/components/published-apps/preview.security.test.ts
index 79f0dfa2ac..98e4983ef3 100644
--- a/src/components/published-apps/preview.security.test.ts
+++ b/src/components/published-apps/preview.security.test.ts
@@ -94,7 +94,7 @@ describe("the sandbox a published site runs in", () => {
expect(host.querySelector("iframe")).not.toBeNull();
expect(listen.mock.calls.filter(([type]) => type === "message")).toEqual([]);
listen.mockRestore();
- for (const file of ["SiteFrame.tsx", "SiteThumb.tsx", "AppPreviewPanel.tsx", "use-framing.ts"]) {
+ for (const file of ["SiteFrame.tsx", "SiteThumb.tsx", "AppPreviewPanel.tsx", "use-framing.ts", "PublishedSiteCards.tsx"]) {
const text = source(`src/components/published-apps/${file}`);
for (const bridge of ["postMessage", "contentWindow", "contentDocument", "window.ogb", "srcDoc", "mausbot.", "<webview"]) expect(text, `${file}: ${bridge}`).not.toContain(bridge);
}
@@ -135,6 +135,13 @@ describe("a site that can't be shown in the preview", () => {
expect(fixture.api).not.toHaveBeenCalled();
});
+ it("is not framed when the check says it answers with a login", async () => {
+ fixture.api.mockResolvedValue({ framing: "login" });
+ await frame({ url: SITE });
+ expect(host.querySelector("iframe")).toBeNull();
+ expect(host.textContent).toContain("This site asks for a Netlify login. Open it in your browser instead.");
+ });
+
it("falls back when it never loads, and stays when it did", async () => {
vi.useFakeTimers();
await frame({ url: SITE });
diff --git a/src/components/published-apps/use-framing.ts b/src/components/published-apps/use-framing.ts
index 9c0f72f443..7486bec93a 100644
--- a/src/components/published-apps/use-framing.ts
+++ b/src/components/published-apps/use-framing.ts
@@ -2,16 +2,19 @@ import { useEffect, useState } from "react";
import { api } from "@/state/api";
-/** Whether the site refuses to be framed by this app, as its own headers say: the browser fires `load` on a frame it
- * refused, so nothing in the page can tell. Unknown (still asking, offline, not allowed to ask) reads as not refused. */
-export function useFramingRefused(url: string | null, attempt = 0): boolean {
- const [refused, setRefused] = useState<string | null>(null);
+export type FramingBlock = "blocked" | "login";
+
+/** Why the site can't be shown in a frame here, as its own answer says: its headers refuse this app (the browser fires
+ * `load` on a frame it refused, so nothing in the page can tell), or it asks for a login. Unknown (still asking,
+ * offline, not allowed to ask) reads as nothing in the way. */
+export function useFramingBlock(url: string | null, attempt = 0): FramingBlock | null {
+ const [seen, setSeen] = useState<{ url: string; block: FramingBlock } | null>(null);
useEffect(() => {
if (!url) return;
const check = new AbortController();
api<{ framing?: string }>(`/api/published-apps/framing?url=${encodeURIComponent(url)}&origin=${encodeURIComponent(window.location.origin)}`, { background: true, signal: check.signal })
- .then(({ framing }) => { if (!check.signal.aborted) setRefused(framing === "blocked" ? url : null); }, () => undefined);
+ .then(({ framing }) => { if (!check.signal.aborted) setSeen(framing === "blocked" || framing === "login" ? { url, block: framing } : null); }, () => undefined);
return () => check.abort();
}, [url, attempt]);
- return url !== null && refused === url;
+ return url !== null && seen?.url === url ? seen.block : null;
}
diff --git a/src/lib/own-published-apps.ts b/src/lib/own-published-apps.ts
new file mode 100644
index 0000000000..be8bb5522f
--- /dev/null
+++ b/src/lib/own-published-apps.ts
@@ -0,0 +1,38 @@
+import { useSyncExternalStore } from "react";
+
+import type { PublishedApp, PublishedAppsList } from "../../shared/published-apps";
+import { api } from "@/state/api";
+import { knownPublishedApps, onPublishedAppsChange, rememberPublishedApps } from "./published-apps";
+
+/** The list is read at most this often; a request inside that time waits for its end. */
+const REFRESH_EVERY_MS = 15_000;
+let loading = false, loadedAt = 0, later: ReturnType<typeof setTimeout> | null = null;
+const asked = new Set<string>();
+
+async function load(): Promise<void> {
+ loading = true;
+ const list = await Promise.resolve().then(() => api<PublishedAppsList>("/api/published-apps", { background: true })).catch(() => null);
+ if (Array.isArray(list?.apps)) rememberPublishedApps(list.apps);
+ loading = false;
+ loadedAt = Date.now();
+}
+
+/** Reads the viewer's Published apps list again, soon: now, or once the last read is old enough. */
+export function refreshPublishedApps(): void {
+ if (loading || later) return;
+ const wait = loadedAt + REFRESH_EVERY_MS - Date.now();
+ if (wait <= 0) { void load(); return; }
+ later = setTimeout(() => { later = null; void load(); }, wait);
+}
+
+/** A reply linked a site the list doesn't hold, perhaps one a bot has just published: the list is read again, once
+ * for each such link, so a link to someone else's site never keeps asking. */
+export function askAboutSite(href: string): void {
+ if (asked.has(href)) return;
+ asked.add(href);
+ refreshPublishedApps();
+}
+
+export function useKnownPublishedApps(): readonly PublishedApp[] {
+ return useSyncExternalStore(onPublishedAppsChange, knownPublishedApps, knownPublishedApps);
+}
diff --git a/src/lib/published-apps.ts b/src/lib/published-apps.ts
index 4a700da7d3..e20abc4fd7 100644
--- a/src/lib/published-apps.ts
+++ b/src/lib/published-apps.ts
@@ -24,10 +24,22 @@ export function appInitial(title: string): string {
}
let known: readonly PublishedApp[] = [];
+const listeners = new Set<() => void>();
-/** The list the Published apps page last loaded: a link to one of these opens beside the chat. */
+/** The viewer's Published apps list as last loaded (at startup, by the Published apps page, or when a reply links a
+ * site it doesn't hold yet): a link to one of these opens beside the chat, and a reply gets its preview card. */
export function rememberPublishedApps(apps: readonly PublishedApp[]): void {
known = apps;
+ for (const listener of listeners) listener();
+}
+
+export function knownPublishedApps(): readonly PublishedApp[] {
+ return known;
+}
+
+export function onPublishedAppsChange(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
}
/** The app in the loaded list that this address is inside. */
diff --git a/src/lib/published-site-links.ts b/src/lib/published-site-links.ts
new file mode 100644
index 0000000000..104bb65eb9
--- /dev/null
+++ b/src/lib/published-site-links.ts
@@ -0,0 +1,47 @@
+import { isNetlifySiteUrl, type PublishedApp } from "../../shared/published-apps";
+import type { AppPreview } from "./app-preview";
+import { isPublishedPageUrl } from "./page-open";
+import { showable } from "./published-apps";
+
+/** A message shows at most this many sites, so a list of links stays a list. */
+export const SITE_CARDS_MAX = 3;
+
+const CODE = /```[\s\S]*?(?:```|$)|`[^`\n]*`/g;
+const HTTPS_URL = /https:\/\/[^\s<>()[\]{}"'`|\\^]+/g;
+const TRAILING = /[.,;:!?*_~]+$/;
+
+export interface SiteCardLink extends AppPreview {
+ /** The app in the viewer's Published apps list. */
+ appId: string;
+}
+
+function appAt(href: URL, apps: readonly PublishedApp[]): PublishedApp | undefined {
+ return apps.find((app) => {
+ if (!app.url || app.status) return false;
+ let base: URL;
+ try { base = new URL(app.url); } catch { return false; }
+ return href.origin === base.origin && href.pathname.startsWith(base.pathname);
+ });
+}
+
+/** What a message links to among the sites bots put online, in order, never inside code and never the app's own
+ * origin: `cards`, once each, are https sites in the viewer's own Published apps list; `unknown` are Netlify sites and
+ * published pages the list doesn't hold (someone else's, or not listed yet), which stay plain links. */
+export function publishedSiteLinks(text: string, appOrigin: string, apps: readonly PublishedApp[]): { cards: SiteCardLink[]; unknown: string[] } {
+ const cards: SiteCardLink[] = [];
+ const unknown: string[] = [];
+ for (const [raw] of text.replace(CODE, " ").matchAll(HTTPS_URL)) {
+ const href = raw.replace(TRAILING, "");
+ let url: URL;
+ try { url = new URL(href); } catch { continue; }
+ if (!showable(href, appOrigin)) continue;
+ const app = appAt(url, apps);
+ if (!app) {
+ if ((isNetlifySiteUrl(href) || isPublishedPageUrl(href)) && !unknown.includes(href)) unknown.push(href);
+ continue;
+ }
+ if (cards.length === SITE_CARDS_MAX || cards.some((card) => card.appId === app.id)) continue;
+ cards.push({ appId: app.id, url: href, title: app.title, ...(app.access === "netlify-team" ? { loginOnly: true } : {}) });
+ }
+ return { cards, unknown };
+}