mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-06 01:57:33 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Self-hosted boards need a way to show occasional product announcements. > - An app release should not be required to publish or withdraw a card. > - Native card controls keep publishing consistent; the hero can use a static image or isolated HTML/CSS animation. > - This pull request renders a validated JSON feed with native components. > - It stores dismissals per account on each instance, so a closed card stays closed across companies and browsers. > - Named staging feeds let authors test content before production publication. ## Linked Issues or Issue Description **Subsystem affected** Board application shell, announcement delivery, and user preferences. **Problem or motivation** Operators need a small, optional announcement card. Users need reliable dismissal state. Authors need to test remote content without changing the production feed. **Proposed solution** Add one non-modal AnnouncementWell. Fetch validated JSON and content-addressed media through the instance server. Keep card controls native, with optional sandboxed HTML/CSS animation in the hero. Use stable announcement IDs for dismissal, an explicit empty manifest and quiet 404 handling. Provide a staged publishing helper and isolated test-drive guide. **Alternatives considered** Hosting the entire card as a page would move navigation and dismissal into remote content. This change limits HTML to a scriptless, isolated visual hero and keeps controls native. Browser-only storage would lose dismissals across browsers, so the instance stores account preferences. **Roadmap alignment** ROADMAP.md has no overlapping announcement feature. A GitHub title search found no related announcement pull requests. This work implements a maintainer-requested feature. ## What Changed - Add shared feed types, strict validation of every object, supported routes, expiration and version checks. - Add a board-only current-feed API, constrained media proxy, and idempotent dismissal API. Store the first dismissal and its company audit entry in one transaction. - Cache upstream data for one hour. Use conditional requests, request deduplication, response limits, public destination checks, and a three-second deadline. Treat a remote 404 as an empty feed with a fifteen-minute retry cooldown. - Keep announcement visibility stable when focus moves to browser chrome or another app pane; only tab visibility starts a return check. - Add a responsive native announcement card. Respect onboarding, dialogs and toast placement. Sync pending dismissals across tabs and retry after reconnect or return. - Add idempotent migrations for dismissals and validated publication IDs, design-guide examples, static and animated Storybook examples, and focused tests. The publication registry supports offline retries without accepting caller-invented IDs. - Add HTML/CSS animated heroes with static posters, automatic playback, reduced-motion handling, strict DOMPurify validation, an empty iframe sandbox and CSP that blocks scripts/network resources. - Add validated staging publication, content-addressed assets, an empty production manifest, preview fixtures, and authoring/operator documentation. ## Verification - The preceding implementation passed 98 targeted shared/server/publisher/route/OpenAPI/UI tests and 127 tests including the master rebase. The playback-control removal passes all 21 announcement UI tests, covering the rendered sandbox, fallback, reduced motion, dismissal and slow/stale state lookups. The preceding shared/server tests cover HTML validation and response sandbox headers. - The playback-control removal passes UI typecheck, production UI build, Storybook build and token gates locally. Browser verification confirms the animated card has only its dismiss button and two links, with no page errors. The full canonical CI matrix passed on current head `00e416431edb610861599d50490270bbd0f3c6b6`: 32 successful checks and two optional Storybook deployment checks skipped. This run needed no retries. Greptile reviewed this same head at 5/5 with no outstanding findings. - The local canonical general-server run passed 12,063 tests before reporting embedded-PostgreSQL startup failures in an unrelated fixture. All 31 tests in that fixture passed across isolated retries. The UI group passed 6,219 tests and other workspace groups passed 3,201; two CLI database-startup failures also passed individually. Serialized server suites were verified by the full CI matrix rather than repeating them locally. No source changes were needed for these environment failures. - The real S3/CloudFront staging manifest and both media asset headers were verified. Production remains empty/unpublished. The guide distinguishes the preview host's disabled edge cache from production cache requirements. - In the isolated test-drive, the animation visibly moves without playback controls. A 390×844 browser viewport keeps the card above navigation. Reduced motion makes no animation request. Both themes render correctly and browser page errors are empty. Browser fault injection verified that scripts cannot execute and CSS cannot make network requests; a missing animation leaves its poster and controls. - Refresh leaves the animated card visible. Closing it persists after reload and the API returns null. Earlier live checks verified dismissal across browsers, company-relative CTA navigation, modal deferral/restoration, and new-ID eligibility after restarting the same database. - The deployed empty feed and a real remote 404 return HTTP 200 with null from the board API, with a usable dashboard and no announcement popup or browser warnings. - Authoring documentation covers staging, animated HTML constraints, test-drive, withdrawal, ID reuse and cache-refresh steps. ## Risks - Animation supports self-contained visual HTML/CSS and inline SVG, without JavaScript or external resources. A static image is required. Older builds that do not recognize the optional animation field quietly hide that unsupported feed. - The default feed makes an outbound request from an instance when a board is used. Operators can disable it. Requests contain no account IDs, company data, cookies or interaction events. - Feed publication and withdrawal can take about 65 minutes to reach returning users because of CDN and instance caches. Expiration also removes visible cards locally. - Dismissals follow an account within one instance. No-login instances share the existing local-board identity. Separate installations do not share state. - Both tables are additive. A unique key prevents duplicate dismissals; the transaction prevents duplicate first-dismissal audit entries. The publication registry retains only validated IDs. AGENTS.md and the implementation spec document the required exception to company scope for these instance-level records. - Publication was limited to separate public staging prefixes on the existing preview host. Production remains empty/unpublished. No AWS policies or infrastructure were changed. ## Model Used OpenAI GPT-6 through Codex. The exact runtime model ID and context-window size are not exposed in this session. Capabilities used: reasoning, code editing, shell execution, tests, browser interaction, and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
134 lines
8.0 KiB
JavaScript
134 lines
8.0 KiB
JavaScript
#!/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;
|
|
});
|
|
}
|