A desktop coding agent with free access to frontier models.
TypeScript
feat: sponsored placement slot
Samrat Talukdarf998085e5eea
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex 26b93f0a..0a85b63c 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -808,6 +808,8 @@ const {omnirushBuildathonSessions,omnirushBuildathonLink,omnirushBuildathonJoin,+ omnirushPlacement,+ omnirushPlacementAction,omnirushBuildathonTagSession,omnirushBuildathonChecklist,omnirushAccountConnect,@@ -880,6 +882,8 @@ export {omnirushBuildathonSessions,omnirushBuildathonLink,omnirushBuildathonJoin,+ omnirushPlacement,+ omnirushPlacementAction,omnirushBuildathonTagSession,omnirushBuildathonChecklist,omnirushAccountConnect,diff --git a/apps/app/src/app/lib/placements.ts b/apps/app/src/app/lib/placements.tsnew file mode 100644index 00000000..4ae4869b--- /dev/null+++ b/apps/app/src/app/lib/placements.ts@@ -0,0 +1,156 @@+// 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.++import { create } from "zustand";++import type { OmniRushPlacement, OmniRushPlacementAction, OmniRushPlacementSlot } from "@omnirush/types/desktop-ipc";++import { omnirushPlacement, omnirushPlacementAction } from "./desktop";++export type Placement = OmniRushPlacement;++const SLOTS: readonly OmniRushPlacementSlot[] = ["home_banner", "turn_footer"];++/** 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;++function shortText(value: unknown, max: number): value is string {+ return typeof value === "string" && Array.from(value).length <= max;+}++function httpsUrl(value: unknown): value is string {+ if (typeof value !== "string") return false;+ try {+ return new URL(value).protocol === "https:";+ } catch {+ return false;+ }+}++/** What the main process sent, if it is a placement this window may draw. */+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 (!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;+ if (!httpsUrl(p.url)) return null;+ if (p.imageUrl !== null && !httpsUrl(p.imageUrl)) return null;+ return {+ id: p.id,+ slot: p.slot as OmniRushPlacementSlot,+ label: `Sponsored · ${p.sponsor}`,+ sponsor: p.sponsor,+ title: p.title,+ body: p.body,+ ctaLabel: p.ctaLabel,+ url: p.url,+ imageUrl: (p.imageUrl as string | null) ?? null,+ snoozeDays: typeof p.snoozeDays === "number" ? p.snoozeDays : 7,+ };+}++type PlacementsState = {+ /** undefined: not asked yet this run; null: nothing to show. */+ home: Placement | null | undefined;+ /** The turn line per session (null: asked, nothing; or it went away). */+ footers: Record<string, Placement | null>;+ setHome: (home: Placement | null) => void;+ setFooter: (sessionId: string, placement: Placement | null) => void;+ hide: (id: string) => void;+};++export const usePlacementsStore = create<PlacementsState>((set) => ({+ home: undefined,+ footers: {},+ 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,+ 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>;+};++let bridge: Bridge = {+ placement: (input) => omnirushPlacement(input),+ action: (input) => omnirushPlacementAction(input),+};++/** Tests: a stand-in for the main process, and a fresh run. */+export function setPlacementsBridgeForTests(next: Bridge | null): void {+ if (next) bridge = next;+ homeAsk = null;+ impressions.clear();+ 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). */+export function loadHomePlacement(): Promise<Placement | null> {+ if (homeAsk) return homeAsk;+ homeAsk = Promise.resolve()+ .then(() => bridge.placement({ slot: "home_banner" }))+ .then(asPlacement)+ .catch(() => null)+ .then((placement) => {+ usePlacementsStore.getState().setHome(placement);+ return placement;+ });+ return homeAsk;+}++/** The turn line for a session whose turn just finished (asked once per session in this run). */+export async function loadTurnFooter(sessionId: string): Promise<Placement | null> {+ if (!sessionId || sessionId in usePlacementsStore.getState().footers) return null;+ usePlacementsStore.getState().setFooter(sessionId, null);+ const placement = await Promise.resolve()+ .then(() => bridge.placement({ slot: "turn_footer", sessionId }))+ .then(asPlacement)+ .catch(() => null);+ if (placement) usePlacementsStore.getState().setFooter(sessionId, placement);+ return placement;+}++/** The next turn started: the line goes and does not come back for this session. */+export function endTurnFooter(sessionId: string): void {+ const footers = usePlacementsStore.getState().footers;+ if (footers[sessionId]) usePlacementsStore.getState().setFooter(sessionId, null);+}++const impressions = 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);+}++/** The click: the main process opens the link in the system browser. */+export function openPlacement(placement: Placement): void {+ void bridge.action({ id: placement.id, action: "open" }).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);+}++/** Whether a turn just finished: this session was running and is not any more. */+export function turnJustFinished(previous: { sessionId: string; running: boolean }, current: { sessionId: string; running: boolean }): boolean {+ return previous.sessionId === current.sessionId && previous.running && !current.running;+}diff --git a/apps/app/src/react-app/domains/placements/placements.tsx b/apps/app/src/react-app/domains/placements/placements.tsxnew file mode 100644index 00000000..83da945c--- /dev/null+++ b/apps/app/src/react-app/domains/placements/placements.tsx@@ -0,0 +1,149 @@+/** @jsxImportSource react */+// Sponsored placements (app/lib/placements.ts): a slim, quiet card on the+// home / new-chat screen and one dim line after a finished turn, once per+// session. Always labelled "Sponsored · <sponsor>"; plain text, the app's own+// 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.++import { useEffect, useRef } from "react";+import { ArrowUpRight, X } from "lucide-react";++import {+ dismissPlacement,+ endTurnFooter,+ loadHomePlacement,+ loadTurnFooter,+ openPlacement,+ placementShown,+ turnJustFinished,+ usePlacementsStore,+ type Placement,+} from "../../../app/lib/placements";++function DismissButton(props: { placement: Placement; testId: string }) {+ return (+ <button+ type="button"+ aria-label="Hide this sponsored message"+ title={`Hide for ${props.placement.snoozeDays} day${props.placement.snoozeDays === 1 ? "" : "s"}`}+ onClick={() => dismissPlacement(props.placement)}+ className="inline-flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground/70 hover:bg-accent hover:text-foreground"+ data-testid={props.testId}+ >+ <X className="size-3" aria-hidden="true" />+ </button>+ );+}++/** The home / new-chat card: under the composer and the suggestions. */+export function PlacementHomeCard() {+ const placement = usePlacementsStore((state) => state.home);+ useEffect(() => {+ void loadHomePlacement();+ }, []);+ useEffect(() => {+ if (placement) placementShown(placement, "home");+ }, [placement]);+ if (!placement) return null;+ return <PlacementHomeCardView placement={placement} />;+}++/** The card itself (tests render it directly). */+export function PlacementHomeCardView({ placement }: { placement: Placement }) {+ return (+ <aside+ aria-label={placement.label}+ data-testid="placement-home"+ data-placement-id={placement.id}+ className="flex items-center gap-3 rounded-lg border border-border/70 bg-background px-3 py-2"+ >+ {placement.imageUrl ? (+ <img+ src={placement.imageUrl}+ alt=""+ aria-hidden="true"+ draggable={false}+ referrerPolicy="no-referrer"+ className="size-8 shrink-0 rounded-md object-cover"+ data-testid="placement-home-image"+ />+ ) : null}+ <div className="min-w-0 flex-1">+ <div className="text-[10.5px] leading-4 text-muted-foreground" data-testid="placement-home-label">{placement.label}</div>+ <div className="truncate text-[12.5px] font-medium leading-5 text-foreground" data-testid="placement-home-title">{placement.title}</div>+ {placement.body ? (+ <div className="line-clamp-2 text-[12px] leading-4 text-muted-foreground" data-testid="placement-home-body">{placement.body}</div>+ ) : null}+ </div>+ <button+ type="button"+ onClick={() => openPlacement(placement)}+ className="inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-border/80 px-2.5 text-[12px] font-medium text-foreground hover:bg-accent"+ data-testid="placement-home-cta"+ >+ {placement.ctaLabel}+ <ArrowUpRight className="size-3.5 text-muted-foreground" aria-hidden="true" />+ </button>+ <DismissButton placement={placement} testId="placement-home-dismiss" />+ </aside>+ );+}++/**+ * The line after a finished turn, above the composer: asked on the running →+ * done edge of this session's turn, gone when the next turn starts, once per+ * session (the main process remembers it across runs too).+ */+export function PlacementTurnFooter(props: { sessionId: string; turnRunning: boolean }) {+ const placement = usePlacementsStore((state) => state.footers[props.sessionId] ?? null);+ const previous = useRef({ sessionId: props.sessionId, running: props.turnRunning });+ useEffect(() => {+ const before = previous.current;+ const now = { sessionId: props.sessionId, running: props.turnRunning };+ previous.current = now;+ if (props.turnRunning) {+ 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} />;+}++/** The line itself (tests render it directly). */+export function PlacementTurnFooterView({ placement }: { placement: Placement }) {+ return (+ <div className="px-4 max-lg:px-3 lg:px-8">+ <div+ role="note"+ aria-label={placement.label}+ data-testid="placement-turn-footer"+ data-placement-id={placement.id}+ 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">+ <span>{placement.label}</span>+ <span aria-hidden="true"> — </span>+ <span className="text-muted-foreground">{placement.title}</span>+ {placement.body ? <span> · {placement.body}</span> : null}+ </span>+ <button+ type="button"+ onClick={() => openPlacement(placement)}+ className="inline-flex shrink-0 items-center gap-0.5 underline-offset-2 hover:text-foreground hover:underline"+ data-testid="placement-turn-footer-cta"+ >+ {placement.ctaLabel}+ <ArrowUpRight className="size-3" aria-hidden="true" />+ </button>+ <DismissButton placement={placement} testId="placement-turn-footer-dismiss" />+ </div>+ </div>+ );+}diff --git a/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsx b/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsxindex 5384437a..7b9487e7 100644--- a/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsx+++ b/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsx@@ -6,6 +6,7 @@ import type { ComposerAttachment } from "@/app/types";import { CODING_STARTER_CARDS, resolveOrganizationPromptCardContent } from "@/components/chat/task-suggestions";import { useCheckDesktopRestriction, useOrgRestrictions } from "@/react-app/domains/cloud/desktop-config-provider";import { BuildathonPromoCard } from "@/react-app/domains/buildathon/buildathon-promo";+import { PlacementHomeCard } from "@/react-app/domains/placements/placements";import {NewTaskComposer,type NewTaskComposerContext,@@ -171,6 +172,8 @@ export function SessionEmptyHero(props: SessionEmptyHeroProps) {</div><BuildathonPromoCard />++ <PlacementHomeCard /></div>);}diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsxindex 09db38c6..468e2f23 100644--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx@@ -100,6 +100,7 @@ import { PermissionApprovalPanel } from "@/react-app/domains/session/chat/permisimport { QuestionPanel } from "@/react-app/domains/session/modals/question-modal";import { QueuedMessagesPanel } from "@/react-app/domains/session/modals/queued-messages-panel";import { GoodSessionChecklistBar, noteUserStop } from "@/react-app/domains/quality/good-session";+import { PlacementTurnFooter } from "@/react-app/domains/placements/placements";import { deriveOpenTargets, sameOpenTargets, selectAutoOpenTarget, type OpenTarget } from "@/react-app/domains/session/artifacts/open-target";import { usePanelTabStore } from "@/react-app/domains/session/panel/panel-tab-store";import {@@ -3475,6 +3476,10 @@ export function SessionSurface(props: SessionSurfaceProps) {onAutoRetry={handleAutoRetry}client={props.client}/>+ <PlacementTurnFooter+ sessionId={props.sessionId}+ turnRunning={chatStreaming || (effectiveActivityStatus !== "idle" && effectiveActivityStatus !== "error")}+ /><ReactSessionComposerrunModeControl={<WorkspaceRunModeMenu client={props.client} workspaceId={props.workspaceId} busy={chatStreaming || preparingCloudTools || Boolean(props.activePermission || props.activeQuestion)} />}fullPermissionsControl={<FullPermissionsToggle client={props.client} workspaceId={props.workspaceId} />}diff --git a/apps/app/tests/placements.test.tsx b/apps/app/tests/placements.test.tsxnew file mode 100644index 00000000..353a2195--- /dev/null+++ b/apps/app/tests/placements.test.tsx@@ -0,0 +1,172 @@+import { afterEach, describe, expect, test } from "bun:test";+import { renderToStaticMarkup } from "react-dom/server";++import {+ asPlacement,+ dismissPlacement,+ endTurnFooter,+ loadHomePlacement,+ loadTurnFooter,+ openPlacement,+ placementShown,+ setPlacementsBridgeForTests,+ turnJustFinished,+ usePlacementsStore,+} from "../src/app/lib/placements";+import { PlacementHomeCard, PlacementHomeCardView, PlacementTurnFooter, PlacementTurnFooterView } from "../src/react-app/domains/placements/placements";++const PLACEMENT = {+ id: "plc_abc",+ slot: "home_banner",+ label: "Sponsored · Acme",+ sponsor: "Acme",+ title: "Fast CI for your repo",+ body: "Run your tests in half the time.",+ ctaLabel: "Try it",+ url: "https://acme.example/ci",+ imageUrl: null,+ snoozeDays: 7,+};++function fakeMain(answer: unknown = PLACEMENT) {+ const asks: unknown[] = [];+ const actions: { id: string; action: string }[] = [];+ setPlacementsBridgeForTests({+ placement: async (input) => {+ asks.push(input);+ return typeof answer === "function" ? (answer as (i: unknown) => unknown)(input) : answer;+ },+ action: async (input) => {+ actions.push(input);+ return { ok: true };+ },+ });+ return { asks, actions };+}++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++afterEach(() => setPlacementsBridgeForTests(null));++describe("placements: what the window accepts", () => {+ test("a placement from the main process", () => {+ expect(asPlacement(PLACEMENT)?.label).toBe("Sponsored · Acme");+ });++ test("the label is always Sponsored · sponsor", () => {+ expect(asPlacement({ ...PLACEMENT, label: "Recommended" })?.label).toBe("Sponsored · Acme");+ });++ test("anything else is nothing", () => {+ for (const bad of [+ null,+ "x",+ { ...PLACEMENT, url: "http://acme.example" },+ { ...PLACEMENT, url: "javascript:alert(1)" },+ { ...PLACEMENT, imageUrl: "http://acme.example/a.png" },+ { ...PLACEMENT, slot: "modal" },+ { ...PLACEMENT, title: "" },+ { ...PLACEMENT, title: "T".repeat(61) },+ { ...PLACEMENT, body: "B".repeat(141) },+ { ...PLACEMENT, ctaLabel: "C".repeat(21) },+ { ...PLACEMENT, sponsor: "" },+ ]) {+ expect(asPlacement(bad)).toBeNull();+ }+ });+});++describe("placements: the home card", () => {+ test("nothing before an answer, and nothing for a null answer", async () => {+ fakeMain(null);+ expect(renderToStaticMarkup(<PlacementHomeCard />)).toBe("");+ await loadHomePlacement();+ expect(usePlacementsStore.getState().home).toBeNull();+ expect(renderToStaticMarkup(<PlacementHomeCard />)).toBe("");+ });++ test("a failing main process is nothing too", async () => {+ setPlacementsBridgeForTests({ placement: async () => { throw new Error("no handler"); }, action: async () => ({ ok: false }) });+ expect(await loadHomePlacement()).toBeNull();+ expect(renderToStaticMarkup(<PlacementHomeCard />)).toBe("");+ });++ test("labelled, title, body, CTA and ×; plain text, no motion", async () => {+ const { asks } = fakeMain();+ await loadHomePlacement();+ await loadHomePlacement();+ expect(asks).toEqual([{ slot: "home_banner" }]);+ const placement = usePlacementsStore.getState().home!;+ 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("Sponsored · Acme");+ expect(html).toContain("Fast CI for your repo");+ expect(html).toContain("Run your tests in half the time.");+ expect(html).toContain("Try it");+ expect(html).toContain('aria-label="Hide this sponsored message"');+ expect(html).not.toMatch(/animate-|transition|<a /);+ expect(html).not.toContain("<img");+ // The link is never in the page: the main process opens it on a click.+ expect(html).not.toContain("acme.example");+ });++ test("an https image only when there is one", async () => {+ fakeMain({ ...PLACEMENT, imageUrl: "https://acme.example/logo.png" });+ const placement = await loadHomePlacement();+ const html = renderToStaticMarkup(<PlacementHomeCardView placement={placement!} />);+ expect(html).toContain('src="https://acme.example/logo.png"');+ expect(html).toMatch(/referrerpolicy="no-referrer"/i);+ });++ test("impression once, click opens through the main process, × hides it", async () => {+ const { actions } = fakeMain();+ const placement = await loadHomePlacement();+ placementShown(placement!, "home");+ placementShown(placement!, "home");+ openPlacement(placement!);+ dismissPlacement(placement!);+ await flush();+ expect(actions).toEqual([+ { id: "plc_abc", action: "impression" },+ { id: "plc_abc", action: "open" },+ { id: "plc_abc", action: "dismiss" },+ ]);+ expect(usePlacementsStore.getState().home).toBeNull();+ });+});++describe("placements: the turn line", () => {+ test("only on the running → done edge of the same session", () => {+ expect(turnJustFinished({ sessionId: "a", running: true }, { sessionId: "a", running: false })).toBe(true);+ expect(turnJustFinished({ sessionId: "a", running: false }, { sessionId: "a", running: false })).toBe(false);+ expect(turnJustFinished({ sessionId: "a", running: true }, { sessionId: "b", running: false })).toBe(false);+ expect(turnJustFinished({ sessionId: "a", running: false }, { sessionId: "a", running: true })).toBe(false);+ });++ 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" });+ await loadTurnFooter("ses_1");+ await loadTurnFooter("ses_1");+ expect(asks).toEqual([{ slot: "turn_footer", sessionId: "ses_1" }]);+ const placement = usePlacementsStore.getState().footers.ses_1!;+ const line = renderToStaticMarkup(<PlacementTurnFooterView placement={placement} />);+ expect(line).toContain('data-testid="placement-turn-footer"');+ expect(line).toContain("Sponsored · Acme");+ expect(line).not.toMatch(/animate-|transition|<a /);+ // While a turn runs: nothing (the container's rule, before any state).+ expect(renderToStaticMarkup(<PlacementTurnFooter sessionId="ses_1" turnRunning />)).toBe("");+ expect(usePlacementsStore.getState().footers.ses_2).toBeUndefined();+ endTurnFooter("ses_1");+ expect(usePlacementsStore.getState().footers.ses_1).toBeNull();+ await loadTurnFooter("ses_1");+ expect(asks.length).toBe(1);+ });++ test("none from the main process: nothing", async () => {+ fakeMain(null);+ await loadTurnFooter("ses_1");+ expect(usePlacementsStore.getState().footers.ses_1).toBeNull();+ expect(renderToStaticMarkup(<PlacementTurnFooter sessionId="ses_1" turnRunning={false} />)).toBe("");+ });+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 53046778..eb419913 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -75,6 +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 { classifyLocalOpen, isNetworkPath, localPathFromFileUrl } from "./open-local-path.mjs";import { resolveAppIdentifier, resolveUserDataPath } from "./dev-profile.mjs";import { fetchAgentContextDiagnosticsResponse } from "./agent-context-diagnostics-fetch.mjs";@@ -1407,6 +1408,15 @@ const omnirushAccountStore = createDesktopOmniRushAccountStore({}),});+// Sponsored placements (placements-desktop.mjs): a quiet card on the home+// screen and one line after a finished turn, only when the server sends one.+const desktopPlacements = createDesktopPlacements({+ request: (pathAndQuery, init) => omnirushAccountStore.placementsRequest(pathAndQuery, init),+ userDataPath: app.getPath("userData"),+ version: app.getVersion(),+ openUrl: (url) => openExternalUrl(url),+});+function omnirushUiMcpLaunch() {return resolveOmniRushUiMcpLaunch({devMode: process.env.OMNIRUSH_DEV_MODE === "1",@@ -2408,6 +2418,14 @@ const desktopCommandHandlers = {const input = args[0] && typeof args[0] === "object" ? args[0] : {};return omnirushAccountStore.spinQuality({ idempotencyKey: typeof input.idempotencyKey === "string" ? input.idempotencyKey : undefined });},+ // Sponsored placements: a placement to draw or null (never an error), and+ // what happened to it (impression, open = the click, dismiss).+ "omnirushPlacement": async (event, ...args) => {+ return desktopPlacements.placement(args[0] && typeof args[0] === "object" ? args[0] : {}).catch(() => null);+ },+ "omnirushPlacementAction": async (event, ...args) => {+ return desktopPlacements.action(args[0] && typeof args[0] === "object" ? args[0] : {}).catch(() => ({ ok: false }));+ },// Buildathon: shown only to enrolled accounts; every failure is a null// (or a "retry"), never a thrown error, so the app quietly shows nothing."omnirushBuildathon": async (event) => {@@ -3304,6 +3322,8 @@ or use: pnpm dev:worktree`);showShutdownScreen();desktopAutomationRunner.stop();browserLoginSync.shutdown();+ // The queued placement events: best effort, never waited for (the rest go next start).+ void desktopPlacements.stop().catch(() => undefined);// The uploads finish as the services stop: the computer stays awake for them.const releaseKeepAwake = keepAwake.hold();runDetachedTask("stop services before quit", async () => {@@ -3434,6 +3454,8 @@ or use: pnpm dev:worktree`);queueDeepLinks(forwardedDeepLinks(process.argv));const win = await createMainWindow();+ // In the background: the window never waits for it.+ desktopPlacements.start();if (startReset.ran && startReset.moved.length > 0) {runDetachedTask("show app data reset notice", async () => {const { response } = await dialog.showMessageBox(win, {diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex e8cebf32..59ddb62d 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -1148,18 +1148,19 @@ export function createDesktopOmniRushAccountStore({* A request to the account server with the device credential, refreshed* once on a 401 (as the profile check does). Null while signed out.*/- async function sendAuthorized(pathname, init = {}, refreshesLeft = 1, credentials = undefined) {+ async function sendAuthorized(pathname, init = {}, refreshesLeft = 1, credentials = undefined, search = "") {const current = credentials === undefined ? await load() : credentials;if (!current) return null;const url = controlPlaneBase(current.gatewayUrl);url.pathname += pathname;+ if (search) url.search = search;const headers = new Headers(init.headers);headers.set("Authorization", `Bearer ${current.accessToken}`);const response = await send(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(20_000) });if (response.status === 401 && refreshesLeft > 0) {const refreshed = await refresh(current.accessToken);if (!refreshed) return response;- return sendAuthorized(pathname, init, refreshesLeft - 1, refreshed);+ return sendAuthorized(pathname, init, refreshesLeft - 1, refreshed, search);}return response;}@@ -1312,6 +1313,27 @@ export function createDesktopOmniRushAccountStore({return status ? { ok: true, status } : { ok: false, error: "That code is not linked to an event you can join." };}+ /**+ * One sponsored-placements call (placements-desktop.mjs): `pathAndQuery`+ * under the account server, the device credential, `timeoutMs` at most.+ * Resolves { status, data } (data: the JSON of a 200, else null), or null+ * while signed out. Throws on network errors and timeouts.+ * @param {string} pathAndQuery+ * @param {{ method?: string, body?: unknown, timeoutMs?: number }} [init]+ * @returns {Promise<{ status: number, data: any } | null>}+ */+ async function placementsRequest(pathAndQuery, { method = "GET", body = undefined, timeoutMs = 2_000 } = {}) {+ const [pathname, query = ""] = String(pathAndQuery).split("?");+ const response = await sendAuthorized(`${pathname}`, {+ method,+ ...(body !== undefined ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}),+ signal: AbortSignal.timeout(timeoutMs),+ }, 1, undefined, query);+ if (!response) return null;+ const data = response.status === 200 ? await response.json().catch(() => null) : null;+ return { status: response.status, data };+ }+/*** Join the event from the app (POST /me/buildathon/join; only offered when* the promo says `join: true`). The answer is the enrolled status.@@ -1420,5 +1442,6 @@ export function createDesktopOmniRushAccountStore({buildathonLink,buildathonJoin,buildathonTagSession,+ placementsRequest,};}diff --git a/apps/desktop/electron/placements-desktop.mjs b/apps/desktop/electron/placements-desktop.mjsnew file mode 100644index 00000000..dc27a5ee--- /dev/null+++ b/apps/desktop/electron/placements-desktop.mjs@@ -0,0 +1,92 @@+// Sponsored placements in the desktop app (the main process's side).+//+// The rules live in ./placements/placements.mjs (the same file as the CLI's,+// PARITY.sha256 there). Here: the account's authorized call, the cache in the+// app's data folder, and what the window may ask (IPC omnirushPlacement and+// omnirushPlacementAction). The window only ever gets a placement to draw;+// the link is opened here, in the system browser, after a click.+//+// OMNIRUSH_PLACEMENTS=0 turns it off (the server is not asked).++import path from "node:path";++import { createPlacements, osName, refreshDue, SLOTS, STATE_FILE } from "./placements/placements.mjs";++/** 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"]);++/** @param {Record<string, string | undefined>} [env] */+export function desktopPlacementsAllowed(env = process.env) {+ return !["0", "false", "no", "off"].includes(String(env.OMNIRUSH_PLACEMENTS ?? "").trim().toLowerCase());+}++/**+ * `request(pathAndQuery, init)` resolves { status, data } or null (signed+ * out); `openUrl(url)` opens an https link in the system browser.+ * @param {{+ * request: import("./placements/placements.mjs").PlacementsRequest,+ * userDataPath: string,+ * version?: string,+ * platform?: string,+ * env?: Record<string, string | undefined>,+ * openUrl?: ((url: string) => Promise<{ ok: boolean } | boolean | void>) | null,+ * now?: () => number,+ * log?: (level: string, message: string, data?: object) => void,+ * }} options+ */+export function createDesktopPlacements({ request, userDataPath, version = "", platform = process.platform, env = process.env, openUrl = null, now = Date.now, log = () => undefined }) {+ const service = createPlacements({+ request,+ stateFile: path.join(userDataPath, STATE_FILE),+ client: "desktop",+ version,+ os: osName(platform),+ allowed: desktopPlacementsAllowed(env),+ now,+ log,+ });+ let lastAsk = 0;++ /** A fresh answer when the cache is due (signed in late, a long-running app), at most every RETRY_AFTER_MS. */+ async function refreshIfDue() {+ if (!refreshDue(service.state(), now()) || now() - lastAsk < RETRY_AFTER_MS) return;+ lastAsk = now();+ await service.refresh().catch(() => null);+ }++ return {+ service,+ start: () => {+ // The start's own ask counts: the window's first look does not ask again right after a failure.+ if (refreshDue(service.state(), now())) lastAsk = now();+ return service.start();+ },+ stop: () => service.stop(),+ /** IPC omnirushPlacement {slot, sessionId?}: the placement to draw, or null. */+ async placement(input) {+ const slot = typeof input?.slot === "string" && SLOTS.includes(input.slot) ? input.slot : null;+ if (!slot) return null;+ const sessionId = typeof input?.sessionId === "string" && input.sessionId.length <= 200 ? input.sessionId : null;+ if (slot === "turn_footer" && !sessionId) return null;+ await refreshIfDue();+ try {+ return service.claim(slot, { sessionId });+ } catch {+ return null;+ }+ },+ /** IPC omnirushPlacementAction {id, action}: impression, open (the click) or dismiss. */+ 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 === "dismiss") return { ok: service.dismiss(id) };+ const url = service.click(id);+ if (!url) return { ok: false };+ const opened = typeof openUrl === "function" ? await Promise.resolve(openUrl(url)).then((r) => (typeof r === "object" && r !== null ? r.ok !== false : r !== false)).catch(() => false) : false;+ return { ok: true, opened };+ },+ };+}diff --git a/apps/desktop/electron/placements-desktop.test.mjs b/apps/desktop/electron/placements-desktop.test.mjsnew file mode 100644index 00000000..42d0154d--- /dev/null+++ b/apps/desktop/electron/placements-desktop.test.mjs@@ -0,0 +1,259 @@+// Sponsored placements: the shared module (./placements/placements.mjs, the same+// file in the CLI, PARITY.sha256) and the main process's side+// (placements-desktop.mjs, the account store's placementsRequest). The CLI's+// test/placements.test.js covers the same rules with its own launcher.+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ clampText,+ createPlacements,+ FETCH_TIMEOUT_MS,+ httpsOnly,+ LIMITS,+ MIN_REFRESH_S,+ parseAnswer,+ parsePlacement,+ placementsQuery,+} from "./placements/placements.mjs";+import { createDesktopPlacements, desktopPlacementsAllowed } from "./placements-desktop.mjs";+import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";++const here = path.dirname(fileURLToPath(import.meta.url));+const DAY = 86_400_000;+const T0 = Date.parse("2026-10-18T09:00:00");++function tmp(name) {+ return fs.mkdtempSync(path.join(os.tmpdir(), `placements-${name}-`));+}++function placement(over = {}) {+ return {+ id: "plc_abc",+ slot: "home_banner",+ sponsor: "Acme",+ label: "Sponsored",+ title: "Fast CI for your repo",+ body: "Run your tests in half the time.",+ cta_label: "Try it",+ url: "https://acme.example/ci",+ image_url: null,+ starts_at: "2026-10-01T00:00:00Z",+ ends_at: "2026-11-01T00:00:00Z",+ max_per_day: 1,+ snooze_days: 7,+ priority: 0,+ ...over,+ };+}++function answer(list = [placement()], over = {}) {+ return { enabled: true, refresh_after_s: 3600, placements: list, ...over };+}++function desktop({ routes = (/** @type {string} */ _p, /** @type {any} */ _o) => /** @type {any} */ ({ status: 200, data: answer() }), now = () => T0, userDataPath = tmp("desk"), env = {}, opened = [] } = {}) {+ const calls = [];+ const d = createDesktopPlacements({+ request: async (p, o = {}) => {+ calls.push({ path: p, ...o });+ return routes(p, o);+ },+ userDataPath,+ version: "3.5.5",+ platform: "darwin",+ env,+ now,+ openUrl: async (url) => {+ opened.push(url);+ return { ok: true };+ },+ });+ return { d, calls, opened, userDataPath };+}++// --- the shared rules ------------------------------------------------------------------------++test("shared: copy is clamped, single-line and labelled Sponsored", () => {+ const p = parsePlacement(placement({ title: "T".repeat(80), body: `a\nb ${"x".repeat(300)}`, cta_label: "C".repeat(30), label: "Recommended" }));+ assert.equal(Array.from(p.title).length, LIMITS.title);+ assert.equal(Array.from(p.body).length, LIMITS.body);+ assert.equal(Array.from(p.ctaLabel).length, LIMITS.cta_label);+ assert.equal(p.label, "Sponsored");+ assert.equal(clampText("xy\u0000z", 10), "x y z");+});++test("shared: https links only", () => {+ for (const bad of ["http://acme.example", "javascript:alert(1)", "file:///x", "https://a:[email protected]", "data:,x"]) {+ assert.equal(httpsOnly(bad), null, bad);+ assert.equal(parsePlacement(placement({ url: bad })), null, bad);+ }+ assert.equal(parsePlacement(placement({ image_url: "http://x.example/a.png" })).imageUrl, null);+});++test("shared: disabled, empty and malformed answers are off; refresh at least 15 minutes", () => {+ assert.equal(parseAnswer({ enabled: false, placements: [placement()] }).enabled, false);+ assert.equal(parseAnswer(answer([])).enabled, false);+ assert.equal(parseAnswer(answer([/** @type {any} */ ({ id: 1 })])).enabled, false);+ assert.equal(parseAnswer("x"), null);+ assert.equal(parseAnswer(answer(undefined, { refresh_after_s: 1 })).refreshAfterS, MIN_REFRESH_S);+ assert.equal(placementsQuery({ client: "desktop", version: "3.5.5", os: "mac" }), "/client/placements?client=desktop&version=3.5.5&os=mac");+});++test("shared: caps, snooze and expiry", async () => {+ let now = T0;+ const stateFile = path.join(tmp("caps"), "placements.json");+ const make = () => createPlacements({ request: async () => ({ status: 200, data: answer([placement({ snooze_days: 2 })]) }), stateFile, client: "desktop", now: () => now });+ 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");+ now = T0 + DAY;+ const b = make();+ await b.refresh();+ assert.ok(b.claim("home_banner"), "the next day");+ assert.ok(b.dismiss("plc_abc"));+ now = T0 + 2 * DAY;+ const c = make();+ await c.refresh();+ assert.equal(c.claim("home_banner"), null, "snoozed");+ now = T0 + 3 * DAY + 1;+ const d = make();+ await d.refresh();+ assert.ok(d.claim("home_banner"), "snooze over");+ now = Date.parse("2026-11-02T00:00:00Z");+ const e = make();+ await e.refresh();+ assert.equal(e.claim("home_banner"), null, "ended");+});++test("shared: the file is the CLI's (PARITY.sha256)", () => {+ const dir = path.join(here, "placements");+ const rows = fs.readFileSync(path.join(dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));+ assert.ok(rows.length > 0);+ for (const row of rows) {+ const [hash, name] = row.split(/\s+/);+ assert.equal(createHash("sha256").update(fs.readFileSync(path.join(dir, name))).digest("hex"), hash, `${name} changed: port it to the CLI and update PARITY.sha256 in both`);+ }+});++// --- the main process's side --------------------------------------------------------------------++test("desktop: asks with client=desktop and the OS, 2 s timeout, and hands the window a placement", async () => {+ const { d, calls } = desktop();+ 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.equal(p.label, "Sponsored · Acme");+ // The same one for the rest of the run.+ assert.deepEqual(await d.placement({ slot: "home_banner" }), p);+ assert.equal(calls.length, 1, "asked once");+});++test("desktop: the turn line needs a session and shows once per session", async () => {+ const { d } = desktop({ routes: () => ({ status: 200, data: answer([placement({ slot: "turn_footer", max_per_day: 5 })]) }) });+ assert.equal(await d.placement({ slot: "turn_footer" }), null);+ assert.ok(await d.placement({ slot: "turn_footer", sessionId: "ses_1" }));+ assert.equal(await d.placement({ slot: "turn_footer", sessionId: "ses_1" }), null);+ assert.equal(await d.placement({ slot: "popup" }), null);+});++test("desktop: off answers, 404, errors and signed out show nothing; a failed ask is not repeated at once", async () => {+ for (const routes of [() => ({ status: 200, data: { enabled: false } }), () => ({ status: 404 }), () => ({ status: 500 }), () => null, () => { throw new Error("timeout"); }]) {+ const { d, calls } = desktop({ routes });+ assert.equal(await d.placement({ slot: "home_banner" }), null);+ assert.equal(await d.placement({ slot: "home_banner" }), null);+ assert.equal(calls.length, 1);+ }+});++test("desktop: a failed ask at start is not repeated by the window's first look", async () => {+ const { d, calls } = desktop({ routes: () => ({ status: 500 }) });+ d.start();+ await new Promise((r) => setTimeout(r, 10));+ assert.equal(await d.placement({ slot: "home_banner" }), null);+ assert.equal(calls.length, 1);+ await d.stop();+});++test("desktop: OMNIRUSH_PLACEMENTS=0: never asks", async () => {+ assert.equal(desktopPlacementsAllowed({ OMNIRUSH_PLACEMENTS: "0" }), false);+ assert.equal(desktopPlacementsAllowed({}), true);+ const { d, calls, userDataPath } = desktop({ env: { OMNIRUSH_PLACEMENTS: "0" } });+ d.start();+ assert.equal(await d.placement({ slot: "home_banner" }), null);+ assert.equal(calls.length, 0);+ assert.equal(fs.existsSync(path.join(userDataPath, "placements.json")), false);+});++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 });+ 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.equal(await d.placement({ slot: "home_banner" }), null);+ assert.deepEqual(d.service.state().events.map((e) => e.kind), ["impression", "click", "dismiss"]);+});++test("desktop: the cache lives in the app's data folder, not in any workspace", async () => {+ const { d, userDataPath } = desktop();+ await d.placement({ slot: "home_banner" });+ const saved = JSON.parse(fs.readFileSync(path.join(userDataPath, "placements.json"), "utf8"));+ assert.equal(saved.v, 1);+ assert.equal(saved.answer.placements[0].id, "plc_abc");+});++test("account store: placementsRequest goes to the account server with the device credential (renewed on a 401)", async () => {+ const seen = [];+ const fetchImpl = async (url, init = {}) => {+ const u = new URL(String(url));+ const headers = new Headers(init.headers);+ seen.push({ method: init.method ?? "GET", path: `${u.pathname}${u.search}`, auth: headers.get("authorization"), client: headers.get("x-omnirush-client"), body: init.body ?? null, signal: Boolean(init.signal) });+ if (u.pathname.endsWith("/client/placements") && headers.get("authorization") === "Bearer access-1") return new Response("", { status: 401 });+ if (u.pathname.includes("/device/token") || u.pathname.includes("/refresh")) {+ return new Response(JSON.stringify({ access_token: "access-2", refresh_token: "refresh-2", expires_in: 3600 }), { status: 200, headers: { "content-type": "application/json" } });+ }+ if (init.method === "POST" && u.pathname.endsWith("/client/placements/events")) return new Response(null, { status: 204 });+ return new Response(JSON.stringify(answer()), { status: 200, headers: { "content-type": "application/json" } });+ };+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "omnirush-placements-"));+ const store = createDesktopOmniRushAccountStore({+ filePath: path.join(directory, "account.bin"),+ loadSafeStorage: () => ({+ isAsyncEncryptionAvailable: async () => true,+ getSelectedStorageBackend: () => "keychain",+ encryptStringAsync: async (value) => Buffer.from(value, "utf8"),+ decryptStringAsync: async (value) => ({ result: value.toString("utf8"), shouldReEncrypt: false }),+ }),+ platform: /** @type {NodeJS.Platform} */ ("linux"),+ env: { OMNIRUSH_DEV_MODE: "1" },+ sleep: async () => undefined,+ execFileImpl: async (file) => { throw new Error(`unexpected ${file}`); },+ clientVersion: "3.5.5",+ fetchImpl,+ });+ assert.equal(await store.placementsRequest("/client/placements?client=desktop"), null, "signed out: null, nothing asked");+ assert.equal(seen.length, 0);+ await store.save({ gatewayUrl: "http://localhost:8090/omnirush/v1", accessToken: "access-1", refreshToken: "refresh-1" });+ const got = await store.placementsRequest("/client/placements?client=desktop&version=3.5.5&os=linux");+ assert.equal(got.status, 200);+ assert.equal(got.data.enabled, true);+ const asks = seen.filter((s) => s.path.startsWith("/omnirush/client/placements?"));+ assert.equal(asks[0].path, "/omnirush/client/placements?client=desktop&version=3.5.5&os=linux");+ assert.equal(asks.at(-1).auth, "Bearer access-2", "renewed once");+ assert.equal(asks[0].client, "gui/3.5.5");+ assert.ok(asks.every((s) => s.signal), "always with a timeout");+ const posted = await store.placementsRequest("/client/placements/events", { method: "POST", body: { events: [{ id: "plc_abc", kind: "impression", at: "x" }] } });+ assert.equal(posted.status, 204);+ assert.equal(posted.data, null);+ assert.deepEqual(JSON.parse(seen.at(-1).body), { events: [{ id: "plc_abc", kind: "impression", at: "x" }] });+});diff --git a/apps/desktop/electron/placements/PARITY.sha256 b/apps/desktop/electron/placements/PARITY.sha256new file mode 100644index 00000000..5c3744c2--- /dev/null+++ b/apps/desktop/electron/placements/PARITY.sha256@@ -0,0 +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.+b7b8f275d2c6c4bd14942723056b0b30a2423ffce1808d5cc2a07ba4829bb317 placements.mjsdiff --git a/apps/desktop/electron/placements/placements.mjs b/apps/desktop/electron/placements/placements.mjsnew file mode 100644index 00000000..7ef6cb88--- /dev/null+++ b/apps/desktop/electron/placements/placements.mjs@@ -0,0 +1,570 @@+// Sponsored placements: at most one quiet line or card on the home screen+// and one dim line after a finished turn. The same file ships in omnirush-cli+// (assets/extensions/omnirush/placements/) and omnirush-gui+// (apps/desktop/electron/placements/); both list it in PARITY.sha256 there.+//+// The server decides everything (GET /client/placements?client&version&os).+// Nothing shows unless it answers `enabled: true` with a usable placement:+// a 404, an error, a timeout (2 s), `enabled: false`, an empty list or a+// malformed answer all mean nothing. The answer is cached in the app's data+// folder and asked again after `refresh_after_s` (at least 15 minutes);+// 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.+//+// 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.+//+// Nothing here touches sessions, prompts, files or uploads. Node builtins+// only; the transport (`request`) is the app's own authorized call.++import fs from "node:fs";+import path from "node:path";++export const PLACEMENTS_PATH = "/client/placements";+export const EVENTS_PATH = "/client/placements/events";+export const STATE_FILE = "placements.json";+export const SLOTS = Object.freeze(["home_banner", "turn_footer"]);+export const LABEL = "Sponsored";+export const LIMITS = Object.freeze({ id: 64, sponsor: 40, title: 60, body: 140, cta_label: 20 });+export const FETCH_TIMEOUT_MS = 2_000;+export const MIN_REFRESH_S = 900;+export const DEFAULT_REFRESH_S = 3_600;+export const MAX_REFRESH_S = 86_400;+/** A cached answer older than this (no fresh one since) shows nothing. */+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_FLUSH_MS = 60_000;+export const MAX_QUEUED_EVENTS = 200;+export const MAX_EVENT_BATCH = 50;+/** Sessions whose turn line was shown, kept this many (newest). */+export const MAX_FOOTER_SESSIONS = 500;+const DAY_MS = 86_400_000;+const STATE_VERSION = 1;++// --- copy -------------------------------------------------------------------++// Control characters, bidi overrides and zero-width marks never reach a screen.+// eslint-disable-next-line no-control-regex+const UNSAFE_CHARS = /[\u0000-\u001f\u007f-\u009f---]/g;++/** Plain one-line text, at most `max` characters (cut with "…"); "" for anything else. */+export function clampText(value, max) {+ if (typeof value !== "string") return "";+ const text = value.replace(UNSAFE_CHARS, " ").replace(/\s+/g, " ").trim();+ const chars = Array.from(text);+ if (chars.length <= max) return text;+ return `${chars.slice(0, Math.max(0, max - 1)).join("").trimEnd()}…`;+}++/** An https URL without credentials, else null. */+export function httpsOnly(value) {+ if (typeof value !== "string" || !value.trim() || value.length > 2_048) return null;+ try {+ const url = new URL(value.trim());+ if (url.protocol !== "https:" || url.username || url.password || !url.hostname) return null;+ return url.href;+ } catch {+ return null;+ }+}++function time(value) {+ if (typeof value !== "string" || !value) return null;+ const ms = Date.parse(value);+ return Number.isFinite(ms) ? ms : null;+}++function intIn(value, min, max, fallback) {+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;+ if (!Number.isFinite(n)) return fallback;+ return Math.min(max, Math.max(min, Math.floor(n)));+}++/**+ * One placement from the server, checked and clamped, or null when it is not+ * usable (no id, unknown slot, no sponsor or title, no https link, a window+ * that ends before it starts).+ */+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 slot = SLOTS.includes(raw.slot) ? raw.slot : null;+ const sponsor = clampText(raw.sponsor, LIMITS.sponsor);+ const title = clampText(raw.title, LIMITS.title);+ const url = httpsOnly(raw.url);+ if (!id || !slot || !sponsor || !title || !url) return null;+ const startsAt = time(raw.starts_at);+ const endsAt = time(raw.ends_at);+ if (raw.starts_at != null && startsAt === null) return null;+ if (raw.ends_at != null && endsAt === null) return null;+ if (startsAt !== null && endsAt !== null && endsAt <= startsAt) return null;+ return {+ id,+ slot,+ sponsor,+ label: LABEL,+ title,+ body: clampText(raw.body, LIMITS.body),+ ctaLabel: clampText(raw.cta_label, LIMITS.cta_label) || "Learn more",+ url,+ imageUrl: httpsOnly(raw.image_url),+ startsAt,+ endsAt,+ 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 server's answer: { enabled, refreshAfterS, placements } with only the+ * usable placements, or null when it is not an answer at all. Off unless+ * `enabled` is exactly true.+ */+export function parseAnswer(body) {+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;+ const refreshAfterS = intIn(body.refresh_after_s, MIN_REFRESH_S, MAX_REFRESH_S, DEFAULT_REFRESH_S);+ const enabled = body.enabled === true;+ const seen = new Set();+ const placements = [];+ if (enabled && Array.isArray(body.placements)) {+ for (const raw of body.placements.slice(0, 50)) {+ const placement = parsePlacement(raw);+ if (!placement || seen.has(placement.id)) continue;+ seen.add(placement.id);+ placements.push(placement);+ }+ }+ return { enabled: enabled && placements.length > 0, refreshAfterS, placements };+}++/** "Sponsored · Acme" */+export function sponsoredLabel(placement) {+ return `${LABEL} · ${placement.sponsor}`;+}++/**+ * The placement as one plain line of at most `width` characters:+ * "Sponsored · Acme — Title · body". `suffix` (a hint) is kept whole when it fits.+ */+export function placementLine(placement, { width = 100, suffix = "" } = {}) {+ const head = `${sponsoredLabel(placement)} — ${placement.title}${placement.body ? ` · ${placement.body}` : ""}`;+ const tail = suffix ? ` ${suffix}` : "";+ const room = Math.max(10, Math.floor(width));+ if (Array.from(head + tail).length <= room) return head + tail;+ if (tail && Array.from(tail).length < room - 20) return clampText(head, room - Array.from(tail).length) + tail;+ return clampText(head, room);+}++/** The placement as the apps show it (the UI never sees more). */+export function placementView(placement) {+ return {+ id: placement.id,+ slot: placement.slot,+ label: sponsoredLabel(placement),+ sponsor: placement.sponsor,+ title: placement.title,+ body: placement.body,+ ctaLabel: placement.ctaLabel,+ url: placement.url,+ imageUrl: placement.imageUrl,+ snoozeDays: placement.snoozeDays,+ };+}++/**+ * The `os` the server targets by: win, mac or linux.+ * @param {string} [platform]+ */+export function osName(platform = process.platform) {+ if (platform === "win32") return "win";+ if (platform === "darwin") return "mac";+ return "linux";+}++export function placementsQuery({ client, version, os }) {+ const query = new URLSearchParams();+ query.set("client", client === "desktop" ? "desktop" : "cli");+ query.set("version", typeof version === "string" && version ? version.slice(0, 40) : "0");+ query.set("os", ["win", "mac", "linux"].includes(os) ? os : osName());+ return `${PLACEMENTS_PATH}?${query.toString()}`;+}++/** The local calendar day of `ms` (YYYY-MM-DD). */+export function localDay(ms) {+ const d = new Date(ms);+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;+}++// --- state ------------------------------------------------------------------++/** An empty state. */+export function emptyState() {+ return { v: STATE_VERSION, fetched_at: 0, answer: null, shown: {}, snoozed: {}, hidden_until: 0, footer_sessions: [], events: [] };+}++function record(value) {+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};+}++/** The state file, repaired: anything damaged reads as empty. */+export function readState(file) {+ let data = null;+ try {+ data = JSON.parse(fs.readFileSync(file, "utf8"));+ } catch {+ data = null;+ }+ const base = emptyState();+ if (!data || typeof data !== "object" || Array.isArray(data) || data.v !== STATE_VERSION) return base;+ const shown = {};+ for (const [id, entry] of Object.entries(record(data.shown))) {+ const e = record(entry);+ if (typeof e.day === "string" && Number.isFinite(e.count)) shown[id] = { day: e.day, count: Math.max(0, Math.floor(e.count)) };+ }+ const snoozed = {};+ for (const [id, until] of Object.entries(record(data.snoozed))) if (Number.isFinite(until)) snoozed[id] = until;+ return {+ ...base,+ fetched_at: Number.isFinite(data.fetched_at) ? data.fetched_at : 0,+ answer: data.answer && typeof data.answer === "object" ? data.answer : null,+ shown,+ 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)+ : [],+ };+}++export function writeState(file, state) {+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify(state)}\n`, { mode: 0o600 });+ fs.renameSync(tmp, file);+ return true;+ } catch {+ return false;+ }+}++/** The cached answer, parsed again (the file may have been edited), or null when absent or too old. */+export function cachedAnswer(state, now) {+ if (!state.answer || !Number.isFinite(state.fetched_at) || state.fetched_at <= 0) return null;+ if (now - state.fetched_at > CACHE_MAX_AGE_MS || state.fetched_at - now > DAY_MS) return null;+ return parseAnswer(state.answer);+}++/** Whether the cached answer is due for a fresh one. */+export function refreshDue(state, now) {+ if (!state.fetched_at) return true;+ const answer = state.answer ? parseAnswer(state.answer) : null;+ const every = (answer?.refreshAfterS ?? DEFAULT_REFRESH_S) * 1000;+ 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). */+export function eligible(placement, slot, state, now) {+ if (placement.slot !== slot) return false;+ if (placement.startsAt !== null && now < placement.startsAt) return false;+ if (placement.endsAt !== null && now >= placement.endsAt) return false;+ if (state.hidden_until && now < state.hidden_until) return false;+ const snoozedUntil = state.snoozed[placement.id];+ 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;+ return true;+}++/** The placement for `slot` now: the highest priority, then the soonest to end, then the id. */+export function pickPlacement(answer, slot, state, now) {+ if (!answer?.enabled) return null;+ const candidates = answer.placements.filter((p) => eligible(p, slot, state, now));+ candidates.sort((a, b) => b.priority - a.priority || (a.endsAt ?? Infinity) - (b.endsAt ?? Infinity) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+ return candidates[0] ?? null;+}++// --- the service ----------------------------------------------------------------++const noop = () => undefined;++/**+ * @typedef {{ status: number, data?: any } | null} PlacementsResponse+ * @typedef {(pathAndQuery: string, init: { method?: string, body?: unknown, timeoutMs?: number }) => Promise<PlacementsResponse>} PlacementsRequest+ * @typedef {{+ * request?: PlacementsRequest | null,+ * stateFile: string,+ * client: string,+ * version?: string,+ * os?: string,+ * allowed?: boolean,+ * now?: () => number,+ * log?: (level: string, message: string, data?: object) => void,+ * timeoutMs?: number,+ * flushMs?: number,+ * setTimer?: (fn: () => void, ms: number) => any,+ * clearTimer?: (timer: any) => void,+ * }} PlacementsOptions+ */++/**+ * The app's placements. `request(pathAndQuery, { method, body, timeoutMs })`+ * resolves { status, data } (data: the parsed JSON or null) or null when+ * signed out, and may throw; it is the app's own authorized call (renewing an+ * expired sign-in). `allowed: false` (headless, no terminal, CI, switched+ * off) never asks the server and never shows anything.+ * @param {PlacementsOptions} options+ */+export function createPlacements({+ request,+ stateFile,+ client,+ version = "",+ os = osName(),+ allowed = true,+ now = Date.now,+ log = noop,+ timeoutMs = FETCH_TIMEOUT_MS,+ flushMs = EVENT_FLUSH_MS,+ setTimer = (fn, ms) => setTimeout(fn, ms),+ clearTimer = (timer) => clearTimeout(timer),+}) {+ 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();+ const footerSessions = new Set(state.footer_sessions);++ const save = () => (allowed ? writeState(stateFile, state) : false);+ const answer = () => cachedAnswer(state, now());+ const known = (id) => answer()?.placements.find((p) => p.id === id) ?? null;++ const schedule = () => {+ if (stopped || !started) return;+ if (refreshTimer) clearTimer(refreshTimer);+ const every = (answer()?.refreshAfterS ?? DEFAULT_REFRESH_S) * 1000;+ const wait = Math.max(MIN_REFRESH_S * 1000, every - Math.max(0, now() - state.fetched_at));+ refreshTimer = setTimer(() => {+ refreshTimer = null;+ void service.refresh().catch(noop).finally(schedule);+ }, wait);+ 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() });+ if (state.events.length > MAX_QUEUED_EVENTS) state.events = state.events.slice(-MAX_QUEUED_EVENTS);+ save();+ if (!flushTimer && !stopped && started) {+ flushTimer = setTimer(() => {+ flushTimer = null;+ void service.flush().catch(noop);+ }, flushMs);+ flushTimer?.unref?.();+ }+ return true;+ };++ const service = {+ /** Starts the background refresh (never waited for). */+ start() {+ if (!allowed || started || stopped) return service;+ started = true;+ if (refreshDue(state, now())) void service.refresh().catch(noop).finally(schedule);+ else schedule();+ if (state.events.length) {+ flushTimer = setTimer(() => {+ flushTimer = null;+ void service.flush().catch(noop);+ }, Math.min(flushMs, 5_000));+ flushTimer?.unref?.();+ }+ return service;+ },+ /** Stops the timers and sends what is queued (best effort, bounded by the request timeout). */+ async stop() {+ stopped = true;+ if (refreshTimer) clearTimer(refreshTimer);+ if (flushTimer) clearTimer(flushTimer);+ refreshTimer = null;+ flushTimer = null;+ if (allowed && state.events.length) await service.flush().catch(noop);+ },+ /** Asks the server once; resolves the parsed answer in use afterwards (null: nothing to show). */+ async refresh() {+ if (!allowed || typeof request !== "function") return null;+ if (inFlight) return inFlight;+ inFlight = (async () => {+ let result = null;+ try {+ result = await request(placementsQuery({ client, version, os }), { method: "GET", timeoutMs });+ } catch {+ result = null;+ }+ const at = now();+ if (result && result.status === 200) {+ const parsed = parseAnswer(result.data);+ // A malformed answer is an answer that shows nothing.+ state.answer = parsed ? result.data : { enabled: false };+ state.fetched_at = at;+ if (!parsed?.enabled) state.events = [];+ save();+ log("info", "placements refreshed", { enabled: Boolean(parsed?.enabled), count: parsed?.placements.length ?? 0 });+ } else if (result && (result.status === 404 || result.status === 410)) {+ // An older server: nothing, asked again after the default time.+ state.answer = { enabled: false };+ state.fetched_at = at;+ state.events = [];+ save();+ }+ // Signed out, offline, slow, 5xx: the last answer stays (until it is a day old).+ return answer();+ })();+ try {+ return await inFlight;+ } finally {+ inFlight = null;+ }+ },+ /**+ * 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.+ */+ 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));+ 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") {+ footerSessions.add(sessionId);+ state.footer_sessions = [...state.footer_sessions.filter((s) => s !== sessionId), sessionId].slice(-MAX_FOOTER_SESSIONS);+ }+ runClaims.set(slot, placement.id);+ save();+ return placementView(placement);+ },+ /** The placement this run claimed for `slot` (not counted again), or null. */+ current(slot) {+ const id = runClaims.get(slot);+ const placement = id ? known(id) : null;+ return placement && eligibleKept(placement, now()) ? placementView(placement) : null;+ },+ /** It was drawn on screen. */+ impression(id) {+ return queue(id, "impression");+ },+ /** The click: its https link (the app opens it) or null. */+ click(id) {+ const placement = known(id);+ if (!placement) return null;+ queue(id, "click");+ return placement.url;+ },+ /** × / hide: snoozed for its `snooze_days`; gone from this run. */+ dismiss(id) {+ const placement = known(id);+ 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);+ save();+ return true;+ },+ /** Hides every placement for `days` (0 shows them again). */+ 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. */+ status() {+ const current = answer();+ return {+ allowed,+ enabled: Boolean(current?.enabled),+ count: current?.placements.length ?? 0,+ fetchedAt: state.fetched_at || null,+ hiddenUntil: state.hidden_until && state.hidden_until > now() ? state.hidden_until : null,+ snoozed: Object.values(state.snoozed).filter((until) => until > now()).length,+ queued: state.events.length,+ };+ },+ /** Sends the queued events (at most MAX_EVENT_BATCH per request). */+ async flush() {+ if (!allowed || typeof request !== "function" || !state.events.length) return 0;+ if (!answer()?.enabled) {+ state.events = [];+ save();+ return 0;+ }+ let sent = 0;+ while (state.events.length) {+ const batch = state.events.slice(0, MAX_EVENT_BATCH);+ let result = null;+ try {+ result = await request(EVENTS_PATH, { method: "POST", body: { events: batch }, timeoutMs });+ } catch {+ result = null;+ }+ if (!result) break;+ if (result.status >= 200 && result.status < 300) {+ state.events = state.events.slice(batch.length);+ sent += batch.length;+ save();+ continue;+ }+ if (result.status >= 400 && result.status < 500 && result.status !== 401 && result.status !== 408 && result.status !== 429) {+ // Refused (no route, off, bad batch): dropped, never retried.+ state.events = [];+ save();+ }+ break;+ }+ return sent;+ },+ /** Tests and the status command. */+ state: () => state,+ };++ // A placement kept for the run 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;+ if (state.hidden_until && at < state.hidden_until) return false;+ const snoozedUntil = state.snoozed[placement.id];+ return !(Number.isFinite(snoozedUntil) && at < snoozedUntil);+ }++ return service;+}diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 17fb498d..8ff42386 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,7 +27,7 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/placements-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 5dd1ed88..429bc436 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -385,6 +385,28 @@ export type OmniRushBuildathonLinkResult =| { ok: false; error: string; closed?: boolean };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 OmniRushPlacement = {+ id: string;+ slot: OmniRushPlacementSlot;+ /** "Sponsored · <sponsor>" */+ label: string;+ sponsor: string;+ /** Plain text, at most 60 characters. */+ title: string;+ /** Plain text, at most 140 characters (may be empty). */+ body: string;+ /** At most 20 characters. */+ ctaLabel: string;+ /** https only; opened by the main process after a click. */+ url: string;+ /** https only, or null. */+ imageUrl: string | null;+ snoozeDays: number;+};+export type OmniRushPlacementAction = "impression" | "open" | "dismiss";+export type OmniRushSessionStatus = {sessionId: string;status: "on_track" | "at_risk" | "failing" | "unknown";@@ -940,6 +962,8 @@ 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 } };omnirushBuildathonSessions: { args: []; result: OmniRushBuildathonSession[] | null };omnirushBuildathonLink: { args: [input: { code: string }]; result: OmniRushBuildathonLinkResult };omnirushBuildathonChecklist: {