Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: placement display ids and viewable time

ogsamrat0d6880695e25
diff --git a/apps/app/src/app/lib/placement-viewability.ts b/apps/app/src/app/lib/placement-viewability.ts
new file mode 100644
index 00000000..7dd189b1
--- /dev/null
+++ b/apps/app/src/app/lib/placement-viewability.ts
@@ -0,0 +1,156 @@
+// Sponsored placements: the viewable measurement (desktop only).
+//
+// A display is viewable once at least half of its card has been on screen
+// for one continuous second while the page is visible and the app window is
+// focused (not minimized, not hidden). Any condition failing resets the
+// second. It fires at most once per display: scrolling away and back, typing
+// or a streaming reply never count it again. Without IntersectionObserver
+// nothing is measured (and nothing counted).
+
+/** At least this share of the card in the viewport. */
+export const VIEWABLE_RATIO = 0.5;
+/** For this long, continuously. */
+export const VIEWABLE_MS = 1_000;
+/** Main → page window state (apps/desktop/electron/placements-desktop.mjs WINDOW_STATE_CHANNEL, re-sent by the preload). */
+export const WINDOW_STATE_EVENT = "omnirush:placements:window";
+
+export type ViewabilityConditions = {
+ /** The card's intersection ratio with the viewport (0 when not intersecting). */
+ ratio: number;
+ /** document.visibilityState === "visible" */
+ pageVisible: boolean;
+ /** document.hasFocus() / window focus, and the window not minimized or hidden. */
+ windowFocused: boolean;
+};
+
+export function qualifies(c: ViewabilityConditions): boolean {
+ return c.ratio >= VIEWABLE_RATIO && c.pageVisible && c.windowFocused;
+}
+
+type TimerFns = {
+ setTimer?: (fn: () => void, ms: number) => unknown;
+ clearTimer?: (timer: unknown) => void;
+ now?: () => number;
+};
+
+export type ViewabilityTimer = {
+ /** New measurements (any subset); starts, keeps or resets the continuous second. */
+ update: (next: Partial<ViewabilityConditions>) => void;
+ /** Stops for good (unmounted). */
+ stop: () => void;
+ /** Whether it fired. */
+ fired: () => boolean;
+};
+
+/** The continuous-second timer: `onViewable` at most once. */
+export function createViewabilityTimer(
+ onViewable: () => void,
+ { setTimer = (fn, ms) => setTimeout(fn, ms), clearTimer = (t) => clearTimeout(t as ReturnType<typeof setTimeout>), now = Date.now }: TimerFns = {},
+): ViewabilityTimer {
+ let conditions: ViewabilityConditions = { ratio: 0, pageVisible: false, windowFocused: false };
+ let timer: unknown = null;
+ let since = 0;
+ let done = false;
+ let stopped = false;
+
+ const cancel = () => {
+ if (timer !== null) clearTimer(timer);
+ timer = null;
+ };
+ const arm = (ms: number) => {
+ timer = setTimer(() => {
+ timer = null;
+ if (done || stopped || !qualifies(conditions)) return;
+ // A timer may run late, never early; checked against the clock anyway.
+ const left = VIEWABLE_MS - (now() - since);
+ if (left > 0) {
+ arm(left);
+ return;
+ }
+ done = true;
+ onViewable();
+ }, ms);
+ };
+
+ return {
+ update(next) {
+ if (done || stopped) return;
+ conditions = { ...conditions, ...next };
+ if (!qualifies(conditions)) {
+ cancel();
+ return;
+ }
+ if (timer === null) {
+ since = now();
+ arm(VIEWABLE_MS);
+ }
+ },
+ stop() {
+ stopped = true;
+ cancel();
+ },
+ fired: () => done,
+ };
+}
+
+type ObserverEntry = { isIntersecting: boolean; intersectionRatio: number };
+type ObserverCtor = new (callback: (entries: ObserverEntry[]) => void, options: { threshold: number[] }) => { observe: (el: Element) => void; disconnect: () => void };
+
+export type ViewabilityEnv = {
+ win: Pick<Window, "addEventListener" | "removeEventListener">;
+ doc: Pick<Document, "visibilityState" | "hasFocus" | "addEventListener" | "removeEventListener">;
+ IntersectionObserver?: ObserverCtor | null;
+} & TimerFns;
+
+function defaultEnv(): ViewabilityEnv | null {
+ if (typeof window === "undefined" || typeof document === "undefined") return null;
+ return { win: window, doc: document, IntersectionObserver: (globalThis as { IntersectionObserver?: ObserverCtor }).IntersectionObserver ?? null };
+}
+
+/**
+ * Measures `element` (the card) and calls `onViewable` once when it
+ * qualifies. Resolves the cleanup.
+ */
+export function observeViewability(element: Element, onViewable: () => void, env: ViewabilityEnv | null = defaultEnv()): () => void {
+ if (!env || typeof env.IntersectionObserver !== "function") return () => undefined;
+ const { win, doc } = env;
+ const timer = createViewabilityTimer(onViewable, env);
+ let minimized = false;
+ let hidden = false;
+ const focus = () => !minimized && !hidden && doc.hasFocus();
+ const pageVisible = () => doc.visibilityState === "visible";
+ timer.update({ pageVisible: pageVisible(), windowFocused: focus() });
+
+ const observer = new env.IntersectionObserver(
+ (entries) => {
+ const last = entries[entries.length - 1];
+ if (!last) return;
+ timer.update({ ratio: last.isIntersecting ? last.intersectionRatio : 0 });
+ },
+ { threshold: [0, VIEWABLE_RATIO, 1] },
+ );
+ observer.observe(element);
+
+ const onVisibility = () => timer.update({ pageVisible: pageVisible(), windowFocused: focus() });
+ const onFocus = () => timer.update({ windowFocused: focus() });
+ const onBlur = () => timer.update({ windowFocused: false });
+ const onWindowState = (event: Event) => {
+ const detail = (event as CustomEvent<{ focused?: boolean; minimized?: boolean; visible?: boolean }>).detail ?? {};
+ minimized = detail.minimized === true;
+ hidden = detail.visible === false;
+ timer.update({ windowFocused: detail.focused === false ? false : focus(), pageVisible: pageVisible() });
+ };
+ doc.addEventListener("visibilitychange", onVisibility);
+ win.addEventListener("focus", onFocus);
+ win.addEventListener("blur", onBlur);
+ win.addEventListener(WINDOW_STATE_EVENT, onWindowState);
+
+ return () => {
+ timer.stop();
+ observer.disconnect();
+ doc.removeEventListener("visibilitychange", onVisibility);
+ win.removeEventListener("focus", onFocus);
+ win.removeEventListener("blur", onBlur);
+ win.removeEventListener(WINDOW_STATE_EVENT, onWindowState);
+ };
+}
diff --git a/apps/app/src/app/lib/placements.ts b/apps/app/src/app/lib/placements.ts
index 4ae4869b..ba8ddb7f 100644
--- a/apps/app/src/app/lib/placements.ts
+++ b/apps/app/src/app/lib/placements.ts
@@ -1,20 +1,27 @@
// Sponsored placements, renderer side. The Electron main process decides
// (apps/desktop/electron/placements-desktop.mjs and the shared
// placements/placements.mjs): it answers a placement to draw or null (none,
-// switched off, offline, any error), counts it, and opens its link after a
-// click. Here: one home placement per app run, the turn line once per
-// session, and the dismissals of this run. Nothing here is awaited on the way
-// to the first screen, and nothing here touches a session's messages.
+// switched off, offline, any error) with its display id, counts it, and
+// opens its link after a click. Here: the home display (the main process
+// keeps it until a new conversation or 30 idle minutes), the turn line once
+// per session, the dismissals of this run, and each display's events:
+// rendered (first painted), viewable (placement-viewability.ts), click and
+// dismiss, once per display. Nothing here is awaited on the way to the first
+// screen, and nothing here touches a session's messages.
import { create } from "zustand";
-import type { OmniRushPlacement, OmniRushPlacementAction, OmniRushPlacementSlot } from "@omnirush/types/desktop-ipc";
+import type { OmniRushPlacement, OmniRushPlacementAction, OmniRushPlacementSlot, OmniRushPlacementSurface } from "@omnirush/types/desktop-ipc";
import { omnirushPlacement, omnirushPlacementAction } from "./desktop";
export type Placement = OmniRushPlacement;
const SLOTS: readonly OmniRushPlacementSlot[] = ["home_banner", "turn_footer"];
+const SURFACE: Record<OmniRushPlacementSlot, OmniRushPlacementSurface> = { home_banner: "desktop_home", turn_footer: "desktop_turn" };
+const DISPLAY_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+/** Activity is reported at most this often (the main process only needs it for the 30-minute idle rule). */
+export const ACTIVITY_EVERY_MS = 60_000;
/** Copy limits (the shared module clamps them already; checked again here). */
export const PLACEMENT_LIMITS = { sponsor: 40, title: 60, body: 140, ctaLabel: 20 } as const;
@@ -37,6 +44,8 @@ export function asPlacement(value: unknown): Placement | null {
if (!value || typeof value !== "object") return null;
const p = value as Record<string, unknown>;
if (typeof p.id !== "string" || !p.id || !SLOTS.includes(p.slot as OmniRushPlacementSlot)) return null;
+ if (typeof p.displayId !== "string" || !DISPLAY_ID_RE.test(p.displayId)) return null;
+ if (p.surface !== SURFACE[p.slot as OmniRushPlacementSlot]) return null;
if (!shortText(p.sponsor, PLACEMENT_LIMITS.sponsor) || !p.sponsor) return null;
if (!shortText(p.title, PLACEMENT_LIMITS.title) || !p.title) return null;
if (!shortText(p.body, PLACEMENT_LIMITS.body) || !shortText(p.ctaLabel, PLACEMENT_LIMITS.ctaLabel) || !p.ctaLabel) return null;
@@ -44,6 +53,8 @@ export function asPlacement(value: unknown): Placement | null {
if (p.imageUrl !== null && !httpsUrl(p.imageUrl)) return null;
return {
id: p.id,
+ displayId: p.displayId,
+ surface: p.surface as OmniRushPlacementSurface,
slot: p.slot as OmniRushPlacementSlot,
label: `Sponsored · ${p.sponsor}`,
sponsor: p.sponsor,
@@ -72,14 +83,14 @@ export const usePlacementsStore = create<PlacementsState>((set) => ({
setHome: (home) => set({ home }),
setFooter: (sessionId, placement) => set((state) => ({ footers: { ...state.footers, [sessionId]: placement } })),
hide: (id) => set((state) => ({
- home: state.home?.id === id ? null : state.home,
+ home: state.home && state.home.id === id ? null : state.home,
footers: Object.fromEntries(Object.entries(state.footers).map(([sid, p]) => [sid, p?.id === id ? null : p])),
})),
}));
type Bridge = {
placement: (input: { slot: OmniRushPlacementSlot; sessionId?: string }) => Promise<unknown>;
- action: (input: { id: string; action: OmniRushPlacementAction }) => Promise<unknown>;
+ action: (input: { action: OmniRushPlacementAction; id?: string; displayId?: string; sessionId?: string }) => Promise<unknown>;
};
let bridge: Bridge = {
@@ -91,13 +102,20 @@ let bridge: Bridge = {
export function setPlacementsBridgeForTests(next: Bridge | null): void {
if (next) bridge = next;
homeAsk = null;
- impressions.clear();
+ sent.clear();
+ homeCards = 0;
+ lastActivity = 0;
+ lastConversation = null;
usePlacementsStore.setState({ home: undefined, footers: {} });
}
let homeAsk: Promise<Placement | null> | null = null;
-/** The home placement of this run (asked once; the main process keeps the same one for the run). */
+/**
+ * The home display: asked whenever the home card mounts or the window comes
+ * back; the main process answers the same display (same id) until a new
+ * conversation or 30 idle minutes, so asking again never counts it again.
+ */
export function loadHomePlacement(): Promise<Placement | null> {
if (homeAsk) return homeAsk;
homeAsk = Promise.resolve()
@@ -105,8 +123,13 @@ export function loadHomePlacement(): Promise<Placement | null> {
.then(asPlacement)
.catch(() => null)
.then((placement) => {
- usePlacementsStore.getState().setHome(placement);
+ const current = usePlacementsStore.getState().home;
+ // The same display: the card stays as it is (its timer keeps running).
+ if (!(placement && current && current.displayId === placement.displayId)) usePlacementsStore.getState().setHome(placement);
return placement;
+ })
+ .finally(() => {
+ homeAsk = null;
});
return homeAsk;
}
@@ -129,25 +152,84 @@ export function endTurnFooter(sessionId: string): void {
if (footers[sessionId]) usePlacementsStore.getState().setFooter(sessionId, null);
}
-const impressions = new Set<string>();
+/** `${displayId}:${kind}` already sent from this window (the main process refuses repeats too). */
+const sent = new Set<string>();
-/** Drawn: one impression per placement and place (home, or a session's turn line). */
-export function placementShown(placement: Placement, where: string): void {
- const key = `${where}:${placement.id}`;
- if (impressions.has(key)) return;
- impressions.add(key);
- void bridge.action({ id: placement.id, action: "impression" }).catch(() => undefined);
+function once(placement: Placement, action: "rendered" | "viewable" | "dismiss"): void {
+ const key = `${placement.displayId}:${action}`;
+ if (sent.has(key)) return;
+ sent.add(key);
+ void bridge.action({ action, id: placement.id, displayId: placement.displayId }).catch(() => undefined);
}
-/** The click: the main process opens the link in the system browser. */
+/** First painted: once per display. */
+export function placementRendered(placement: Placement): void {
+ once(placement, "rendered");
+}
+
+/** Measured viewable (≥ 50% for one continuous second, focused and visible): once per display. */
+export function placementViewable(placement: Placement): void {
+ once(placement, "viewable");
+}
+
+/** Whether this display was already measured viewable in this window. */
+export function placementViewableSent(placement: Placement): boolean {
+ return sent.has(`${placement.displayId}:viewable`);
+}
+
+/** The click: the main process opens the link in the system browser (one click event per display). */
export function openPlacement(placement: Placement): void {
- void bridge.action({ id: placement.id, action: "open" }).catch(() => undefined);
+ void bridge.action({ action: "open", id: placement.id, displayId: placement.displayId }).catch(() => undefined);
}
/** ×: hidden for its snooze days. */
export function dismissPlacement(placement: Placement): void {
usePlacementsStore.getState().hide(placement.id);
- void bridge.action({ id: placement.id, action: "dismiss" }).catch(() => undefined);
+ once(placement, "dismiss");
+}
+
+let lastActivity = 0;
+let lastConversation: string | null = null;
+
+/** Home cards on screen now: a due rotation is asked for only while one is (a display nobody sees is never made). */
+let homeCards = 0;
+
+/** The home card mounted; resolves the unmount. */
+export function homeCardMounted(): () => void {
+ homeCards += 1;
+ return () => {
+ homeCards = Math.max(0, homeCards - 1);
+ };
+}
+
+function rotateIfDue(answer: unknown): void {
+ if (homeCards > 0 && answer && typeof answer === "object" && (answer as { rotate?: unknown }).rotate === true) void loadHomePlacement();
+}
+
+let activityInstalled = false;
+
+/** Key presses and clicks anywhere in the window count as activity (installed once). */
+export function installPlacementActivity(target: Pick<Window, "addEventListener"> | null = typeof window === "undefined" ? null : window): void {
+ if (activityInstalled || !target) return;
+ activityInstalled = true;
+ const onInput = () => placementActivity();
+ target.addEventListener("keydown", onInput, { capture: true, passive: true });
+ target.addEventListener("pointerdown", onInput, { capture: true, passive: true });
+}
+
+/** The user typed or clicked (at most once a minute): the main process's 30-minute idle rule. */
+export function placementActivity(now = Date.now()): void {
+ if (now - lastActivity < ACTIVITY_EVERY_MS) return;
+ lastActivity = now;
+ void Promise.resolve().then(() => bridge.action({ action: "activity" })).then(rotateIfDue, () => undefined);
+}
+
+/** A turn started in `sessionId`: a different conversation than last time means a new home display next. */
+export function placementConversation(sessionId: string): void {
+ if (!sessionId || sessionId === lastConversation) return;
+ lastConversation = sessionId;
+ lastActivity = Date.now();
+ void Promise.resolve().then(() => bridge.action({ action: "conversation", sessionId })).then(rotateIfDue, () => undefined);
}
/** Whether a turn just finished: this session was running and is not any more. */
diff --git a/apps/app/src/react-app/domains/placements/placements.tsx b/apps/app/src/react-app/domains/placements/placements.tsx
index 83da945c..599a351e 100644
--- a/apps/app/src/react-app/domains/placements/placements.tsx
+++ b/apps/app/src/react-app/domains/placements/placements.tsx
@@ -5,21 +5,49 @@
// colours, no motion, no sound, no toast. The link opens in the system
// browser only on a click; × hides it for the placement's snooze days.
// Nothing renders while the main process has no placement to show.
+//
+// Each display reports rendered when first painted and viewable once it has
+// been ≥ 50% on screen for one continuous second with the window focused and
+// visible (placement-viewability.ts); both once per display id.
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, type RefObject } from "react";
import { ArrowUpRight, X } from "lucide-react";
import {
dismissPlacement,
endTurnFooter,
+ homeCardMounted,
+ installPlacementActivity,
loadHomePlacement,
loadTurnFooter,
openPlacement,
- placementShown,
+ placementConversation,
+ placementRendered,
+ placementViewable,
+ placementViewableSent,
turnJustFinished,
usePlacementsStore,
type Placement,
} from "../../../app/lib/placements";
+import { observeViewability } from "../../../app/lib/placement-viewability";
+
+/** rendered on the first paint, viewable when measured: once per display. */
+function useDisplayMeasurement(ref: RefObject<HTMLElement | null>, placement: Placement) {
+ useEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ let frame: number | null = null;
+ if (typeof requestAnimationFrame === "function") frame = requestAnimationFrame(() => placementRendered(placement));
+ else placementRendered(placement);
+ const stop = placementViewableSent(placement) ? () => undefined : observeViewability(element, () => placementViewable(placement));
+ return () => {
+ if (frame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frame);
+ stop();
+ };
+ // One measurement per display: a new display id starts a new one.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [placement.displayId]);
+}
function DismissButton(props: { placement: Placement; testId: string }) {
return (
@@ -40,22 +68,36 @@ function DismissButton(props: { placement: Placement; testId: string }) {
export function PlacementHomeCard() {
const placement = usePlacementsStore((state) => state.home);
useEffect(() => {
+ installPlacementActivity();
+ const unmount = homeCardMounted();
void loadHomePlacement();
+ // Back to the window: the same display, or a new one after 30 idle minutes.
+ const back = () => {
+ if (typeof document === "undefined" || document.visibilityState === "visible") void loadHomePlacement();
+ };
+ window.addEventListener("focus", back);
+ document.addEventListener("visibilitychange", back);
+ return () => {
+ unmount();
+ window.removeEventListener("focus", back);
+ document.removeEventListener("visibilitychange", back);
+ };
}, []);
- useEffect(() => {
- if (placement) placementShown(placement, "home");
- }, [placement]);
if (!placement) return null;
- return <PlacementHomeCardView placement={placement} />;
+ return <PlacementHomeCardView key={placement.displayId} placement={placement} />;
}
/** The card itself (tests render it directly). */
export function PlacementHomeCardView({ placement }: { placement: Placement }) {
+ const ref = useRef<HTMLElement | null>(null);
+ useDisplayMeasurement(ref, placement);
return (
<aside
+ ref={ref}
aria-label={placement.label}
data-testid="placement-home"
data-placement-id={placement.id}
+ data-display-id={placement.displayId}
className="flex items-center gap-3 rounded-lg border border-border/70 bg-background px-3 py-2"
>
{placement.imageUrl ? (
@@ -103,28 +145,32 @@ export function PlacementTurnFooter(props: { sessionId: string; turnRunning: boo
const now = { sessionId: props.sessionId, running: props.turnRunning };
previous.current = now;
if (props.turnRunning) {
+ installPlacementActivity();
+ // A turn in this conversation: the home card's next display may be a new one.
+ placementConversation(props.sessionId);
endTurnFooter(props.sessionId);
return;
}
if (turnJustFinished(before, now)) void loadTurnFooter(props.sessionId);
}, [props.sessionId, props.turnRunning]);
const visible = Boolean(placement) && !props.turnRunning;
- useEffect(() => {
- if (visible && placement) placementShown(placement, `turn:${props.sessionId}`);
- }, [placement, props.sessionId, visible]);
if (!visible || !placement) return null;
- return <PlacementTurnFooterView placement={placement} />;
+ return <PlacementTurnFooterView key={placement.displayId} placement={placement} />;
}
/** The line itself (tests render it directly). */
export function PlacementTurnFooterView({ placement }: { placement: Placement }) {
+ const ref = useRef<HTMLDivElement | null>(null);
+ useDisplayMeasurement(ref, placement);
return (
<div className="px-4 max-lg:px-3 lg:px-8">
<div
+ ref={ref}
role="note"
aria-label={placement.label}
data-testid="placement-turn-footer"
data-placement-id={placement.id}
+ data-display-id={placement.displayId}
className="mx-auto flex max-w-[800px] items-center gap-2 pb-1 text-[11px] leading-4 text-muted-foreground/80"
>
<span className="min-w-0 flex-1 truncate">
diff --git a/apps/app/tests/placement-viewability.test.ts b/apps/app/tests/placement-viewability.test.ts
new file mode 100644
index 00000000..edc109e0
--- /dev/null
+++ b/apps/app/tests/placement-viewability.test.ts
@@ -0,0 +1,332 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ createViewabilityTimer,
+ observeViewability,
+ qualifies,
+ VIEWABLE_MS,
+ VIEWABLE_RATIO,
+ WINDOW_STATE_EVENT,
+} from "../src/app/lib/placement-viewability";
+
+/** A manual clock: timers run only when `advance` passes them. */
+function clock() {
+ let now = 0;
+ let next = 1;
+ const timers = new Map<number, { at: number; fn: () => void }>();
+ return {
+ now: () => now,
+ setTimer: (fn: () => void, ms: number) => {
+ const id = next++;
+ timers.set(id, { at: now + ms, fn });
+ return id;
+ },
+ clearTimer: (id: unknown) => {
+ timers.delete(id as number);
+ },
+ advance(ms: number) {
+ const end = now + ms;
+ for (;;) {
+ const due = [...timers.entries()].filter(([, t]) => t.at <= end).sort((a, b) => a[1].at - b[1].at)[0];
+ if (!due) break;
+ timers.delete(due[0]);
+ now = due[1].at;
+ due[1].fn();
+ }
+ now = end;
+ },
+ pending: () => timers.size,
+ };
+}
+
+const ALL = { ratio: 1, pageVisible: true, windowFocused: true };
+
+describe("viewability: the rule", () => {
+ test("≥ 50% visible, page visible and window focused", () => {
+ expect(VIEWABLE_RATIO).toBe(0.5);
+ expect(VIEWABLE_MS).toBe(1_000);
+ expect(qualifies(ALL)).toBe(true);
+ expect(qualifies({ ...ALL, ratio: 0.5 })).toBe(true);
+ expect(qualifies({ ...ALL, ratio: 0.49 })).toBe(false);
+ expect(qualifies({ ...ALL, pageVisible: false })).toBe(false);
+ expect(qualifies({ ...ALL, windowFocused: false })).toBe(false);
+ });
+});
+
+describe("viewability: the continuous second", () => {
+ test("fires after one continuous second, not before", () => {
+ const c = clock();
+ let fired = 0;
+ const t = createViewabilityTimer(() => fired++, c);
+ t.update(ALL);
+ c.advance(999);
+ expect(fired).toBe(0);
+ c.advance(1);
+ expect(fired).toBe(1);
+ expect(t.fired()).toBe(true);
+ });
+
+ test("below the threshold never fires", () => {
+ const c = clock();
+ let fired = 0;
+ const t = createViewabilityTimer(() => fired++, c);
+ t.update({ ...ALL, ratio: 0.4 });
+ c.advance(10_000);
+ expect(fired).toBe(0);
+ });
+
+ for (const [name, fail] of [
+ ["blur", { windowFocused: false }],
+ ["hidden page", { pageVisible: false }],
+ ["minimize (window not focused)", { windowFocused: false }],
+ ["scrolled out", { ratio: 0 }],
+ ["scrolled to under half", { ratio: 0.3 }],
+ ] as const) {
+ test(`resets on ${name}`, () => {
+ const c = clock();
+ let fired = 0;
+ const t = createViewabilityTimer(() => fired++, c);
+ t.update(ALL);
+ c.advance(800);
+ t.update(fail);
+ c.advance(5_000);
+ expect(fired).toBe(0);
+ expect(c.pending()).toBe(0);
+ // Back: a full second again, from zero.
+ t.update(ALL);
+ c.advance(800);
+ expect(fired).toBe(0);
+ c.advance(200);
+ expect(fired).toBe(1);
+ });
+ }
+
+ test("several short looks never add up", () => {
+ const c = clock();
+ let fired = 0;
+ const t = createViewabilityTimer(() => fired++, c);
+ for (let i = 0; i < 10; i++) {
+ t.update(ALL);
+ c.advance(900);
+ t.update({ windowFocused: false });
+ c.advance(100);
+ }
+ expect(fired).toBe(0);
+ });
+
+ test("once per display: scrolling away and back, typing or streaming never count again", () => {
+ const c = clock();
+ let fired = 0;
+ const t = createViewabilityTimer(() => fired++, c);
+ t.update(ALL);
+ c.advance(1_000);
+ expect(fired).toBe(1);
+ for (let i = 0; i < 5; i++) {
+ t.update({ ratio: 0 });
+ c.advance(500);
+ t.update({ ratio: 1 });
+ c.advance(2_000);
+ // Re-renders while typing or streaming send the same conditions again.
+ t.update(ALL);
+ c.advance(2_000);
+ }
+ expect(fired).toBe(1);
+ });
+
+ test("updates with the same conditions keep the running second (no restart)", () => {
+ const c = clock();
+ let fired = 0;
+ const t = createViewabilityTimer(() => fired++, c);
+ t.update(ALL);
+ c.advance(600);
+ t.update(ALL);
+ t.update({ ratio: 0.9 });
+ c.advance(400);
+ expect(fired).toBe(1);
+ });
+
+ test("a stopped timer (unmounted card) never fires", () => {
+ const c = clock();
+ let fired = 0;
+ const t = createViewabilityTimer(() => fired++, c);
+ t.update(ALL);
+ c.advance(500);
+ t.stop();
+ c.advance(5_000);
+ t.update(ALL);
+ c.advance(5_000);
+ expect(fired).toBe(0);
+ });
+});
+
+/** A fake page: an IntersectionObserver, focus, visibility and the main process's window state. */
+function page({ focused = true, visible = true } = {}) {
+ const listeners = new Map<string, Set<(e: Event) => void>>();
+ const docListeners = new Map<string, Set<() => void>>();
+ let observerCallback: ((entries: { isIntersecting: boolean; intersectionRatio: number }[]) => void) | null = null;
+ let disconnected = false;
+ const state = { focused, visible };
+ const c = clock();
+ const env = {
+ ...c,
+ win: {
+ addEventListener: (type: string, fn: (e: Event) => void) => {
+ if (!listeners.has(type)) listeners.set(type, new Set());
+ listeners.get(type)!.add(fn);
+ },
+ removeEventListener: (type: string, fn: (e: Event) => void) => listeners.get(type)?.delete(fn),
+ },
+ doc: {
+ get visibilityState() {
+ return state.visible ? "visible" : "hidden";
+ },
+ hasFocus: () => state.focused,
+ addEventListener: (type: string, fn: () => void) => {
+ if (!docListeners.has(type)) docListeners.set(type, new Set());
+ docListeners.get(type)!.add(fn);
+ },
+ removeEventListener: (type: string, fn: () => void) => docListeners.get(type)?.delete(fn),
+ },
+ IntersectionObserver: class {
+ constructor(cb: typeof observerCallback, options: { threshold: number[] }) {
+ observerCallback = cb;
+ expect(options.threshold).toContain(0.5);
+ }
+ observe() {}
+ disconnect() {
+ disconnected = true;
+ }
+ },
+ };
+ const emit = (type: string, detail?: unknown) => {
+ for (const fn of listeners.get(type) ?? []) fn(detail === undefined ? new Event(type) : new CustomEvent(type, { detail }));
+ };
+ return {
+ env: env as never,
+ clock: c,
+ intersect: (ratio: number) => observerCallback?.([{ isIntersecting: ratio > 0, intersectionRatio: ratio }]),
+ focus: () => {
+ state.focused = true;
+ emit("focus");
+ },
+ blur: () => {
+ state.focused = false;
+ emit("blur");
+ },
+ hide: () => {
+ state.visible = false;
+ for (const fn of docListeners.get("visibilitychange") ?? []) fn();
+ },
+ show: () => {
+ state.visible = true;
+ for (const fn of docListeners.get("visibilitychange") ?? []) fn();
+ },
+ windowState: (detail: { focused: boolean; minimized: boolean; visible: boolean }) => emit(WINDOW_STATE_EVENT, detail),
+ listenerCount: () => [...listeners.values()].reduce((n, s) => n + s.size, 0) + [...docListeners.values()].reduce((n, s) => n + s.size, 0),
+ disconnected: () => disconnected,
+ };
+}
+
+const el = {} as Element;
+
+describe("viewability: on the page", () => {
+ test("visible card, focused window: viewable after 1 s", () => {
+ const p = page();
+ let fired = 0;
+ observeViewability(el, () => fired++, p.env);
+ p.intersect(0.8);
+ p.clock.advance(999);
+ expect(fired).toBe(0);
+ p.clock.advance(1);
+ expect(fired).toBe(1);
+ });
+
+ test("blurred window: none, until focused for a full second", () => {
+ const p = page({ focused: false });
+ let fired = 0;
+ observeViewability(el, () => fired++, p.env);
+ p.intersect(1);
+ p.clock.advance(5_000);
+ expect(fired).toBe(0);
+ p.focus();
+ p.clock.advance(1_000);
+ expect(fired).toBe(1);
+ });
+
+ test("hidden page: none", () => {
+ const p = page({ visible: false });
+ let fired = 0;
+ observeViewability(el, () => fired++, p.env);
+ p.intersect(1);
+ p.clock.advance(5_000);
+ expect(fired).toBe(0);
+ });
+
+ test("blur, hide, minimize and scroll-out each reset the second", () => {
+ const p = page();
+ let fired = 0;
+ observeViewability(el, () => fired++, p.env);
+ p.intersect(1);
+ p.clock.advance(900);
+ p.blur();
+ p.clock.advance(100);
+ p.focus();
+ p.clock.advance(900);
+ p.hide();
+ p.clock.advance(100);
+ p.show();
+ p.clock.advance(900);
+ p.windowState({ focused: false, minimized: true, visible: true });
+ p.clock.advance(5_000);
+ p.windowState({ focused: true, minimized: false, visible: true });
+ p.clock.advance(900);
+ p.intersect(0.2);
+ p.clock.advance(100);
+ p.intersect(1);
+ p.clock.advance(900);
+ expect(fired).toBe(0);
+ p.clock.advance(100);
+ expect(fired).toBe(1);
+ });
+
+ test("minimized but still reporting focus: no count", () => {
+ const p = page();
+ let fired = 0;
+ observeViewability(el, () => fired++, p.env);
+ p.windowState({ focused: true, minimized: true, visible: true });
+ p.intersect(1);
+ p.clock.advance(5_000);
+ expect(fired).toBe(0);
+ });
+
+ test("once: scrolling away and back does not count again", () => {
+ const p = page();
+ let fired = 0;
+ observeViewability(el, () => fired++, p.env);
+ p.intersect(1);
+ p.clock.advance(1_000);
+ p.intersect(0);
+ p.clock.advance(1_000);
+ p.intersect(1);
+ p.clock.advance(5_000);
+ expect(fired).toBe(1);
+ });
+
+ test("no IntersectionObserver: nothing measured, nothing counted", () => {
+ const p = page();
+ let fired = 0;
+ const stop = observeViewability(el, () => fired++, { ...(p.env as object), IntersectionObserver: null } as never);
+ p.clock.advance(5_000);
+ expect(fired).toBe(0);
+ stop();
+ });
+
+ test("cleanup removes every listener and the observer", () => {
+ const p = page();
+ const stop = observeViewability(el, () => undefined, p.env);
+ expect(p.listenerCount()).toBeGreaterThan(0);
+ stop();
+ expect(p.listenerCount()).toBe(0);
+ expect(p.disconnected()).toBe(true);
+ });
+});
diff --git a/apps/app/tests/placements.test.tsx b/apps/app/tests/placements.test.tsx
index 353a2195..c754f33a 100644
--- a/apps/app/tests/placements.test.tsx
+++ b/apps/app/tests/placements.test.tsx
@@ -7,16 +7,24 @@ import {
endTurnFooter,
loadHomePlacement,
loadTurnFooter,
+ homeCardMounted,
openPlacement,
- placementShown,
+ placementActivity,
+ placementConversation,
+ placementRendered,
+ placementViewable,
+ placementViewableSent,
setPlacementsBridgeForTests,
turnJustFinished,
usePlacementsStore,
} from "../src/app/lib/placements";
import { PlacementHomeCard, PlacementHomeCardView, PlacementTurnFooter, PlacementTurnFooterView } from "../src/react-app/domains/placements/placements";
+const DISPLAY = "3f2b6c1e-8a4d-4f7b-9c2e-1d5a6b7c8d9e";
const PLACEMENT = {
id: "plc_abc",
+ displayId: DISPLAY,
+ surface: "desktop_home",
slot: "home_banner",
label: "Sponsored · Acme",
sponsor: "Acme",
@@ -30,7 +38,8 @@ const PLACEMENT = {
function fakeMain(answer: unknown = PLACEMENT) {
const asks: unknown[] = [];
- const actions: { id: string; action: string }[] = [];
+ const actions: Record<string, unknown>[] = [];
+ let rotate = false;
setPlacementsBridgeForTests({
placement: async (input) => {
asks.push(input);
@@ -38,10 +47,10 @@ function fakeMain(answer: unknown = PLACEMENT) {
},
action: async (input) => {
actions.push(input);
- return { ok: true };
+ return { ok: true, rotate };
},
});
- return { asks, actions };
+ return { asks, actions, setRotate: (v: boolean) => { rotate = v; } };
}
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
@@ -70,6 +79,10 @@ describe("placements: what the window accepts", () => {
{ ...PLACEMENT, body: "B".repeat(141) },
{ ...PLACEMENT, ctaLabel: "C".repeat(21) },
{ ...PLACEMENT, sponsor: "" },
+ { ...PLACEMENT, displayId: undefined },
+ { ...PLACEMENT, displayId: "not-a-uuid" },
+ { ...PLACEMENT, surface: "cli_home" },
+ { ...PLACEMENT, surface: "desktop_turn" },
]) {
expect(asPlacement(bad)).toBeNull();
}
@@ -94,12 +107,16 @@ describe("placements: the home card", () => {
test("labelled, title, body, CTA and ×; plain text, no motion", async () => {
const { asks } = fakeMain();
await loadHomePlacement();
+ const first = usePlacementsStore.getState().home;
await loadHomePlacement();
- expect(asks).toEqual([{ slot: "home_banner" }]);
+ expect(asks).toEqual([{ slot: "home_banner" }, { slot: "home_banner" }]);
const placement = usePlacementsStore.getState().home!;
+ expect(placement).toBe(first!);
+ expect(placement.displayId).toBe(DISPLAY);
expect(placement.title).toBe("Fast CI for your repo");
const html = renderToStaticMarkup(<PlacementHomeCardView placement={placement} />);
expect(html).toContain('data-testid="placement-home"');
+ expect(html).toContain(`data-display-id="${DISPLAY}"`);
expect(html).toContain("Sponsored · Acme");
expect(html).toContain("Fast CI for your repo");
expect(html).toContain("Run your tests in half the time.");
@@ -119,21 +136,77 @@ describe("placements: the home card", () => {
expect(html).toMatch(/referrerpolicy="no-referrer"/i);
});
- test("impression once, click opens through the main process, × hides it", async () => {
+ test("rendered and viewable once per display, click and × with the same display id", async () => {
const { actions } = fakeMain();
const placement = await loadHomePlacement();
- placementShown(placement!, "home");
- placementShown(placement!, "home");
+ placementRendered(placement!);
+ placementRendered(placement!);
+ expect(placementViewableSent(placement!)).toBe(false);
+ placementViewable(placement!);
+ placementViewable(placement!);
+ expect(placementViewableSent(placement!)).toBe(true);
openPlacement(placement!);
dismissPlacement(placement!);
+ dismissPlacement(placement!);
await flush();
expect(actions).toEqual([
- { id: "plc_abc", action: "impression" },
- { id: "plc_abc", action: "open" },
- { id: "plc_abc", action: "dismiss" },
+ { action: "rendered", id: "plc_abc", displayId: DISPLAY },
+ { action: "viewable", id: "plc_abc", displayId: DISPLAY },
+ { action: "open", id: "plc_abc", displayId: DISPLAY },
+ { action: "dismiss", id: "plc_abc", displayId: DISPLAY },
]);
expect(usePlacementsStore.getState().home).toBeNull();
});
+
+ test("a new display id is a new display: its own rendered and viewable", async () => {
+ const second = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d";
+ let n = 0;
+ const { actions } = fakeMain(() => ({ ...PLACEMENT, displayId: n++ === 0 ? DISPLAY : second }));
+ const a = await loadHomePlacement();
+ placementRendered(a!);
+ placementViewable(a!);
+ const b = await loadHomePlacement();
+ expect(usePlacementsStore.getState().home?.displayId).toBe(second);
+ placementRendered(b!);
+ placementViewable(b!);
+ await flush();
+ expect(actions.map((x) => `${x.action}:${x.displayId}`)).toEqual([`rendered:${DISPLAY}`, `viewable:${DISPLAY}`, `rendered:${second}`, `viewable:${second}`]);
+ });
+});
+
+describe("placements: the display rotation signals", () => {
+ test("a turn starting tells the main process once per conversation", async () => {
+ const { actions } = fakeMain();
+ placementConversation("ses_1");
+ placementConversation("ses_1");
+ placementConversation("ses_2");
+ await flush();
+ expect(actions).toEqual([{ action: "conversation", sessionId: "ses_1" }, { action: "conversation", sessionId: "ses_2" }]);
+ });
+
+ test("activity at most once a minute", async () => {
+ const { actions } = fakeMain();
+ placementActivity(1_000_000);
+ placementActivity(1_030_000);
+ placementActivity(1_061_000);
+ await flush();
+ expect(actions).toEqual([{ action: "activity" }, { action: "activity" }]);
+ });
+
+ test("a due rotation asks again only while the home card is on screen", async () => {
+ const { asks, setRotate } = fakeMain();
+ setRotate(true);
+ placementActivity(5_000_000);
+ await flush();
+ await flush();
+ expect(asks.length).toBe(0);
+ const unmount = homeCardMounted();
+ placementActivity(5_100_000);
+ await flush();
+ await flush();
+ expect(asks).toEqual([{ slot: "home_banner" }]);
+ unmount();
+ });
});
describe("placements: the turn line", () => {
@@ -145,7 +218,7 @@ describe("placements: the turn line", () => {
});
test("asked once per session, drawn only while no turn runs, gone when the next turn starts", async () => {
- const { asks } = fakeMain({ ...PLACEMENT, slot: "turn_footer" });
+ const { asks } = fakeMain({ ...PLACEMENT, slot: "turn_footer", surface: "desktop_turn" });
await loadTurnFooter("ses_1");
await loadTurnFooter("ses_1");
expect(asks).toEqual([{ slot: "turn_footer", sessionId: "ses_1" }]);
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index eb419913..8aefd840 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -75,7 +75,7 @@ import {
} from "./connect-link-branding.mjs";
import { resolveConnectLinkPublicKeys } from "./connect-link-keys.mjs";
import { openExternalUrl } from "./open-external.mjs";
-import { createDesktopPlacements } from "./placements-desktop.mjs";
+import { createDesktopPlacements, watchWindowForPlacements } from "./placements-desktop.mjs";
import { classifyLocalOpen, isNetworkPath, localPathFromFileUrl } from "./open-local-path.mjs";
import { resolveAppIdentifier, resolveUserDataPath } from "./dev-profile.mjs";
import { fetchAgentContextDiagnosticsResponse } from "./agent-context-diagnostics-fetch.mjs";
@@ -3042,6 +3042,8 @@ async function createMainWindow() {
await applyCachedBrandIcon(cachedBrandImage, bootSourceUrl);
}
applicationMenu.applyVisibility(mainWindow);
+ // Sponsored placements: the page's viewability timer stops while the window is blurred, minimized or hidden.
+ watchWindowForPlacements(mainWindow);
mainWindow.on("page-title-updated", (event) => {
event.preventDefault();
diff --git a/apps/desktop/electron/placements-desktop.mjs b/apps/desktop/electron/placements-desktop.mjs
index dc27a5ee..1d6d41ca 100644
--- a/apps/desktop/electron/placements-desktop.mjs
+++ b/apps/desktop/electron/placements-desktop.mjs
@@ -6,6 +6,15 @@
// omnirushPlacementAction). The window only ever gets a placement to draw;
// the link is opened here, in the system browser, after a click.
//
+// Displays and events (placements.mjs): the window reports each display it
+// drew (rendered), the one it measured viewable (≥ 50% of the card on screen
+// for one continuous second while the window is focused and visible: the
+// renderer's timer, app/lib/placement-viewability.ts), the click and the ×,
+// each with the display id it was given. It also says when a conversation
+// starts and when the user is active, for the display rotation. The window's
+// focus / minimize / show state is pushed to it (WINDOW_STATE_CHANNEL) so the
+// timer stops when the window is minimized or hidden.
+//
// OMNIRUSH_PLACEMENTS=0 turns it off (the server is not asked).
import path from "node:path";
@@ -14,7 +23,30 @@ import { createPlacements, osName, refreshDue, SLOTS, STATE_FILE } from "./place
/** After a failed ask, the window's next look waits at least this long before asking again. */
export const RETRY_AFTER_MS = 5 * 60_000;
-const ACTIONS = new Set(["impression", "open", "dismiss"]);
+const ACTIONS = new Set(["rendered", "impression", "viewable", "open", "dismiss", "conversation", "activity"]);
+/** Main → window: { focused, minimized, visible } of the window. */
+export const WINDOW_STATE_CHANNEL = "omnirush:placements:window";
+
+/**
+ * Pushes the window's focus / minimize / show state to its page (the
+ * viewability timer's "window focused and visible"). Returns the unhook.
+ * @param {{ on: Function, removeListener: Function, isFocused: () => boolean, isMinimized: () => boolean, isVisible: () => boolean, isDestroyed: () => boolean, webContents: { send: Function, isDestroyed?: () => boolean } }} win
+ */
+export function watchWindowForPlacements(win) {
+ const events = ["focus", "blur", "minimize", "restore", "show", "hide"];
+ const send = () => {
+ try {
+ if (win.isDestroyed() || win.webContents.isDestroyed?.()) return;
+ win.webContents.send(WINDOW_STATE_CHANNEL, { focused: win.isFocused(), minimized: win.isMinimized(), visible: win.isVisible() });
+ } catch {
+ /* closing */
+ }
+ };
+ for (const name of events) win.on(name, send);
+ return () => {
+ for (const name of events) win.removeListener(name, send);
+ };
+}
/** @param {Record<string, string | undefined>} [env] */
export function desktopPlacementsAllowed(env = process.env) {
@@ -76,12 +108,27 @@ export function createDesktopPlacements({ request, userDataPath, version = "", p
return null;
}
},
- /** IPC omnirushPlacementAction {id, action}: impression, open (the click) or dismiss. */
+ /**
+ * IPC omnirushPlacementAction {action, displayId, id?, sessionId?}:
+ * rendered, viewable, open (the click) or dismiss of a display;
+ * conversation {sessionId} (a turn started in it) and activity (both
+ * resolve `rotate`: the home display is due for a change).
+ */
async action(input) {
- const id = typeof input?.id === "string" ? input.id : "";
const action = typeof input?.action === "string" && ACTIONS.has(input.action) ? input.action : null;
- if (!id || !action) return { ok: false };
- if (action === "impression") return { ok: service.impression(id) };
+ if (!action) return { ok: false };
+ if (action === "activity") return { ok: true, rotate: service.activity() };
+ if (action === "conversation") {
+ const sessionId = typeof input?.sessionId === "string" && input.sessionId.length <= 200 ? input.sessionId : "";
+ if (!sessionId) return { ok: false };
+ service.conversation(sessionId);
+ return { ok: true, rotate: service.activity() };
+ }
+ // The display id; a bare placement id (older windows) means its newest display.
+ const id = typeof input?.displayId === "string" && input.displayId ? input.displayId : typeof input?.id === "string" ? input.id : "";
+ if (!id || id.length > 64) return { ok: false };
+ if (action === "rendered" || action === "impression") return { ok: service.rendered(id) };
+ if (action === "viewable") return { ok: service.viewable(id) };
if (action === "dismiss") return { ok: service.dismiss(id) };
const url = service.click(id);
if (!url) return { ok: false };
diff --git a/apps/desktop/electron/placements-desktop.test.mjs b/apps/desktop/electron/placements-desktop.test.mjs
index 62c2e56a..910c1014 100644
--- a/apps/desktop/electron/placements-desktop.test.mjs
+++ b/apps/desktop/electron/placements-desktop.test.mjs
@@ -21,7 +21,7 @@ import {
parsePlacement,
placementsQuery,
} from "./placements/placements.mjs";
-import { createDesktopPlacements, desktopPlacementsAllowed } from "./placements-desktop.mjs";
+import { createDesktopPlacements, desktopPlacementsAllowed, WINDOW_STATE_CHANNEL, watchWindowForPlacements } from "./placements-desktop.mjs";
import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
@@ -111,7 +111,10 @@ test("shared: caps, snooze and expiry", async () => {
const a = make();
await a.refresh();
assert.ok(a.claim("home_banner"));
- assert.equal(make().claim("home_banner"), null, "max_per_day 1: not again today");
+ const same = make();
+ assert.ok(same.claim("home_banner"), "a restart within 30 minutes: the same display");
+ same.conversation("ses_new");
+ assert.equal(same.claim("home_banner"), null, "a new display is due; max_per_day 1: not again today");
now = T0 + DAY;
const b = make();
await b.refresh();
@@ -149,7 +152,7 @@ test("shared: events go to /client/placements/events?client=desktop", async () =
const paths = [];
const { d } = desktop({ routes: (p) => { paths.push(p); return p.startsWith("/client/placements/events") ? { status: 204 } : { status: 200, data: answer() }; } });
const p = await d.placement({ slot: "home_banner" });
- await d.action({ id: p.id, action: "impression" });
+ await d.action({ id: p.id, displayId: p.displayId, action: "rendered" });
assert.equal(await d.service.flush(), 1);
assert.equal(paths.at(-1), "/client/placements/events?client=desktop");
});
@@ -171,9 +174,11 @@ test("desktop: asks with client=desktop and the OS, 2 s timeout, and hands the w
const p = await d.placement({ slot: "home_banner" });
assert.equal(calls[0].path, "/client/placements?client=desktop&version=3.5.5&os=mac");
assert.equal(calls[0].timeoutMs, FETCH_TIMEOUT_MS);
- assert.deepEqual(Object.keys(p).sort(), ["body", "ctaLabel", "id", "imageUrl", "label", "slot", "snoozeDays", "sponsor", "title", "url"]);
+ assert.deepEqual(Object.keys(p).sort(), ["body", "ctaLabel", "displayId", "id", "imageUrl", "label", "slot", "snoozeDays", "sponsor", "surface", "title", "url"]);
assert.equal(p.label, "Sponsored · Acme");
- // The same one for the rest of the run.
+ assert.equal(p.surface, "desktop_home");
+ assert.match(p.displayId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
+ // The same display while nothing changed.
assert.deepEqual(await d.placement({ slot: "home_banner" }), p);
assert.equal(calls.length, 1, "asked once");
});
@@ -217,14 +222,87 @@ test("desktop: OMNIRUSH_PLACEMENTS=0: never asks", async () => {
test("desktop: open (the click) opens the placement's own https link; dismiss snoozes; bad input is refused", async () => {
const { d, opened } = desktop();
const p = await d.placement({ slot: "home_banner" });
- assert.deepEqual(await d.action({ id: p.id, action: "impression" }), { ok: true });
- assert.deepEqual(await d.action({ id: p.id, action: "open" }), { ok: true, opened: true });
+ const displayId = p.displayId;
+ assert.deepEqual(await d.action({ displayId, action: "rendered" }), { ok: true });
+ assert.deepEqual(await d.action({ displayId, action: "open" }), { ok: true, opened: true });
assert.deepEqual(opened, ["https://acme.example/ci"]);
- assert.deepEqual(await d.action({ id: "other", action: "open" }), { ok: false });
- assert.deepEqual(await d.action({ id: p.id, action: "navigate" }), { ok: false });
- assert.deepEqual(await d.action({ id: p.id, action: "dismiss" }), { ok: true });
+ assert.deepEqual(await d.action({ displayId: "other", action: "open" }), { ok: false });
+ assert.deepEqual(await d.action({ displayId, action: "navigate" }), { ok: false });
+ assert.deepEqual(await d.action({ displayId, action: "dismiss" }), { ok: true });
assert.equal(await d.placement({ slot: "home_banner" }), null);
- assert.deepEqual(d.service.state().events.map((e) => e.kind), ["impression", "click", "dismiss"]);
+ assert.deepEqual(d.service.state().events.map((e) => e.kind), ["rendered", "click", "dismiss"]);
+});
+
+test("desktop: viewable once per display, with the exact event shape", async () => {
+ const { d } = desktop();
+ const p = await d.placement({ slot: "home_banner" });
+ assert.deepEqual(await d.action({ displayId: p.displayId, action: "rendered" }), { ok: true });
+ assert.deepEqual(await d.action({ displayId: p.displayId, action: "rendered" }), { ok: false }, "once");
+ assert.deepEqual(await d.action({ displayId: p.displayId, action: "viewable" }), { ok: true });
+ assert.deepEqual(await d.action({ displayId: p.displayId, action: "viewable" }), { ok: false }, "never recounted");
+ // The window asks again (re-mount, focus): the same display, nothing new.
+ const again = await d.placement({ slot: "home_banner" });
+ assert.equal(again.displayId, p.displayId);
+ assert.deepEqual(await d.action({ displayId: again.displayId, action: "viewable" }), { ok: false });
+ assert.deepEqual(d.service.state().events, [
+ { display_id: p.displayId, placement_id: "plc_abc", kind: "rendered", surface: "desktop_home" },
+ { display_id: p.displayId, placement_id: "plc_abc", kind: "viewable", surface: "desktop_home" },
+ ]);
+});
+
+test("desktop: the turn line is its own display (desktop_turn), viewable too", async () => {
+ const { d } = desktop({ routes: () => ({ status: 200, data: answer([placement({ id: "plc_t", slot: "turn_footer", max_per_day: 5 })]) }) });
+ const t = await d.placement({ slot: "turn_footer", sessionId: "ses_1" });
+ assert.equal(t.surface, "desktop_turn");
+ assert.deepEqual(await d.action({ displayId: t.displayId, action: "viewable" }), { ok: true });
+ assert.deepEqual(d.service.state().events.map((e) => `${e.kind}:${e.surface}`), ["viewable:desktop_turn"]);
+});
+
+test("desktop: rotation: a new conversation or 30 idle minutes gives a new display; activity keeps it", async () => {
+ let now = T0;
+ const { d } = desktop({ now: () => now, routes: () => ({ status: 200, data: answer([placement({ max_per_day: 10 })]) }) });
+ const a = await d.placement({ slot: "home_banner" });
+ assert.deepEqual(await d.action({ action: "conversation", sessionId: "ses_1" }), { ok: true, rotate: true });
+ const b = await d.placement({ slot: "home_banner" });
+ assert.notEqual(b.displayId, a.displayId, "new conversation");
+ assert.deepEqual(await d.action({ action: "conversation", sessionId: "ses_1" }), { ok: true, rotate: false }, "the same one again: no change");
+ for (let i = 0; i < 4; i++) {
+ now += 20 * 60_000;
+ assert.deepEqual(await d.action({ action: "activity" }), { ok: true, rotate: false });
+ }
+ assert.equal((await d.placement({ slot: "home_banner" })).displayId, b.displayId, "active all along: same display");
+ now += 31 * 60_000;
+ assert.deepEqual(await d.action({ action: "activity" }), { ok: true, rotate: true }, "back after 31 idle minutes");
+ const c = await d.placement({ slot: "home_banner" });
+ assert.notEqual(c.displayId, b.displayId);
+ assert.deepEqual(await d.action({ action: "conversation" }), { ok: false }, "needs a session");
+});
+
+test("desktop: the window state goes to the page on focus, blur, minimize, restore, show and hide", () => {
+ const handlers = new Map();
+ const sent = [];
+ const state = { focused: true, minimized: false, visible: true };
+ const win = {
+ on: (name, fn) => handlers.set(name, fn),
+ removeListener: (name) => handlers.delete(name),
+ isFocused: () => state.focused,
+ isMinimized: () => state.minimized,
+ isVisible: () => state.visible,
+ isDestroyed: () => false,
+ webContents: { send: (channel, detail) => sent.push({ channel, detail }), isDestroyed: () => false },
+ };
+ const off = watchWindowForPlacements(win);
+ assert.deepEqual([...handlers.keys()].sort(), ["blur", "focus", "hide", "minimize", "restore", "show"]);
+ state.focused = false;
+ state.minimized = true;
+ handlers.get("minimize")();
+ assert.deepEqual(sent, [{ channel: WINDOW_STATE_CHANNEL, detail: { focused: false, minimized: true, visible: true } }]);
+ off();
+ assert.equal(handlers.size, 0);
+ const preload = fs.readFileSync(path.join(here, "preload.mjs"), "utf8");
+ assert.ok(preload.includes(`ipcRenderer.on("${WINDOW_STATE_CHANNEL}"`), "the preload passes it on");
+ const main = fs.readFileSync(path.join(here, "main.mjs"), "utf8");
+ assert.match(main, /watchWindowForPlacements\(mainWindow\)/);
});
test("desktop: the cache lives in the app's data folder, not in any workspace", async () => {
diff --git a/apps/desktop/electron/placements/PARITY.sha256 b/apps/desktop/electron/placements/PARITY.sha256
index 410208b9..f67a7e9b 100644
--- a/apps/desktop/electron/placements/PARITY.sha256
+++ b/apps/desktop/electron/placements/PARITY.sha256
@@ -1,3 +1,3 @@
# Sponsored placements: the same file in omnirush-cli (assets/extensions/omnirush/placements/)
# and omnirush-gui (apps/desktop/electron/placements/). A change to one must be ported to the other and this list updated in both.
-fc2c3cabdde4c1460481324807abd058575540bad2a2c95e1fe883018687f543 placements.mjs
+47323966e54972473adb398c358af34ed9451d452e9deb977e7fffcbf12ccc74 placements.mjs
diff --git a/apps/desktop/electron/placements/placements.mjs b/apps/desktop/electron/placements/placements.mjs
index 74a361c1..e5fb29cd 100644
--- a/apps/desktop/electron/placements/placements.mjs
+++ b/apps/desktop/electron/placements/placements.mjs
@@ -11,19 +11,33 @@
// start-up never waits for it.
//
// Local rules, on top of the server's: a placement's window (starts_at,
-// ends_at), `max_per_day` per placement per local day, `snooze_days` after a
-// dismissal, the home slot once per app run (the same one stays for the run),
-// the turn slot once per session. Copy is plain text, clamped (sponsor 40,
-// title 60, body 140, CTA 20) and always labelled "Sponsored · <sponsor>";
-// links are https only and opened by the app only after a click.
+// ends_at), `max_per_day` displays per placement per local day, at most
+// `max_per_advertiser_per_day` (default 3) displays per `advertiser_id` (else
+// per sponsor name) per local day, `snooze_days` after a dismissal, the turn
+// slot once per session. Copy is plain text,
+// clamped (sponsor 40, title 60, body 140, CTA 20) and always labelled
+// "Sponsored · <sponsor>"; links are https only and opened by the app only
+// after a click.
//
-// Events (impression, click, dismiss: id, kind, time, nothing else) are
-// queued in the same file and sent in batches, best effort; a 404 or an
-// answer that says placements are off drops them.
+// Displays: every time a placement is put on screen anew it gets a display
+// id, a random UUID made here (never derived from the user, device or
+// account). The home slot keeps its display (same placement, same id, nothing
+// counted or sent again) until a new conversation starts or after
+// `rotate_after_idle_minutes` (default 30) without activity; only then may a
+// new display (and a new placement) come.
+//
+// Events: { display_id, placement_id, kind, surface } and nothing else, at
+// most one of each kind per display. Kinds: rendered (drawn), viewable (desktop only:
+// the window measured ≥ 50% of the card on screen for one continuous second
+// while focused and visible), click, dismiss. Surfaces: desktop_home,
+// desktop_turn, cli_home, cli_turn. The CLI never sends viewable. Queued in the
+// same file and sent in batches, best effort; a 404 or an answer that says
+// placements are off drops them.
//
// Nothing here touches sessions, prompts, files or uploads. Node builtins
// only; the transport (`request`) is the app's own authorized call.
+import { randomUUID } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
@@ -42,7 +56,17 @@ export const CACHE_MAX_AGE_MS = 24 * 3_600_000;
export const DEFAULT_SNOOZE_DAYS = 7;
export const MAX_SNOOZE_DAYS = 365;
export const MAX_PER_DAY_LIMIT = 24;
-export const EVENT_KINDS = Object.freeze(["impression", "click", "dismiss"]);
+export const EVENT_KINDS = Object.freeze(["rendered", "viewable", "click", "dismiss"]);
+/** Where a display was: `${client}_${home|turn}`. */
+export const SURFACES = Object.freeze(["desktop_home", "desktop_turn", "cli_home", "cli_turn"]);
+/** The surfaces whose displays may be measured viewable (the CLI's never are). */
+export const VIEWABLE_SURFACES = Object.freeze(["desktop_home", "desktop_turn"]);
+/** The home slot's display changes after this long without activity (or on a new conversation), unless the placement says `rotate_after_idle_minutes`. */
+export const ROTATE_IDLE_MS = 30 * 60_000;
+/** Displays per advertiser per local day (both slots), unless the placement says `max_per_advertiser_per_day`. */
+export const ADVERTISER_DAILY_CAP = 3;
+/** Displays remembered (for once-per-display events), the newest. */
+export const MAX_DISPLAYS = 300;
export const EVENT_FLUSH_MS = 60_000;
export const MAX_QUEUED_EVENTS = 200;
export const MAX_EVENT_BATCH = 50;
@@ -50,6 +74,8 @@ export const MAX_EVENT_BATCH = 50;
export const MAX_FOOTER_SESSIONS = 500;
const DAY_MS = 86_400_000;
const STATE_VERSION = 1;
+const ID_RE = /^[A-Za-z0-9._:-]{1,64}$/;
+const DISPLAY_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
// --- copy -------------------------------------------------------------------
@@ -97,7 +123,7 @@ function intIn(value, min, max, fallback) {
*/
export function parsePlacement(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const id = typeof raw.id === "string" && /^[A-Za-z0-9._:-]{1,64}$/.test(raw.id) ? raw.id : null;
+ const id = typeof raw.id === "string" && ID_RE.test(raw.id) ? raw.id : null;
const slot = SLOTS.includes(raw.slot) ? raw.slot : null;
const sponsor = clampText(raw.sponsor, LIMITS.sponsor);
const title = clampText(raw.title, LIMITS.title);
@@ -123,9 +149,23 @@ export function parsePlacement(raw) {
maxPerDay: intIn(raw.max_per_day, 1, MAX_PER_DAY_LIMIT, 1),
snoozeDays: intIn(raw.snooze_days, 1, MAX_SNOOZE_DAYS, DEFAULT_SNOOZE_DAYS),
priority: intIn(raw.priority, -1_000_000, 1_000_000, 0),
+ // The frequency cap's key: the server's advertiser id, else the sponsor's name.
+ advertiser: advertiserId(raw.advertiser_id) ?? `name:${sponsor.toLowerCase()}`,
+ maxPerAdvertiserPerDay: intIn(raw.max_per_advertiser_per_day, 1, MAX_PER_DAY_LIMIT, ADVERTISER_DAILY_CAP),
+ rotateAfterIdleMs: intIn(raw.rotate_after_idle_minutes, 1, 1_440, ROTATE_IDLE_MS / 60_000) * 60_000,
};
}
+function advertiserId(value) {
+ if (typeof value === "number" && Number.isSafeInteger(value)) return `id:${value}`;
+ return typeof value === "string" && ID_RE.test(value) ? `id:${value}` : null;
+}
+
+/** The surface of `slot` in `client`: desktop_home, desktop_turn, cli_home or cli_turn. */
+export function surfaceOf(client, slot) {
+ return `${client === "desktop" ? "desktop" : "cli"}_${slot === "turn_footer" ? "turn" : "home"}`;
+}
+
/**
* The server's answer: { enabled, refreshAfterS, placements } with only the
* usable placements, or null when it is not an answer at all. Off unless
@@ -169,10 +209,12 @@ export function placementLine(placement, { width = 100, suffix = "" } = {}) {
return clampText(head, room);
}
-/** The placement as the apps show it (the UI never sees more). */
-export function placementView(placement) {
+/** The placement as the apps show it (the UI never sees more), with its display. */
+export function placementView(placement, display = null) {
return {
id: placement.id,
+ displayId: display?.display_id ?? null,
+ surface: display?.surface ?? null,
slot: placement.slot,
label: sponsoredLabel(placement),
sponsor: placement.sponsor,
@@ -213,7 +255,22 @@ export function localDay(ms) {
/** An empty state. */
export function emptyState() {
- return { v: STATE_VERSION, fetched_at: 0, answer: null, shown: {}, snoozed: {}, hidden_until: 0, footer_sessions: [], events: [] };
+ return {
+ v: STATE_VERSION,
+ fetched_at: 0,
+ answer: null,
+ shown: {},
+ snoozed: {},
+ hidden_until: 0,
+ footer_sessions: [],
+ events: [],
+ displays: {},
+ advertisers: {},
+ home_display: null,
+ last_active_at: 0,
+ rotate_home: false,
+ last_conversation: null,
+ };
}
function record(value) {
@@ -237,6 +294,17 @@ export function readState(file) {
}
const snoozed = {};
for (const [id, until] of Object.entries(record(data.snoozed))) if (Number.isFinite(until)) snoozed[id] = until;
+ const displays = {};
+ for (const [displayId, entry] of Object.entries(record(data.displays))) {
+ const d = record(entry);
+ if (!DISPLAY_ID_RE.test(displayId) || typeof d.id !== "string" || !SLOTS.includes(d.slot) || !SURFACES.includes(d.surface) || !Number.isFinite(d.at)) continue;
+ displays[displayId] = { display_id: displayId, id: d.id, slot: d.slot, surface: d.surface, at: d.at, sent: Array.isArray(d.sent) ? d.sent.filter((k) => EVENT_KINDS.includes(k)) : [] };
+ }
+ const advertisers = {};
+ for (const [key, entry] of Object.entries(record(data.advertisers))) {
+ const e = record(entry);
+ if (typeof e.day === "string" && Number.isFinite(e.count)) advertisers[key] = { day: e.day, count: Math.max(0, Math.floor(e.count)) };
+ }
return {
...base,
fetched_at: Number.isFinite(data.fetched_at) ? data.fetched_at : 0,
@@ -245,12 +313,25 @@ export function readState(file) {
snoozed,
hidden_until: Number.isFinite(data.hidden_until) ? data.hidden_until : 0,
footer_sessions: Array.isArray(data.footer_sessions) ? data.footer_sessions.filter((s) => typeof s === "string").slice(-MAX_FOOTER_SESSIONS) : [],
- events: Array.isArray(data.events)
- ? data.events.filter((e) => e && typeof e.id === "string" && EVENT_KINDS.includes(e.kind) && typeof e.at === "string").slice(-MAX_QUEUED_EVENTS)
- : [],
+ events: Array.isArray(data.events) ? data.events.filter(validEvent).slice(-MAX_QUEUED_EVENTS) : [],
+ displays,
+ advertisers,
+ home_display: typeof data.home_display === "string" && displays[data.home_display]?.slot === "home_banner" ? data.home_display : null,
+ last_active_at: Number.isFinite(data.last_active_at) ? data.last_active_at : 0,
+ rotate_home: data.rotate_home === true,
+ last_conversation: typeof data.last_conversation === "string" ? data.last_conversation.slice(0, 200) : null,
};
}
+/** An event as it is queued and sent: { display_id, placement_id, kind, surface }, nothing else. */
+export function validEvent(e) {
+ return Boolean(e) && typeof e === "object" && !Array.isArray(e) && Object.keys(e).length === 4
+ && typeof e.display_id === "string" && DISPLAY_ID_RE.test(e.display_id)
+ && typeof e.placement_id === "string" && ID_RE.test(e.placement_id)
+ && EVENT_KINDS.includes(e.kind) && SURFACES.includes(e.surface)
+ && (e.kind !== "viewable" || VIEWABLE_SURFACES.includes(e.surface));
+}
+
export function writeState(file, state) {
try {
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
@@ -278,7 +359,7 @@ export function refreshDue(state, now) {
return now - state.fetched_at >= every || state.fetched_at - now > DAY_MS;
}
-/** Whether `placement` may show in `slot` now (window, snooze, the day's count, hidden). */
+/** Whether `placement` may show in `slot` now (window, snooze, the day's counts, hidden). */
export function eligible(placement, slot, state, now) {
if (placement.slot !== slot) return false;
if (placement.startsAt !== null && now < placement.startsAt) return false;
@@ -288,6 +369,8 @@ export function eligible(placement, slot, state, now) {
if (Number.isFinite(snoozedUntil) && now < snoozedUntil) return false;
const shown = state.shown[placement.id];
if (shown && shown.day === localDay(now) && shown.count >= placement.maxPerDay) return false;
+ const advertiser = state.advertisers?.[placement.advertiser];
+ if (advertiser && advertiser.day === localDay(now) && advertiser.count >= placement.maxPerAdvertiserPerDay) return false;
return true;
}
@@ -319,6 +402,7 @@ const noop = () => undefined;
* flushMs?: number,
* setTimer?: (fn: () => void, ms: number) => any,
* clearTimer?: (timer: any) => void,
+ * newDisplayId?: () => string,
* }} PlacementsOptions
*/
@@ -343,21 +427,31 @@ export function createPlacements({
flushMs = EVENT_FLUSH_MS,
setTimer = (fn, ms) => setTimeout(fn, ms),
clearTimer = (timer) => clearTimeout(timer),
+ newDisplayId = randomUUID,
}) {
+ const appClient = client === "desktop" ? "desktop" : "cli";
let state = allowed ? readState(stateFile) : emptyState();
let refreshTimer = null;
let flushTimer = null;
let inFlight = null;
let stopped = false;
let started = false;
- /** This run's choice per slot: the home slot keeps its placement for the run. */
- const runClaims = new Map();
+ /** This run's turn-slot display (the last one claimed). */
+ let footerDisplay = null;
const footerSessions = new Set(state.footer_sessions);
const save = () => (allowed ? writeState(stateFile, state) : false);
const answer = () => cachedAnswer(state, now());
/** The placement with `id` (in `slot` when given: one id may have an entry per slot). */
const known = (id, slot = null) => answer()?.placements.find((p) => p.id === id && (!slot || p.slot === slot)) ?? null;
+ /** A display by its id, or (older callers) the newest display of a placement id. */
+ const displayOf = (ref) => {
+ if (typeof ref !== "string" || !ref) return null;
+ if (Object.hasOwn(state.displays, ref)) return state.displays[ref];
+ let newest = null;
+ for (const d of Object.values(state.displays)) if (d.id === ref && (!newest || d.at >= newest.at)) newest = d;
+ return newest;
+ };
const schedule = () => {
if (stopped || !started) return;
@@ -371,9 +465,13 @@ export function createPlacements({
refreshTimer?.unref?.();
};
- const queue = (id, kind) => {
- if (!allowed || !EVENT_KINDS.includes(kind) || !known(id) || !answer()?.enabled) return false;
- state.events.push({ id, kind, at: new Date(now()).toISOString() });
+ /** One event for a display, at most once per kind; false when it may not be sent. */
+ const queue = (display, kind) => {
+ if (!allowed || !display || !EVENT_KINDS.includes(kind) || !answer()?.enabled || !known(display.id, display.slot)) return false;
+ if (kind === "viewable" && !VIEWABLE_SURFACES.includes(display.surface)) return false;
+ if (display.sent.includes(kind)) return false;
+ display.sent.push(kind);
+ state.events.push({ display_id: display.display_id, placement_id: display.id, kind, surface: display.surface });
if (state.events.length > MAX_QUEUED_EVENTS) state.events = state.events.slice(-MAX_QUEUED_EVENTS);
save();
if (!flushTimer && !stopped && started) {
@@ -386,6 +484,41 @@ export function createPlacements({
return true;
};
+ /** A new display of `placement` in `slot`: counted for the day (placement and advertiser). */
+ const newDisplay = (placement, slot, at) => {
+ let displayId = String(newDisplayId()).toLowerCase();
+ while (Object.hasOwn(state.displays, displayId)) displayId = String(newDisplayId()).toLowerCase();
+ const day = localDay(at);
+ const shown = state.shown[placement.id];
+ state.shown[placement.id] = { day, count: shown && shown.day === day ? shown.count + 1 : 1 };
+ const advertiser = state.advertisers[placement.advertiser];
+ state.advertisers[placement.advertiser] = { day, count: advertiser && advertiser.day === day ? advertiser.count + 1 : 1 };
+ // Old days are forgotten.
+ for (const [id, entry] of Object.entries(state.shown)) if (entry.day !== day) delete state.shown[id];
+ for (const [key, entry] of Object.entries(state.advertisers)) if (entry.day !== day) delete state.advertisers[key];
+ const display = { display_id: displayId, id: placement.id, slot, surface: surfaceOf(appClient, slot), at, sent: [] };
+ state.displays[displayId] = display;
+ const all = Object.values(state.displays);
+ if (all.length > MAX_DISPLAYS) {
+ all.sort((a, b) => a.at - b.at);
+ for (const old of all.slice(0, all.length - MAX_DISPLAYS)) if (old.display_id !== state.home_display) delete state.displays[old.display_id];
+ }
+ return display;
+ };
+
+ /** How long the home display may sit idle before it changes (its placement's `rotate_after_idle_minutes`). */
+ const idleLimit = () => {
+ const kept = state.home_display ? state.displays[state.home_display] : null;
+ return (kept ? known(kept.id, kept.slot)?.rotateAfterIdleMs : null) ?? ROTATE_IDLE_MS;
+ };
+ /** Activity: after the idle limit without any, the home display changes when next asked. */
+ const touch = (at) => {
+ if (state.last_active_at && state.home_display && at - state.last_active_at >= idleLimit()) state.rotate_home = true;
+ const changed = at - state.last_active_at >= 60_000 || at < state.last_active_at;
+ state.last_active_at = at;
+ return changed;
+ };
+
const service = {
/** Starts the background refresh (never waited for). */
start() {
@@ -448,59 +581,107 @@ export function createPlacements({
}
},
/**
- * The placement to show in `slot`, counted as shown for the day, or null.
- * The home slot: once per run (later asks get the same one, not counted
- * again). The turn slot: once per `sessionId`, ever.
+ * The placement to show in `slot` with its display, or null.
+ * The home slot: the same display (not counted, nothing sent again) until
+ * a new conversation or the idle limit without activity; then a new one
+ * (or nothing). The turn slot: once per `sessionId`, ever.
*/
claim(slot, { sessionId = null } = {}) {
if (!allowed || !SLOTS.includes(slot)) return null;
const at = now();
- if (slot === "home_banner" && runClaims.has(slot)) {
- const kept = known(runClaims.get(slot), slot);
- return kept && eligibleKept(kept, at) ? placementView(kept) : null;
- }
if (slot === "turn_footer") {
if (typeof sessionId !== "string" || !sessionId || footerSessions.has(sessionId)) return null;
- }
- const placement = pickPlacement(answer(), slot, state, at);
- if (!placement) return null;
- const day = localDay(at);
- const shown = state.shown[placement.id];
- state.shown[placement.id] = { day, count: shown && shown.day === day ? shown.count + 1 : 1 };
- // Old days are forgotten.
- for (const [id, entry] of Object.entries(state.shown)) if (entry.day !== day && id !== placement.id) delete state.shown[id];
- if (slot === "turn_footer") {
+ const placement = pickPlacement(answer(), slot, state, at);
+ if (!placement) return null;
+ touch(at);
footerSessions.add(sessionId);
state.footer_sessions = [...state.footer_sessions.filter((s) => s !== sessionId), sessionId].slice(-MAX_FOOTER_SESSIONS);
+ footerDisplay = newDisplay(placement, slot, at).display_id;
+ save();
+ return placementView(placement, state.displays[footerDisplay]);
+ }
+ // Idle since the last activity: due for a new display.
+ const wasChanged = touch(at);
+ const kept = state.home_display ? state.displays[state.home_display] : null;
+ if (kept && !state.rotate_home) {
+ const placement = known(kept.id, slot);
+ if (wasChanged) save();
+ return placement && eligibleKept(placement, at) ? placementView(placement, kept) : null;
+ }
+ const placement = pickPlacement(answer(), slot, state, at);
+ if (!placement) {
+ // Due for a change with nothing to show: the old display is over.
+ if (kept) {
+ state.home_display = null;
+ state.rotate_home = false;
+ }
+ if (wasChanged || kept) save();
+ return null;
}
- runClaims.set(slot, placement.id);
+ state.rotate_home = false;
+ state.home_display = newDisplay(placement, slot, at).display_id;
save();
- return placementView(placement);
+ return placementView(placement, state.displays[state.home_display]);
},
- /** The placement this run claimed for `slot` (not counted again), or null. */
+ /** The display shown in `slot` now (not counted again), or null. */
current(slot) {
- const id = runClaims.get(slot);
- const placement = id ? known(id, slot) : null;
- return placement && eligibleKept(placement, now()) ? placementView(placement) : null;
+ const displayId = slot === "home_banner" ? state.home_display : slot === "turn_footer" ? footerDisplay : null;
+ const display = displayId ? state.displays[displayId] : null;
+ const placement = display ? known(display.id, slot) : null;
+ return placement && eligibleKept(placement, now()) ? placementView(placement, display) : null;
+ },
+ /**
+ * A conversation started or was picked up (any opaque local id, never
+ * sent): a different one than last time means the home slot's next ask is
+ * a new display.
+ */
+ conversation(conversationId) {
+ if (!allowed || typeof conversationId !== "string" || !conversationId) return false;
+ const at = now();
+ touch(at);
+ const id = conversationId.slice(0, 200);
+ const changed = id !== state.last_conversation;
+ if (changed) {
+ state.last_conversation = id;
+ if (state.home_display) state.rotate_home = true;
+ }
+ save();
+ return changed;
+ },
+ /** The user did something (typed, clicked); resolves whether the home display is due for a change. */
+ activity() {
+ if (!allowed) return false;
+ if (touch(now())) save();
+ return state.rotate_home;
+ },
+ /** It was drawn on screen (once per display). */
+ rendered(ref) {
+ return queue(displayOf(ref), "rendered");
+ },
+ /** Older name for rendered. */
+ impression(ref) {
+ return service.rendered(ref);
},
- /** It was drawn on screen. */
- impression(id) {
- return queue(id, "impression");
+ /** The window measured it viewable (desktop surfaces only, once per display). */
+ viewable(ref) {
+ return queue(displayOf(ref), "viewable");
},
- /** The click: its https link (the app opens it) or null. */
- click(id) {
- const placement = known(id);
+ /** The click: its https link (the app opens it) or null; one click event per display. */
+ click(ref) {
+ const display = displayOf(ref);
+ const placement = display ? known(display.id, display.slot) : null;
if (!placement) return null;
- queue(id, "click");
+ queue(display, "click");
+ touch(now());
return placement.url;
},
- /** × / hide: snoozed for its `snooze_days`; gone from this run. */
- dismiss(id) {
- const placement = known(id);
+ /** × / hide: snoozed for its `snooze_days`; the slot stays empty until its next display. */
+ dismiss(ref) {
+ const display = displayOf(ref);
+ const placement = display ? known(display.id, display.slot) : null;
if (!allowed || !placement) return false;
- queue(id, "dismiss");
- state.snoozed[id] = now() + placement.snoozeDays * DAY_MS;
- for (const [slot, claimed] of runClaims) if (claimed === id) runClaims.delete(slot);
+ queue(display, "dismiss");
+ state.snoozed[placement.id] = now() + placement.snoozeDays * DAY_MS;
save();
return true;
},
@@ -508,7 +689,6 @@ export function createPlacements({
hideAll(days = 30) {
const n = intIn(days, 0, MAX_SNOOZE_DAYS, 30);
state.hidden_until = n > 0 ? now() + n * DAY_MS : 0;
- if (n > 0) runClaims.clear();
return save() || !allowed;
},
/** What `omnirush placements` prints. */
@@ -537,7 +717,7 @@ export function createPlacements({
const batch = state.events.slice(0, MAX_EVENT_BATCH);
let result = null;
try {
- result = await request(`${EVENTS_PATH}?client=${client === "desktop" ? "desktop" : "cli"}`, { method: "POST", body: { events: batch }, timeoutMs });
+ result = await request(`${EVENTS_PATH}?client=${appClient}`, { method: "POST", body: { events: batch }, timeoutMs });
} catch {
result = null;
}
@@ -561,7 +741,7 @@ export function createPlacements({
state: () => state,
};
- // A placement kept for the run stays while its window, snooze and hide allow it.
+ // A display kept on screen stays while its window, snooze and hide allow it.
function eligibleKept(placement, at) {
if (!answer()?.enabled) return false;
if (placement.endsAt !== null && at >= placement.endsAt) return false;
diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjs
index e3b99791..3e78763e 100644
--- a/apps/desktop/electron/preload.mjs
+++ b/apps/desktop/electron/preload.mjs
@@ -351,6 +351,12 @@ ipcRenderer.on(FINISH_GUARD_EVENT, (_event, detail) => {
window.dispatchEvent(new CustomEvent(FINISH_GUARD_EVENT, { detail }));
});
+// Sponsored placements (placements-desktop.mjs WINDOW_STATE_CHANNEL): the window's focus / minimize / show state.
+ipcRenderer.on("omnirush:placements:window", (_event, detail) => {
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(new CustomEvent("omnirush:placements:window", { detail }));
+});
+
ipcRenderer.on(NATIVE_MENU_ZOOM_EVENT, (_event, action) => {
if (typeof window === "undefined") return;
window.dispatchEvent(new CustomEvent(NATIVE_MENU_ZOOM_EVENT, { detail: action }));
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index bb8bcba3..dc5c7807 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -387,8 +387,12 @@ export type OmniRushBuildathonTagResult = "tagged" | "refused" | "retry";
/** A sponsored placement as the window draws it (apps/desktop/electron/placements/placements.mjs placementView). */
export type OmniRushPlacementSlot = "home_banner" | "turn_footer";
+export type OmniRushPlacementSurface = "desktop_home" | "desktop_turn";
export type OmniRushPlacement = {
id: string;
+ /** This display's id (a random UUID made by the main process); every event about it carries it. */
+ displayId: string;
+ surface: OmniRushPlacementSurface;
slot: OmniRushPlacementSlot;
/** "Sponsored · <sponsor>" */
label: string;
@@ -405,7 +409,8 @@ export type OmniRushPlacement = {
imageUrl: string | null;
snoozeDays: number;
};
-export type OmniRushPlacementAction = "impression" | "open" | "dismiss";
+/** rendered / viewable / open (the click) / dismiss: about one display; conversation / activity: for the display rotation. */
+export type OmniRushPlacementAction = "rendered" | "viewable" | "open" | "dismiss" | "conversation" | "activity";
export type OmniRushSessionStatus = {
sessionId: string;
@@ -965,7 +970,7 @@ export type DesktopCommandMap = {
omnirushBuildathon: { args: []; result: OmniRushBuildathonAnswer };
omnirushBuildathonJoin: { args: []; result: OmniRushBuildathonLinkResult };
omnirushPlacement: { args: [input: { slot: OmniRushPlacementSlot; sessionId?: string }]; result: OmniRushPlacement | null };
- omnirushPlacementAction: { args: [input: { id: string; action: OmniRushPlacementAction }]; result: { ok: boolean; opened?: boolean } };
+ omnirushPlacementAction: { args: [input: { action: OmniRushPlacementAction; id?: string; displayId?: string; sessionId?: string }]; result: { ok: boolean; opened?: boolean; rotate?: boolean } };
omnirushBuildathonSessions: { args: []; result: OmniRushBuildathonSession[] | null };
omnirushBuildathonLink: { args: [input: { code: string }]; result: OmniRushBuildathonLinkResult };
omnirushBuildathonChecklist: {