mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-27 19:35:13 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Self-hosted boards need a way to show occasional product announcements. > - An app release should not be required to publish or withdraw a card. > - Native card controls keep publishing consistent; the hero can use a static image or isolated HTML/CSS animation. > - This pull request renders a validated JSON feed with native components. > - It stores dismissals per account on each instance, so a closed card stays closed across companies and browsers. > - Named staging feeds let authors test content before production publication. ## Linked Issues or Issue Description **Subsystem affected** Board application shell, announcement delivery, and user preferences. **Problem or motivation** Operators need a small, optional announcement card. Users need reliable dismissal state. Authors need to test remote content without changing the production feed. **Proposed solution** Add one non-modal AnnouncementWell. Fetch validated JSON and content-addressed media through the instance server. Keep card controls native, with optional sandboxed HTML/CSS animation in the hero. Use stable announcement IDs for dismissal, an explicit empty manifest and quiet 404 handling. Provide a staged publishing helper and isolated test-drive guide. **Alternatives considered** Hosting the entire card as a page would move navigation and dismissal into remote content. This change limits HTML to a scriptless, isolated visual hero and keeps controls native. Browser-only storage would lose dismissals across browsers, so the instance stores account preferences. **Roadmap alignment** ROADMAP.md has no overlapping announcement feature. A GitHub title search found no related announcement pull requests. This work implements a maintainer-requested feature. ## What Changed - Add shared feed types, strict validation of every object, supported routes, expiration and version checks. - Add a board-only current-feed API, constrained media proxy, and idempotent dismissal API. Store the first dismissal and its company audit entry in one transaction. - Cache upstream data for one hour. Use conditional requests, request deduplication, response limits, public destination checks, and a three-second deadline. Treat a remote 404 as an empty feed with a fifteen-minute retry cooldown. - Keep announcement visibility stable when focus moves to browser chrome or another app pane; only tab visibility starts a return check. - Add a responsive native announcement card. Respect onboarding, dialogs and toast placement. Sync pending dismissals across tabs and retry after reconnect or return. - Add idempotent migrations for dismissals and validated publication IDs, design-guide examples, static and animated Storybook examples, and focused tests. The publication registry supports offline retries without accepting caller-invented IDs. - Add HTML/CSS animated heroes with static posters, automatic playback, reduced-motion handling, strict DOMPurify validation, an empty iframe sandbox and CSP that blocks scripts/network resources. - Add validated staging publication, content-addressed assets, an empty production manifest, preview fixtures, and authoring/operator documentation. ## Verification - The preceding implementation passed 98 targeted shared/server/publisher/route/OpenAPI/UI tests and 127 tests including the master rebase. The playback-control removal passes all 21 announcement UI tests, covering the rendered sandbox, fallback, reduced motion, dismissal and slow/stale state lookups. The preceding shared/server tests cover HTML validation and response sandbox headers. - The playback-control removal passes UI typecheck, production UI build, Storybook build and token gates locally. Browser verification confirms the animated card has only its dismiss button and two links, with no page errors. The full canonical CI matrix passed on current head `00e416431edb610861599d50490270bbd0f3c6b6`: 32 successful checks and two optional Storybook deployment checks skipped. This run needed no retries. Greptile reviewed this same head at 5/5 with no outstanding findings. - The local canonical general-server run passed 12,063 tests before reporting embedded-PostgreSQL startup failures in an unrelated fixture. All 31 tests in that fixture passed across isolated retries. The UI group passed 6,219 tests and other workspace groups passed 3,201; two CLI database-startup failures also passed individually. Serialized server suites were verified by the full CI matrix rather than repeating them locally. No source changes were needed for these environment failures. - The real S3/CloudFront staging manifest and both media asset headers were verified. Production remains empty/unpublished. The guide distinguishes the preview host's disabled edge cache from production cache requirements. - In the isolated test-drive, the animation visibly moves without playback controls. A 390×844 browser viewport keeps the card above navigation. Reduced motion makes no animation request. Both themes render correctly and browser page errors are empty. Browser fault injection verified that scripts cannot execute and CSS cannot make network requests; a missing animation leaves its poster and controls. - Refresh leaves the animated card visible. Closing it persists after reload and the API returns null. Earlier live checks verified dismissal across browsers, company-relative CTA navigation, modal deferral/restoration, and new-ID eligibility after restarting the same database. - The deployed empty feed and a real remote 404 return HTTP 200 with null from the board API, with a usable dashboard and no announcement popup or browser warnings. - Authoring documentation covers staging, animated HTML constraints, test-drive, withdrawal, ID reuse and cache-refresh steps. ## Risks - Animation supports self-contained visual HTML/CSS and inline SVG, without JavaScript or external resources. A static image is required. Older builds that do not recognize the optional animation field quietly hide that unsupported feed. - The default feed makes an outbound request from an instance when a board is used. Operators can disable it. Requests contain no account IDs, company data, cookies or interaction events. - Feed publication and withdrawal can take about 65 minutes to reach returning users because of CDN and instance caches. Expiration also removes visible cards locally. - Dismissals follow an account within one instance. No-login instances share the existing local-board identity. Separate installations do not share state. - Both tables are additive. A unique key prevents duplicate dismissals; the transaction prevents duplicate first-dismissal audit entries. The publication registry retains only validated IDs. AGENTS.md and the implementation spec document the required exception to company scope for these instance-level records. - Publication was limited to separate public staging prefixes on the existing preview host. Production remains empty/unpublished. No AWS policies or infrastructure were changed. ## Model Used OpenAI GPT-6 through Codex. The exact runtime model ID and context-window size are not exposed in this session. Capabilities used: reasoning, code editing, shell execution, tests, browser interaction, and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
205 lines
10 KiB
TypeScript
205 lines
10 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { act } from "react";
|
|
import { createRoot, type Root } from "react-dom/client";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { useAnnouncement } from "./useAnnouncement";
|
|
import { announcementPreview } from "@/lib/announcement-preview";
|
|
import { announcementStoragePrefix } from "@/lib/announcement-dismissals";
|
|
|
|
const api = vi.hoisted(() => ({ current: vi.fn(), dismiss: vi.fn() }));
|
|
vi.mock("@/api/announcements", () => ({ announcementsApi: api }));
|
|
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
describe("announcement lifecycle", () => {
|
|
let container: HTMLDivElement;
|
|
let root: Root;
|
|
let userId: string;
|
|
let companyId: string;
|
|
let enabled: boolean;
|
|
let failure: ReturnType<typeof vi.fn<(savedLocally: boolean) => void>>;
|
|
let observed: ReturnType<typeof useAnnouncement>;
|
|
let sequence = 0;
|
|
function Harness() {
|
|
observed = useAnnouncement({ userId, companyId, enabled, onSaveFailure: failure });
|
|
return <div>{observed.announcement?.id}</div>;
|
|
}
|
|
const render = async () => { await act(async () => root.render(<Harness />)); };
|
|
const settle = async () => { await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); };
|
|
const event = async (name: string) => { await act(async () => window.dispatchEvent(new Event(name))); };
|
|
const visibility = async (value: "hidden" | "visible") => {
|
|
Object.defineProperty(document, "visibilityState", { configurable: true, value });
|
|
await act(async () => document.dispatchEvent(new Event("visibilitychange")));
|
|
};
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
vi.clearAllMocks();
|
|
api.current.mockResolvedValue(announcementPreview);
|
|
api.dismiss.mockResolvedValue(undefined);
|
|
userId = `user-${++sequence}`;
|
|
companyId = "company-one";
|
|
enabled = true;
|
|
failure = vi.fn();
|
|
// The repository's generic storage stub lacks key()/length; this feature
|
|
// enumerates per-announcement entries, so exercise the full browser API.
|
|
const entries = new Map<string, string>();
|
|
const storage = {
|
|
get length() { return entries.size; },
|
|
key: (index: number) => [...entries.keys()][index] ?? null,
|
|
getItem: (key: string) => entries.get(key) ?? null,
|
|
setItem: (key: string, value: string) => { entries.set(key, String(value)); },
|
|
removeItem: (key: string) => { entries.delete(key); },
|
|
clear: () => entries.clear(),
|
|
};
|
|
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
|
|
Object.defineProperty(window, "localStorage", { configurable: true, value: storage });
|
|
Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" });
|
|
container = document.createElement("div");
|
|
document.body.append(container);
|
|
root = createRoot(container);
|
|
});
|
|
afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
|
it("settles before showing and never polls during uninterrupted work", async () => {
|
|
await render();
|
|
expect(container.textContent).toBe("");
|
|
await settle();
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(3_600_000); });
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
companyId = "company-two";
|
|
await render();
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
});
|
|
it("keeps a visible card stable when page focus moves to browser chrome or another pane", async () => {
|
|
await render(); await settle();
|
|
const request = api.current.mock.calls[0][0] as AbortSignal;
|
|
await event("blur");
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await event("focus");
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await settle();
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
expect(request.aborted).toBe(false);
|
|
});
|
|
it("does not restart the initial settling period when a visible page gains focus", async () => {
|
|
await render();
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(2500); });
|
|
await event("blur"); await event("focus");
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(500); });
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
});
|
|
it("dismisses immediately and stays dismissed after a remount and copy edit", async () => {
|
|
await render(); await settle();
|
|
await act(async () => observed.dismiss(announcementPreview.id));
|
|
expect(container.textContent).toBe("");
|
|
expect(api.dismiss).toHaveBeenCalledWith(announcementPreview.id, companyId, expect.any(AbortSignal));
|
|
await act(async () => root.unmount());
|
|
root = createRoot(container);
|
|
api.current.mockResolvedValue({ ...announcementPreview, title: "Corrected" });
|
|
await render(); await settle();
|
|
expect(container.textContent).toBe("");
|
|
expect(api.dismiss).toHaveBeenCalledTimes(1);
|
|
});
|
|
it("refreshes on return, showing a new ID but honoring dismissal in another browser", async () => {
|
|
await render(); await settle();
|
|
api.current.mockResolvedValue(null);
|
|
await visibility("hidden"); await visibility("visible"); await settle();
|
|
expect(container.textContent).toBe("");
|
|
api.current.mockResolvedValue({ ...announcementPreview, id: "new-id" });
|
|
await visibility("hidden"); await visibility("visible"); await settle();
|
|
expect(container.textContent).toBe("new-id");
|
|
});
|
|
it("withholds a returning tab until its fresh dismissal check completes", async () => {
|
|
await render(); await settle();
|
|
await visibility("hidden");
|
|
expect(container.textContent).toBe("");
|
|
let resolve!: (value: null) => void;
|
|
api.current.mockReturnValueOnce(new Promise((done) => { resolve = done; }));
|
|
await visibility("visible");
|
|
// Browsers may report focus as well; it must not abort or duplicate the check.
|
|
await event("focus"); await settle();
|
|
expect(api.current).toHaveBeenCalledTimes(2);
|
|
expect(container.textContent).toBe("");
|
|
await act(async () => resolve(null));
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
it("ignores a late response from before the tab was hidden", async () => {
|
|
let resolve!: (value: typeof announcementPreview) => void;
|
|
api.current.mockReturnValueOnce(new Promise((done) => { resolve = done; }));
|
|
await render();
|
|
const request = api.current.mock.calls[0][0] as AbortSignal;
|
|
await visibility("hidden");
|
|
expect(request.aborted).toBe(true);
|
|
await act(async () => resolve(announcementPreview)); await settle();
|
|
expect(container.textContent).toBe("");
|
|
api.current.mockResolvedValue({ ...announcementPreview, id: "after-return" });
|
|
await visibility("visible");
|
|
expect(container.textContent).toBe("");
|
|
await settle();
|
|
expect(container.textContent).toBe("after-return");
|
|
});
|
|
it("keeps failed writes pending and retries on reconnect", async () => {
|
|
api.dismiss.mockRejectedValueOnce(new Error("offline"));
|
|
await render(); await settle();
|
|
await act(async () => observed.dismiss(announcementPreview.id));
|
|
expect(container.textContent).toBe("");
|
|
expect(failure).toHaveBeenCalledWith(true);
|
|
expect(localStorage.getItem(`${announcementStoragePrefix(userId)}${announcementPreview.id}`)).toBe("pending");
|
|
await event("online");
|
|
expect(localStorage.getItem(`${announcementStoragePrefix(userId)}${announcementPreview.id}`)).toBe("synced");
|
|
});
|
|
it("does not leak a late fetch across an account change", async () => {
|
|
let resolve!: (value: typeof announcementPreview) => void;
|
|
api.current.mockReturnValueOnce(new Promise((done) => { resolve = done; }));
|
|
await render(); await settle();
|
|
userId = "different-account";
|
|
api.current.mockResolvedValue(null);
|
|
await render();
|
|
await act(async () => resolve(announcementPreview));
|
|
await settle();
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
it("closes after another tab writes a dismissal", async () => {
|
|
await render(); await settle();
|
|
const key = `${announcementStoragePrefix(userId)}${announcementPreview.id}`;
|
|
localStorage.setItem(key, "synced");
|
|
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key, newValue: "synced" })));
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
it("honors a broadcast even when browser storage is unavailable", async () => {
|
|
let channel!: { onmessage: ((event: MessageEvent) => void) | null };
|
|
vi.stubGlobal("BroadcastChannel", class {
|
|
onmessage = null;
|
|
constructor() { channel = this; }
|
|
postMessage() {}
|
|
close() {}
|
|
});
|
|
await render(); await settle();
|
|
vi.spyOn(localStorage, "setItem").mockImplementation(() => { throw new Error("Storage denied"); });
|
|
await act(async () => channel.onmessage?.(new MessageEvent("message", { data: announcementPreview.id })));
|
|
expect(container.textContent).toBe("");
|
|
await visibility("hidden"); await visibility("visible"); await settle();
|
|
expect(container.textContent).toBe("");
|
|
expect(api.dismiss).toHaveBeenCalled();
|
|
});
|
|
it("withholds unknown state, disabled/onboarding state and hidden tabs", async () => {
|
|
api.current.mockRejectedValue(new Error("unavailable"));
|
|
await render(); await settle();
|
|
expect(container.textContent).toBe("");
|
|
enabled = false; await render();
|
|
api.current.mockClear();
|
|
await event("focus"); await settle();
|
|
expect(api.current).not.toHaveBeenCalled();
|
|
Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });
|
|
enabled = true; await render(); await settle();
|
|
expect(api.current).not.toHaveBeenCalled();
|
|
});
|
|
it("expires while visible", async () => {
|
|
api.current.mockResolvedValue({ ...announcementPreview, expiresAt: new Date(Date.now() + 4000).toISOString() });
|
|
await render(); await settle();
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
});
|