YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(announcements): local /notify reaches every surface, and a cta can open the pipe installer (#6240)
Louis Beaumontabaad1907346
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/announcements.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/announcements.test.tsindex a450087d2..454df7b95 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/announcements.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/announcements.test.ts@@ -146,6 +146,58 @@ describe("parseAnnouncement", () => {expect(a!.cta).toBeUndefined();});+ it("keeps a cta whose only destination is a pipe slug", () => {+ const a = parseAnnouncement({ ...VALID, cta: { label: "install it", pipe: "daily-email-summary" } });+ expect(a!.cta).toEqual({ label: "install it", pipe: "daily-email-summary" });+ });++ it("strips a pipe cta from a locally pushed announcement", () => {+ // `POST /notify` is reachable by any same-user process and renders exactly+ // like a first-party announcement, so it must not be able to open the+ // installer. Routing to the Store page is still allowed.+ const local = parseAnnouncement(+ { ...VALID, cta: { label: "install it", pipe: "daily-email-summary" } },+ "local",+ );+ expect(local!.cta).toBeUndefined();++ const remote = parseAnnouncement({+ ...VALID,+ cta: { label: "install it", pipe: "daily-email-summary" },+ });+ expect(remote!.cta).toEqual({ label: "install it", pipe: "daily-email-summary" });+ });++ it("keeps route and url on a locally pushed announcement", () => {+ const a = parseAnnouncement(+ {+ ...VALID,+ cta: { label: "see it", route: "/home?section=pipes", pipe: "daily-email-summary" },+ },+ "local",+ );+ expect(a!.cta).toEqual({ label: "see it", route: "/home?section=pipes" });+ });++ it("rejects pipe slugs that could escape the registry source", () => {+ // the slug is interpolated into `registry:<slug>`, so anything that could+ // change what gets installed has to be dropped rather than sanitized.+ for (const pipe of [+ "../../etc/passwd",+ "slug/../other",+ "https://evil.example/pipe",+ "Daily-Email-Summary",+ "slug with spaces",+ "slug:extra",+ "-leading-hyphen",+ "",+ "a".repeat(81),+ ]) {+ const a = parseAnnouncement({ ...VALID, cta: { label: "go", pipe } });+ expect(a!.cta, `expected ${JSON.stringify(pipe)} to be rejected`).toBeUndefined();+ }+ });+it("prefers route over url but keeps url when only url is set", () => {const both = parseAnnouncement({ ...VALID, cta: { label: "go", url: "https://screenpipe.com/blog", route: "/r" } });expect(both!.cta).toEqual({ label: "go", url: "https://screenpipe.com/blog", route: "/r" });diff --git a/apps/screenpipe-app-tauri/lib/announcements.ts b/apps/screenpipe-app-tauri/lib/announcements.tsindex 0ea6beda6..6af6984a4 100644--- a/apps/screenpipe-app-tauri/lib/announcements.ts+++ b/apps/screenpipe-app-tauri/lib/announcements.ts@@ -68,6 +68,19 @@ export type AnnouncementPosition =| CardPosition| BubblePosition;+/** Which channel an announcement arrived on.+ *+ * `remote` is the PostHog `app-announcement` flag: authenticated, audited,+ * first-party, and changed by a named human in a dashboard.+ *+ * `local` is a `POST /notify` push. The control server rejects foreign+ * `Origin`/`Host`, but a headerless same-user process (a pipe, an agent, a+ * plain curl) is accepted by design — loopback bind is not an authorization+ * boundary. A local push also carries no provenance, so it renders exactly+ * like a first-party announcement. Destinations that start a privileged flow+ * are therefore remote-only. */+export type AnnouncementSource = "remote" | "local";+export interface AnnouncementCta {/** button label. shown UPPERCASE by the host per brand. */label: string;@@ -76,6 +89,13 @@ export interface AnnouncementCta {/** internal app route (e.g. "/settings?section=account"). takes precedence* over `url` when both are set. */route?: string;+ /** Store slug. Opens the normal install dialog for that pipe — the same+ * consent surface as a `screenpipe://install-pipe` deep link, showing+ * permissions and required connections before anything is written. A+ * remote payload can name a Store slug and nothing else: it cannot supply+ * an install URL, cannot install silently, and cannot enable a pipe.+ * Takes precedence over `route` and `url` when several are set. */+ pipe?: string;}export interface Announcement {@@ -250,7 +270,20 @@ export function safeAnnouncementExternalUrl(raw: unknown): string | null {}}-function normalizeCta(raw: unknown): AnnouncementCta | undefined {+/** Store slugs are lowercase kebab identifiers. Narrower than `IDENTIFIER` on+ * purpose: the value is interpolated into a `registry:<slug>` source, so no+ * dots, colons, slashes or uppercase. */+const PIPE_SLUG = /^[a-z0-9][a-z0-9-]*$/;++export function safeAnnouncementPipeSlug(raw: unknown): string | null {+ const value = boundedString(raw, 80);+ return value && PIPE_SLUG.test(value) ? value : null;+}++function normalizeCta(+ raw: unknown,+ source: AnnouncementSource,+): AnnouncementCta | undefined {if (!raw || typeof raw !== "object") return undefined;const r = raw as Record<string, unknown>;const label = boundedString(r.label, 40);@@ -258,10 +291,16 @@ function normalizeCta(raw: unknown): AnnouncementCta | undefined {const cta: AnnouncementCta = { label };const url = safeAnnouncementExternalUrl(r.url);const route = safeInternalRoute(r.route);+ // `pipe` opens the installer, so it is remote-only. A local push carries no+ // provenance and renders identically to a first-party announcement, which+ // would make it a convincing way to talk someone into installing something.+ // A local caller can still route to the Store page and let the user choose.+ const pipe = source === "remote" ? safeAnnouncementPipeSlug(r.pipe) : null;if (url) cta.url = url;if (route) cta.route = route;- // a cta with neither destination is a dead button — drop it.- if (!cta.url && !cta.route) return undefined;+ if (pipe) cta.pipe = pipe;+ // a cta with no destination is a dead button — drop it.+ if (!cta.url && !cta.route && !cta.pipe) return undefined;return cta;}@@ -347,8 +386,14 @@ export function sanitizeSurveyAnswers(* Validate + normalize an untrusted payload (PostHog JSON, preview blob) into a* fully-defaulted `Announcement`, or `null` if it isn't a usable announcement.* Never throws — bad remote data must not crash the app.+ *+ * `source` narrows the contract by channel, it does not widen it. See+ * `AnnouncementSource`.*/-export function parseAnnouncement(raw: unknown): Announcement | null {+export function parseAnnouncement(+ raw: unknown,+ source: AnnouncementSource = "remote",+): Announcement | null {if (!raw || typeof raw !== "object") return null;const r = raw as Record<string, unknown>;@@ -385,7 +430,7 @@ export function parseAnnouncement(raw: unknown): Announcement | null {announcement.dismissible = true;}- const cta = normalizeCta(r.cta);+ const cta = normalizeCta(r.cta, source);if (cta) announcement.cta = cta;const survey = normalizeSurvey(r.survey);if (r.survey !== undefined && !survey) return null;diff --git a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-announcement.test.tsx b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-announcement.test.tsxindex 67569b68b..97ec274b1 100644--- a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-announcement.test.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-announcement.test.tsx@@ -12,6 +12,7 @@ const {reloadFlagsMock,pushMock,openMock,+ emitMock,flagPayload,optedOut,appName,@@ -22,6 +23,7 @@ const {reloadFlagsMock: vi.fn(),pushMock: vi.fn(),openMock: vi.fn(() => Promise.resolve()),+ emitMock: vi.fn(() => Promise.resolve()),// mutable holder so each test can set the active flag payloadflagPayload: { current: null as unknown },optedOut: { current: false },@@ -55,6 +57,7 @@ vi.mock("@tauri-apps/api/event", () => ({return () => set?.delete(handler);},),+ emit: emitMock,}));vi.mock("@tauri-apps/api/app", () => ({@@ -90,6 +93,7 @@ describe("useAnnouncement", () => {reloadFlagsMock.mockClear();pushMock.mockClear();openMock.mockClear();+ emitMock.mockClear();flagPayload.current = null;optedOut.current = false;appName.current = "screenpipe";@@ -271,6 +275,74 @@ describe("useAnnouncement", () => {expect(pushMock).not.toHaveBeenCalled();});+ it("activateCta opens the install dialog for a pipe cta instead of installing", async () => {+ flagPayload.current = {+ ...FLAG,+ cta: { label: "install it", pipe: "daily-email-summary" },+ };+ const { result } = renderHook(() => useAnnouncement());+ await flushAnnouncementEffects();++ await act(async () => {+ result.current.activateCta();+ });++ // the same event a `screenpipe://install-pipe` deep link emits, so the+ // user still sees permissions and connections before anything is written.+ expect(emitMock).toHaveBeenCalledWith("install-pipe", {+ url: "registry:daily-email-summary",+ });+ expect(pushMock).not.toHaveBeenCalled();+ expect(openMock).not.toHaveBeenCalled();+ expect(captureMock).toHaveBeenCalledWith(+ "announcement_cta_clicked",+ expect.objectContaining({ cta_target: "pipe" }),+ );+ });++ it("does not offer a pipe install for an announcement pushed via /notify", async () => {+ const { result } = renderHook(() => useAnnouncement());+ await flushAnnouncementEffects();++ act(() =>+ fireAnnouncement({+ ...FLAG,+ id: "local-1",+ cta: { label: "install it", pipe: "daily-email-summary" },+ }),+ );++ // the cta had no destination left once `pipe` was stripped, so it is gone+ // rather than rendering a dead button.+ expect(result.current.announcement?.id).toBe("local-1");+ expect(result.current.announcement?.cta).toBeUndefined();++ act(() => result.current.activateCta());+ expect(emitMock).not.toHaveBeenCalled();+ });++ it("prefers the pipe destination over route and url on the same cta", async () => {+ flagPayload.current = {+ ...FLAG,+ cta: {+ label: "install it",+ pipe: "daily-email-summary",+ route: "/settings",+ url: "https://screenpi.pe/blog",+ },+ };+ const { result } = renderHook(() => useAnnouncement());+ await flushAnnouncementEffects();++ await act(async () => {+ result.current.activateCta();+ });++ expect(emitMock).toHaveBeenCalledTimes(1);+ expect(pushMock).not.toHaveBeenCalled();+ expect(openMock).not.toHaveBeenCalled();+ });+it("submits only configured survey option ids and dismisses", async () => {flagPayload.current = {...FLAG,diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-announcement.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-announcement.tsxindex befa65190..07d415c26 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-announcement.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-announcement.tsx@@ -175,8 +175,10 @@ export function useAnnouncement(): UseAnnouncementResult {// rust side emits the `announcement` event with the announcement object.// The hook swallows a failed `listen()` (e.g. not running under Tauri in// tests), matching the previous `.catch(() => {})` guard.+ // Parsed as `local`: this channel is reachable by any same-user process and+ // carries no provenance, so it does not get the pipe-install destination.useTauriEvent("announcement", (event) => {- const a = parseAnnouncement(event.payload);+ const a = parseAnnouncement(event.payload, "local");if (a) setTriggered(a);});@@ -235,10 +237,24 @@ export function useAnnouncement(): UseAnnouncementResult {kind: announcement.kind,surface: announcement.surface,cta_label: cta.label,+ // which destination kind fired, so A/B arms that differ only in the+ // action are separable. never carries the slug, route or url.+ cta_target: cta.pipe ? "pipe" : cta.route ? "route" : "url",});} catch {}- if (cta.route) {+ if (cta.pipe) {+ // Hand off to the same dialog a `screenpipe://install-pipe` deep link+ // opens. It fetches the Store detail, shows permissions and required+ // connections, and installs only after the user confirms. Nothing is+ // written here, and the installed pipe stays disabled until the user+ // enables it.+ import("@tauri-apps/api/event")+ .then((m) => m.emit("install-pipe", { url: `registry:${cta.pipe}` }))+ .catch((err) =>+ console.error("failed to open pipe install dialog:", err),+ );+ } else if (cta.route) {router.push(cta.route);} else if (cta.url) {// open externally in the system browser (never inside the webview).diff --git a/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rs b/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rsindex 79c431018..e289719cb 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rs@@ -623,27 +623,38 @@ pub struct NotifyPayload {pub source_url: Option<String>,// ── announcement mode ────────────────────────────────────────────- // When `surface` names an announcement surface (modal/banner/card),- // `/notify` pushes an in-app announcement instead of a notification- // panel — the on-demand counterpart to the PostHog `app-announcement`- // flag. These fields mirror the announcement payload; validation /- // normalization happens in the frontend (lib/announcements.ts).+ // When `surface` names an announcement surface, `/notify` pushes an+ // in-app announcement instead of a notification panel — the on-demand+ // counterpart to the PostHog `app-announcement` flag. These fields mirror+ // the announcement payload; validation / normalization happens in the+ // frontend (lib/announcements.ts).#[serde(default)]pub surface: Option<String>,#[serde(default)]pub kind: Option<String>,#[serde(default)]pub position: Option<String>,+ /// Stable `data-announcement-anchor` value. Required by `bubble`, ignored+ /// by every other surface. A bubble without one is dropped in+ /// `parseAnnouncement`, so it must survive the hand-off.+ #[serde(default)]+ pub anchor: Option<String>,#[serde(default)]pub cta: Option<serde_json::Value>,+ /// Bounded single/multiple-choice survey. Mirrors the flag payload so a+ /// locally triggered prompt can ask the same question a remote one can.+ #[serde(default)]+ pub survey: Option<serde_json::Value>,#[serde(default)]pub dismissible: Option<bool>,#[serde(default, alias = "expiresAt")]pub expires_at: Option<String>,}-/// Surfaces that turn a `/notify` call into an announcement push.-const ANNOUNCEMENT_SURFACES: [&str; 3] = ["modal", "banner", "card"];+/// Surfaces that turn a `/notify` call into an announcement push. Kept in step+/// with `SURFACES` in `lib/announcements.ts` — a surface the frontend renders+/// but this list omits is unreachable for locally triggered announcements.+const ANNOUNCEMENT_SURFACES: [&str; 5] = ["modal", "banner", "card", "bubble", "sidebar"];/// When the `/notify` payload carries an announcement `surface`, build the/// announcement object to hand to the frontend. Returns `None` for ordinary@@ -659,9 +670,11 @@ fn announcement_from_payload(payload: &NotifyPayload, id: &str) -> Option<serde_"kind": payload.kind,"surface": surface,"position": payload.position,+ "anchor": payload.anchor,"title": payload.title,"body": payload.body,"cta": payload.cta,+ "survey": payload.survey,"dismissible": payload.dismissible,"autoDismissMs": payload.auto_dismiss_ms,"expiresAt": payload.expires_at,@@ -831,7 +844,9 @@ mod tests {surface: surface.map(ToOwned::to_owned),kind: Some("news".to_string()),position: Some("bottom-right".to_string()),+ anchor: None,cta: Some(json!({ "label": "open settings", "route": "/settings" })),+ survey: None,dismissible: Some(true),expires_at: None,}@@ -859,6 +874,59 @@ mod tests {assert!(announcement_from_payload(¬ify_payload(Some("toast")), "x").is_none());}+ #[test]+ fn every_frontend_surface_can_be_pushed_locally() {+ // Kept in step with `SURFACES` in lib/announcements.ts. A surface the+ // renderer supports but this list omits is unreachable for a locally+ // triggered announcement, which is the bug this guards.+ for surface in ["modal", "banner", "card", "bubble", "sidebar"] {+ let ann = announcement_from_payload(¬ify_payload(Some(surface)), "ann-1")+ .unwrap_or_else(|| panic!("{surface} should produce an announcement"));+ assert_eq!(ann["surface"], surface);+ }+ }++ #[test]+ fn anchor_survives_the_handoff_for_bubbles() {+ // parseAnnouncement drops a bubble with no anchor, so losing it here+ // would make every locally pushed bubble silently disappear.+ let mut payload = notify_payload(Some("bubble"));+ payload.anchor = Some("pipes-nav".to_string());+ let ann = announcement_from_payload(&payload, "ann-1").expect("bubble announcement");+ assert_eq!(ann["anchor"], "pipes-nav");+ }++ #[test]+ fn survey_survives_the_handoff() {+ let mut payload = notify_payload(Some("card"));+ payload.survey = Some(json!({+ "questions": [{+ "id": "q1",+ "type": "single-choice",+ "prompt": "did this help?",+ "options": [{ "id": "yes", "label": "yes" }],+ }],+ }));+ let ann = announcement_from_payload(&payload, "ann-1").expect("card announcement");+ assert_eq!(ann["survey"]["questions"][0]["id"], "q1");+ }++ #[test]+ fn cta_is_forwarded_verbatim_for_the_frontend_to_narrow() {+ // This layer does not decide which destinations are legal. It hands the+ // cta over unchanged and `parseAnnouncement` applies the per-channel+ // contract — notably it drops `pipe` for a locally pushed announcement,+ // because this endpoint is reachable by any same-user process and the+ // result is indistinguishable from a first-party announcement.+ let mut payload = notify_payload(Some("card"));+ payload.cta = Some(json!({+ "label": "install it",+ "pipe": "daily-email-summary",+ }));+ let ann = announcement_from_payload(&payload, "ann-1").expect("card announcement");+ assert_eq!(ann["cta"]["pipe"], "daily-email-summary");+ }+#[test]fn announcement_accepts_modal_and_banner() {assert!(announcement_from_payload(¬ify_payload(Some("modal")), "x").is_some());@@ -899,7 +967,9 @@ mod tests {surface: None,kind: None,position: None,+ anchor: None,cta: None,+ survey: None,dismissible: None,expires_at: None,};