Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ import {
useBuddyChatShortcuts,
useBuddyPage,
useBuddyQueuedRunCount,
useBuddyWindowInView,
useBuddyHermesControls,
} from "../lazurio/BuddySurface";
import { BuddyPageChip } from "../lazurio/BuddySurfacePageChip";
Expand Down Expand Up @@ -605,6 +606,7 @@ export default function ChatView(props: ChatViewProps) {
const buddySurface = useBuddyHermesControls(environmentId);
// The page Buddy is asked from travels with the person's next message (buddySurfacePage.ts).
const buddyPage = useBuddyPage(environmentId);
const buddyInView = useBuddyWindowInView(environmentId);
const environmentSettings = useEnvironmentSettings(environmentId);
const settings = buddySurface
? { ...environmentSettings, followUpBehavior: "steer" as const }
Expand Down Expand Up @@ -4157,7 +4159,7 @@ export default function ChatView(props: ChatViewProps) {
onConfirm={onConfirmRevertStable}
/>
{embedded ? null : <LinkPullRequestDialogHost />}
<ThreadVisitWatermark threadRef={routeThreadRef} />
{buddyInView ? <ThreadVisitWatermark threadRef={routeThreadRef} /> : null}
<ExpandedImageDialogHost threadKey={routeThreadKey} />
</div>
);
Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/lazurio/BuddySurface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import { pageRecordOf } from "./buddySurfacePage";
import { useLinkedUnlistedProjectIds } from "./unlistedRows";
import { BUDDY_WORKING_ROW, buddyConversationRows, buddyFailureOf } from "./buddySurfaceTimeline";
import { prefersCzech } from "./threadTabs";
import { buddyHostOfWindow, buddyWindowInView } from "./buddySurfaceFrame";
import { useBuddyFrame } from "./useBuddyFrame";

type BuddyConfig = { readonly lazurioBuddy?: true; readonly lazurioBuddyOrigin?: string } | null;
Expand Down Expand Up @@ -90,6 +91,16 @@ export function useBuddyHermesControls(environmentId?: string): boolean {
return useBuddySurfaceMode(environmentId) === true && config?.lazurioBuddy === true;
}

/**
* Whether the thread view counts as the person looking: not in Buddy's hidden window. A page a host
* of the bubble frames waits for the host's word from its first render, before the config is known.
*/
export function useBuddyWindowInView(environmentId: string): boolean {
const framed = buddyHostOfWindow(window) !== null;
const { shown, context } = useBuddyFrame(useBuddySurfaceMode(environmentId) === true || framed);
return buddyWindowInView(framed, shown, context !== null);
}

/** Buddy's surface, read outside React when a command runs: false until the config is known. */
export const isBuddySurfaceNow = (): boolean =>
isBuddySurfaceConfig(appAtomRegistry.get(primaryServerConfigAtom));
Expand Down
71 changes: 69 additions & 2 deletions apps/web/src/lazurio/buddySurfaceFrame.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import { describe, expect, it } from "vite-plus/test";

import { startBuddyFrame } from "./buddySurfaceFrame";
import { buddyHostOfWindow, buddyWindowInView, startBuddyFrame } from "./buddySurfaceFrame";

const HOST = "https://launchpad.example-person.lazurio.io";
// What the host sends after the frame's ready, about its own Environment.
const personalContext = {
type: "lazurio.buddy.context",
v: 1,
lang: "cs",
theme: "light",
environment: { id: "example-person", kind: "personal", name: "Osobní" },
organization: null,
app: null,
page: { path: "/" },
guide: null,
};

/** A frame's window as far as the frame uses it: its parent, its ancestors and its listeners. */
function frameWindow(options: { readonly host?: string; readonly openMenu?: boolean } = {}) {
Expand Down Expand Up @@ -33,7 +45,9 @@ function frameWindow(options: { readonly host?: string; readonly openMenu?: bool
shiftKey: false,
...overrides,
});
return { win: win as unknown as Window, posted, key };
const receive = (data: unknown, origin = options.host ?? HOST, source: unknown = parent) =>
listeners.get("message")?.({ data, origin, source });
return { win: win as unknown as Window, posted, key, receive };
}

const layouts = (posted: ReadonlyArray<{ readonly message: unknown }>) =>
Expand Down Expand Up @@ -69,6 +83,59 @@ describe("Buddy's frame", () => {
expect(layouts(posted)).toEqual([]);
});

it("counts its thread as seen only once the host shows the window, also when loaded anew while hidden", () => {
const { win, receive } = frameWindow();
const frame = startBuddyFrame(win);
const inView = () =>
buddyWindowInView(frame.hostOrigin !== null, frame.shown(), frame.context() !== null);
// A frame loaded anew behind a closed window: until the host answers, an unread answer stays
// unread.
expect(frame.shown()).toBeNull();
expect(inView()).toBe(false);
// The host answers its ready: hidden first, then the context.
receive({ type: "lazurio.buddy.shown", v: 1, shown: false });
receive(personalContext);
expect(inView()).toBe(false);
// Only the parent on the host's origin says it is shown.
receive({ type: "lazurio.buddy.shown", v: 1, shown: true }, "https://example.com");
receive({ type: "lazurio.buddy.shown", v: 1, shown: true }, HOST, {});
expect(inView()).toBe(false);
receive({ type: "lazurio.buddy.shown", v: 1, shown: true });
expect(inView()).toBe(true);
// Outside a host's frame the thread counts as seen, as before.
expect(buddyWindowInView(false, null, false)).toBe(true);
});

it("counts nothing in a host's frame before the config is known, then only once the host shows it", () => {
// Loaded anew at Buddy's thread behind a closed window; the config is still loading, so no
// frame has started yet. The window alone says a host frames it.
const { win, receive, posted } = frameWindow();
const framed = buddyHostOfWindow(win) !== null;
expect(framed).toBe(true);
expect(posted).toEqual([]);
expect(buddyWindowInView(framed, null, false)).toBe(false);
// The config arrives and the frame starts; the host answers its ready, hidden.
const frame = startBuddyFrame(win);
const inView = () => buddyWindowInView(framed, frame.shown(), frame.context() !== null);
receive({ type: "lazurio.buddy.shown", v: 1, shown: false });
receive(personalContext);
expect(inView()).toBe(false);
receive({ type: "lazurio.buddy.shown", v: 1, shown: true });
expect(inView()).toBe(true);
// A page no host frames counts as before.
expect(buddyHostOfWindow(frameWindow({ host: "https://example.com" }).win)).toBeNull();
});

it("behaves as before with an older host, which sends its context and never says shown", () => {
const { win, receive } = frameWindow();
const frame = startBuddyFrame(win);
receive(personalContext);
expect(frame.shown()).toBeNull();
expect(
buddyWindowInView(frame.hostOrigin !== null, frame.shown(), frame.context() !== null),
).toBe(true);
});

it("talks to nobody outside a host's frame", () => {
const { win, posted, key } = frameWindow({ host: "https://example.com" });
const frame = startBuddyFrame(win);
Expand Down
47 changes: 37 additions & 10 deletions apps/web/src/lazurio/buddySurfaceFrame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/
import {
acceptBuddyContext,
acceptBuddyShown,
type BuddyContext,
type BuddyLayout,
buddyHostOriginOf,
Expand All @@ -19,21 +20,38 @@ export interface BuddyFrame {
readonly context: () => BuddyContext | null;
/** The size the frame asked for last; the panel until it asks. */
readonly layout: () => Exclude<BuddyLayout, "closed">;
/** Whether the host's window shows the frame; null until the host says (an older Lazurio never does). */
readonly shown: () => boolean | null;
readonly subscribe: (listener: () => void) => () => void;
readonly requestLayout: (mode: BuddyLayout) => void;
readonly stop: () => void;
}

/**
* Whether the frame's thread counts as seen. In a host's frame only once the host says it shows the
* window: a hidden frame, also one loaded anew, would otherwise read Buddy's answers first. A host
* that sends a context without `shown` first (an older Lazurio) never says, so then as before.
*/
export const buddyWindowInView = (
framed: boolean,
shown: boolean | null,
heardContext: boolean,
): boolean => !framed || shown === true || (shown === null && heardContext);

/** An open menu, dialog or list inside the surface takes Escape before the frame does. */
const ESCAPE_TAKERS = '[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]';

/** The host page around this one, if a host of the bubble frames it; read without side effects. */
export const buddyHostOfWindow = (win: Window): string | null =>
win.parent === win
? null
: buddyHostOriginOf(win.location.ancestorOrigins?.[0], win.document.referrer);

export function startBuddyFrame(win: Window): BuddyFrame {
const hostOrigin =
win.parent === win
? null
: buddyHostOriginOf(win.location.ancestorOrigins?.[0], win.document.referrer);
const hostOrigin = buddyHostOfWindow(win);
let context: BuddyContext | null = null;
let layout: Exclude<BuddyLayout, "closed"> = "panel";
let shown: boolean | null = null;
const listeners = new Set<() => void>();
const notify = () => {
for (const listener of listeners) listener();
Expand All @@ -49,12 +67,20 @@ export function startBuddyFrame(win: Window): BuddyFrame {
notify();
};
const onMessage = (event: MessageEvent) => {
const accepted = acceptBuddyContext(
{ data: event.data, origin: event.origin, fromParent: event.source === win.parent },
hostOrigin,
);
if (accepted === null) return;
context = accepted;
const received = {
data: event.data,
origin: event.origin,
fromParent: event.source === win.parent,
};
const accepted = acceptBuddyContext(received, hostOrigin);
if (accepted !== null) {
context = accepted;
notify();
return;
}
const nowShown = acceptBuddyShown(received, hostOrigin);
if (nowShown === null || nowShown === shown) return;
shown = nowShown;
notify();
};
const onKeyDown = (event: KeyboardEvent) => {
Expand All @@ -79,6 +105,7 @@ export function startBuddyFrame(win: Window): BuddyFrame {
hostOrigin,
context: () => context,
layout: () => layout,
shown: () => shown,
subscribe: (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
Expand Down
25 changes: 25 additions & 0 deletions apps/web/src/lazurio/buddySurfaceProtocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test";

import {
acceptBuddyContext,
acceptBuddyShown,
buddyHostOriginOf,
buddyLayoutRequest,
buddyReady,
Expand Down Expand Up @@ -117,6 +118,30 @@ describe("a context from the host", () => {
});
});

describe("whether the host's window shows the frame", () => {
const shown = (value: unknown, overrides: Record<string, unknown> = {}) => ({
type: "lazurio.buddy.shown",
v: 1,
shown: value,
...overrides,
});

it("is taken from the parent on the host's origin, and dropped whole for any defect", () => {
expect(acceptBuddyShown(event(shown(false)), host)).toBe(false);
expect(acceptBuddyShown(event(shown(true)), host)).toBe(true);
for (const [data, origin, fromParent, hostOrigin] of [
[shown(false), host, false, host],
[shown(false), "https://launchpad.vm-01.example.lazurio.io", true, host],
[shown(false), host, true, null],
[shown("false"), host, true, host],
[shown(false, { v: 2 }), host, true, host],
[shown(false, { extra: true }), host, true, host],
[context(), host, true, host],
] as const)
expect(acceptBuddyShown(event(data, origin, fromParent), hostOrigin)).toBeNull();
});
});

describe("what the frame sends", () => {
it("is ready and a request for one of the three sizes", () => {
expect(buddyReady()).toEqual({ type: "lazurio.buddy.ready", v: 1 });
Expand Down
23 changes: 23 additions & 0 deletions apps/web/src/lazurio/buddySurfaceProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const BUDDY_MESSAGE = {
ready: "lazurio.buddy.ready",
layout: "lazurio.buddy.layout",
context: "lazurio.buddy.context",
shown: "lazurio.buddy.shown",
} as const;

const BUDDY_PROTOCOL_VERSION = 1;
Expand Down Expand Up @@ -270,6 +271,28 @@ export function acceptBuddyContext(
return context;
}

/**
* The frame's side of `lazurio.buddy.shown`: whether the host's window shows the frame, from the
* same parent and origin as a context; null to drop the message.
*/
export function acceptBuddyShown(
event: { readonly data: unknown; readonly origin: string; readonly fromParent: boolean },
hostOrigin: string | null,
): boolean | null {
if (event.fromParent !== true) return null;
if (buddyHostEnvironment(hostOrigin) === null || event.origin !== hostOrigin) return null;
const data = event.data;
if (
!isPlain(data) ||
!hasOnly(data, ["type", "v", "shown"]) ||
data.type !== BUDDY_MESSAGE.shown ||
data.v !== BUDDY_PROTOCOL_VERSION ||
typeof data.shown !== "boolean"
)
return null;
return data.shown;
}

export const buddyReady = () => ({ type: BUDDY_MESSAGE.ready, v: BUDDY_PROTOCOL_VERSION });

/** A request for the window's size; null for a size there is none of. */
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/lazurio/buddySurfaceTheme.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ vi.mock(import("./useBuddyFrame"), async (original) => ({
framed: frame.context !== null,
context: frame.context,
layout: "panel" as const,
shown: null,
requestLayout: () => {},
}),
}));
Expand Down
3 changes: 3 additions & 0 deletions apps/web/src/lazurio/useBuddyFrame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const NO_FRAME: Omit<BuddyFrame, "stop"> = {
hostOrigin: null,
context: () => null,
layout: () => "panel",
shown: () => null,
subscribe: () => () => {},
requestLayout: () => {},
};
Expand All @@ -29,10 +30,12 @@ export function useBuddyFrame(buddy: boolean) {
const current = buddy ? buddyFrame() : NO_FRAME;
const context = useSyncExternalStore(current.subscribe, current.context, () => null);
const layout = useSyncExternalStore(current.subscribe, current.layout, () => "panel" as const);
const shown = useSyncExternalStore(current.subscribe, current.shown, () => null);
return {
framed: current.hostOrigin !== null,
context,
layout,
shown,
requestLayout: current.requestLayout,
};
}
Loading