mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-08 00:54:38 +02:00
feat: add native in-app announcements with persistent dismissal (#13403)
## 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>
This commit is contained in:
1 parent
f1d57863d2
commit
728f7185f6
53 files changed
+97886
No files matched your search
@@ -74,6 +74,11 @@ pnpm dev
|
||||
1. Keep changes company-scoped.
|
||||
Every domain entity should be scoped to a company and company boundaries must be enforced in routes/services.
|
||||
|
||||
Explicit exception: announcement dismissals are instance-wide user preferences,
|
||||
keyed by user and announcement so they persist across companies. Their audit
|
||||
context must still validate company membership. The announcement publication-ID
|
||||
registry is instance-level feed metadata; it contains no company or user data.
|
||||
|
||||
2. Keep contracts synchronized.
|
||||
If you change schema/API behavior, update all impacted layers:
|
||||
- `packages/db` schema and exports
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"announcement": null
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
+12
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html><head><style>
|
||||
*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden}body{font-family:system-ui,sans-serif;background:#14171c;color:#e9edf2;display:grid;place-items:center}
|
||||
.scene{position:relative;width:100%;height:100%;min-height:90px;background:radial-gradient(ellipse at 50% 120%,#403762 0%,transparent 68%),linear-gradient(110deg,#181c22,#20242c)}
|
||||
.grid{position:absolute;inset:0;background-image:linear-gradient(#ffffff06 1px,transparent 1px),linear-gradient(90deg,#ffffff06 1px,transparent 1px);background-size:20px 20px}
|
||||
.label{position:absolute;top:12%;left:7%;font-size:9px;letter-spacing:2px;color:#a9b0bf}.spark{display:inline-block;width:5px;height:5px;border-radius:50%;background:#ac9af7;margin-right:6px;box-shadow:0 0 10px #ac9af7}
|
||||
.flow{position:absolute;inset:38% 7% 16%;display:flex;align-items:center;justify-content:space-between;gap:12px}.track{position:absolute;left:10%;right:10%;top:50%;height:1px;background:#505167}.packet{position:absolute;top:-2px;width:5px;height:5px;border-radius:50%;background:#c4b5fd;box-shadow:0 0 9px #b7a0fc;animation:travel 4.8s linear infinite}
|
||||
.node{position:relative;display:flex;align-items:center;justify-content:center;gap:7px;width:29%;height:42px;border:1px solid #4b4b60;border-radius:10px;background:#262834;box-shadow:0 4px 12px #0003;font-size:11px;font-weight:500;animation:breathe 4.8s ease-in-out infinite}.node:nth-of-type(3){animation-delay:1.6s}.node:nth-of-type(4){animation-delay:3.2s}.icon{width:15px;height:15px;fill:none;stroke:#c4b5fd;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
|
||||
@keyframes travel{0%{left:0;opacity:0}8%{opacity:1}92%{opacity:1}100%{left:100%;opacity:0}}
|
||||
@keyframes breathe{0%,65%,100%{transform:translateY(0);border-color:#4b4b60}15%,35%{transform:translateY(-3px);border-color:#a79ade;box-shadow:0 4px 20px #9580d52b}}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important}}
|
||||
</style></head><body><div class="scene"><div class="grid"></div><div class="label"><span class="spark"></span>ONE IDEA. A WHOLE TEAM.</div><div class="flow"><div class="track"><div class="packet"></div></div><div class="node"><svg class="icon" viewBox="0 0 20 20"><path d="M6 8a4 4 0 1 1 8 0c0 2-2 2-2 5H8c0-3-2-3-2-5M8 16h4" /></svg>Plan</div><div class="node"><svg class="icon" viewBox="0 0 20 20"><path d="m6 6-4 4 4 4m8-8 4 4-4 4m-3-10-2 12" /></svg>Build</div><div class="node"><svg class="icon" viewBox="0 0 20 20"><circle cx="10" cy="10" r="7"/><path d="m6 10 3 3 5-6"/></svg>Review</div></div></div></body></html>
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"announcement": {
|
||||
"id": "preview-animated-team",
|
||||
"eyebrow": "Staging preview",
|
||||
"title": "From one idea to a working team",
|
||||
"description": "Set a goal, bring in your agents, and follow the work as it moves forward.",
|
||||
"image": {
|
||||
"path": "assets/6ac073cb3447e26f856b15ec058bb9d4d036b0babff60af88ee0dd49cabfa124.png",
|
||||
"alt": "Paperclip. Ideas become work."
|
||||
},
|
||||
"secondaryLink": {
|
||||
"kind": "external",
|
||||
"label": "Learn more",
|
||||
"url": "https://paperclip.ing"
|
||||
},
|
||||
"primaryAction": {
|
||||
"kind": "route",
|
||||
"label": "Explore your projects",
|
||||
"path": "/projects"
|
||||
},
|
||||
"animation": {
|
||||
"path": "assets/78bafb6adbfd9da899cdbb5d934b4c0b9df5d419d6f0a5104a87a7b25dcc6bd8.html",
|
||||
"alt": "Agents plan, build and review work together."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"announcement": null
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"announcement": {
|
||||
"id": "staging-announcement-2026-09-14",
|
||||
"eyebrow": "Staging preview",
|
||||
"title": "Your next idea starts here",
|
||||
"description": "Bring your agents and work together in one place. Explore your projects, or learn more about Paperclip.",
|
||||
"image": {
|
||||
"path": "assets/6ac073cb3447e26f856b15ec058bb9d4d036b0babff60af88ee0dd49cabfa124.png",
|
||||
"alt": "Paperclip. Ideas become work."
|
||||
},
|
||||
"secondaryLink": {
|
||||
"kind": "external",
|
||||
"label": "Learn more",
|
||||
"url": "https://paperclip.ing"
|
||||
},
|
||||
"primaryAction": {
|
||||
"kind": "route",
|
||||
"label": "Explore your projects",
|
||||
"path": "/projects"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
# In-app announcements
|
||||
|
||||
Paperclip displays one optional announcement card in the board UI. Its feed is
|
||||
`https://pages.paperclip.ing/announcements/v1/current.json`. The instance fetches
|
||||
JSON on demand and renders it with native components.
|
||||
|
||||
## Operator configuration
|
||||
|
||||
- `PAPERCLIP_ANNOUNCEMENTS_ENABLED=false` disables fetching and display.
|
||||
- `PAPERCLIP_ANNOUNCEMENTS_FEED_URL` overrides the public HTTPS manifest URL.
|
||||
Credentials, query strings, private destinations and redirects are rejected.
|
||||
|
||||
Announcements are independent of telemetry. Feed/media requests originate from
|
||||
the instance without account IDs, company data, cookies or event tracking. The
|
||||
host sees ordinary server network request metadata. The browser requests only
|
||||
its own Paperclip API.
|
||||
|
||||
## Authoring and publishing
|
||||
|
||||
The shared `announcementManifestSchema` defines the format:
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"announcement": {
|
||||
"id": "2026-09-projects",
|
||||
"eyebrow": "New in Paperclip",
|
||||
"title": "Your next idea starts here",
|
||||
"description": "Bring your agents and work together in a project.",
|
||||
"secondaryLink": { "kind": "external", "label": "Learn more", "url": "https://paperclip.ing" },
|
||||
"primaryAction": { "kind": "route", "label": "Open projects", "path": "/projects" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Content is plain text. Every manifest object rejects unknown fields, including
|
||||
misspellings in actions and media. Optional fields: `image: { path, alt }`,
|
||||
`animation: { path, alt }`, `expiresAt` (ISO
|
||||
timestamp), and `minimumPaperclipVersion` (stable `major.minor.patch`). Internal
|
||||
actions accept stable pages in `ANNOUNCEMENT_APP_ROUTES` and use the selected
|
||||
company. External HTTPS links open a new tab. Actions only navigate.
|
||||
|
||||
Images are `assets/<sha256>.png`, `.jpg` or `.webp`, at most 2 MiB, relative to
|
||||
the manifest directory. Use an approximately 2.6:1 banner with important content
|
||||
near the center; mobile crops it shorter. The manifest is limited to 64 KiB.
|
||||
Run `shasum -a 256 hero.png` to get the image digest, copy the file to
|
||||
`announcements/assets/<digest>.png`, and use `assets/<digest>.png` in the
|
||||
manifest. An image correction changes this asset filename while retaining the
|
||||
announcement ID.
|
||||
|
||||
Edit `announcements/current.json`, put its image under `announcements/assets/`,
|
||||
then run:
|
||||
|
||||
```sh
|
||||
node cli/node_modules/tsx/dist/cli.mjs scripts/publish-announcements.ts announcements --dry-run
|
||||
```
|
||||
|
||||
Set `PAPERCLIP_PAGE_BUCKET`, optionally `PAPERCLIP_PAGE_BASE_URL`, and the page
|
||||
uploader's namespaced `PAPERCLIP_PAGE_AWS_ACCESS_KEY_ID` and
|
||||
`PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY` (optional `PAPERCLIP_PAGE_AWS_SESSION_TOKEN`),
|
||||
or `PAPERCLIP_PAGE_AWS_PROFILE`. Ambient AWS credentials also work.
|
||||
For a host serving a subdirectory, `PAPERCLIP_PAGE_DEFAULT_PREFIX` prepends a
|
||||
validated path to both S3 keys and public URLs. Use lowercase letters, numbers
|
||||
and hyphens in each segment, without leading/trailing slashes.
|
||||
|
||||
```sh
|
||||
node cli/node_modules/tsx/dist/cli.mjs scripts/publish-announcements.ts announcements --publish
|
||||
```
|
||||
|
||||
The helper rejects symlinks, validates asset digests and animated HTML, uploads assets first and
|
||||
the manifest last, and verifies the public manifest and asset headers. It writes
|
||||
only the resolved announcement prefix; no remote objects are deleted or
|
||||
infrastructure changed. Allow up
|
||||
to six minutes for CDN propagation. Manifest caching is five minutes; immutable
|
||||
assets use one year. Before first publication verify the distribution's active
|
||||
cache policy has minimum TTL <= 300 and maximum TTL >= 300 for the manifest,
|
||||
and maximum TTL >= 31536000 for assets. Check the behavior matching each path,
|
||||
including any referenced cache policy. Public response headers alone cannot
|
||||
prove the effective cache lifetime or override a higher minimum. See
|
||||
[AWS cache expiration](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html).
|
||||
|
||||
Retain the ID when fixing copy/images/animations. Use a new ID to announce something new.
|
||||
ETags improve fetching but never determine redisplay.
|
||||
|
||||
## Animated hero media
|
||||
|
||||
An announcement can show a self-contained **HTML/CSS animation** in its hero
|
||||
area. The headline, description, close button and actions remain native
|
||||
Paperclip controls. Add an `animation` alongside the required static `image`:
|
||||
|
||||
```json
|
||||
"image": { "path": "assets/<image-sha256>.png", "alt": "A team working together" },
|
||||
"animation": { "path": "assets/<html-sha256>.html", "alt": "Agents plan, build and review work together." }
|
||||
```
|
||||
|
||||
Replace the placeholders with the files' actual 64-character SHA-256 digests.
|
||||
HTML is UTF-8, limited to 128 KiB, and uses a responsive document with zero body
|
||||
margin. The hero is about 352 × 136 on desktop and shorter on phones. Use CSS
|
||||
keyframes, inline styles, system fonts, and visual HTML (`div`, `span`, `p`,
|
||||
`br`, `strong`, `em`, `b`, `i`) or inline SVG shapes/text (`svg`, `g`, `path`,
|
||||
`circle`, `ellipse`, `rect`, `line`, `polyline`, `polygon`, `text`, `tspan`,
|
||||
`title`, `desc`). No scripts, external libraries, links, forms, iframes, images,
|
||||
SVG SMIL/foreignObject, meta refresh or other embedded resources. CSS URL
|
||||
requests and imports are blocked by CSP; keep all styling self-contained.
|
||||
The publisher and server use the same strict DOMPurify allowlist and reject
|
||||
unsupported markup rather than publishing a silently changed animation.
|
||||
|
||||
Paperclip verifies the digest, validates the HTML, and renders the result in an
|
||||
opaque sandboxed iframe with no permissions. A Content Security Policy blocks
|
||||
scripts and network resources both inside the card and on direct API visits.
|
||||
The browser fetches HTML from its own authenticated instance; it never loads
|
||||
the publisher's page in an unsandboxed frame. The frame cannot receive pointer
|
||||
or keyboard focus; its accessible description is supplied by `animation.alt`.
|
||||
See [iframe sandboxing](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/iframe).
|
||||
|
||||
The animation plays automatically without playback controls. The static image
|
||||
stays visible while loading and on failure. With reduced motion enabled,
|
||||
Paperclip does not request or play the animation. Also include a
|
||||
`prefers-reduced-motion` CSS rule in authored documents for standalone previews.
|
||||
Animations share the feed's constrained host, three-second server timeout,
|
||||
bounded cache, request deduplication and fifteen-minute failure cooldown.
|
||||
Dismissal and ID reuse rules are identical for animated and static cards.
|
||||
Older Paperclip builds that do not recognize `animation` treat that feed as
|
||||
unsupported and quietly show no card.
|
||||
|
||||
The complete authoring example is `announcements/examples/animated/`. Preview
|
||||
it with the same staging/test-drive workflow below:
|
||||
|
||||
```sh
|
||||
cp -R announcements/examples/animated .paperclip/announcement-animation-preview
|
||||
# Edit HTML; recompute its digest and rename it; update current.json.
|
||||
node cli/node_modules/tsx/dist/cli.mjs scripts/publish-announcements.ts .paperclip/announcement-animation-preview --staging animated-preview --dry-run
|
||||
node cli/node_modules/tsx/dist/cli.mjs scripts/publish-announcements.ts .paperclip/announcement-animation-preview --staging animated-preview --publish
|
||||
```
|
||||
|
||||
Point the isolated instance at the printed URL and restart it. Verify movement,
|
||||
reduced motion, mobile sizing, and dismissal across reloads. Try a
|
||||
missing animation asset: the poster and native controls must remain usable.
|
||||
Storybook's Animated, AnimatedDark, AnimatedMobile and MissingAnimation stories,
|
||||
and the design guide, provide local examples without changing the remote feed.
|
||||
|
||||
## Preview an announcement before publishing
|
||||
|
||||
Use a named staging feed. `--staging <name>` writes
|
||||
`announcements/staging/<name>/v1/` instead of `announcements/v1/`, so a preview
|
||||
cannot overwrite the production manifest. With no source directory it uses
|
||||
`announcements/examples/staging/`, including a sample banner. Commands default
|
||||
to dry-run unless `--publish` is supplied.
|
||||
|
||||
For Paperclip's existing preview host, use the branch preview area that
|
||||
CloudFront already has permission to read:
|
||||
|
||||
```sh
|
||||
aws sso login --profile paperclip-dev
|
||||
export PAPERCLIP_PAGE_AWS_PROFILE=paperclip-dev
|
||||
export PAPERCLIP_PAGE_BUCKET=paperclipai-runner-e2e-history-078455283791-us-east-1
|
||||
export PAPERCLIP_PAGE_BASE_URL=https://d1p6rlowie26tp.cloudfront.net
|
||||
export PAPERCLIP_PAGE_DEFAULT_PREFIX=storybook/branches/codex-announcements
|
||||
|
||||
# Copy the public fixture into an ignored directory and edit current.json there.
|
||||
mkdir -p .paperclip
|
||||
cp -R announcements/examples/staging .paperclip/announcement-preview
|
||||
node cli/node_modules/tsx/dist/cli.mjs scripts/publish-announcements.ts .paperclip/announcement-preview --staging my-preview --dry-run
|
||||
node cli/node_modules/tsx/dist/cli.mjs scripts/publish-announcements.ts .paperclip/announcement-preview --staging my-preview --publish
|
||||
```
|
||||
|
||||
Choose a unique staging name for your test and use the printed manifest URL.
|
||||
The preview host currently uses CloudFront's `Managed-CachingDisabled` policy
|
||||
for this branch area: edge TTL is zero even though public responses preserve
|
||||
the five-minute manifest and one-year asset cache headers. This is useful for
|
||||
preview iteration; it does not verify a production distribution's effective
|
||||
cache lifetime. For another host, configure its bucket, base URL and optional
|
||||
prefix, then verify its matching cache behavior as described above.
|
||||
|
||||
Create a test-drive configuration in this worktree. Put the feed override in
|
||||
the **selected instance's `.env`**, not just the invoking shell: test-drive
|
||||
deliberately clears inherited `PAPERCLIP_*` variables.
|
||||
|
||||
```sh
|
||||
mkdir -p .paperclip/announcement-test-drive/instances/default
|
||||
# On a new test directory, create this file. On reuse, update these entries
|
||||
# while preserving the file's existing keys.
|
||||
cat > .paperclip/announcement-test-drive/instances/default/.env <<'EOF'
|
||||
PAPERCLIP_ANNOUNCEMENTS_FEED_URL=https://d1p6rlowie26tp.cloudfront.net/storybook/branches/codex-announcements/announcements/staging/my-preview/v1/current.json
|
||||
PAPERCLIP_ANNOUNCEMENTS_ENABLED=true
|
||||
PAPERCLIP_DB_BACKUP_ENABLED=false
|
||||
HEARTBEAT_SCHEDULER_ENABLED=false
|
||||
EOF
|
||||
|
||||
# A fresh test-drive needs a provider key for its initial CEO. Use your usual
|
||||
# provider environment variable; never put a real key into a manifest or commit.
|
||||
# Reusing an initialized data directory does not require a bootstrap key.
|
||||
node cli/node_modules/tsx/dist/cli.mjs cli/src/index.ts test-drive --data-dir .paperclip/announcement-test-drive --no-browser
|
||||
```
|
||||
|
||||
See [test-drive setup](DEVELOPING.md#one-command-isolated-manual-test-drive) for harness/key options.
|
||||
Open the printed local URL. The app chooses a free port starting at 3100 and
|
||||
keeps its database under the supplied directory. It creates no tasks or initial
|
||||
agent run. After onboarding/company selection, allow three seconds for the card.
|
||||
|
||||
Before promoting content, verify:
|
||||
|
||||
- The image, copy and both actions fit desktop/mobile and both themes.
|
||||
- A dialog or bottom-left toast temporarily hides the card, then restores it.
|
||||
- Close or follow a link; reload, switch companies and open another tab/browser.
|
||||
The same account should keep that ID dismissed.
|
||||
- Edit copy with the same ID: it stays dismissed. Publish a new ID: it appears
|
||||
on the next eligible visit. Clearing browser storage alone does not reset
|
||||
database dismissals; use a new ID or a fresh isolated data directory.
|
||||
- Try the empty fixture and a URL that returns 404. The dashboard remains usable
|
||||
with no announcement and no announcement error popup.
|
||||
|
||||
Stop and restart test-drive after changing its feed URL or republishing content
|
||||
when you need immediate results. This clears the server's one-hour feed cache
|
||||
while retaining dismissal records in the same data directory. Reload or return
|
||||
to the app after restart; an uninterrupted active tab does not discover cards.
|
||||
For promotion, validate the reviewed content again, configure the production
|
||||
host/prefix, and publish without `--staging`. Production's checked-in manifest
|
||||
remains empty until a real announcement is ready.
|
||||
|
||||
## No announcement and withdrawal
|
||||
|
||||
The explicit **none** value is JSON `null`, not the string `"none"`:
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"announcement": null
|
||||
}
|
||||
```
|
||||
|
||||
Publish this manifest to withdraw an announcement while retaining every user's
|
||||
dismissed IDs. Restoring an old announcement cannot resurrect it for people who
|
||||
dismissed it. The ready-to-publish empty fixture is
|
||||
`announcements/examples/none/current.json`:
|
||||
|
||||
```sh
|
||||
node cli/node_modules/tsx/dist/cli.mjs scripts/publish-announcements.ts announcements/examples/none --staging my-empty-preview --publish
|
||||
```
|
||||
|
||||
A remote **404** is also a normal empty feed: the board API returns HTTP 200
|
||||
with `null`, clears previous content/ETag, and waits fifteen minutes before
|
||||
checking upstream again. It produces no announcement warning in server logs or
|
||||
popup in the UI. Other unavailable or invalid feeds likewise produce no card
|
||||
or UI error popup; unexpected upstream failures can be logged for operators.
|
||||
Withdrawal follows the cache/return timing below. Explicit expiration also
|
||||
removes a visible card when its deadline arrives.
|
||||
|
||||
## Timing and persistence
|
||||
|
||||
Show after three seconds when opening or returning to Paperclip, after company
|
||||
selection and onboarding. Dialogs and toasts take priority. Phones show it above
|
||||
bottom navigation. No automatic timeout, outside-click dismissal or carousel.
|
||||
Tab visibility controls the return check: moving focus to the address bar or
|
||||
an adjacent app pane leaves the card visible and does not restart its settling
|
||||
period. A hidden tab clears the card; becoming visible fetches fresh dismissal
|
||||
state before showing anything, even if that lookup takes longer than three
|
||||
seconds.
|
||||
|
||||
The instance caches the feed for an hour, deduplicates concurrent fetches, and
|
||||
uses conditional requests. Failed requests have a fifteen-minute cooldown; no
|
||||
card appears for unavailable/invalid/incompatible content. Each request has a
|
||||
three-second deadline. Active tabs do not poll for announcements. Publication
|
||||
and withdrawal are discovered on a return after cache expiry (normally within
|
||||
about 65 minutes for returning users).
|
||||
|
||||
Closing or following either link saves a unique `(userId, announcementId)`
|
||||
record in the instance DB, shared across browsers and companies. Its first
|
||||
write and audit entry commit together; the active company is audit context.
|
||||
Viewers can dismiss their own card. No-login instances share `local-board`.
|
||||
Separate installations do not share state.
|
||||
|
||||
The browser hides immediately, stores pending writes per account, and retries
|
||||
on reconnect/return. Failed saves explain that cross-device sync has not
|
||||
completed. If browser storage is unavailable, state lasts for this visit. Other
|
||||
tabs close through BroadcastChannel/storage events; another browser refreshes
|
||||
state on return. Logout clears displayed state and aborts account-bound work.
|
||||
A failed state lookup never shows a card.
|
||||
|
||||
Board-only APIs: `GET /api/announcements/current`,
|
||||
`GET /api/announcements/:id/image`, `GET /api/announcements/:id/animation`, and `POST /api/announcements/:id/dismiss`
|
||||
with `{ "companyId": "..." }`. Responses use `private, no-store`. Repeated POSTs
|
||||
return 204 without duplicate audits. Pending dismissals remain valid after the
|
||||
feed moves to another ID. The instance retains only the IDs of validated
|
||||
announcements in a publication registry, so offline retries survive withdrawal
|
||||
and restarts. A caller-invented ID returns 404 without creating dismissal or
|
||||
audit rows. This registry is not an archive and records no interaction events.
|
||||
|
||||
Production ships with an empty manifest. Design guide / Storybook fixtures are
|
||||
never used as a production fallback.
|
||||
@@ -192,3 +192,10 @@ Chat instructions require selecting a suitable project, reusing an existing one
|
||||
The `create_project` runtime tool uses the normal project API with durable idempotency. `list_projects` and `list_project_repositories` support selection. Multiple `repositoryIds` select authorized catalog entries; multiple HTTPS GitHub `repositoryUrls` register existing repositories absent from the catalog. IDs and URLs may be combined, but cannot accompany an explicit `workspace`. URLs do not create repositories on GitHub or grant credentials. Execution uses normal repository access rules. Repository IDs are revalidated against the authenticated run's responsible user and connection grants. Agents should consider proper available repositories, clarify material ambiguity, and use repository-free projects when appropriate for non-code work.
|
||||
|
||||
Confirmed project creation appears as a durable card in the shared task transcript, including selected repository links. Tasks are linked inline. Failed creation never produces a success card. Tool evals cover planning/handoff, project/repository selection, retries, permission and mode denials, and ordinary delegation regressions using the production chat directive.
|
||||
|
||||
### In-app announcements
|
||||
|
||||
An optional announcement card shares product news with board users on opening
|
||||
or returning to Paperclip. Dismissals persist per user across companies and
|
||||
browsers within an instance. Operators can disable fetching independently of
|
||||
telemetry. See [Announcements](ANNOUNCEMENTS.md).
|
||||
@@ -1664,3 +1664,17 @@ with bounded continuation and visible recovery. Preserve explicit approvals,
|
||||
current task ownership, cancellation, dependencies, and newer task state. See
|
||||
`doc/architecture/native-status-arbitration.md` for finish feedback and the
|
||||
provenance-checked cleanup of historical automatic completion reviews.
|
||||
|
||||
### In-app announcements
|
||||
|
||||
A versioned remote JSON manifest supplies one optional board announcement.
|
||||
The instance validates/caches content, proxies its raster image, and stores
|
||||
user-scoped dismissals. Closing or following an action dismisses the ID; copy
|
||||
edits retain it. Writes are board-only, idempotent and transactionally audited
|
||||
using an authorized company's context. Viewers may dismiss their own card.
|
||||
This is an explicit exception to company-scoped business entities: the
|
||||
preference follows one account across companies on the instance. A separate
|
||||
instance-level registry retains validated publication IDs, allowing offline
|
||||
dismissal retries after withdrawal while rejecting caller-invented IDs. It
|
||||
stores no announcement content, account data or interaction events.
|
||||
See [Announcements](ANNOUNCEMENTS.md) for API and publishing details.
|
||||
@@ -418,3 +418,9 @@ Per-component rationale:
|
||||
| Setup completion | `ConnectionSetupCompletionScreen` in the shared setup module | Page and dialog; identity, granted agent access and enabled actions |
|
||||
|
||||
Independently addressable examples live under `Connections/In-task connections` in Storybook. The task composer remains available while a card is pending. These components use the existing token and primitive layers.
|
||||
|
||||
## Announcements
|
||||
|
||||
- `AnnouncementCard`: image, eyebrow, headline, description, navigation links and dismissal; accepts an announcement and `onDismiss`.
|
||||
- `AnnouncementWell`: one app-shell placement that owns eligibility, dismissal sync, modal deferral and toast priority. Use only once in Layout.
|
||||
- Preview variants live in `/design-guide` and Storybook under `Announcements/AnnouncementCard`.
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE IF NOT EXISTS "announcement_dismissals" (
|
||||
"user_id" text NOT NULL,
|
||||
"announcement_id" text NOT NULL,
|
||||
"dismissed_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "announcement_dismissals_user_id_announcement_id_pk" PRIMARY KEY("user_id","announcement_id")
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
CREATE TABLE IF NOT EXISTS "announcement_publications" (
|
||||
"announcement_id" text PRIMARY KEY NOT NULL
|
||||
);
|
||||
+47783
File diff suppressed because it is too large.
Load diff
+47802
File diff suppressed because it is too large.
Load diff
+14
@@ -1933,6 +1933,20 @@
|
||||
"when": 1789260211664,
|
||||
"tag": "0277_uneven_lady_deathstrike",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 278,
|
||||
"version": "7",
|
||||
"when": 1789308547419,
|
||||
"tag": "0278_nappy_colonel_america",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 279,
|
||||
"version": "7",
|
||||
"when": 1789390281190,
|
||||
"tag": "0279_tired_deathstrike",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { pgTable, text, timestamp, primaryKey } from "drizzle-orm/pg-core";
|
||||
|
||||
// Only IDs from a validated feed are registered. This durable allowlist keeps
|
||||
// offline dismissal retries working without accepting caller-invented IDs.
|
||||
// It contains no announcement content, account data or interaction events.
|
||||
export const announcementPublications = pgTable("announcement_publications", {
|
||||
announcementId: text("announcement_id").primaryKey(),
|
||||
});
|
||||
|
||||
// Instance-wide personal preference, like user_sidebar_preferences. No auth
|
||||
// foreign key: local_trusted uses the synthetic local-board principal.
|
||||
export const announcementDismissals = pgTable("announcement_dismissals", {
|
||||
userId: text("user_id").notNull(),
|
||||
announcementId: text("announcement_id").notNull(),
|
||||
dismissedAt: timestamp("dismissed_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({ pk: primaryKey({ columns: [table.userId, table.announcementId] }) }));
|
||||
@@ -208,3 +208,4 @@ export { chatTelegramDraftIds } from "./chat_telegram_draft_ids.js";
|
||||
export { aiConnectionDefaults } from "./ai_connection_defaults.js";
|
||||
export { aiProviderDefaults } from "./ai_provider_defaults.js";
|
||||
export * from "./email.js";
|
||||
export { announcementDismissals, announcementPublications } from "./announcement_dismissals.js";
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { announcementManifestSchema, announcementSchema, isAnnouncementEligible } from "./announcements.js";
|
||||
|
||||
const announcement = { id: "new-projects", eyebrow: "New", title: "Projects", description: "Organize your work.", primaryAction: { kind: "route", label: "Open", path: "/projects" } };
|
||||
describe("announcement contract", () => {
|
||||
it("supports an empty feed and a plain-text card", () => {
|
||||
expect(announcementManifestSchema.parse({ schemaVersion: 1, announcement: null }).announcement).toBeNull();
|
||||
expect(announcementSchema.parse(announcement).id).toBe("new-projects");
|
||||
expect(announcementSchema.parse({ ...announcement, title: "<script>alert(1)</script>" }).title).toContain("<script>");
|
||||
});
|
||||
it.each(["/api/companies", "//evil.test", "/projects/../auth", "/company/settings?danger=yes", "/unknown", "javascript:alert(1)"])("rejects unsupported route %s", (path) => {
|
||||
expect(announcementSchema.safeParse({ ...announcement, primaryAction: { kind: "route", label: "Open", path } }).success).toBe(false);
|
||||
});
|
||||
it.each(["not a URL", "http://example.com", "javascript:alert(1)", "https://user:password@example.com"])("rejects unsafe external URL %s", (url) => {
|
||||
expect(announcementSchema.safeParse({ ...announcement, primaryAction: { kind: "external", label: "Open", url } }).success).toBe(false);
|
||||
});
|
||||
it.each(["../secret.png", "https://example.com/a.png", "/assets/a.png", `assets/${"0".repeat(64)}.svg`])("rejects unsafe image path %s", (path) => {
|
||||
expect(announcementSchema.safeParse({ ...announcement, image: { path, alt: "" } }).success).toBe(false);
|
||||
});
|
||||
it("requires a content-addressed HTML animation and a static fallback", () => {
|
||||
const image = { path: `assets/${"0".repeat(64)}.png`, alt: "Poster" };
|
||||
const animation = { path: `assets/${"1".repeat(64)}.html`, alt: "Animated team" };
|
||||
expect(announcementSchema.safeParse({ ...announcement, image, animation }).success).toBe(true);
|
||||
expect(announcementSchema.safeParse({ ...announcement, animation }).success).toBe(false);
|
||||
for (const path of ["https://evil.test/a.html", "../a.html", "assets/a.html", `assets/${"1".repeat(64)}.js`]) {
|
||||
expect(announcementSchema.safeParse({ ...announcement, image, animation: { ...animation, path } }).success).toBe(false);
|
||||
}
|
||||
});
|
||||
it("rejects unknown schema versions and oversized copy", () => {
|
||||
expect(announcementManifestSchema.safeParse({ schemaVersion: 2, announcement }).success).toBe(false);
|
||||
expect(announcementSchema.safeParse({ ...announcement, description: "a".repeat(401) }).success).toBe(false);
|
||||
});
|
||||
it("rejects unknown fields throughout the remotely authored manifest", () => {
|
||||
const image = { path: `assets/${"0".repeat(64)}.png`, alt: "Preview" };
|
||||
const external = { kind: "external", label: "Learn more", url: "https://paperclip.ing" };
|
||||
for (const value of [
|
||||
{ schemaVersion: 1, announcement, extra: true },
|
||||
{ schemaVersion: 1, announcement: { ...announcement, secondaryLinks: external } },
|
||||
{ schemaVersion: 1, announcement: { ...announcement, image: { ...image, title: "Typo" } } },
|
||||
{ schemaVersion: 1, announcement: { ...announcement, primaryAction: { ...announcement.primaryAction, extra: true } } },
|
||||
{ schemaVersion: 1, announcement: { ...announcement, secondaryLink: { ...external, extra: true } } },
|
||||
]) expect(announcementManifestSchema.safeParse(value).success).toBe(false);
|
||||
});
|
||||
it("checks expiration and minimum versions numerically, including prereleases", () => {
|
||||
const item = announcementSchema.parse({ ...announcement, expiresAt: "2027-01-01T00:00:00Z", minimumPaperclipVersion: "2026.913.0" });
|
||||
for (const version of ["2026.912.0", "2026.913.0-canary.1", "unknown"]) expect(isAnnouncementEligible(item, version, 0)).toBe(false);
|
||||
for (const version of ["2026.913.0", "2026.913.0+1.git.abc", "2026.1001.0"]) expect(isAnnouncementEligible(item, version, 0)).toBe(true);
|
||||
expect(isAnnouncementEligible(item, "2026.913.0", Date.parse(item.expiresAt!))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DEFAULT_ANNOUNCEMENT_FEED_URL = "https://pages.paperclip.ing/announcements/v1/current.json";
|
||||
export const ANNOUNCEMENT_MANIFEST_MAX_BYTES = 64 * 1024;
|
||||
export const ANNOUNCEMENT_IMAGE_MAX_BYTES = 2 * 1024 * 1024;
|
||||
export const ANNOUNCEMENT_ANIMATION_MAX_BYTES = 128 * 1024;
|
||||
// Used both in the isolated srcdoc and on the asset endpoint. The HTTP
|
||||
// response additionally applies CSP sandbox (not supported in a meta tag).
|
||||
export const ANNOUNCEMENT_ANIMATION_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'";
|
||||
|
||||
// Only stable, company-relative board pages. Never API paths, entity IDs, or
|
||||
// routes that depend on an experimental feature being enabled.
|
||||
export const ANNOUNCEMENT_APP_ROUTES = [
|
||||
"/dashboard", "/issues", "/projects", "/agents", "/skills", "/apps",
|
||||
"/routines", "/artifacts", "/company/settings",
|
||||
] as const;
|
||||
|
||||
export const announcementIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,95}$/);
|
||||
const label = z.string().trim().min(1).max(48);
|
||||
const httpsUrl = z.string().max(2048).url().refine((value) => {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "https:" && !url.username && !url.password;
|
||||
} catch { return false; }
|
||||
}, "Use an HTTPS URL without credentials");
|
||||
|
||||
export const announcementActionSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("external"), label, url: httpsUrl }).strict(),
|
||||
z.object({ kind: z.literal("route"), label, path: z.enum(ANNOUNCEMENT_APP_ROUTES) }).strict(),
|
||||
]);
|
||||
|
||||
export const announcementSchema = z.object({
|
||||
id: announcementIdSchema,
|
||||
eyebrow: z.string().trim().min(1).max(48),
|
||||
title: z.string().trim().min(1).max(100),
|
||||
description: z.string().trim().min(1).max(400),
|
||||
image: z.object({
|
||||
// Immutable, content-addressed raster assets beneath the feed directory.
|
||||
path: z.string().regex(/^assets\/[a-f0-9]{64}\.(png|jpg|webp)$/),
|
||||
alt: z.string().max(200),
|
||||
}).strict().optional(),
|
||||
animation: z.object({
|
||||
path: z.string().regex(/^assets\/[a-f0-9]{64}\.html$/),
|
||||
alt: z.string().trim().min(1).max(200),
|
||||
}).strict().optional(),
|
||||
secondaryLink: announcementActionSchema.optional(),
|
||||
primaryAction: announcementActionSchema,
|
||||
expiresAt: z.string().datetime({ offset: true }).optional(),
|
||||
minimumPaperclipVersion: z.string().regex(/^\d+\.\d+\.\d+$/).optional(),
|
||||
}).strict().refine((value) => !value.animation || Boolean(value.image), {
|
||||
message: "An animation requires a static fallback image", path: ["image"],
|
||||
});
|
||||
|
||||
export const announcementManifestSchema = z.object({
|
||||
schemaVersion: z.literal(1),
|
||||
announcement: announcementSchema.nullable(),
|
||||
}).strict();
|
||||
export const dismissAnnouncementSchema = z.object({ companyId: z.string().uuid() }).strict();
|
||||
export type AnnouncementAction = z.infer<typeof announcementActionSchema>;
|
||||
export type Announcement = z.infer<typeof announcementSchema>;
|
||||
export type AnnouncementManifest = z.infer<typeof announcementManifestSchema>;
|
||||
|
||||
export function isAnnouncementEligible(announcement: Announcement, version: string, now = Date.now()): boolean {
|
||||
if (announcement.expiresAt && Date.parse(announcement.expiresAt) <= now) return false;
|
||||
if (!announcement.minimumPaperclipVersion) return true;
|
||||
const installed = /^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
|
||||
if (!installed) return false;
|
||||
const minimum = announcement.minimumPaperclipVersion.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const difference = Number(installed[i + 1]) - minimum[i]!;
|
||||
if (difference !== 0) return difference > 0;
|
||||
}
|
||||
return !installed[4]; // A prerelease of the minimum is not that release yet.
|
||||
}
|
||||
@@ -2763,3 +2763,4 @@ export { EXECUTION_RECONCILIATION_CAUSES, requiresExecutionReconciliation } from
|
||||
export * from "./ai-connections.js";
|
||||
export * from "./types/email.js";
|
||||
export * from "./validators/email.js";
|
||||
export * from "./announcements.js";
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env -S node --import tsx
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { lstat, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ANNOUNCEMENT_ANIMATION_MAX_BYTES, ANNOUNCEMENT_IMAGE_MAX_BYTES, ANNOUNCEMENT_MANIFEST_MAX_BYTES, announcementIdSchema, announcementManifestSchema } from "../packages/shared/src/announcements.js";
|
||||
|
||||
import { validateAnnouncementAnimation } from "../server/src/services/announcement-animation.js";
|
||||
|
||||
export function announcementPublishPrefix(staging?: string, hostPrefix?: string) {
|
||||
if (hostPrefix !== undefined && !/^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/.test(hostPrefix)) {
|
||||
throw new Error("Invalid PAPERCLIP_PAGE_DEFAULT_PREFIX: use lowercase path segments without leading or trailing slashes");
|
||||
}
|
||||
const prefix = staging === undefined ? "announcements/v1" : `announcements/staging/${announcementIdSchema.parse(staging)}/v1`;
|
||||
return hostPrefix ? `${hostPrefix}/${prefix}` : prefix;
|
||||
}
|
||||
|
||||
export function parseAnnouncementPublishArgs(args: string[]) {
|
||||
let sourceDirectory: string | undefined;
|
||||
let staging: string | undefined;
|
||||
let mode: "publish" | "dry-run" | undefined;
|
||||
const usage = "Usage: publish-announcements.ts [directory] [--staging name] [--dry-run | --publish]";
|
||||
for (let index = 0; index < args.length; index++) {
|
||||
const arg = args[index];
|
||||
if (arg === "--publish" || arg === "--dry-run") {
|
||||
if (mode) throw new Error(usage);
|
||||
mode = arg === "--publish" ? "publish" : "dry-run";
|
||||
} else if (arg === "--staging") {
|
||||
if (staging !== undefined || !args[index + 1]) throw new Error(usage);
|
||||
staging = announcementIdSchema.parse(args[++index]);
|
||||
} else if (arg.startsWith("--") || sourceDirectory !== undefined) {
|
||||
throw new Error(usage);
|
||||
} else {
|
||||
sourceDirectory = arg;
|
||||
}
|
||||
}
|
||||
return { sourceDirectory: sourceDirectory ?? (staging ? "announcements/examples/staging" : "announcements"), staging, publish: mode === "publish" };
|
||||
}
|
||||
|
||||
export async function prepareAnnouncementPublish(sourceDirectory: string, staging?: string, hostPrefix?: string) {
|
||||
const prefix = announcementPublishPrefix(staging, hostPrefix);
|
||||
const source = path.resolve(sourceDirectory);
|
||||
if (!(await lstat(source)).isDirectory()) throw new Error("Source must be a real directory");
|
||||
const manifestPath = path.join(source, "current.json");
|
||||
const stat = await lstat(manifestPath);
|
||||
if (!stat.isFile() || stat.size > ANNOUNCEMENT_MANIFEST_MAX_BYTES) throw new Error("Invalid or oversized current.json");
|
||||
const manifest = announcementManifestSchema.parse(JSON.parse(await readFile(manifestPath, "utf8")));
|
||||
const files: Array<{ file: string; key: string; contentType: string; cacheControl: string }> = [];
|
||||
for (const kind of ["image", "animation"] as const) {
|
||||
const asset = manifest.announcement?.[kind];
|
||||
if (!asset) continue;
|
||||
if (!(await lstat(path.join(source, "assets"))).isDirectory()) throw new Error("Assets must be a real directory");
|
||||
const assetPath = asset.path;
|
||||
const file = path.join(source, assetPath);
|
||||
const assetStat = await lstat(file);
|
||||
const maximum = kind === "animation" ? ANNOUNCEMENT_ANIMATION_MAX_BYTES : ANNOUNCEMENT_IMAGE_MAX_BYTES;
|
||||
if (!assetStat.isFile() || assetStat.size > maximum) throw new Error(`Invalid or oversized ${kind}`);
|
||||
const bytes = await readFile(file);
|
||||
const digest = createHash("sha256").update(bytes).digest("hex");
|
||||
if (!assetPath.startsWith(`assets/${digest}.`)) throw new Error("Asset filename must match its SHA-256 digest");
|
||||
if (kind === "animation") validateAnnouncementAnimation(bytes);
|
||||
files.push({ file, key: `${prefix}/${assetPath}`, contentType: kind === "animation" ? "text/html" : assetPath.endsWith(".png") ? "image/png" : assetPath.endsWith(".jpg") ? "image/jpeg" : "image/webp", cacheControl: "public,max-age=31536000,immutable" });
|
||||
}
|
||||
files.push({ file: manifestPath, key: `${prefix}/current.json`, contentType: "application/json", cacheControl: "public,max-age=300" });
|
||||
return { manifest, files };
|
||||
}
|
||||
|
||||
export function announcementUploadArgs(bucket: string, file: Awaited<ReturnType<typeof prepareAnnouncementPublish>>["files"][number]) {
|
||||
return ["s3api", "put-object", "--bucket", bucket, "--key", file.key, "--body", file.file,
|
||||
"--content-type", file.contentType, "--cache-control", file.cacheControl];
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { sourceDirectory, staging, publish } = parseAnnouncementPublishArgs(process.argv.slice(2));
|
||||
const hostPrefix = process.env.PAPERCLIP_PAGE_DEFAULT_PREFIX;
|
||||
const prepared = await prepareAnnouncementPublish(sourceDirectory, staging, hostPrefix);
|
||||
const bucket = process.env.PAPERCLIP_PAGE_BUCKET;
|
||||
const baseUrl = process.env.PAPERCLIP_PAGE_BASE_URL?.replace(/\/+$/, "") ?? "https://pages.paperclip.ing";
|
||||
const url = `${baseUrl}/${announcementPublishPrefix(staging, hostPrefix)}/current.json`;
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.search || parsed.hash) throw new Error("Invalid public base URL");
|
||||
console.log(JSON.stringify({ mode: publish ? "publish" : "dry-run", target: staging ? `staging/${staging}` : "production", bucket: bucket ?? "(unset)", url, announcementId: prepared.manifest.announcement?.id ?? null, files: prepared.files }, null, 2));
|
||||
if (!publish) return;
|
||||
if (!bucket) throw new Error("Set PAPERCLIP_PAGE_BUCKET before publishing");
|
||||
const env = { ...process.env };
|
||||
const key = env.PAPERCLIP_PAGE_AWS_ACCESS_KEY_ID;
|
||||
const secret = env.PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY;
|
||||
if (Boolean(key) !== Boolean(secret)) throw new Error("Set both namespaced page uploader credential variables");
|
||||
if (key && secret) {
|
||||
env.AWS_ACCESS_KEY_ID = key;
|
||||
env.AWS_SECRET_ACCESS_KEY = secret;
|
||||
delete env.AWS_SESSION_TOKEN;
|
||||
if (env.PAPERCLIP_PAGE_AWS_SESSION_TOKEN) env.AWS_SESSION_TOKEN = env.PAPERCLIP_PAGE_AWS_SESSION_TOKEN;
|
||||
} else if (env.PAPERCLIP_PAGE_AWS_PROFILE) {
|
||||
delete env.AWS_ACCESS_KEY_ID;
|
||||
delete env.AWS_SECRET_ACCESS_KEY;
|
||||
delete env.AWS_SESSION_TOKEN;
|
||||
env.AWS_PROFILE = env.PAPERCLIP_PAGE_AWS_PROFILE;
|
||||
}
|
||||
// Only validated files, assets before manifest; credentials are scoped to AWS.
|
||||
for (const file of prepared.files) execFileSync("aws", announcementUploadArgs(bucket, file), { env, stdio: "pipe" });
|
||||
console.log("Uploaded. Checking the public manifest (CDN propagation can take five minutes)…");
|
||||
for (let attempt = 0; attempt < 23; attempt++) {
|
||||
try {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(10_000), credentials: "omit", redirect: "error" });
|
||||
const body = announcementManifestSchema.parse(await response.json());
|
||||
if (response.ok && JSON.stringify(body) === JSON.stringify(prepared.manifest)
|
||||
&& /(?:^|,)\s*max-age=300(?:\s*,|$)/i.test(response.headers.get("cache-control") ?? "")) {
|
||||
for (const asset of prepared.files.slice(0, -1)) {
|
||||
const image = await fetch(`${baseUrl}/${asset.key}`, { method: "HEAD", signal: AbortSignal.timeout(10_000), credentials: "omit", redirect: "error" });
|
||||
const caching = image.headers.get("cache-control") ?? "";
|
||||
if (!image.ok || image.headers.get("content-type") !== asset.contentType
|
||||
|| !/(?:^|,)\s*max-age=31536000(?:\s*,|$)/i.test(caching)
|
||||
|| !/(?:^|,)\s*immutable(?:\s*,|$)/i.test(caching)) {
|
||||
throw new Error("Public announcement asset headers are not ready");
|
||||
}
|
||||
}
|
||||
console.log(`Published and verified: ${url}`);
|
||||
return;
|
||||
}
|
||||
} catch { /* Retry edge propagation; uploads have already completed. */ }
|
||||
if (attempt < 22) await new Promise((resolve) => setTimeout(resolve, 15_000));
|
||||
}
|
||||
throw new Error(`Uploaded, but public verification did not finish. Check ${url} and the CloudFront cache policy (minimum TTL must not exceed 300 seconds).`);
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
main().catch((error) => {
|
||||
console.error(error instanceof Error ? error.message : "Announcement publish failed");
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { validateAnnouncementAnimation } from "../services/announcement-animation.js";
|
||||
|
||||
describe("announcement animation documents", () => {
|
||||
it("preserves CSS keyframes and visual HTML/SVG", () => {
|
||||
const html = "<html><head><style>@keyframes pulse{to{opacity:.5}}.dot{animation:pulse 2s infinite}</style></head><body><div class='dot'><svg viewBox='0 0 10 10'><circle cx='5' cy='5' r='3'/></svg></div></body></html>";
|
||||
expect(validateAnnouncementAnimation(Buffer.from(html))).toContain("@keyframes pulse");
|
||||
expect(validateAnnouncementAnimation(Buffer.from(html))).toContain('viewBox="0 0 10 10"');
|
||||
});
|
||||
it.each([
|
||||
"<script>fetch('/api/companies')</script>", "<div onclick='alert(1)'>Click</div>",
|
||||
"<a href='https://evil.test'>Navigate</a>", "<form action='/api/test'><input></form>",
|
||||
"<meta http-equiv='refresh' content='0;url=https://evil.test'>", "<base href='https://evil.test'>",
|
||||
"<iframe src='https://evil.test'></iframe>", "<img src='https://evil.test/pixel'>", "<link rel='stylesheet' href='https://evil.test'>",
|
||||
"<svg><foreignObject><p>Other namespace</p></foreignObject></svg>",
|
||||
"<svg><a xlink:href='https://evil.test'><text>Go</text></a></svg>",
|
||||
"<svg><animate attributeName='href' values='https://evil.test'/></svg>",
|
||||
"<object data='https://evil.test'></object>", "<button>Click</button>",
|
||||
])("rejects active or resource-loading markup: %s", (html) => {
|
||||
expect(() => validateAnnouncementAnimation(Buffer.from(html))).toThrow();
|
||||
});
|
||||
it("rejects empty, oversized and invalid UTF-8 files", () => {
|
||||
for (const bytes of [Buffer.alloc(0), Buffer.alloc(128 * 1024 + 1), Buffer.from([0xff])]) {
|
||||
expect(() => validateAnnouncementAnimation(bytes)).toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { announcementFeedService, ANNOUNCEMENT_CACHE_MS, ANNOUNCEMENT_FAILURE_MS } from "../services/announcement-feed.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
const item = { id: "new-projects", eyebrow: "New", title: "Projects", description: "Organize your work.", primaryAction: { kind: "route", label: "Open", path: "/projects" } };
|
||||
const json = (announcement: unknown = item, etag = '"v1"') => new Response(JSON.stringify({ schemaVersion: 1, announcement }), { headers: { "Content-Type": "application/json", ETag: etag } });
|
||||
afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
|
||||
describe("announcement feed", () => {
|
||||
it("treats a 404 as quiet empty content, drops stale ETags, and recovers after cooldown", async () => {
|
||||
let now = 0;
|
||||
const warn = vi.spyOn(logger, "warn");
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json())
|
||||
.mockImplementationOnce(async () => new Response("Not found", { status: 404 }))
|
||||
.mockImplementationOnce(async () => json({ ...item, id: "restored" }));
|
||||
const service = announcementFeedService({ version: "1.0.0", now: () => now, fetch });
|
||||
expect(await service.current()).toEqual(item);
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
now += ANNOUNCEMENT_FAILURE_MS - 1;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
now++;
|
||||
expect((await service.current())?.id).toBe("restored");
|
||||
expect(fetch.mock.calls[2][1].headers).not.toHaveProperty("If-None-Match");
|
||||
});
|
||||
|
||||
it("deduplicates requests, caches for an hour, then revalidates with ETag", async () => {
|
||||
let now = 0;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json()).mockResolvedValueOnce(new Response(null, { status: 304 }));
|
||||
const service = announcementFeedService({ version: "2026.913.0", now: () => now, fetch });
|
||||
expect(await Promise.all([service.current(), service.current()])).toEqual([item, item]);
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
now = ANNOUNCEMENT_CACHE_MS - 1;
|
||||
await service.current();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
now++;
|
||||
expect(await service.current()).toEqual(item);
|
||||
expect(fetch.mock.calls[1][1]).toMatchObject({ headers: { "If-None-Match": '"v1"' }, credentials: "omit" });
|
||||
expect(Object.keys(fetch.mock.calls[0][1].headers)).toEqual(["Accept"]);
|
||||
});
|
||||
it("withdraws, updates same-ID copy and discovers new IDs after refresh", async () => {
|
||||
let now = 0;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json()).mockImplementationOnce(async () => json({ ...item, title: "Corrected" }, '"v2"')).mockImplementationOnce(async () => json(null)).mockImplementationOnce(async () => json({ ...item, id: "next" }));
|
||||
const service = announcementFeedService({ version: "2026.913.0", now: () => now, fetch });
|
||||
expect((await service.current())?.id).toBe(item.id);
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect((await service.current())?.title).toBe("Corrected");
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect(await service.current()).toBeNull();
|
||||
now += ANNOUNCEMENT_CACHE_MS;
|
||||
expect((await service.current())?.id).toBe("next");
|
||||
});
|
||||
it.each([
|
||||
() => new Response("bad json", { headers: { "Content-Type": "application/json" } }),
|
||||
() => new Response(JSON.stringify({ schemaVersion: 9, announcement: item }), { headers: { "Content-Type": "application/json" } }),
|
||||
() => new Response("x".repeat(65537), { headers: { "Content-Type": "application/json" } }),
|
||||
() => new Response("", { status: 302, headers: { Location: "http://127.0.0.1" } }),
|
||||
() => new Response("<html>error</html>", { status: 503 }),
|
||||
])("suppresses invalid/unavailable feeds and observes failure cooldown", async (response) => {
|
||||
let now = 0;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => response()).mockImplementationOnce(async () => json());
|
||||
const service = announcementFeedService({ version: "1.0.0", now: () => now, fetch });
|
||||
expect(await service.current()).toBeNull();
|
||||
now = ANNOUNCEMENT_FAILURE_MS - 1;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
now++;
|
||||
expect(await service.current()).toEqual(item);
|
||||
});
|
||||
it("bounds a hung fetch to three seconds", async () => {
|
||||
vi.useFakeTimers();
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch: () => new Promise(() => {}) });
|
||||
const result = service.current();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(await result).toBeNull();
|
||||
});
|
||||
it("does not fetch when disabled or an operator URL is invalid", async () => {
|
||||
const fetch = vi.fn();
|
||||
for (const options of [{ enabled: false }, { feedUrl: "http://localhost/feed" }, { feedUrl: "https://user:secret@example.com/feed" }]) {
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch, ...options });
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
expect(await service.animation(item.id)).toBeNull();
|
||||
}
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
it("expires a cached announcement and filters version-incompatible content", async () => {
|
||||
let now = 0;
|
||||
const service = announcementFeedService({ version: "1.0.0", now: () => now, fetch: async () => json({ ...item, expiresAt: "1970-01-01T00:00:01Z" }) });
|
||||
expect(await service.current()).not.toBeNull();
|
||||
now = 1000;
|
||||
expect(await service.current()).toBeNull();
|
||||
expect(await announcementFeedService({ version: "1.0.0", fetch: async () => json({ ...item, minimumPaperclipVersion: "2.0.0" }) }).current()).toBeNull();
|
||||
});
|
||||
it("proxies only the current content-addressed image and caches bytes", async () => {
|
||||
const bytes = Buffer.from("test-image");
|
||||
const path = `assets/${createHash("sha256").update(bytes).digest("hex")}.png`;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path, alt: "" } })).mockImplementationOnce(async () => new Response(bytes, { headers: { "Content-Type": "image/png" } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch });
|
||||
expect(await service.image("other")).toBeNull();
|
||||
const images = await Promise.all([service.image(item.id), service.image(item.id)]);
|
||||
expect(images[0]?.bytes).toEqual(bytes);
|
||||
expect(images[1]).toEqual(images[0]);
|
||||
await service.image(item.id);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(String(fetch.mock.calls[1][0])).toBe(`https://pages.paperclip.ing/announcements/v1/${path}`);
|
||||
});
|
||||
it("rejects image digest mismatches and cools down image retries", async () => {
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "" } })).mockImplementation(async () => new Response("wrong", { headers: { "Content-Type": "image/png" } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch });
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
expect(await service.image(item.id)).toBeNull();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("deduplicates and caches validated animations on the configured host", async () => {
|
||||
const bytes = Buffer.from("<div style='animation:pulse 2s infinite'>Team</div>");
|
||||
const path = `assets/${createHash("sha256").update(bytes).digest("hex")}.html`;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "Poster" }, animation: { path, alt: "Team" } }))
|
||||
.mockImplementationOnce(async () => new Response(bytes, { headers: { "Content-Type": "text/html; charset=utf-8" } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", feedUrl: "https://mirror.example/preview/current.json", fetch });
|
||||
expect(await service.animation("wrong-id")).toBeNull();
|
||||
const result = await Promise.all([service.animation(item.id), service.animation(item.id)]);
|
||||
expect(result[0]?.bytes.toString()).toContain("Team");
|
||||
expect(result[1]).toEqual(result[0]);
|
||||
await service.animation(item.id);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(String(fetch.mock.calls[1][0])).toBe(`https://mirror.example/preview/${path}`);
|
||||
expect(fetch.mock.calls[1][1]).toMatchObject({ credentials: "omit", redirect: "error", headers: { Accept: "text/html" } });
|
||||
});
|
||||
it.each([
|
||||
["<script>alert(1)</script>", "text/html", 200],
|
||||
["<div>ok</div>", "text/plain", 200],
|
||||
["not found", "text/html", 404],
|
||||
["x".repeat(128 * 1024 + 1), "text/html", 200],
|
||||
])("falls back on rejected animation assets and cools down retries", async (html, contentType, status) => {
|
||||
const path = `assets/${createHash("sha256").update(html).digest("hex")}.html`;
|
||||
const fetch = vi.fn().mockImplementationOnce(async () => json({ ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "Poster" }, animation: { path, alt: "Team" } }))
|
||||
.mockImplementation(async () => new Response(html, { status, headers: { "Content-Type": contentType } }));
|
||||
const service = announcementFeedService({ version: "1.0.0", fetch });
|
||||
expect(await service.animation(item.id)).toBeNull();
|
||||
expect(await service.animation(item.id)).toBeNull();
|
||||
expect((await service.current())?.id).toBe(item.id);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, mkdir, writeFile, symlink, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { prepareAnnouncementPublish, announcementUploadArgs, parseAnnouncementPublishArgs, announcementPublishPrefix } from "../../../scripts/publish-announcements.js";
|
||||
|
||||
const dirs: string[] = [];
|
||||
async function fixture() { const dir = await mkdtemp(path.join(os.tmpdir(), "announcement-publish-")); dirs.push(dir); return dir; }
|
||||
afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); });
|
||||
describe("announcement publishing", () => {
|
||||
it("keeps named staging feeds separate from production and defaults to dry-run", async () => {
|
||||
const dir = await fixture();
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: null }));
|
||||
const result = await prepareAnnouncementPublish(dir, "preview-projects");
|
||||
expect(result.files.map((file) => file.key)).toEqual(["announcements/staging/preview-projects/v1/current.json"]);
|
||||
expect(parseAnnouncementPublishArgs(["--staging", "preview-projects"])).toEqual({
|
||||
sourceDirectory: "announcements/examples/staging", staging: "preview-projects", publish: false,
|
||||
});
|
||||
expect(parseAnnouncementPublishArgs([dir, "--staging", "preview-projects", "--publish"]).publish).toBe(true);
|
||||
expect(announcementPublishPrefix()).toBe("announcements/v1");
|
||||
expect((await prepareAnnouncementPublish(dir, "preview-projects", "storybook/branches/codex-announcements")).files[0].key)
|
||||
.toBe("storybook/branches/codex-announcements/announcements/staging/preview-projects/v1/current.json");
|
||||
for (const prefix of ["../outside", "/leading", "trailing/", "bad//path", "", "https://example.com"]) {
|
||||
expect(() => announcementPublishPrefix("preview-projects", prefix)).toThrow();
|
||||
}
|
||||
for (const name of ["../v1", "", "/production", "preview/nested"]) {
|
||||
expect(() => announcementPublishPrefix(name)).toThrow();
|
||||
}
|
||||
for (const args of [["--staging"], ["--publish", "--dry-run"], ["one", "two"], ["--unknown"]]) {
|
||||
expect(() => parseAnnouncementPublishArgs(args)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("uploads content-addressed assets before the five-minute manifest", async () => {
|
||||
const dir = await fixture();
|
||||
const bytes = Buffer.from("test-image");
|
||||
const imagePath = `assets/${createHash("sha256").update(bytes).digest("hex")}.png`;
|
||||
await mkdir(path.join(dir, "assets"));
|
||||
await writeFile(path.join(dir, imagePath), bytes);
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: { id: "test", title: "Test", eyebrow: "New", description: "Example", image: { path: imagePath, alt: "" }, primaryAction: { kind: "route", label: "Open", path: "/projects" } } }));
|
||||
const { files } = await prepareAnnouncementPublish(dir);
|
||||
expect(files.map((file) => file.key)).toEqual([`announcements/v1/${imagePath}`, "announcements/v1/current.json"]);
|
||||
expect(files[0].cacheControl).toContain("immutable");
|
||||
expect(announcementUploadArgs("bucket", files[1])).toContain("public,max-age=300");
|
||||
await writeFile(path.join(dir, imagePath), "changed");
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow("SHA-256");
|
||||
});
|
||||
it("validates HTML animation fixtures and uploads both assets before the manifest", async () => {
|
||||
const result = await prepareAnnouncementPublish(path.resolve(import.meta.dirname, "../../../announcements/examples/animated"), "animated-preview");
|
||||
expect(result.files.map((file) => file.contentType)).toEqual(["image/png", "text/html", "application/json"]);
|
||||
const dir = await fixture();
|
||||
await mkdir(path.join(dir, "assets"));
|
||||
const html = "<meta http-equiv='refresh' content='0;url=https://evil.test'>";
|
||||
const asset = `assets/${createHash("sha256").update(html).digest("hex")}.html`;
|
||||
const image = result.files[0];
|
||||
const imagePath = result.manifest.announcement!.image!.path;
|
||||
await writeFile(path.join(dir, imagePath), await import("node:fs/promises").then((fs) => fs.readFile(image.file)));
|
||||
await writeFile(path.join(dir, asset), html);
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ ...result.manifest, announcement: { ...result.manifest.announcement, animation: { path: asset, alt: "Unsafe" } } }));
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow("only visual HTML/CSS");
|
||||
});
|
||||
it("supports withdrawal and rejects symlinks and unsupported schemas", async () => {
|
||||
const dir = await fixture();
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: null }));
|
||||
expect((await prepareAnnouncementPublish(dir)).files).toHaveLength(1);
|
||||
const link = path.join(dir, "link"); await symlink(dir, link);
|
||||
await expect(prepareAnnouncementPublish(link)).rejects.toThrow("real directory");
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 2, announcement: null }));
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow();
|
||||
await writeFile(path.join(dir, "current.json"), JSON.stringify({ schemaVersion: 1, announcement: null, announcements: [] }));
|
||||
await expect(prepareAnnouncementPublish(dir)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import express from "express";
|
||||
import { createHash } from "node:crypto";
|
||||
import request from "supertest";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { activityLog, announcementDismissals, announcementPublications, companies, createDb, startEmbeddedPostgresTestDatabase, type EmbeddedPostgresTestDatabase } from "@paperclipai/db";
|
||||
import { announcementRoutes } from "../routes/announcements.js";
|
||||
import { announcementService } from "../services/announcements.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
|
||||
const companyId = "11111111-1111-4111-8111-111111111111";
|
||||
const otherCompanyId = "22222222-2222-4222-8222-222222222222";
|
||||
const item = { id: "new-projects", eyebrow: "New", title: "Projects", description: "Organize your work.", primaryAction: { kind: "route", label: "Open", path: "/projects" } };
|
||||
describe("announcement routes and durable dismissals", () => {
|
||||
let database: EmbeddedPostgresTestDatabase;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
function app(userId = "alice", actorOverride?: Record<string, unknown>, announcement: unknown = item, feedStatus = 200, animationHtml?: string) {
|
||||
const server = express();
|
||||
server.use(express.json());
|
||||
server.use((req, _res, next) => {
|
||||
req.actor = (actorOverride ?? { type: "board", userId, source: "session", companyIds: [companyId, otherCompanyId], memberships: [{ companyId, membershipRole: "viewer", status: "active" }] }) as never;
|
||||
next();
|
||||
});
|
||||
server.use("/api", announcementRoutes(db, { version: "2026.913.0", fetch: async (url) => animationHtml && url.pathname.endsWith(".html") ? new Response(animationHtml, { headers: { "Content-Type": "text/html" } }) : new Response(JSON.stringify({ schemaVersion: 1, announcement }), { status: feedStatus, headers: { "Content-Type": "application/json" } }) }));
|
||||
server.use(errorHandler);
|
||||
return server;
|
||||
}
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-announcements-");
|
||||
db = createDb(database.connectionString);
|
||||
await db.insert(companies).values([{ id: companyId, name: "Test", issuePrefix: "ANN" }, { id: otherCompanyId, name: "Other", issuePrefix: "ANB" }]);
|
||||
}, 90_000);
|
||||
beforeEach(async () => { await db.delete(announcementDismissals); await db.delete(announcementPublications); await db.delete(activityLog); });
|
||||
afterAll(async () => { await database?.cleanup(); }, 30_000);
|
||||
it.each([200, 404])("returns a successful empty response for no remote announcement (HTTP %s)", async (status) => {
|
||||
const response = await request(app("alice", undefined, null, status)).get("/api/announcements/current");
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toBeNull();
|
||||
expect(response.headers["cache-control"]).toBe("private, no-store");
|
||||
});
|
||||
it("serves animation documents with a sandbox and network-denying CSP", async () => {
|
||||
const html = "<div>Team</div>";
|
||||
const path = `assets/${createHash("sha256").update(html).digest("hex")}.html`;
|
||||
const server = app("alice", undefined, { ...item, image: { path: `assets/${"0".repeat(64)}.png`, alt: "Poster" }, animation: { path, alt: "Team" } }, 200, html);
|
||||
const response = await request(server).get(`/api/announcements/${item.id}/animation`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers["cache-control"]).toBe("private, no-store");
|
||||
expect(response.headers["content-security-policy"]).toContain("sandbox; default-src 'none'");
|
||||
expect(response.headers["referrer-policy"]).toBe("no-referrer");
|
||||
expect(response.headers["x-content-type-options"]).toBe("nosniff");
|
||||
expect(response.type).toBe("text/html");
|
||||
expect((await request(server).get("/api/announcements/wrong-id/animation")).status).toBe(404);
|
||||
});
|
||||
it("persists across app/service restarts, browsers and companies, isolated by user", async () => {
|
||||
const first = app();
|
||||
const response = await request(first).get("/api/announcements/current");
|
||||
expect(response.body.id).toBe(item.id);
|
||||
expect(response.headers["cache-control"]).toBe("private, no-store");
|
||||
expect((await request(first).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(204);
|
||||
expect((await request(app()).get("/api/announcements/current")).body).toBeNull();
|
||||
expect((await request(app("bob")).get("/api/announcements/current")).body.id).toBe(item.id);
|
||||
await request(app()).post(`/api/announcements/${item.id}/dismiss`).send({ companyId: otherCompanyId });
|
||||
expect(await db.select().from(activityLog)).toHaveLength(1);
|
||||
});
|
||||
it("accepts viewers and concurrent duplicate dismissals with one audit", async () => {
|
||||
const server = app();
|
||||
await request(server).get("/api/announcements/current");
|
||||
const responses = await Promise.all(Array.from({ length: 5 }, () => request(server).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })));
|
||||
expect(responses.map((res) => res.status)).toEqual([204, 204, 204, 204, 204]);
|
||||
expect(await db.select().from(announcementDismissals)).toHaveLength(1);
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "announcement.dismissed"))).toHaveLength(1);
|
||||
});
|
||||
it("rolls back the dismissal if its audit cannot commit", async () => {
|
||||
await announcementService(db).registerPublication(item.id);
|
||||
await expect(announcementService(db).dismiss("alice", item.id, "33333333-3333-4333-8333-333333333333")).rejects.toThrow();
|
||||
expect(await announcementService(db).isDismissed("alice", item.id)).toBe(false);
|
||||
});
|
||||
it("never resurrects a dismissed ID after copy changes or rollback; a new ID appears", async () => {
|
||||
await announcementService(db).registerPublication(item.id);
|
||||
await announcementService(db).dismiss("alice", item.id, companyId);
|
||||
expect((await request(app("alice", undefined, { ...item, title: "Fixed copy" })).get("/api/announcements/current")).body).toBeNull();
|
||||
expect((await request(app("alice", undefined, { ...item, id: "next" })).get("/api/announcements/current")).body.id).toBe("next");
|
||||
expect((await request(app()).get("/api/announcements/current")).body).toBeNull();
|
||||
});
|
||||
it("uses the local-board identity without an auth user row", async () => {
|
||||
const server = app("local-board", { type: "board", userId: "local-board", source: "local_implicit" });
|
||||
await request(server).get("/api/announcements/current");
|
||||
expect((await request(server).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(204);
|
||||
expect(await announcementService(db).isDismissed("local-board", item.id)).toBe(true);
|
||||
});
|
||||
it("rejects invented IDs without storing dismissals or audit entries", async () => {
|
||||
const server = app();
|
||||
await request(server).get("/api/announcements/current");
|
||||
for (const id of ["invented-one", "invented-two", "invented-three"]) {
|
||||
expect((await request(server).post(`/api/announcements/${id}/dismiss`).send({ companyId })).status).toBe(404);
|
||||
}
|
||||
expect(await db.select().from(announcementDismissals)).toHaveLength(0);
|
||||
expect(await db.select().from(activityLog)).toHaveLength(0);
|
||||
expect(await db.select().from(announcementPublications)).toEqual([{ announcementId: item.id }]);
|
||||
});
|
||||
it("accepts offline retries for validated IDs after withdrawal and restart", async () => {
|
||||
await request(app()).get("/api/announcements/current");
|
||||
const restarted = app("alice", undefined, null, 404);
|
||||
expect((await request(restarted).get("/api/announcements/current")).body).toBeNull();
|
||||
expect((await request(restarted).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(204);
|
||||
expect(await announcementService(db).isDismissed("alice", item.id)).toBe(true);
|
||||
expect(await db.select().from(activityLog)).toHaveLength(1);
|
||||
});
|
||||
it("rejects anonymous/agent callers and inaccessible audit companies", async () => {
|
||||
for (const actor of [{ type: "none" }, { type: "agent", companyId, userId: "alice" }]) {
|
||||
const server = app("alice", actor);
|
||||
const expected = actor.type === "none" ? 401 : 403;
|
||||
for (const url of ["current", `${item.id}/image`, `${item.id}/animation`]) expect((await request(server).get(`/api/announcements/${url}`)).status).toBe(expected);
|
||||
expect((await request(server).post(`/api/announcements/${item.id}/dismiss`).send({ companyId })).status).toBe(expected);
|
||||
}
|
||||
expect((await request(app()).post(`/api/announcements/${item.id}/dismiss`).send({ companyId: "33333333-3333-4333-8333-333333333333" })).status).toBe(404);
|
||||
expect((await request(app()).post(`/api/announcements/${item.id}/dismiss`).send({ companyId, userId: "bob" })).status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"activity.ts": "/api",
|
||||
"adapters.ts": "/api",
|
||||
"agents.ts": "/api",
|
||||
"announcements.ts": "/api",
|
||||
"ai-connections.ts": "/api",
|
||||
"attention.ts": "/api",
|
||||
"approvals.ts": "/api",
|
||||
@@ -223,6 +224,26 @@ function loadSpecRoutes() {
|
||||
}
|
||||
|
||||
describe("openapi routes", () => {
|
||||
it("documents personal board-only announcements and private responses", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const current = spec.paths["/api/announcements/current"].get;
|
||||
const image = spec.paths["/api/announcements/{id}/image"].get;
|
||||
const animation = spec.paths["/api/announcements/{id}/animation"].get;
|
||||
const dismiss = spec.paths["/api/announcements/{id}/dismiss"].post;
|
||||
for (const operation of [current, image, animation, dismiss]) {
|
||||
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
|
||||
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
||||
const success = operation.responses["200"] ?? operation.responses["204"];
|
||||
expect(success.headers["Cache-Control"].schema.enum).toEqual(["private, no-store"]);
|
||||
}
|
||||
expect(current.responses["200"].content["application/json"].schema.nullable).toBe(true);
|
||||
expect(Object.keys(image.responses["200"].content)).toEqual(["image/png", "image/jpeg", "image/webp"]);
|
||||
expect(dismiss.requestBody.content["application/json"].schema).toMatchObject({
|
||||
required: ["companyId"], additionalProperties: false,
|
||||
});
|
||||
expect(dismiss.description).toContain("viewers may dismiss their own");
|
||||
});
|
||||
|
||||
it("documents exact failed-run selection and durable accepted retry responses", async () => {
|
||||
const res = await request(createApp()).get("/api/openapi.json");
|
||||
const wake = res.body.paths["/api/agents/{id}/wakeup"].post;
|
||||
|
||||
@@ -91,6 +91,8 @@ import type { DecisionServiceOptions } from "./services/decisions.js";
|
||||
import { userProfileRoutes } from "./routes/user-profiles.js";
|
||||
import { sidebarBadgeRoutes } from "./routes/sidebar-badges.js";
|
||||
import { sidebarPreferenceRoutes } from "./routes/sidebar-preferences.js";
|
||||
import { announcementRoutes } from "./routes/announcements.js";
|
||||
import { serverVersion } from "./version.js";
|
||||
import { resourceMembershipRoutes } from "./routes/resource-memberships.js";
|
||||
import { inboxDismissalRoutes } from "./routes/inbox-dismissals.js";
|
||||
import { instanceSettingsRoutes } from "./routes/instance-settings.js";
|
||||
@@ -474,6 +476,7 @@ export async function createApp(
|
||||
chatWebhookPublicBaseUrl?: string;
|
||||
authReady: boolean;
|
||||
companyDeletionEnabled: boolean;
|
||||
announcements?: { enabled: boolean; feedUrl: string };
|
||||
instanceId?: string;
|
||||
hostVersion?: string;
|
||||
localPluginDir?: string;
|
||||
@@ -776,6 +779,7 @@ export async function createApp(
|
||||
api.use(userProfileRoutes(db));
|
||||
api.use(sidebarBadgeRoutes(db));
|
||||
api.use(sidebarPreferenceRoutes(db));
|
||||
api.use(announcementRoutes(db, { ...opts.announcements, version: opts.hostVersion ?? serverVersion }));
|
||||
api.use(resourceMembershipRoutes(db));
|
||||
api.use(inboxDismissalRoutes(db));
|
||||
api.use(instanceSettingsRoutes(db));
|
||||
|
||||
@@ -95,6 +95,8 @@ export interface Config {
|
||||
heartbeatSchedulerIntervalMs: number;
|
||||
companyDeletionEnabled: boolean;
|
||||
telemetryEnabled: boolean;
|
||||
announcementsEnabled: boolean;
|
||||
announcementsFeedUrl: string;
|
||||
}
|
||||
|
||||
function detectTailnetBindHost(): string | undefined {
|
||||
@@ -364,5 +366,7 @@ export function loadConfig(): Config {
|
||||
heartbeatSchedulerIntervalMs: Math.max(10000, Number(process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS) || 30000),
|
||||
companyDeletionEnabled,
|
||||
telemetryEnabled: fileConfig?.telemetry?.enabled ?? true,
|
||||
announcementsEnabled: process.env.PAPERCLIP_ANNOUNCEMENTS_ENABLED !== "false",
|
||||
announcementsFeedUrl: process.env.PAPERCLIP_ANNOUNCEMENTS_FEED_URL?.trim() || "https://pages.paperclip.ing/announcements/v1/current.json",
|
||||
};
|
||||
}
|
||||
@@ -911,6 +911,7 @@ async function startServerWithDatabaseTeardown(
|
||||
chatWebhookPublicBaseUrl: config.chatWebhookPublicBaseUrl,
|
||||
authReady,
|
||||
companyDeletionEnabled: config.companyDeletionEnabled,
|
||||
announcements: { enabled: config.announcementsEnabled, feedUrl: config.announcementsFeedUrl },
|
||||
pluginMigrationDb: pluginMigrationDb as any,
|
||||
betterAuthHandler,
|
||||
resolveSession,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { companies, type Db } from "@paperclipai/db";
|
||||
import { ANNOUNCEMENT_ANIMATION_CSP, announcementIdSchema, dismissAnnouncementSchema } from "@paperclipai/shared";
|
||||
import { badRequest, forbidden, notFound } from "../errors.js";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { assertAuthenticated, assertBoard, hasCompanyAccess } from "./authz.js";
|
||||
import { announcementService } from "../services/announcements.js";
|
||||
import { announcementFeedService, type AnnouncementFeedOptions } from "../services/announcement-feed.js";
|
||||
|
||||
export function announcementRoutes(db: Db, options: AnnouncementFeedOptions) {
|
||||
const router = Router();
|
||||
const feed = announcementFeedService(options);
|
||||
const service = announcementService(db);
|
||||
router.use("/announcements", (req, res, next) => {
|
||||
assertAuthenticated(req);
|
||||
assertBoard(req);
|
||||
if (!req.actor.userId) throw forbidden("Board user context required");
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
next();
|
||||
});
|
||||
router.get("/announcements/current", async (req, res) => {
|
||||
const announcement = await feed.current();
|
||||
if (announcement) await service.registerPublication(announcement.id);
|
||||
res.json(announcement && !await service.isDismissed(req.actor.userId!, announcement.id) ? announcement : null);
|
||||
});
|
||||
router.get("/announcements/:id/image", async (req, res) => {
|
||||
const id = announcementIdSchema.safeParse(req.params.id);
|
||||
if (!id.success) throw badRequest("Invalid announcement ID");
|
||||
const image = await feed.image(id.data);
|
||||
if (!image) throw notFound("Announcement image unavailable");
|
||||
res.setHeader("Content-Type", image.contentType);
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.send(image.bytes);
|
||||
});
|
||||
router.get("/announcements/:id/animation", async (req, res) => {
|
||||
const id = announcementIdSchema.safeParse(req.params.id);
|
||||
if (!id.success) throw badRequest("Invalid announcement ID");
|
||||
const animation = await feed.animation(id.data);
|
||||
if (!animation) throw notFound("Announcement animation unavailable");
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.setHeader("Content-Security-Policy", `sandbox; ${ANNOUNCEMENT_ANIMATION_CSP}`);
|
||||
res.setHeader("Referrer-Policy", "no-referrer");
|
||||
res.send(animation.bytes);
|
||||
});
|
||||
router.post("/announcements/:id/dismiss", validate(dismissAnnouncementSchema), async (req, res) => {
|
||||
const id = announcementIdSchema.safeParse(req.params.id);
|
||||
if (!id.success) throw badRequest("Invalid announcement ID");
|
||||
const { companyId } = req.body;
|
||||
// This writes the caller's personal preference. Viewers may dismiss it;
|
||||
// company read membership supplies audit context, not write authority.
|
||||
if (!hasCompanyAccess(req, companyId)) throw notFound("Company not found");
|
||||
if (!await db.query.companies.findFirst({ where: eq(companies.id, companyId), columns: { id: true } })) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
if (!await service.dismiss(req.actor.userId!, id.data, companyId)) throw notFound("Announcement not found");
|
||||
res.status(204).end();
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -112,6 +112,10 @@ import {
|
||||
resolveBudgetIncidentSchema,
|
||||
// Sidebar
|
||||
upsertSidebarOrderPreferenceSchema,
|
||||
// Announcements
|
||||
announcementIdSchema,
|
||||
announcementSchema,
|
||||
dismissAnnouncementSchema,
|
||||
// Execution workspaces
|
||||
reconcileExecutionWorkspaceBranchSchema,
|
||||
updateExecutionWorkspaceSchema,
|
||||
@@ -1279,6 +1283,7 @@ const PUBLIC_OPERATIONS = new Set([
|
||||
]);
|
||||
|
||||
const BOARD_ONLY_PREFIXES = [
|
||||
"/api/announcements/",
|
||||
"/api/auth/",
|
||||
"/api/admin/",
|
||||
"/api/plugins",
|
||||
@@ -5782,6 +5787,87 @@ registry.registerPath({
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
|
||||
});
|
||||
|
||||
// ─── Announcements ───────────────────────────────────────────────────────────
|
||||
|
||||
const announcementResponseHeaders = {
|
||||
"Cache-Control": { schema: { type: "string", enum: ["private, no-store"] } },
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/announcements/current",
|
||||
tags: ["announcements"],
|
||||
summary: "Get the current user's eligible announcement",
|
||||
description: "Returns null for dismissed, disabled, unavailable, expired or incompatible content. Dismissals follow the board user across companies within this instance; no-login installations use local-board.",
|
||||
responses: {
|
||||
200: { ...r.ok(announcementSchema.nullable()), headers: announcementResponseHeaders },
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
500: r.serverError,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/announcements/{id}/image",
|
||||
tags: ["announcements"],
|
||||
summary: "Get the current announcement's validated image",
|
||||
description: "Proxies only the content-addressed raster asset in the eligible manifest. Arbitrary URLs and asset paths are not accepted.",
|
||||
request: { params: z.object({ id: announcementIdSchema }) },
|
||||
responses: {
|
||||
200: {
|
||||
description: "Validated announcement image",
|
||||
headers: announcementResponseHeaders,
|
||||
content: {
|
||||
"image/png": { schema: { type: "string", format: "binary" } },
|
||||
"image/jpeg": { schema: { type: "string", format: "binary" } },
|
||||
"image/webp": { schema: { type: "string", format: "binary" } },
|
||||
},
|
||||
},
|
||||
400: r.badRequest,
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
404: r.notFound,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/announcements/{id}/animation",
|
||||
tags: ["announcements"],
|
||||
summary: "Get the current announcement's isolated HTML/CSS animation",
|
||||
description: "Board-only, validated content-addressed HTML. Scripts, links, forms and embedded resources are rejected; CSP sandbox and resource restrictions also apply to direct visits. Missing or invalid assets return 404 and the card uses its static image.",
|
||||
request: { params: z.object({ id: announcementIdSchema }) },
|
||||
responses: {
|
||||
200: {
|
||||
description: "Validated visual HTML/CSS document",
|
||||
headers: { ...announcementResponseHeaders, "Content-Security-Policy": { schema: { type: "string" } } },
|
||||
content: { "text/html": { schema: { type: "string" } } },
|
||||
},
|
||||
400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound,
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/announcements/{id}/dismiss",
|
||||
tags: ["announcements"],
|
||||
summary: "Dismiss an announcement for the current user",
|
||||
description: "Idempotently saves a personal preference. The supplied company is validated audit context; viewers may dismiss their own announcement. The first dismissal and its audit entry commit together. IDs from a previously validated feed remain valid for offline retries; unknown IDs return 404 without creating records.",
|
||||
request: {
|
||||
params: z.object({ id: announcementIdSchema }),
|
||||
body: jsonBody(dismissAnnouncementSchema),
|
||||
},
|
||||
responses: {
|
||||
204: { ...r.noContent, headers: announcementResponseHeaders },
|
||||
400: r.badRequest,
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
404: r.notFound,
|
||||
500: r.serverError,
|
||||
},
|
||||
});
|
||||
|
||||
// ─── Inbox dismissals ────────────────────────────────────────────────────────
|
||||
|
||||
registry.registerPath({
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import createDOMPurify from "dompurify";
|
||||
import { JSDOM } from "jsdom";
|
||||
import { ANNOUNCEMENT_ANIMATION_MAX_BYTES } from "@paperclipai/shared";
|
||||
|
||||
// A visual HTML/CSS document, never an application. JSDOM does not execute
|
||||
// scripts or load resources. DOMPurify handles HTML parsing/normalization;
|
||||
// CSP on delivery also blocks all network requests, including CSS URLs.
|
||||
export function validateAnnouncementAnimation(bytes: Uint8Array): string {
|
||||
if (!bytes.length || bytes.byteLength > ANNOUNCEMENT_ANIMATION_MAX_BYTES) {
|
||||
throw new Error("Invalid or oversized announcement animation");
|
||||
}
|
||||
const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
const dom = new JSDOM("");
|
||||
try {
|
||||
const purifier = createDOMPurify(dom.window as unknown as Parameters<typeof createDOMPurify>[0]);
|
||||
const html = purifier.sanitize(source, {
|
||||
WHOLE_DOCUMENT: true,
|
||||
ALLOWED_TAGS: ["html", "head", "body", "style", "div", "span", "p", "br", "strong", "em", "b", "i",
|
||||
"svg", "g", "path", "circle", "ellipse", "rect", "line", "polyline", "polygon", "text", "tspan", "title", "desc"],
|
||||
ALLOWED_ATTR: ["class", "id", "style", "viewBox", "xmlns", "width", "height", "x", "y", "x1", "x2", "y1", "y2",
|
||||
"cx", "cy", "r", "rx", "ry", "d", "points", "fill", "stroke", "stroke-width", "stroke-linecap",
|
||||
"stroke-linejoin", "stroke-dasharray", "stroke-dashoffset", "opacity", "transform", "text-anchor"],
|
||||
ALLOW_DATA_ATTR: false,
|
||||
ALLOW_ARIA_ATTR: false,
|
||||
});
|
||||
if (purifier.removed.length) {
|
||||
throw new Error("Animation must contain only visual HTML/CSS or inline SVG; scripts, navigation, resources and interactive elements are not supported");
|
||||
}
|
||||
return html;
|
||||
} finally {
|
||||
dom.window.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
ANNOUNCEMENT_IMAGE_MAX_BYTES, ANNOUNCEMENT_MANIFEST_MAX_BYTES, ANNOUNCEMENT_ANIMATION_MAX_BYTES,
|
||||
DEFAULT_ANNOUNCEMENT_FEED_URL, announcementManifestSchema, isAnnouncementEligible,
|
||||
type AnnouncementManifest,
|
||||
} from "@paperclipai/shared";
|
||||
import { guardedRemoteHttpFetch } from "./remote-http-fetch.js";
|
||||
import { validateAnnouncementAnimation } from "./announcement-animation.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
export const ANNOUNCEMENT_CACHE_MS = 60 * 60 * 1000;
|
||||
export const ANNOUNCEMENT_FAILURE_MS = 15 * 60 * 1000;
|
||||
const TIMEOUT_MS = 3000;
|
||||
type AnnouncementAsset = { path: string; bytes: Buffer; contentType: string };
|
||||
function assetSlot() {
|
||||
return {
|
||||
cache: null as AnnouncementAsset | null,
|
||||
pending: null as { path: string; promise: Promise<AnnouncementAsset | null> } | null,
|
||||
failure: null as { path: string; retryAt: number } | null,
|
||||
};
|
||||
}
|
||||
export interface AnnouncementFeedOptions {
|
||||
enabled?: boolean;
|
||||
feedUrl?: string;
|
||||
version: string;
|
||||
now?: () => number;
|
||||
fetch?: (url: URL, init: RequestInit) => Promise<Response>;
|
||||
}
|
||||
|
||||
export async function readAnnouncementBytes(response: Response, maximum: number): Promise<Buffer> {
|
||||
if (Number(response.headers.get("content-length")) > maximum) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Announcement response is too large");
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) return Buffer.alloc(0);
|
||||
const chunks: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
length += value.byteLength;
|
||||
if (length > maximum) throw new Error("Announcement response is too large");
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks, length);
|
||||
} finally {
|
||||
await reader.cancel().catch(() => {});
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
export function announcementFeedService(options: AnnouncementFeedOptions) {
|
||||
const now = options.now ?? Date.now;
|
||||
const fetchRemote = options.fetch ?? ((url, init) => guardedRemoteHttpFetch(url, init, {
|
||||
error: (message) => new Error(message), dnsTimeoutMs: TIMEOUT_MS,
|
||||
connectTimeoutMs: TIMEOUT_MS, responseTimeoutMs: TIMEOUT_MS,
|
||||
}));
|
||||
let manifest: AnnouncementManifest | null = null;
|
||||
let etag: string | null = null;
|
||||
let nextCheck = 0;
|
||||
let available = false;
|
||||
let pending: Promise<void> | null = null;
|
||||
// One bounded cache slot per media kind, shared across board users.
|
||||
const assets = {
|
||||
image: assetSlot(),
|
||||
animation: assetSlot(),
|
||||
};
|
||||
|
||||
function endpoint() {
|
||||
const url = new URL(options.feedUrl ?? DEFAULT_ANNOUNCEMENT_FEED_URL);
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.hash || url.search) {
|
||||
throw new Error("Announcement feed must be an HTTPS URL without credentials, query, or fragment");
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
async function request<T>(url: URL, headers: Record<string, string>, consume: (response: Response) => Promise<T>): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
reject(new Error("Announcement request timed out"));
|
||||
}, TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
return await Promise.race([
|
||||
fetchRemote(url, { method: "GET", headers, signal: controller.signal, redirect: "error", credentials: "omit" })
|
||||
.then(consume),
|
||||
deadline,
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer!);
|
||||
controller.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const result = await request(endpoint(), {
|
||||
Accept: "application/json", ...(etag ? { "If-None-Match": etag } : {}),
|
||||
}, async (response) => {
|
||||
if (response.status === 304 && manifest) return { manifest, etag, ttl: ANNOUNCEMENT_CACHE_MS };
|
||||
if (response.status === 404) {
|
||||
await response.body?.cancel();
|
||||
// An unpublished/removed feed is an expected empty state. Forget the
|
||||
// previous ETag so recovery cannot resurrect a stale cached card.
|
||||
return { manifest: { schemaVersion: 1, announcement: null } as AnnouncementManifest, etag: null, ttl: ANNOUNCEMENT_FAILURE_MS };
|
||||
}
|
||||
if (!response.ok || response.status >= 300) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Announcement feed unavailable");
|
||||
}
|
||||
if (response.headers.get("content-type")?.split(";")[0]?.trim() !== "application/json") {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Announcement feed is not JSON");
|
||||
}
|
||||
const bytes = await readAnnouncementBytes(response, ANNOUNCEMENT_MANIFEST_MAX_BYTES);
|
||||
return { manifest: announcementManifestSchema.parse(JSON.parse(bytes.toString("utf8"))), etag: response.headers.get("etag"), ttl: ANNOUNCEMENT_CACHE_MS };
|
||||
});
|
||||
manifest = result.manifest;
|
||||
etag = result.etag;
|
||||
available = true;
|
||||
nextCheck = now() + result.ttl;
|
||||
} catch {
|
||||
available = false;
|
||||
nextCheck = now() + ANNOUNCEMENT_FAILURE_MS;
|
||||
// Do not log remote content or operator URLs (which can carry secrets).
|
||||
logger.warn("Announcement feed unavailable; retrying on demand after cooldown");
|
||||
}
|
||||
}
|
||||
|
||||
async function current() {
|
||||
if (options.enabled === false) return null;
|
||||
if (pending) await pending;
|
||||
else if (now() >= nextCheck) {
|
||||
pending = refresh().finally(() => { pending = null; });
|
||||
await pending;
|
||||
}
|
||||
const announcement = available ? manifest?.announcement : null;
|
||||
return announcement && isAnnouncementEligible(announcement, options.version, now()) ? announcement : null;
|
||||
}
|
||||
|
||||
async function asset(id: string, kind: "image" | "animation") {
|
||||
const announcement = await current();
|
||||
const media = announcement?.[kind];
|
||||
if (announcement?.id !== id || !media) return null;
|
||||
const { path } = media;
|
||||
const slot = assets[kind];
|
||||
if (slot.cache?.path === path) return slot.cache;
|
||||
if (slot.pending?.path === path) return slot.pending.promise;
|
||||
if (slot.failure?.path === path && now() < slot.failure.retryAt) return null;
|
||||
const expected = kind === "animation" ? "text/html" : path.endsWith(".png") ? "image/png" : path.endsWith(".jpg") ? "image/jpeg" : "image/webp";
|
||||
const promise = (async () => {
|
||||
try {
|
||||
const result = await request(new URL(path, endpoint()), { Accept: expected }, async (response) => {
|
||||
const contentType = response.headers.get("content-type")?.split(";")[0]?.trim();
|
||||
if (!response.ok || contentType !== expected) {
|
||||
await response.body?.cancel();
|
||||
throw new Error("Invalid announcement asset response");
|
||||
}
|
||||
const bytes = await readAnnouncementBytes(response, kind === "animation" ? ANNOUNCEMENT_ANIMATION_MAX_BYTES : ANNOUNCEMENT_IMAGE_MAX_BYTES);
|
||||
const hash = createHash("sha256").update(bytes).digest("hex");
|
||||
if (!path.startsWith(`assets/${hash}.`)) throw new Error("Announcement asset digest mismatch");
|
||||
return { path, bytes: kind === "animation" ? Buffer.from(validateAnnouncementAnimation(bytes)) : bytes, contentType };
|
||||
});
|
||||
slot.cache = result;
|
||||
slot.failure = null;
|
||||
return result;
|
||||
} catch {
|
||||
slot.failure = { path, retryAt: now() + ANNOUNCEMENT_FAILURE_MS };
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
const entry = { path, promise };
|
||||
slot.pending = entry;
|
||||
try { return await promise; }
|
||||
finally { if (slot.pending === entry) slot.pending = null; }
|
||||
}
|
||||
|
||||
return { current, image: (id: string) => asset(id, "image"), animation: (id: string) => asset(id, "animation") };
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { announcementDismissals, announcementPublications, type Db } from "@paperclipai/db";
|
||||
import { persistActivity, publishActivity } from "./activity-log.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
export function announcementService(db: Db) {
|
||||
return {
|
||||
async registerPublication(announcementId: string) {
|
||||
await db.insert(announcementPublications).values({ announcementId }).onConflictDoNothing();
|
||||
},
|
||||
async isDismissed(userId: string, announcementId: string) {
|
||||
const row = await db.query.announcementDismissals.findFirst({
|
||||
where: and(eq(announcementDismissals.userId, userId), eq(announcementDismissals.announcementId, announcementId)),
|
||||
});
|
||||
return Boolean(row);
|
||||
},
|
||||
async dismiss(userId: string, announcementId: string, companyId: string) {
|
||||
const result = await db.transaction(async (tx) => {
|
||||
const known = await tx.query.announcementPublications.findFirst({
|
||||
where: eq(announcementPublications.announcementId, announcementId),
|
||||
});
|
||||
if (!known) {
|
||||
// Preserve idempotency for dismissals written before the registry was
|
||||
// added, but never create a new row or audit for an unknown ID.
|
||||
const existing = await tx.query.announcementDismissals.findFirst({
|
||||
where: and(eq(announcementDismissals.userId, userId), eq(announcementDismissals.announcementId, announcementId)),
|
||||
});
|
||||
return { known: Boolean(existing), publication: null };
|
||||
}
|
||||
const [inserted] = await tx.insert(announcementDismissals).values({ userId, announcementId })
|
||||
.onConflictDoNothing().returning();
|
||||
if (!inserted) return { known: true, publication: null };
|
||||
const activity = await persistActivity(tx as unknown as Db, {
|
||||
companyId, actorType: "user", actorId: userId,
|
||||
action: "announcement.dismissed", entityType: "announcement", entityId: announcementId,
|
||||
});
|
||||
return { known: true, publication: activity.publication };
|
||||
});
|
||||
if (result.publication) {
|
||||
try { publishActivity(result.publication); }
|
||||
catch { logger.warn("Could not publish committed announcement dismissal activity"); }
|
||||
}
|
||||
return result.known;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="704" height="272" viewBox="0 0 704 272">
|
||||
<defs>
|
||||
<linearGradient id="background" x2="1" y2="1"><stop stop-color="#e8e4dc"/><stop offset="1" stop-color="#d0dbd3"/></linearGradient>
|
||||
<pattern id="grid" width="32" height="32" patternUnits="userSpaceOnUse"><path d="M32 0H0V32" fill="none" stroke="#677d72" stroke-opacity=".12"/></pattern>
|
||||
</defs>
|
||||
<path fill="url(#background)" d="M0 0h704v272H0z"/><path fill="url(#grid)" d="M0 0h704v272H0z"/>
|
||||
<circle cx="610" cy="45" r="135" fill="none" stroke="#677d72" stroke-opacity=".18"/>
|
||||
<circle cx="610" cy="45" r="90" fill="none" stroke="#677d72" stroke-opacity=".18"/>
|
||||
<text x="40" y="140" font-family="Arial,sans-serif" font-size="56" font-weight="700" letter-spacing="-2" fill="#273b32">paperclip</text>
|
||||
<text x="43" y="181" font-family="Arial,sans-serif" font-size="18" fill="#50665b">Ideas become work.</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 929 B |
@@ -0,0 +1,24 @@
|
||||
import { announcementSchema, type Announcement } from "@paperclipai/shared";
|
||||
import { ApiError } from "./client";
|
||||
|
||||
async function request(path: string, init: RequestInit) {
|
||||
const response = await fetch(`/api/announcements/${path}`, {
|
||||
credentials: "same-origin", cache: "no-store", ...init,
|
||||
});
|
||||
if (!response.ok) throw new ApiError("Announcement request failed", response.status, null);
|
||||
return response;
|
||||
}
|
||||
|
||||
export const announcementsApi = {
|
||||
// Deliberately not coalesced by URL across account changes.
|
||||
async current(signal: AbortSignal): Promise<Announcement | null> {
|
||||
const response = await request("current", { signal });
|
||||
const payload = await response.json();
|
||||
return payload === null ? null : announcementSchema.parse(payload);
|
||||
},
|
||||
async dismiss(id: string, companyId: string, signal: AbortSignal) {
|
||||
await request(`${encodeURIComponent(id)}/dismiss`, {
|
||||
method: "POST", signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ companyId }),
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, type ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { AnnouncementCard } from "./AnnouncementCard";
|
||||
import { announcementPreview, announcementAnimationPreview } from "@/lib/announcement-preview";
|
||||
|
||||
vi.mock("@/lib/router", () => ({ Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => <a href={to} {...props}>{children}</a> }));
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
describe("AnnouncementCard", () => {
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
||||
async function animatedCard() {
|
||||
const div = document.createElement("div"); document.body.append(div);
|
||||
const root = createRoot(div);
|
||||
const dismiss = vi.fn();
|
||||
await act(async () => root.render(<AnnouncementCard announcement={announcementAnimationPreview} onDismiss={dismiss} />));
|
||||
return { div, root, dismiss, cleanup: async () => { await act(async () => root.unmount()); div.remove(); } };
|
||||
}
|
||||
it("renders isolated animated media with only the announcement controls", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("<div>Animated hero</div>", { headers: { "Content-Type": "text/html" } })));
|
||||
const { div, dismiss, cleanup } = await animatedCard();
|
||||
const frame = div.querySelector("iframe")!;
|
||||
expect(frame.getAttribute("sandbox")).toBe("");
|
||||
expect(frame.getAttribute("tabindex")).toBe("-1");
|
||||
expect(frame.getAttribute("aria-hidden")).toBe("true");
|
||||
expect(frame.srcdoc).toContain("default-src 'none'");
|
||||
expect(frame.srcdoc).toContain("Animated hero");
|
||||
expect(div.querySelector('[role="img"]')?.getAttribute("aria-label")).toBe(announcementAnimationPreview.animation!.alt);
|
||||
expect(Array.from(div.querySelectorAll("button"), (button) => button.getAttribute("aria-label")))
|
||||
.toEqual(["Dismiss announcement"]);
|
||||
expect(div.querySelectorAll("a")).toHaveLength(2);
|
||||
expect(dismiss).not.toHaveBeenCalled();
|
||||
await cleanup();
|
||||
});
|
||||
it("does not load animation when reduced motion is requested", async () => {
|
||||
vi.stubGlobal("matchMedia", () => ({ matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() }));
|
||||
const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
|
||||
const { div, cleanup } = await animatedCard();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(div.querySelector("iframe")).toBeNull();
|
||||
expect(div.querySelector("img")).not.toBeNull();
|
||||
await cleanup();
|
||||
});
|
||||
it.each([404, 503])("keeps the poster and actions usable for animation HTTP %s", async (status) => {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("unavailable", { status })));
|
||||
const { div, dismiss, cleanup } = await animatedCard();
|
||||
expect(div.querySelector("iframe")).toBeNull();
|
||||
expect(div.querySelector("img")).not.toBeNull();
|
||||
await act(async () => div.querySelector<HTMLButtonElement>('[aria-label="Dismiss announcement"]')!.click());
|
||||
expect(dismiss).toHaveBeenCalledOnce();
|
||||
await cleanup();
|
||||
});
|
||||
it("aborts a pending animation fetch when dismissed", async () => {
|
||||
let signal: AbortSignal | undefined;
|
||||
vi.stubGlobal("fetch", vi.fn((_url, init) => { signal = init.signal; return new Promise(() => {}); }));
|
||||
const { div, cleanup } = await animatedCard();
|
||||
expect(div.querySelector("img")).not.toBeNull();
|
||||
await cleanup();
|
||||
expect(signal?.aborted).toBe(true);
|
||||
});
|
||||
it("renders accessible plain text, navigational actions, image fallback and dismissal", async () => {
|
||||
const div = document.createElement("div"); document.body.append(div);
|
||||
const root = createRoot(div);
|
||||
const dismiss = vi.fn();
|
||||
await act(async () => root.render(<AnnouncementCard announcement={{ ...announcementPreview, title: "<script>hello</script>" }} onDismiss={dismiss} />));
|
||||
expect(div.querySelector("script")).toBeNull();
|
||||
expect(div.querySelector("h2")?.textContent).toBe("<script>hello</script>");
|
||||
expect(div.querySelector('[role="region"]')?.getAttribute("aria-labelledby")).toBe(div.querySelector("h2")?.id);
|
||||
expect(div.querySelector('a[href="https://paperclip.ing"]')?.getAttribute("rel")).toContain("noreferrer");
|
||||
expect(div.querySelector('a[href="/projects"]')).not.toBeNull();
|
||||
await act(async () => div.querySelector("img")!.dispatchEvent(new Event("error")));
|
||||
expect(div.querySelector("img")).toBeNull();
|
||||
await act(async () => div.querySelector("button")!.click());
|
||||
expect(dismiss).toHaveBeenCalledTimes(1);
|
||||
await act(async () => div.querySelector('[role="region"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })));
|
||||
expect(dismiss).toHaveBeenCalledTimes(2);
|
||||
for (const link of div.querySelectorAll("a")) {
|
||||
await act(async () => link.dispatchEvent(new MouseEvent("auxclick", { button: 1, bubbles: true })));
|
||||
}
|
||||
expect(dismiss).toHaveBeenCalledTimes(4);
|
||||
await act(async () => div.querySelector("a")!.dispatchEvent(new MouseEvent("auxclick", { button: 2, bubbles: true })));
|
||||
expect(dismiss).toHaveBeenCalledTimes(4); // Opening a context menu is not navigation.
|
||||
await act(async () => root.unmount()); div.remove();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useId, useState, type MouseEvent } from "react";
|
||||
import { ArrowUpRight, X } from "lucide-react";
|
||||
import type { Announcement, AnnouncementAction } from "@paperclipai/shared";
|
||||
import { Link } from "@/lib/router";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useAnnouncementAnimation } from "@/hooks/useAnnouncementAnimation";
|
||||
|
||||
export interface AnnouncementCardProps {
|
||||
announcement: Announcement;
|
||||
onDismiss: () => void;
|
||||
imageSrc?: string;
|
||||
animationSrc?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function Action({ action, primary, onClick }: { action: AnnouncementAction; primary?: boolean; onClick: () => void }) {
|
||||
const content = <>{action.label}{!primary && action.kind === "external" && <ArrowUpRight className="size-3.5 shrink-0" aria-hidden="true" />}</>;
|
||||
const onAuxClick = (event: MouseEvent<HTMLAnchorElement>) => { if (event.button === 1) onClick(); };
|
||||
return (
|
||||
<Button asChild variant={primary ? "default" : "ghost"} size="sm" className="h-auto min-h-9 min-w-0 whitespace-normal py-2 text-left">
|
||||
{action.kind === "external" ? (
|
||||
<a href={action.url} target="_blank" rel="noopener noreferrer" onClick={onClick} onAuxClick={onAuxClick}>{content}</a>
|
||||
) : <Link to={action.path} onClick={onClick} onAuxClick={onAuxClick}>{content}</Link>}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function AnnouncementCard({ announcement, onDismiss, imageSrc, animationSrc, className }: AnnouncementCardProps) {
|
||||
const titleId = useId();
|
||||
const [failedImage, setFailedImage] = useState<string | null>(null);
|
||||
const src = imageSrc ?? `/api/announcements/${encodeURIComponent(announcement.id)}/image`;
|
||||
const showImage = Boolean(announcement.image && failedImage !== src);
|
||||
const animationDocument = useAnnouncementAnimation(announcement, animationSrc);
|
||||
const showAnimation = Boolean(animationDocument);
|
||||
return (
|
||||
<Card
|
||||
role="region"
|
||||
aria-labelledby={titleId}
|
||||
className={cn("relative w-full max-w-(--announcement-width) gap-0 overflow-hidden rounded-xl p-0 shadow-sm", className)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); onDismiss(); }
|
||||
}}
|
||||
>
|
||||
{(showImage || animationDocument) && <div className="relative h-(--announcement-image-mobile-height) w-full shrink-0 overflow-hidden bg-muted md:h-(--announcement-image-height)">
|
||||
{showImage && <img src={src} alt={showAnimation ? "" : announcement.image!.alt} referrerPolicy="no-referrer" onError={() => setFailedImage(src)} className="h-full w-full object-cover" />}
|
||||
{showAnimation && <div role="img" aria-label={announcement.animation!.alt} className="pointer-events-none absolute inset-0">
|
||||
<iframe title={announcement.animation!.alt} aria-hidden="true" tabIndex={-1} sandbox="" referrerPolicy="no-referrer" srcDoc={animationDocument!} className="h-full w-full border-0" />
|
||||
</div>}
|
||||
</div>}
|
||||
<Button variant="secondary" size="icon" aria-label="Dismiss announcement" onClick={onDismiss} className="absolute right-2 top-2 z-10 size-8 rounded-full shadow-sm">
|
||||
<X className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
<div className={cn("flex flex-col gap-1 px-4 py-4", !showImage && !animationDocument && "pr-12")}>
|
||||
<p className="text-xs text-muted-foreground">{announcement.eyebrow}</p>
|
||||
<h2 id={titleId} className="break-words text-base font-semibold leading-snug">{announcement.title}</h2>
|
||||
<p className="break-words text-sm leading-snug text-muted-foreground">{announcement.description}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-t px-3 py-2">
|
||||
{announcement.secondaryLink && <Action action={announcement.secondaryLink} onClick={onDismiss} />}
|
||||
<div className="ml-auto min-w-0 max-w-full"><Action action={announcement.primaryAction} primary onClick={onDismiss} /></div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// @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 type { HealthStatus } from "@/api/health";
|
||||
import { AnnouncementWell } from "./AnnouncementWell";
|
||||
import { announcementPreview } from "@/lib/announcement-preview";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
userId: "alice" as string | null, settled: true, companyId: "company", loading: false,
|
||||
onboardingOpen: false, toasts: [] as unknown[], dismiss: vi.fn(), hook: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/api/companies-query", () => ({ useAccountIdentity: () => ({ userId: state.userId, settled: state.settled }) }));
|
||||
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: state.companyId, loading: state.loading }) }));
|
||||
vi.mock("@/context/DialogContext", () => ({ useDialogState: () => ({ onboardingOpen: state.onboardingOpen }) }));
|
||||
vi.mock("@/context/ToastContext", () => ({ useOptionalToastActions: () => null, useOptionalToastState: () => state.toasts }));
|
||||
vi.mock("@/hooks/useAnnouncement", () => ({ useAnnouncement: (options: { enabled: boolean }) => {
|
||||
state.hook(options);
|
||||
return { announcement: options.enabled ? announcementPreview : null, dismiss: state.dismiss };
|
||||
} }));
|
||||
vi.mock("./AnnouncementCard", () => ({ AnnouncementCard: ({ onDismiss }: { onDismiss: () => void }) => <button onClick={onDismiss}>Dismiss fixture</button> }));
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
describe("announcement placement gates", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let health: HealthStatus;
|
||||
const render = async () => { await act(async () => root.render(<AnnouncementWell health={health} />)); };
|
||||
const visible = () => Boolean(container.querySelector('[aria-label="Paperclip announcements"]'));
|
||||
beforeEach(() => {
|
||||
Object.assign(state, { userId: "alice", settled: true, companyId: "company", loading: false, onboardingOpen: false, toasts: [] });
|
||||
vi.clearAllMocks();
|
||||
health = { deploymentMode: "authenticated" } as HealthStatus;
|
||||
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
|
||||
});
|
||||
afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
|
||||
it("waits for identity, company and onboarding, and uses local-board in no-login mode", async () => {
|
||||
state.settled = false; await render(); expect(visible()).toBe(false);
|
||||
state.settled = true; state.loading = true; await render(); expect(visible()).toBe(false);
|
||||
state.loading = false; state.onboardingOpen = true; await render(); expect(visible()).toBe(false);
|
||||
state.onboardingOpen = false; await render(); expect(visible()).toBe(true);
|
||||
state.userId = null; await render(); expect(visible()).toBe(false);
|
||||
health = { deploymentMode: "local_trusted" } as HealthStatus; await render(); expect(visible()).toBe(true);
|
||||
expect(state.hook).toHaveBeenLastCalledWith(expect.objectContaining({ userId: "local-board", enabled: true }));
|
||||
});
|
||||
it("yields to toasts and modal/command dialogs without dismissing", async () => {
|
||||
await render(); expect(visible()).toBe(true);
|
||||
state.toasts = [{}]; await render(); expect(visible()).toBe(false);
|
||||
state.toasts = []; await render(); expect(visible()).toBe(true);
|
||||
const dialog = document.createElement("div"); dialog.setAttribute("role", "dialog"); dialog.setAttribute("data-state", "open");
|
||||
await act(async () => { document.body.append(dialog); }); expect(visible()).toBe(false);
|
||||
await act(async () => { dialog.remove(); }); expect(visible()).toBe(true);
|
||||
expect(state.dismiss).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useAccountIdentity } from "@/api/companies-query";
|
||||
import type { HealthStatus } from "@/api/health";
|
||||
import { useCompany } from "@/context/CompanyContext";
|
||||
import { useDialogState } from "@/context/DialogContext";
|
||||
import { useOptionalToastActions, useOptionalToastState } from "@/context/ToastContext";
|
||||
import { useAnnouncement } from "@/hooks/useAnnouncement";
|
||||
import { AnnouncementCard } from "./AnnouncementCard";
|
||||
|
||||
// Includes the command palette, sheets and dialogs created outside DialogContext.
|
||||
const MODAL_SELECTOR = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]';
|
||||
function useModalOpen(enabled: boolean) {
|
||||
const [open, setOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const scan = () => setOpen(Boolean(document.querySelector(MODAL_SELECTOR)));
|
||||
scan();
|
||||
const observer = new MutationObserver(scan);
|
||||
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-state", "aria-modal", "open"] });
|
||||
return () => observer.disconnect();
|
||||
}, [enabled]);
|
||||
return open;
|
||||
}
|
||||
|
||||
export function AnnouncementWell({ health }: { health?: HealthStatus }) {
|
||||
const { userId: accountId, settled } = useAccountIdentity();
|
||||
const { selectedCompanyId, loading } = useCompany();
|
||||
const { onboardingOpen } = useDialogState();
|
||||
const toastActions = useOptionalToastActions();
|
||||
const toasts = useOptionalToastState();
|
||||
const userId = health?.deploymentMode === "local_trusted" ? "local-board" : (settled ? accountId : null);
|
||||
const { announcement, dismiss } = useAnnouncement({
|
||||
userId, companyId: selectedCompanyId,
|
||||
enabled: Boolean(userId && !loading && selectedCompanyId && !onboardingOpen),
|
||||
onSaveFailure: (savedLocally) => toastActions?.pushToast({
|
||||
title: savedLocally ? "Dismissed in this browser" : "Dismissed for this visit",
|
||||
body: "Couldn’t save across devices. We’ll retry when you reconnect or return.",
|
||||
tone: "info", dedupeKey: "announcement-dismissal-sync",
|
||||
}),
|
||||
});
|
||||
const modalOpen = useModalOpen(Boolean(announcement));
|
||||
if (!announcement || modalOpen || (toasts?.length ?? 0) > 0) return null;
|
||||
return (
|
||||
<aside aria-label="Paperclip announcements" className="announcement-well fixed left-3 bottom-(--announcement-mobile-bottom) z-40 w-(--announcement-available-width) max-w-(--announcement-width) max-h-(--announcement-mobile-max-height) overflow-y-auto md:bottom-3 md:max-h-(--announcement-max-height)">
|
||||
<AnnouncementCard key={announcement.id} announcement={announcement} onDismiss={() => dismiss(announcement.id)} />
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -145,6 +145,10 @@ vi.mock("./ToastViewport", () => ({
|
||||
ToastViewport: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("./AnnouncementWell", () => ({
|
||||
AnnouncementWell: () => <div data-announcement-well />,
|
||||
}));
|
||||
|
||||
vi.mock("./MobileBottomNav", () => ({
|
||||
MobileBottomNav: () => null,
|
||||
}));
|
||||
@@ -348,6 +352,7 @@ describe("Layout", () => {
|
||||
expect(mockHealthApi.get).toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("Breadcrumbs");
|
||||
expect(container.textContent).toContain("Outlet content");
|
||||
expect(container.querySelectorAll("[data-announcement-well]")).toHaveLength(1);
|
||||
expect(container.textContent).not.toContain("Company rail");
|
||||
expect(container.textContent).not.toContain("Authenticated private");
|
||||
expect(container.textContent).not.toContain(
|
||||
|
||||
@@ -18,6 +18,7 @@ import { NewGoalDialog } from "./NewGoalDialog";
|
||||
import { NewAgentDialog } from "./NewAgentDialog";
|
||||
import { KeyboardShortcutsCheatsheet } from "./KeyboardShortcutsCheatsheet";
|
||||
import { ToastViewport } from "./ToastViewport";
|
||||
import { AnnouncementWell } from "./AnnouncementWell";
|
||||
import { MobileBottomNav } from "./MobileBottomNav";
|
||||
import { WorktreeBanner } from "./WorktreeBanner";
|
||||
import { DevRestartBanner } from "./DevRestartBanner";
|
||||
@@ -783,6 +784,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
|
||||
<NewAgentDialog />
|
||||
<KeyboardShortcutsCheatsheet open={shortcutsOpen} onOpenChange={setShortcutsOpen} />
|
||||
<ToastViewport />
|
||||
<AnnouncementWell health={health} />
|
||||
</div>
|
||||
</GeneralSettingsProvider>
|
||||
);
|
||||
|
||||
@@ -193,6 +193,10 @@ export function useOptionalToastActions() {
|
||||
return useContext(ToastActionsContext);
|
||||
}
|
||||
|
||||
export function useOptionalToastState() {
|
||||
return useContext(ToastStateContext);
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const toasts = useToastState();
|
||||
const actions = useToastActions();
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
// @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("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { announcementIdSchema, type Announcement } from "@paperclipai/shared";
|
||||
import { announcementsApi } from "@/api/announcements";
|
||||
import { announcementStoragePrefix, readAnnouncementDismissals, saveAnnouncementDismissal } from "@/lib/announcement-dismissals";
|
||||
|
||||
export const ANNOUNCEMENT_SETTLE_MS = 3000;
|
||||
interface Options {
|
||||
userId: string | null;
|
||||
companyId: string | null;
|
||||
enabled: boolean;
|
||||
onSaveFailure: (savedLocally: boolean) => void;
|
||||
}
|
||||
|
||||
export function useAnnouncement(options: Options) {
|
||||
const { userId, enabled } = options;
|
||||
const latest = useRef(options);
|
||||
latest.current = options;
|
||||
const [state, setState] = useState<{ userId: string; announcement: Announcement } | null>(null);
|
||||
const dismissRef = useRef<(id: string) => void>(() => {});
|
||||
|
||||
useEffect(() => {
|
||||
setState(null);
|
||||
if (!userId || !enabled) return;
|
||||
let disposed = false;
|
||||
let generation = 0;
|
||||
let fetchController: AbortController | null = null;
|
||||
let settleTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const writes = new Map<string, AbortController>();
|
||||
const warned = new Set<string>();
|
||||
const prefix = announcementStoragePrefix(userId);
|
||||
let channel: BroadcastChannel | null = null;
|
||||
try { channel = new BroadcastChannel(prefix); } catch { /* storage events still synchronize tabs */ }
|
||||
const active = () => !disposed && latest.current.userId === userId && latest.current.enabled;
|
||||
|
||||
async function sync(id: string, savedLocally = true) {
|
||||
if (!active() || writes.has(id) || !latest.current.companyId) return;
|
||||
const controller = new AbortController();
|
||||
writes.set(id, controller);
|
||||
const timer = setTimeout(() => controller.abort(), 10_000);
|
||||
try {
|
||||
await announcementsApi.dismiss(id, latest.current.companyId, controller.signal);
|
||||
if (active()) saveAnnouncementDismissal(userId!, id, false);
|
||||
} catch {
|
||||
if (active() && !warned.has(id)) {
|
||||
warned.add(id);
|
||||
latest.current.onSaveFailure(savedLocally);
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
writes.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
for (const [id, pending] of readAnnouncementDismissals(userId!)) {
|
||||
if (!active()) return;
|
||||
if (pending) await sync(id);
|
||||
}
|
||||
}
|
||||
|
||||
function suspend() {
|
||||
generation++;
|
||||
clearTimeout(settleTimer);
|
||||
fetchController?.abort();
|
||||
fetchController = null;
|
||||
setState(null);
|
||||
}
|
||||
|
||||
function resume() {
|
||||
if (!active() || document.visibilityState === "hidden") return;
|
||||
suspend();
|
||||
const currentGeneration = generation;
|
||||
const controller = new AbortController();
|
||||
fetchController = controller;
|
||||
const stillCurrent = () => active() && generation === currentGeneration && !controller.signal.aborted;
|
||||
let settled = false;
|
||||
let loaded = false;
|
||||
let candidate: Announcement | null = null;
|
||||
const show = () => {
|
||||
if (!stillCurrent() || !settled || !loaded) return;
|
||||
if (candidate && !readAnnouncementDismissals(userId!).has(candidate.id)
|
||||
&& (!candidate.expiresAt || Date.parse(candidate.expiresAt) > Date.now())) {
|
||||
setState({ userId: userId!, announcement: candidate });
|
||||
}
|
||||
};
|
||||
settleTimer = setTimeout(() => { settled = true; show(); }, ANNOUNCEMENT_SETTLE_MS);
|
||||
void flush();
|
||||
void announcementsApi.current(controller.signal).then((value) => {
|
||||
candidate = value;
|
||||
loaded = true;
|
||||
show();
|
||||
}).catch(() => { /* Optional content stays absent when state is unknown. */ });
|
||||
}
|
||||
|
||||
function receive() {
|
||||
const dismissed = readAnnouncementDismissals(userId!);
|
||||
setState((previous) => previous?.userId === userId && dismissed.has(previous.announcement.id) ? null : previous);
|
||||
}
|
||||
function onStorage(event: StorageEvent) { if (event.key?.startsWith(prefix)) receive(); }
|
||||
function onVisibility() { if (document.visibilityState === "hidden") suspend(); else resume(); }
|
||||
function onOnline() { void flush(); }
|
||||
if (channel) channel.onmessage = (event) => {
|
||||
const id = announcementIdSchema.safeParse(event.data);
|
||||
if (!id.success) return;
|
||||
// BroadcastChannel also works when persistent storage is unavailable.
|
||||
if (!readAnnouncementDismissals(userId!).has(id.data)) saveAnnouncementDismissal(userId!, id.data, true);
|
||||
receive();
|
||||
};
|
||||
dismissRef.current = (id) => {
|
||||
if (!active()) return;
|
||||
const savedLocally = saveAnnouncementDismissal(userId, id, true);
|
||||
setState(null);
|
||||
// Invalidate any response that started before this dismissal.
|
||||
generation++;
|
||||
fetchController?.abort();
|
||||
try { channel?.postMessage(id); } catch { /* Storage events are the fallback. */ }
|
||||
void sync(id, savedLocally);
|
||||
};
|
||||
// Window focus also changes for browser chrome and adjacent app panes.
|
||||
// Only leaving/returning to the tab should clear and revalidate its card.
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
window.addEventListener("online", onOnline);
|
||||
window.addEventListener("storage", onStorage);
|
||||
resume();
|
||||
return () => {
|
||||
disposed = true;
|
||||
generation++;
|
||||
clearTimeout(settleTimer);
|
||||
fetchController?.abort();
|
||||
for (const controller of writes.values()) controller.abort();
|
||||
channel?.close();
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
window.removeEventListener("online", onOnline);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
dismissRef.current = () => {};
|
||||
};
|
||||
}, [userId, enabled]);
|
||||
|
||||
const announcement = enabled && state?.userId === userId ? state.announcement : null;
|
||||
useEffect(() => {
|
||||
if (!announcement?.expiresAt) return;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const check = () => {
|
||||
const remaining = Date.parse(announcement.expiresAt!) - Date.now();
|
||||
if (remaining <= 0) setState(null);
|
||||
else timer = setTimeout(check, Math.min(remaining, 2_147_483_647));
|
||||
};
|
||||
check();
|
||||
return () => clearTimeout(timer);
|
||||
}, [announcement]);
|
||||
return { announcement, dismiss: useCallback((id: string) => dismissRef.current(id), []) };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { ANNOUNCEMENT_ANIMATION_CSP, type Announcement } from "@paperclipai/shared";
|
||||
import { usePrefersReducedMotion } from "./usePrefersReducedMotion";
|
||||
|
||||
export function useAnnouncementAnimation(announcement: Announcement, previewSrc?: string) {
|
||||
const reducedMotion = usePrefersReducedMotion();
|
||||
const src = previewSrc ?? `/api/announcements/${encodeURIComponent(announcement.id)}/animation`;
|
||||
const key = `${src}:${announcement.animation?.path ?? ""}`;
|
||||
const [loaded, setLoaded] = useState<{ key: string; document: string } | null>(null);
|
||||
const enabled = Boolean(announcement.animation) && !reducedMotion;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await fetch(src, {
|
||||
credentials: "same-origin", cache: "no-store", redirect: "error",
|
||||
referrerPolicy: "no-referrer", signal: controller.signal,
|
||||
});
|
||||
if (!response.ok || response.headers.get("content-type")?.split(";")[0] !== "text/html") return;
|
||||
const html = await response.text();
|
||||
if (!controller.signal.aborted) {
|
||||
// srcdoc does not inherit the fetch response's CSP. Apply its
|
||||
// resource restrictions again, alongside the iframe's empty sandbox.
|
||||
setLoaded({ key, document: `<meta http-equiv="Content-Security-Policy" content="${ANNOUNCEMENT_ANIMATION_CSP}">${html}` });
|
||||
}
|
||||
} catch { /* The static image stays visible, with no error popup. */ }
|
||||
finally { clearTimeout(timeout); }
|
||||
})();
|
||||
return () => { controller.abort(); clearTimeout(timeout); };
|
||||
}, [enabled, key, src]);
|
||||
|
||||
return enabled && loaded?.key === key ? loaded.document : null;
|
||||
}
|
||||
@@ -3028,3 +3028,23 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {
|
||||
max-height: min(var(--sz-300px), calc(100dvh - calc(var(--spacing) * 24))) !important;
|
||||
}
|
||||
}
|
||||
:root {
|
||||
--announcement-width: 22rem;
|
||||
--announcement-available-width: calc(100vw - var(--spacing) * 6);
|
||||
--announcement-image-height: 8.5rem;
|
||||
--announcement-image-mobile-height: 6rem;
|
||||
--announcement-mobile-bottom: calc(var(--spacing) * 19 + env(safe-area-inset-bottom, 0px));
|
||||
--announcement-max-height: calc(100dvh - var(--spacing) * 6);
|
||||
--announcement-mobile-max-height: calc(100dvh - var(--announcement-mobile-bottom) - var(--spacing) * 3);
|
||||
}
|
||||
|
||||
.announcement-well {
|
||||
animation: announcement-enter var(--motion-duration-fast) var(--motion-ease-standard) both;
|
||||
}
|
||||
@keyframes announcement-enter {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.announcement-well { animation: none; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { announcementIdSchema } from "@paperclipai/shared";
|
||||
|
||||
const memory = new Map<string, boolean>();
|
||||
export function announcementStoragePrefix(userId: string) {
|
||||
return `paperclip.announcement-dismissals.v1:${encodeURIComponent(userId)}:`;
|
||||
}
|
||||
|
||||
export function readAnnouncementDismissals(userId: string): Map<string, boolean> {
|
||||
const prefix = announcementStoragePrefix(userId);
|
||||
const entries = new Map<string, boolean>();
|
||||
try {
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
if (!key?.startsWith(prefix)) continue;
|
||||
const id = key.slice(prefix.length);
|
||||
const value = localStorage.getItem(key);
|
||||
if (announcementIdSchema.safeParse(id).success && (value === "pending" || value === "synced")) {
|
||||
memory.set(key, value === "pending");
|
||||
}
|
||||
}
|
||||
} catch { /* Private browsing/storage limits: retain this visit's state. */ }
|
||||
for (const [key, pending] of memory) {
|
||||
if (key.startsWith(prefix)) entries.set(key.slice(prefix.length), pending);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function saveAnnouncementDismissal(userId: string, id: string, pending: boolean): boolean {
|
||||
const key = `${announcementStoragePrefix(userId)}${id}`;
|
||||
memory.set(key, pending);
|
||||
try {
|
||||
localStorage.setItem(key, pending ? "pending" : "synced");
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import animatedHero from "../../../announcements/examples/animated/assets/78bafb6adbfd9da899cdbb5d934b4c0b9df5d419d6f0a5104a87a7b25dcc6bd8.html?raw";
|
||||
import type { Announcement } from "@paperclipai/shared";
|
||||
|
||||
/** Design guide / Storybook only. Never a runtime feed fallback. */
|
||||
export const announcementPreview: Announcement = {
|
||||
id: "preview-work-together",
|
||||
eyebrow: "New in Paperclip",
|
||||
title: "Give your next idea a team",
|
||||
description: "Bring agents, projects, and work together. Set the direction, then follow your team’s progress in Paperclip.",
|
||||
image: { path: `assets/${"0".repeat(64)}.png`, alt: "Paperclip — ideas become work" },
|
||||
secondaryLink: { kind: "external", label: "Learn more", url: "https://paperclip.ing" },
|
||||
primaryAction: { kind: "route", label: "Explore your projects", path: "/projects" },
|
||||
};
|
||||
|
||||
export const announcementAnimationPreview: Announcement = {
|
||||
...announcementPreview,
|
||||
animation: { path: "assets/78bafb6adbfd9da899cdbb5d934b4c0b9df5d419d6f0a5104a87a7b25dcc6bd8.html", alt: "Agents plan, build and review work together." },
|
||||
};
|
||||
export const announcementAnimationPreviewSrc = `data:text/html;charset=utf-8,${encodeURIComponent(animatedHero)}`;
|
||||
@@ -1,4 +1,6 @@
|
||||
import { TaskChatProjectCreatedCard } from "@/components/task-chat/TaskChatProjectCreatedCard";
|
||||
import { AnnouncementCard } from "@/components/AnnouncementCard";
|
||||
import { announcementPreview, announcementAnimationPreview, announcementAnimationPreviewSrc } from "@/lib/announcement-preview";
|
||||
import { TaskDetailTasksPanel } from "@/components/task-detail/TaskDetailTasksPanel";
|
||||
import { AiConnectionDesignExamples } from "@/components/ai-connections/AiConnectionDesignExamples";
|
||||
import { SavedProviderKeySelect } from "../components/onboarding/SavedProviderKeySelect";
|
||||
@@ -549,6 +551,14 @@ export function DesignGuide() {
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Announcements">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<AnnouncementCard announcement={announcementAnimationPreview} imageSrc="/announcement-preview.svg" animationSrc={announcementAnimationPreviewSrc} onDismiss={() => {}} />
|
||||
<AnnouncementCard announcement={announcementPreview} imageSrc="/announcement-preview.svg" onDismiss={() => {}} />
|
||||
<AnnouncementCard announcement={{ ...announcementPreview, image: undefined, secondaryLink: undefined }} onDismiss={() => {}} />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Task Execution Controls">
|
||||
<TaskExecutionControlsExample />
|
||||
</Section>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { AnnouncementCard } from "@/components/AnnouncementCard";
|
||||
import { announcementPreview, announcementAnimationPreview, announcementAnimationPreviewSrc } from "@/lib/announcement-preview";
|
||||
|
||||
const meta = {
|
||||
title: "Announcements/AnnouncementCard",
|
||||
component: AnnouncementCard,
|
||||
args: { announcement: announcementPreview, imageSrc: "/announcement-preview.svg", onDismiss: () => {} },
|
||||
decorators: [(Story) => <div className="p-4"><Story /></div>],
|
||||
} satisfies Meta<typeof AnnouncementCard>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Default: Story = {};
|
||||
export const Light: Story = { globals: { theme: "light" } };
|
||||
export const Dark: Story = { globals: { theme: "dark" } };
|
||||
export const Mobile: Story = { globals: { viewport: { value: "mobile1", isRotated: false } } };
|
||||
export const MissingImage: Story = { args: { imageSrc: "/missing-announcement-image.png" } };
|
||||
export const TextOnly: Story = { args: { announcement: { ...announcementPreview, image: undefined, secondaryLink: undefined } } };
|
||||
export const LongText: Story = {
|
||||
args: { announcement: { ...announcementPreview, title: "Give your most ambitious ideas a team that can carry them forward", description: "Organize your agents around a shared goal, bring the work into one place, and keep every decision connected to its context. Follow progress, review outcomes, and help your team take the next step whenever it needs your direction.", primaryAction: { kind: "external", label: "See everything that’s new in Paperclip", url: "https://paperclip.ing" } } },
|
||||
};
|
||||
|
||||
export const Animated: Story = { args: { announcement: announcementAnimationPreview, animationSrc: announcementAnimationPreviewSrc } };
|
||||
export const AnimatedDark: Story = { ...Animated, globals: { theme: "dark" } };
|
||||
export const AnimatedMobile: Story = { ...Animated, globals: { viewport: { value: "mobile1", isRotated: false } } };
|
||||
export const MissingAnimation: Story = { args: { announcement: announcementAnimationPreview, animationSrc: "/missing-announcement-animation.html" } };
|
||||
Reference in new issue
Block a user