Create polished demo videos without editing skills. Mac/Windows/Linux
Add live announcements and experimental updates
young8120f82b85f6
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 148bed0d..a892dcac 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -607,7 +607,6 @@ jobs:- name: Stage release assetsshell: bashenv:- IS_PRERELEASE: ${{ needs.prepare-release.outputs.prerelease }}RELEASE_SCOPE: ${{ needs.prepare-release.outputs.release_scope }}run: |set -euo pipefail@@ -632,11 +631,14 @@ jobs:)fi- if [ "$IS_PRERELEASE" != "true" ]; then+ assets+=(+ release-assets/windows-x64/latest*.yml+ release-assets/linux-x64/latest-linux.yml+ )++ if [ "$RELEASE_SCOPE" = "all" ]; thenassets+=(release-assets/macos-merged/latest-mac.yml- release-assets/windows-x64/latest*.yml- release-assets/linux-x64/latest-linux.yml)fidiff --git a/announcements.json b/announcements.jsonnew file mode 100644index 00000000..f7e39713--- /dev/null+++ b/announcements.json@@ -0,0 +1,6 @@+{+ "settings": {+ "aspectRatio": "4:3"+ },+ "announcements": []+}diff --git a/docs/announcements.md b/docs/announcements.mdnew file mode 100644index 00000000..51637ff4--- /dev/null+++ b/docs/announcements.md@@ -0,0 +1,96 @@+# In-app announcements++Recordly can show dismissible announcements in the editor as a popup, carousel slide, lightweight live notification, or header banner. Popups can contain images or video; notifications and banners are text-only with optional buttons.++## Remote announcements++Edit [`announcements.json`](../announcements.json) on the `main` branch to publish an announcement without releasing a new app version. Released clients check the raw GitHub file at most once every six hours per running app instance. Fetch failures are silent and never block startup.++```json+{+ "settings": {+ "aspectRatio": "4:3"+ },+ "announcements": [+ {+ "id": "recordly-1.4-release",+ "title": "A faster Recordly is here",+ "body": "Exports are faster and cursor motion is smoother. Thanks for using Recordly!",+ "presentation": "popup",+ "audience": "editor",+ "priority": 10,+ "mediaMode": "cover",+ "displayDurationSeconds": 15,+ "maxImpressions": 3,+ "controls": {+ "close": true,+ "dismiss": false,+ "action": true,+ "navigation": false,+ "indicators": true+ },+ "startsAt": "2026-09-01T00:00:00Z",+ "endsAt": "2026-10-01T00:00:00Z",+ "minVersion": "1.4.0",+ "media": {+ "type": "image",+ "url": "https://example.com/recordly-1.4-banner.jpg",+ "alt": "Recordly 1.4 feature preview"+ },+ "action": {+ "label": "See what changed",+ "url": "https://github.com/webadderallorg/Recordly/releases"+ }+ },+ {+ "id": "recordly-maintenance-notice",+ "title": "Quick service notice",+ "body": "Cloud sharing will undergo brief maintenance tonight.",+ "presentation": "notification",+ "audience": "editor",+ "displayDurationSeconds": 10,+ "maxImpressions": 2,+ "startsAt": "2026-09-05T00:00:00Z",+ "endsAt": "2026-09-06T00:00:00Z"+ },+ {+ "id": "recordly-editor-banner",+ "title": "Try the new editor",+ "body": "The redesigned timeline is now available.",+ "presentation": "banner",+ "audience": "editor",+ "maxImpressions": 3,+ "action": {+ "label": "Open settings",+ "section": "settings"+ }+ }+ ]+}+```++Use a new stable `id` whenever an announcement should appear again. Once a user dismisses an ID, it remains dismissed. Remote items with the same ID override bundled items.++Supported fields:++- `settings.aspectRatio` sets one shared `width:height` ratio for the entire popup carousel, such as `16:9`, `4:3`, or `1:1`. All slides keep that same size. If omitted, the bundled default is used.+- `id`, `title`, and `body` are required.+- `presentation` is `popup`, `notification`, or `banner` and defaults to `popup`. Notifications appear as text-only non-modal toasts, while banners appear only in the editor directly beneath its header. Media and `mediaMode` are ignored for notifications and banners. At most five notifications are shown from one feed load; banners are shown one at a time by priority.+- `audience` is `all` or `editor` and defaults to `all`.+- `priority` controls carousel order; larger numbers appear first.+- `mediaMode` is `banner` or `cover`. `banner` is the default current layout; `cover` fills the popup with the media and overlays the text.+- `startsAt` and `endsAt` are optional ISO timestamps.+- `displayDurationSeconds` accepts 3–300 seconds. It auto-advances popup slides; for notifications it controls how long the toast remains visible and defaults to 10 seconds.+- `maxImpressions` optionally limits an announcement to 1–100 app sessions. Each announcement counts at most once per session; an explicit dismissal always hides it permanently.+- `controls` can independently show or hide `close`, `dismiss`, `action`, `navigation`, and `indicators`. Every control defaults to `true`. Notifications and banners use only `close` and `action`; popup carousels use the other controls. Escape and clicking outside a popup remain available even when visible close controls are hidden.+- `minVersion` and `maxVersion` are optional inclusive app-version bounds.+- `media.type` is `image` or `video` for popups. Media URLs must be HTTPS or root-relative bundled assets. Videos can also specify `posterUrl`.+- `action` has a label and exactly one destination: an HTTPS `url` opened in the system browser, or an editor `section` opened inside the app. Supported sections are `scene`, `cursor`, `webcam`, `captions`, `settings`, and `extensions`. An action containing both destinations, neither destination, or an unknown section is ignored.++Set `RECORDLY_ANNOUNCEMENTS_URL` before launching the app to use a different HTTPS feed. Set it to `off` to disable remote announcements.++## Announcements bundled with an update++Add typed entries to `src/content/announcements.ts`. Bundled items use the same schema and are available offline. This is useful when a message should ship atomically with a new release.++Remote content is treated as data only: HTML is not rendered, URLs are restricted, feeds are size-limited and time-limited, and malformed items are ignored.diff --git a/electron/appSettingsStore.ts b/electron/appSettingsStore.tsnew file mode 100644index 00000000..c777b100--- /dev/null+++ b/electron/appSettingsStore.ts@@ -0,0 +1,36 @@+import { readFileSync, writeFileSync } from "node:fs";+import { APP_SETTINGS_FILE } from "./ipc/constants";+import { parseJsonWithByteOrderMark } from "./ipc/utils";++export function readAppSettingsStore(): Record<string, unknown> {+ try {+ const content = readFileSync(APP_SETTINGS_FILE, "utf-8");+ const parsed = parseJsonWithByteOrderMark<unknown>(content);+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return {};+ }++ return parsed as Record<string, unknown>;+ } catch {+ return {};+ }+}++export function writeAppSettingsStore(store: Record<string, unknown>) {+ writeFileSync(APP_SETTINGS_FILE, JSON.stringify(store, null, 2), "utf-8");+}++export function hasAppSetting(store: Record<string, unknown>, key: string): boolean {+ return Reflect.getOwnPropertyDescriptor(store, key) !== undefined;+}++export function readAppSetting(key: string): unknown {+ const store = readAppSettingsStore();+ return hasAppSetting(store, key) ? store[key] : null;+}++export function writeAppSetting(key: string, value: unknown) {+ const store = readAppSettingsStore();+ store[key] = value;+ writeAppSettingsStore(store);+}diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.tsindex 7dce4fa0..8e878b3d 100644--- a/electron/electron-env.d.ts+++ b/electron/electron-env.d.ts@@ -815,6 +815,12 @@ interface Window {skipUpdateVersion: () => Promise<{ success: boolean; message?: string }>;getCurrentUpdateToastPayload: () => Promise<UpdateToastState | null>;getUpdateStatusSummary: () => Promise<UpdateStatusSummary>;+ getExperimentalUpdatesEnabled: () => Promise<boolean>;+ setExperimentalUpdatesEnabled: (enabled: boolean) => Promise<{+ success: boolean;+ enabled: boolean;+ error?: string;+ }>;previewUpdateToast: () => Promise<{ success: boolean }>;checkForAppUpdates: () => Promise<{ success: boolean; logPath: string }>;onUpdateToastStateChanged: (@@ -866,6 +872,8 @@ interface Window {}>;/** Returns the app version from package.json */getAppVersion: () => Promise<string>;+ /** Returns the configured remote announcement feed, or null when unavailable. */+ getAnnouncements: () => Promise<unknown | null>;/** Hide the OS cursor before browser capture starts. */hideOsCursor: () => Promise<{ success: boolean }>;/** Recording preferences (mic, system audio) */diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex f6e4dc02..2a0f998e 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -1,4 +1,5 @@import { BrowserWindow } from "electron";+import { registerAnnouncementHandlers } from "./register/announcements";import { registerAssetHandlers } from "./register/assets";import { registerCaptionHandlers } from "./register/captions";import { registerExportHandlers } from "./register/export";@@ -64,6 +65,7 @@ export function registerIpcHandlers(});registerRecordingHandlers(onRecordingStateChange);registerPermissionHandlers();+ registerAnnouncementHandlers();registerAssetHandlers();registerExportHandlers();registerCaptionHandlers();diff --git a/electron/ipc/register/announcements.ts b/electron/ipc/register/announcements.tsnew file mode 100644index 00000000..a582fb4e--- /dev/null+++ b/electron/ipc/register/announcements.ts@@ -0,0 +1,91 @@+import { ipcMain } from "electron";++const DEFAULT_ANNOUNCEMENT_FEED_URL =+ "https://raw.githubusercontent.com/webadderallorg/Recordly/main/announcements.json";+const ANNOUNCEMENT_FETCH_TIMEOUT_MS = 5_000;+const ANNOUNCEMENT_CACHE_TTL_MS = 6 * 60 * 60 * 1_000;+const MAX_ANNOUNCEMENT_FEED_BYTES = 1_000_000;++let cachedFeed: unknown = null;+let cachedAt = 0;+let hasCachedResult = false;+let pendingFetch: Promise<unknown> | null = null;++function getAnnouncementFeedUrl(): string | null {+ const configuredUrl = process.env.RECORDLY_ANNOUNCEMENTS_URL?.trim();+ if (configuredUrl?.toLowerCase() === "off") {+ return null;+ }++ const candidate = configuredUrl || DEFAULT_ANNOUNCEMENT_FEED_URL;+ try {+ const parsed = new URL(candidate);+ return parsed.protocol === "https:" && !parsed.username && !parsed.password+ ? parsed.href+ : null;+ } catch {+ return null;+ }+}++async function requestAnnouncementFeed(feedUrl: string): Promise<unknown> {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), ANNOUNCEMENT_FETCH_TIMEOUT_MS);++ try {+ const response = await fetch(feedUrl, {+ signal: controller.signal,+ headers: { Accept: "application/json" },+ redirect: "follow",+ });+ if (!response.ok) {+ throw new Error(`Announcement feed returned HTTP ${response.status}`);+ }+ if (new URL(response.url).protocol !== "https:") {+ throw new Error("Announcement feed redirected to an unsafe URL");+ }++ const declaredLength = Number(response.headers.get("content-length"));+ if (Number.isFinite(declaredLength) && declaredLength > MAX_ANNOUNCEMENT_FEED_BYTES) {+ throw new Error("Announcement feed is too large");+ }++ const text = await response.text();+ if (Buffer.byteLength(text, "utf8") > MAX_ANNOUNCEMENT_FEED_BYTES) {+ throw new Error("Announcement feed is too large");+ }++ cachedFeed = JSON.parse(text) as unknown;+ return cachedFeed;+ } catch (error) {+ console.warn("Failed to load announcement feed:", error);+ return cachedFeed;+ } finally {+ cachedAt = Date.now();+ hasCachedResult = true;+ clearTimeout(timeout);+ }+}++function fetchAnnouncementFeed(): Promise<unknown> {+ const feedUrl = getAnnouncementFeedUrl();+ if (!feedUrl) {+ return Promise.resolve(null);+ }++ if (hasCachedResult && Date.now() - cachedAt < ANNOUNCEMENT_CACHE_TTL_MS) {+ return Promise.resolve(cachedFeed);+ }++ if (!pendingFetch) {+ pendingFetch = requestAnnouncementFeed(feedUrl).finally(() => {+ pendingFetch = null;+ });+ }++ return pendingFetch;+}++export function registerAnnouncementHandlers() {+ ipcMain.handle("announcements:get", fetchAnnouncementFeed);+}diff --git a/electron/ipc/register/settings.ts b/electron/ipc/register/settings.tsindex e84f6317..dc1f01d9 100644--- a/electron/ipc/register/settings.ts+++ b/electron/ipc/register/settings.ts@@ -1,14 +1,9 @@-import { readFileSync, writeFileSync } from "node:fs";import fs from "node:fs/promises";import { app, ipcMain } from "electron";+import { hasAppSetting, readAppSettingsStore, writeAppSettingsStore } from "../../appSettingsStore";import { hideCursor } from "../../cursorHider";import { closeCountdownWindow, createCountdownWindow, getCountdownWindow } from "../../windows";-import {- APP_SETTINGS_FILE,- COUNTDOWN_SETTINGS_FILE,- RECORDINGS_SETTINGS_FILE,- SHORTCUTS_FILE,-} from "../constants";+import { COUNTDOWN_SETTINGS_FILE, RECORDINGS_SETTINGS_FILE, SHORTCUTS_FILE } from "../constants";import {countdownCancelled,countdownInProgress,@@ -42,28 +37,6 @@ function getBrowserMicrophoneProfileFromEnv() {};}-function readAppSettingsStore(): Record<string, unknown> {- try {- const content = readFileSync(APP_SETTINGS_FILE, "utf-8");- const parsed = parseJsonWithByteOrderMark<unknown>(content);- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {- return {};- }-- return parsed as Record<string, unknown>;- } catch {- return {};- }-}--function writeAppSettingsStore(store: Record<string, unknown>) {- writeFileSync(APP_SETTINGS_FILE, JSON.stringify(store, null, 2), "utf-8");-}--function hasAppSetting(store: Record<string, unknown>, key: string): boolean {- return Reflect.getOwnPropertyDescriptor(store, key) !== undefined;-}-export function registerSettingsHandlers() {ipcMain.handle("app:getVersion", () => {return app.getVersion();diff --git a/electron/main.ts b/electron/main.tsindex 60eb16bb..0758c77e 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -37,11 +37,13 @@ import {dismissUpdateToast,downloadAvailableUpdate,getCurrentUpdateToastPayload,+ getExperimentalUpdatesEnabled,getUpdaterLogPath,getUpdateStatusSummary,installDownloadedUpdateNow,previewUpdateToast,setupAutoUpdates,+ setExperimentalUpdatesEnabled,skipAvailableUpdateVersion,} from "./updater";import {@@ -738,6 +740,29 @@ ipcMain.handle("get-update-status-summary", () => {return getUpdateStatusSummary();});+ipcMain.handle("get-experimental-updates-enabled", () => {+ return getExperimentalUpdatesEnabled();+});++ipcMain.handle("set-experimental-updates-enabled", async (_event, enabled: unknown) => {+ if (typeof enabled !== "boolean") {+ return { success: false, enabled: getExperimentalUpdatesEnabled() };+ }++ try {+ const savedValue = setExperimentalUpdatesEnabled(enabled);+ await checkForAppUpdates(getUpdateDialogWindow);+ return { success: true, enabled: savedValue };+ } catch (error) {+ console.error("Failed to update experimental updates preference:", error);+ return {+ success: false,+ enabled: getExperimentalUpdatesEnabled(),+ error: String(error),+ };+ }+});+ipcMain.handle("preview-update-toast", () => {return { success: previewUpdateToast(sendUpdateToastToWindows) };});diff --git a/electron/preload.ts b/electron/preload.tsindex d53edb54..5ba1567a 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -835,6 +835,12 @@ contextBridge.exposeInMainWorld("electronAPI", {getUpdateStatusSummary: () => {return ipcRenderer.invoke("get-update-status-summary");},+ getExperimentalUpdatesEnabled: () => {+ return ipcRenderer.invoke("get-experimental-updates-enabled");+ },+ setExperimentalUpdatesEnabled: (enabled: boolean) => {+ return ipcRenderer.invoke("set-experimental-updates-enabled", enabled);+ },previewUpdateToast: () => {return ipcRenderer.invoke("preview-update-toast");},@@ -966,6 +972,7 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("mux-native-windows-recording", expectedDurationMs),hideOsCursor: () => ipcRenderer.invoke("hide-cursor"),getAppVersion: () => ipcRenderer.invoke("app:getVersion"),+ getAnnouncements: () => ipcRenderer.invoke("announcements:get"),getRecordingPreferences: () => ipcRenderer.invoke("get-recording-preferences"),getRecordingAudioLabConfig: () => ipcRenderer.invoke("get-recording-audio-lab-config"),setRecordingPreferences: (prefs: {diff --git a/electron/updater.ts b/electron/updater.tsindex 86a02aec..a89bb678 100644--- a/electron/updater.ts+++ b/electron/updater.ts@@ -4,6 +4,7 @@ import type { MessageBoxOptions, MessageBoxReturnValue } from "electron";import { app, BrowserWindow, dialog } from "electron";import { autoUpdater } from "electron-updater";import { USER_DATA_PATH } from "./appPaths";+import { readAppSetting, writeAppSetting } from "./appSettingsStore";const UPDATE_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;export const UPDATE_REMINDER_DELAY_MS = 3 * 60 * 60 * 1000;@@ -16,6 +17,7 @@ const DEV_UPDATE_PREVIEW_VERSION = "9.9.9";const DEV_UPDATE_PREVIEW_PROGRESS_STEP_MS = 300;const DEV_UPDATE_PREVIEW_PROGRESS_INCREMENT = 20;const ONE_MEGABYTE = 1024 * 1024;+const EXPERIMENTAL_UPDATES_SETTING_KEY = "experimentalUpdatesEnabled";export type UpdateToastPhase = "available" | "downloading" | "ready" | "error";@@ -124,6 +126,25 @@ function configureUpdateFeed() {writeUpdaterLog(`Using overridden update feed: ${UPDATE_FEED_URL_OVERRIDE}`);}+export function getExperimentalUpdatesEnabled() {+ return readAppSetting(EXPERIMENTAL_UPDATES_SETTING_KEY) === true;+}++function applyExperimentalUpdatesPreference() {+ const enabled = getExperimentalUpdatesEnabled();+ autoUpdater.allowPrerelease = enabled;+ writeUpdaterLog(`Update channel configured: ${enabled ? "experimental" : "stable"}.`);+ return enabled;+}++export function setExperimentalUpdatesEnabled(enabled: boolean) {+ writeAppSetting(EXPERIMENTAL_UPDATES_SETTING_KEY, enabled);+ autoUpdater.allowPrerelease = enabled;+ skippedVersion = null;+ writeUpdaterLog(`Experimental updates ${enabled ? "enabled" : "disabled"} by user.`);+ return enabled;+}+function canUseAutoUpdates() {return !AUTO_UPDATES_DISABLED && app.isPackaged && !process.mas;}@@ -616,6 +637,7 @@ export async function checkForAppUpdates(manualCheckRequested = Boolean(options?.manual);updateCheckInProgress = true;+ applyExperimentalUpdatesPreference();setUpdateStatusSummary({ status: "checking", detail: "Checking for updates..." });writeUpdaterLog(`Starting ${manualCheckRequested ? "manual" : "automatic"} update check.`);@@ -650,6 +672,7 @@ export function setupAutoUpdates(updaterInitialized = true;configureUpdateFeed();+ applyExperimentalUpdatesPreference();autoUpdater.autoDownload = false;autoUpdater.autoInstallOnAppQuit = false;writeUpdaterLog(`Updater initialized. logPath=${UPDATER_LOG_PATH}`);diff --git a/src/App.tsx b/src/App.tsxindex 513320f4..cc634688 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,4 +1,6 @@import { useEffect, useState } from "react";+import { AnnouncementDialog } from "./components/announcements/AnnouncementDialog";+import { LiveAnnouncementNotifications } from "./components/announcements/LiveAnnouncementNotifications";import { CountdownOverlay } from "./components/countdown/CountdownOverlay";import { LaunchWindow } from "./components/launch/LaunchWindow";import { SourceSelector } from "./components/launch/SourceSelector";@@ -72,10 +74,14 @@ export default function App() {return <UpdateToastWindow />;case "editor":return (- <ShortcutsProvider>- <VideoEditor />- <ShortcutsConfigDialog />- </ShortcutsProvider>+ <>+ <ShortcutsProvider>+ <VideoEditor />+ <ShortcutsConfigDialog />+ </ShortcutsProvider>+ <AnnouncementDialog audience="editor" />+ <LiveAnnouncementNotifications audience="editor" />+ </>);default:return (diff --git a/src/components/announcements/AnnouncementDialog.tsx b/src/components/announcements/AnnouncementDialog.tsxnew file mode 100644index 00000000..42306edc--- /dev/null+++ b/src/components/announcements/AnnouncementDialog.tsx@@ -0,0 +1,360 @@+import { ArrowLeft, ArrowRight, ArrowSquareOut, Megaphone } from "@phosphor-icons/react";+import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { BUNDLED_ANNOUNCEMENT_FEED } from "@/content/announcements";+import { useI18n } from "@/contexts/I18nContext";+import { runAnnouncementAction } from "@/lib/announcementActions";+import {+ type Announcement,+ type AnnouncementAudience,+ parseAnnouncementFeed,+ selectAnnouncements,+} from "@/lib/announcements";+import {+ dismissAnnouncements,+ readAnnouncementImpressionCounts,+ readDismissedAnnouncementIds,+ recordAnnouncementImpression,+} from "@/lib/announcementState";+import { cn } from "@/lib/utils";+import { Button } from "../ui/button";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../ui/dialog";++function AnnouncementMediaBanner({+ announcement,+ cover = false,+}: {+ announcement: Announcement;+ cover?: boolean;+}) {+ const [failed, setFailed] = useState(false);+ const media = announcement.media;++ if (!media || failed) {+ return (+ <div className="flex h-32 items-center justify-center bg-gradient-to-br from-primary/25 via-primary/10 to-transparent">+ <Megaphone className="h-12 w-12 text-primary/70" weight="duotone" />+ </div>+ );+ }++ if (media.type === "video") {+ return (+ <video+ key={media.url}+ className={cn(+ "w-full bg-black",+ cover ? "h-full object-cover" : "max-h-72 object-contain",+ )}+ controls+ playsInline+ preload="metadata"+ poster={media.posterUrl}+ onError={() => setFailed(true)}+ >+ <source src={media.url} />+ </video>+ );+ }++ return (+ <img+ src={media.url}+ alt={media.alt || ""}+ className={cn("w-full bg-black/20 object-cover", cover ? "h-full" : "max-h-72")}+ onError={() => setFailed(true)}+ />+ );+}++export function AnnouncementDialog({ audience }: { audience: AnnouncementAudience }) {+ const { t } = useI18n();+ const [announcements, setAnnouncements] = useState<Announcement[]>([]);+ const [currentIndex, setCurrentIndex] = useState(0);+ const [open, setOpen] = useState(false);+ const [popupAspectRatio, setPopupAspectRatio] = useState(+ BUNDLED_ANNOUNCEMENT_FEED.settings.aspectRatio,+ );+ const countedThisSessionRef = useRef(new Set<string>());++ useEffect(() => {+ let cancelled = false;++ const loadAnnouncements = async () => {+ const dismissedIds = new Set(readDismissedAnnouncementIds());+ const impressionCounts = readAnnouncementImpressionCounts();+ const [appVersion, remoteFeed] = await Promise.all([+ window.electronAPI.getAppVersion().catch(() => "0.0.0"),+ window.electronAPI.getAnnouncements().catch(() => null),+ ]);+ if (cancelled) {+ return;+ }++ const parsedRemoteFeed = parseAnnouncementFeed(remoteFeed);+ const eligible = selectAnnouncements({+ bundled: BUNDLED_ANNOUNCEMENT_FEED.announcements,+ remote: parsedRemoteFeed.announcements,+ dismissedIds,+ impressionCounts,+ appVersion,+ audience,+ }).filter(+ (announcement) =>+ announcement.presentation !== "notification" &&+ announcement.presentation !== "banner",+ );+ setPopupAspectRatio(+ parsedRemoteFeed.settings.aspectRatio ??+ BUNDLED_ANNOUNCEMENT_FEED.settings.aspectRatio,+ );+ setAnnouncements(eligible);+ setCurrentIndex(0);+ setOpen(eligible.length > 0);+ };++ void loadAnnouncements();+ return () => {+ cancelled = true;+ };+ }, [audience]);++ const current = announcements[currentIndex];+ const currentId = current?.id;+ const usesCoverMedia = current?.mediaMode === "cover" && Boolean(current.media);+ const controls = {+ close: current?.controls?.close !== false,+ dismiss: current?.controls?.dismiss !== false,+ action: current?.controls?.action !== false,+ navigation: current?.controls?.navigation !== false,+ indicators: current?.controls?.indicators !== false,+ };++ useEffect(() => {+ if (!open || !currentId || countedThisSessionRef.current.has(currentId)) {+ return;+ }++ countedThisSessionRef.current.add(currentId);+ recordAnnouncementImpression(currentId);+ }, [currentId, open]);++ useEffect(() => {+ if (!open || !current?.displayDurationSeconds) {+ return;+ }++ const timeout = window.setTimeout(() => {+ if (currentIndex >= announcements.length - 1) {+ setOpen(false);+ return;+ }+ setCurrentIndex((index) => index + 1);+ }, current.displayDurationSeconds * 1_000);++ return () => window.clearTimeout(timeout);+ }, [announcements.length, current?.displayDurationSeconds, currentIndex, open]);++ const dismissCurrent = () => {+ if (!current) {+ setOpen(false);+ return;+ }++ dismissAnnouncements([current.id]);++ const remaining = announcements.filter((announcement) => announcement.id !== current.id);+ setAnnouncements(remaining);+ if (remaining.length === 0) {+ setOpen(false);+ setCurrentIndex(0);+ return;+ }++ setCurrentIndex((index) => Math.min(index, remaining.length - 1));+ };++ const dismissAll = () => {+ dismissAnnouncements(announcements.map((announcement) => announcement.id));+ setAnnouncements([]);+ setCurrentIndex(0);+ setOpen(false);+ };++ const openAction = async () => {+ if (!current?.action) {+ return;+ }++ try {+ const result = await runAnnouncementAction(current.action);+ if (!result.success) {+ toast.error(result.error || t("announcements.openFailed", "Failed to open link."));+ return;+ }+ dismissCurrent();+ } catch (error) {+ toast.error(+ `${t("announcements.openFailed", "Failed to open link.")} ${String(error)}`,+ );+ }+ };++ if (!current) {+ return null;+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen) {+ dismissAll();+ }+ }}+ >+ <DialogContent+ className={cn(+ "flex max-h-[90vh] max-w-xl flex-col gap-0 overflow-hidden border-foreground/10 bg-editor-dialog p-0 text-foreground",+ !controls.close && "[&>button]:hidden",+ usesCoverMedia &&+ "isolate min-h-80 text-white [&>button]:bg-black/35 [&>button]:text-white [&>button:hover]:bg-black/55",+ )}+ style={+ popupAspectRatio+ ? { aspectRatio: popupAspectRatio.replace(":", " / ") }+ : undefined+ }+ >+ {usesCoverMedia ? (+ <>+ <div className="absolute inset-0 z-0">+ <AnnouncementMediaBanner+ key={current.id}+ announcement={current}+ cover+ />+ </div>+ <div+ className="pointer-events-none absolute inset-0 z-[1] bg-black/15"+ aria-hidden="true"+ />+ </>+ ) : (+ <AnnouncementMediaBanner key={current.id} announcement={current} />+ )}+ <div+ className={cn(+ "space-y-5 overflow-y-auto p-6",+ usesCoverMedia &&+ "relative z-10 mt-auto w-full bg-gradient-to-t from-black/90 via-black/65 to-transparent pt-20",+ )}+ >+ <DialogHeader>+ <DialogTitle className="cursor-text select-text text-xl leading-tight">+ {current.title}+ </DialogTitle>+ <DialogDescription+ className={cn(+ "cursor-text select-text whitespace-pre-line pt-2 text-sm leading-relaxed text-muted-foreground",+ usesCoverMedia && "text-white/80",+ )}+ >+ {current.body}+ </DialogDescription>+ </DialogHeader>++ {announcements.length > 1 && (controls.navigation || controls.indicators) && (+ <div+ className={cn(+ "flex items-center",+ controls.navigation ? "justify-between" : "justify-center",+ )}+ aria-label={t("announcements.carousel", "Announcements")}+ >+ {controls.navigation && (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className={+ usesCoverMedia ? "text-white hover:bg-white/15" : undefined+ }+ onClick={() =>+ setCurrentIndex(+ (index) =>+ (index - 1 + announcements.length) %+ announcements.length,+ )+ }+ aria-label={t(+ "announcements.previous",+ "Previous announcement",+ )}+ >+ <ArrowLeft />+ </Button>+ )}+ {controls.indicators && (+ <div className="flex gap-1.5">+ {announcements.map((announcement, index) => (+ <button+ type="button"+ key={announcement.id}+ className={`h-1.5 rounded-full transition-all ${+ index === currentIndex+ ? `w-6 ${usesCoverMedia ? "bg-white" : "bg-primary"}`+ : `w-1.5 ${usesCoverMedia ? "bg-white/40" : "bg-foreground/25"}`+ }`}+ onClick={() => setCurrentIndex(index)}+ aria-label={`${t("announcements.show", "Show announcement")} ${index + 1}`}+ />+ ))}+ </div>+ )}+ {controls.navigation && (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className={+ usesCoverMedia ? "text-white hover:bg-white/15" : undefined+ }+ onClick={() =>+ setCurrentIndex(+ (index) => (index + 1) % announcements.length,+ )+ }+ aria-label={t("announcements.next", "Next announcement")}+ >+ <ArrowRight />+ </Button>+ )}+ </div>+ )}++ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">+ {controls.dismiss && (+ <Button+ type="button"+ variant="ghost"+ className={+ usesCoverMedia ? "text-white hover:bg-white/15" : undefined+ }+ onClick={dismissCurrent}+ >+ {t("announcements.dismiss", "Dismiss")}+ </Button>+ )}+ {current.action && controls.action && (+ <Button type="button" onClick={() => void openAction()}>+ {current.action.label}+ {current.action.url ? <ArrowSquareOut /> : <ArrowRight />}+ </Button>+ )}+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/announcements/EditorAnnouncementBanner.tsx b/src/components/announcements/EditorAnnouncementBanner.tsxnew file mode 100644index 00000000..6180c17b--- /dev/null+++ b/src/components/announcements/EditorAnnouncementBanner.tsx@@ -0,0 +1,143 @@+import { ArrowRight, ArrowSquareOut, X } from "@phosphor-icons/react";+import { useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { BUNDLED_ANNOUNCEMENT_FEED } from "@/content/announcements";+import { useI18n } from "@/contexts/I18nContext";+import { runAnnouncementAction } from "@/lib/announcementActions";+import type { Announcement } from "@/lib/announcements";+import { parseAnnouncementFeed, selectAnnouncements } from "@/lib/announcements";+import {+ dismissAnnouncements,+ readAnnouncementImpressionCounts,+ readDismissedAnnouncementIds,+ recordAnnouncementImpression,+} from "@/lib/announcementState";++export function EditorAnnouncementBanner() {+ const { t } = useI18n();+ const [announcements, setAnnouncements] = useState<Announcement[]>([]);+ const countedThisSessionRef = useRef(new Set<string>());+ const current = announcements[0];++ useEffect(() => {+ let cancelled = false;++ const loadBanners = async () => {+ const dismissedIds = new Set(readDismissedAnnouncementIds());+ const impressionCounts = readAnnouncementImpressionCounts();+ const [appVersion, remoteFeed] = await Promise.all([+ window.electronAPI.getAppVersion().catch(() => "0.0.0"),+ window.electronAPI.getAnnouncements().catch(() => null),+ ]);+ if (cancelled) {+ return;+ }++ setAnnouncements(+ selectAnnouncements({+ bundled: BUNDLED_ANNOUNCEMENT_FEED.announcements,+ remote: parseAnnouncementFeed(remoteFeed).announcements,+ dismissedIds,+ impressionCounts,+ appVersion,+ audience: "editor",+ }).filter((announcement) => announcement.presentation === "banner"),+ );+ };++ void loadBanners();+ return () => {+ cancelled = true;+ };+ }, []);++ useEffect(() => {+ if (!current || countedThisSessionRef.current.has(current.id)) {+ return;+ }++ countedThisSessionRef.current.add(current.id);+ recordAnnouncementImpression(current.id);+ }, [current]);++ useEffect(() => {+ if (!current?.displayDurationSeconds) {+ return;+ }++ const timeout = window.setTimeout(() => {+ setAnnouncements((items) => items.slice(1));+ }, current.displayDurationSeconds * 1_000);+ return () => window.clearTimeout(timeout);+ }, [current]);++ if (!current) {+ return null;+ }++ const dismissCurrent = () => {+ dismissAnnouncements([current.id]);+ setAnnouncements((items) => items.slice(1));+ };++ const openAction = async () => {+ if (!current.action) {+ return;+ }++ try {+ const result = await runAnnouncementAction(current.action);+ if (!result.success) {+ toast.error(result.error || t("announcements.openFailed", "Failed to open link."));+ return;+ }+ dismissCurrent();+ } catch (error) {+ toast.error(+ `${t("announcements.openFailed", "Failed to open link.")} ${String(error)}`,+ );+ }+ };++ const showClose = current.controls?.close !== false;+ const showAction = current.action && current.controls?.action !== false;++ return (+ <div className="relative z-40 flex flex-shrink-0 items-center justify-center gap-3 border-b border-black bg-black px-12 py-2 text-white shadow-sm dark:border-white dark:bg-white dark:text-black">+ <div className="min-w-0 cursor-text select-text text-center text-xs leading-relaxed">+ <span className="font-semibold">{current.title}</span>+ <span className="mx-1.5 opacity-65" aria-hidden="true">+ —+ </span>+ <span className="opacity-80">{current.body}</span>+ </div>+ {showAction ? (+ <Button+ type="button"+ variant="link"+ size="sm"+ onClick={() => void openAction()}+ className="h-auto shrink-0 gap-1 px-1 py-0 text-xs text-white underline decoration-white/50 underline-offset-2 hover:text-white dark:text-black dark:decoration-black/50 dark:hover:text-black"+ >+ {current.action?.label}+ {current.action?.url ? (+ <ArrowSquareOut className="h-3.5 w-3.5" />+ ) : (+ <ArrowRight className="h-3.5 w-3.5" />+ )}+ </Button>+ ) : null}+ {showClose ? (+ <button+ type="button"+ onClick={dismissCurrent}+ className="absolute right-4 inline-flex h-6 w-6 items-center justify-center rounded-md text-white/70 transition-colors hover:bg-white/15 hover:text-white dark:text-black/70 dark:hover:bg-black/10 dark:hover:text-black"+ aria-label={t("announcements.dismiss", "Dismiss")}+ >+ <X className="h-3.5 w-3.5" />+ </button>+ ) : null}+ </div>+ );+}diff --git a/src/components/announcements/LiveAnnouncementNotifications.tsx b/src/components/announcements/LiveAnnouncementNotifications.tsxnew file mode 100644index 00000000..3d6bce30--- /dev/null+++ b/src/components/announcements/LiveAnnouncementNotifications.tsx@@ -0,0 +1,118 @@+import { useEffect, useRef } from "react";+import { toast } from "sonner";+import { BUNDLED_ANNOUNCEMENT_FEED } from "@/content/announcements";+import { useI18n } from "@/contexts/I18nContext";+import { runAnnouncementAction } from "@/lib/announcementActions";+import type { AnnouncementAudience } from "@/lib/announcements";+import { parseAnnouncementFeed, selectAnnouncements } from "@/lib/announcements";+import {+ dismissAnnouncements,+ readAnnouncementImpressionCounts,+ readDismissedAnnouncementIds,+ recordAnnouncementImpression,+} from "@/lib/announcementState";++const DEFAULT_NOTIFICATION_DURATION_SECONDS = 10;+const MAX_NOTIFICATIONS_PER_LOAD = 5;++export function LiveAnnouncementNotifications({ audience }: { audience: AnnouncementAudience }) {+ const { t } = useI18n();+ const shownThisSessionRef = useRef(new Set<string>());++ useEffect(() => {+ let cancelled = false;++ const showNotifications = async () => {+ const dismissedIds = new Set(readDismissedAnnouncementIds());+ const impressionCounts = readAnnouncementImpressionCounts();+ const [appVersion, remoteFeed] = await Promise.all([+ window.electronAPI.getAppVersion().catch(() => "0.0.0"),+ window.electronAPI.getAnnouncements().catch(() => null),+ ]);+ if (cancelled) {+ return;+ }++ const notifications = selectAnnouncements({+ bundled: BUNDLED_ANNOUNCEMENT_FEED.announcements,+ remote: parseAnnouncementFeed(remoteFeed).announcements,+ dismissedIds,+ impressionCounts,+ appVersion,+ audience,+ })+ .filter((announcement) => announcement.presentation === "notification")+ .slice(0, MAX_NOTIFICATIONS_PER_LOAD);++ for (const announcement of notifications) {+ if (shownThisSessionRef.current.has(announcement.id)) {+ continue;+ }++ shownThisSessionRef.current.add(announcement.id);+ recordAnnouncementImpression(announcement.id);+ const dismiss = () => dismissAnnouncements([announcement.id]);+ const controls = {+ close: announcement.controls?.close !== false,+ action: announcement.controls?.action !== false,+ };+ const action = announcement.action;++ toast(+ <span className="cursor-text select-text font-semibold">+ {announcement.title}+ </span>,+ {+ id: `live-announcement:${announcement.id}`,+ description: (+ <div className="cursor-text select-text">+ <p className="whitespace-pre-line leading-relaxed">+ {announcement.body}+ </p>+ </div>+ ),+ duration:+ (announcement.displayDurationSeconds ??+ DEFAULT_NOTIFICATION_DURATION_SECONDS) * 1_000,+ closeButton: controls.close,+ onDismiss: dismiss,+ action:+ action && controls.action+ ? {+ label: action.label,+ onClick: () => {+ void runAnnouncementAction(action)+ .then((result) => {+ if (result.success) {+ dismiss();+ return;+ }+ toast.error(+ result.error ||+ t(+ "announcements.openFailed",+ "Failed to open link.",+ ),+ );+ })+ .catch((error) => {+ toast.error(+ `${t("announcements.openFailed", "Failed to open link.")} ${String(error)}`,+ );+ });+ },+ }+ : undefined,+ },+ );+ }+ };++ void showNotifications();+ return () => {+ cancelled = true;+ };+ }, [audience, t]);++ return null;+}diff --git a/src/components/video-editor/SettingsPanel.tsx b/src/components/video-editor/SettingsPanel.tsxindex ea2c0cee..81c934d5 100644--- a/src/components/video-editor/SettingsPanel.tsx+++ b/src/components/video-editor/SettingsPanel.tsx@@ -1119,6 +1119,8 @@ export function SettingsPanel({const [customImages, setCustomImages] = useState<string[]>(initialEditorPreferences.customWallpapers,);+ const [experimentalUpdatesEnabled, setExperimentalUpdatesEnabled] = useState(false);+ const [savingExperimentalUpdates, setSavingExperimentalUpdates] = useState(false);const removeBackgroundStateRef = useRef<{aspectRatio: AspectRatio;padding: Padding;@@ -1136,6 +1138,44 @@ export function SettingsPanel({});};+ useEffect(() => {+ let cancelled = false;+ void window.electronAPI+ .getExperimentalUpdatesEnabled()+ .then((enabled) => {+ if (!cancelled) setExperimentalUpdatesEnabled(enabled);+ })+ .catch((error) => {+ console.error("Failed to load experimental updates preference:", error);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const updateExperimentalUpdatesPreference = async (enabled: boolean) => {+ const previousValue = experimentalUpdatesEnabled;+ setExperimentalUpdatesEnabled(enabled);+ setSavingExperimentalUpdates(true);+ try {+ const result = await window.electronAPI.setExperimentalUpdatesEnabled(enabled);+ setExperimentalUpdatesEnabled(result.enabled);+ if (!result.success) {+ toast.error(+ result.error ||+ tSettings("updates.saveFailed", "Failed to change the update channel."),+ );+ }+ } catch (error) {+ setExperimentalUpdatesEnabled(previousValue);+ toast.error(+ `${tSettings("updates.saveFailed", "Failed to change the update channel.")} ${String(error)}`,+ );+ } finally {+ setSavingExperimentalUpdates(false);+ }+ };+useEffect(() => {let mounted = true;(async () => {@@ -2542,6 +2582,32 @@ export function SettingsPanel({</Select></section>+ <section className="flex flex-col gap-2">+ <SectionLabel>{tSettings("updates.title", "Updates")}</SectionLabel>+ <div className="flex items-center justify-between gap-3 rounded-lg bg-foreground/[0.03] px-2.5 py-2">+ <div>+ <div className="text-[11px] font-medium text-foreground">+ {tSettings("updates.experimental", "Experimental updates")}+ </div>+ <div className="mt-0.5 text-[10px] text-muted-foreground/70">+ {tSettings(+ "updates.experimentalDescription",+ "Receive first-line test builds published as prereleases. These may be less stable.",+ )}+ </div>+ </div>+ <Switch+ checked={experimentalUpdatesEnabled}+ disabled={savingExperimentalUpdates}+ onCheckedChange={(enabled) =>+ void updateExperimentalUpdatesPreference(enabled)+ }+ aria-label={tSettings("updates.experimental", "Experimental updates")}+ className="data-[state=checked]:bg-[#2563EB] scale-75"+ />+ </div>+ </section>+<section className="flex flex-col gap-1.5"><div className="flex items-center justify-between gap-3 rounded-lg bg-foreground/[0.03] px-2.5 py-2"><div>diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsxindex 596a84d8..ad38cb4a 100644--- a/src/components/video-editor/VideoEditor.tsx+++ b/src/components/video-editor/VideoEditor.tsx@@ -31,6 +31,7 @@ import type { Span } from "dnd-timeline";import { motion } from "motion/react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";+import { EditorAnnouncementBanner } from "@/components/announcements/EditorAnnouncementBanner";import { Button } from "@/components/ui/button";import {Dialog,@@ -51,6 +52,8 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popoverimport { Toaster } from "@/components/ui/sonner";import { useI18n } from "@/contexts/I18nContext";import { useShortcuts } from "@/contexts/ShortcutsContext";+import { OPEN_EDITOR_SECTION_EVENT } from "@/lib/announcementActions";+import { type AnnouncementEditorSection, isAnnouncementEditorSection } from "@/lib/announcements";import {calculateOutputDimensions,DEFAULT_MP4_CODEC,@@ -607,6 +610,17 @@ export default function VideoEditor() {initialEditorPreferences.aspectRatio,);const [activeEffectSection, setActiveEffectSection] = useState<EditorEffectSection>("scene");+ useEffect(() => {+ const handleOpenEditorSection = (event: Event) => {+ const section = (event as CustomEvent<AnnouncementEditorSection>).detail;+ if (isAnnouncementEditorSection(section)) {+ setActiveEffectSection(section);+ }+ };++ window.addEventListener(OPEN_EDITOR_SECTION_EVENT, handleOpenEditorSection);+ return () => window.removeEventListener(OPEN_EDITOR_SECTION_EVENT, handleOpenEditorSection);+ }, []);const [exportQuality, setExportQuality] = useState<ExportQuality>(initialEditorPreferences.exportQuality,);@@ -6197,6 +6211,7 @@ export default function VideoEditor() {</DropdownMenu></div></div>+ <EditorAnnouncementBanner /><div className="relative flex min-h-0 flex-1 flex-col gap-3 p-4"><div className="flex min-h-0 flex-1 gap-3 relative z-10">diff --git a/src/content/announcements.ts b/src/content/announcements.tsnew file mode 100644index 00000000..80281a12--- /dev/null+++ b/src/content/announcements.ts@@ -0,0 +1,9 @@+import type { AnnouncementFeed } from "@/lib/announcements";++/** Announcements bundled with a release. Use a new ID when an item should be shown again. */+export const BUNDLED_ANNOUNCEMENT_FEED: AnnouncementFeed = {+ settings: {+ aspectRatio: "4:3",+ },+ announcements: [],+};diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.jsonindex 8f0cfb7b..6f18ef1b 100644--- a/src/i18n/locales/en/settings.json+++ b/src/i18n/locales/en/settings.json@@ -1,4 +1,10 @@{+ "updates": {+ "title": "Updates",+ "experimental": "Experimental updates",+ "experimentalDescription": "Receive first-line test builds published as prereleases. These may be less stable.",+ "saveFailed": "Failed to change the update channel."+ },"zoom": {"level": "Zoom Level","selectRegion": "Select a zoom region to adjust",diff --git a/src/lib/announcementActions.ts b/src/lib/announcementActions.tsnew file mode 100644index 00000000..2e05ab67--- /dev/null+++ b/src/lib/announcementActions.ts@@ -0,0 +1,22 @@+import type { AnnouncementAction, AnnouncementEditorSection } from "./announcements";++export const OPEN_EDITOR_SECTION_EVENT = "recordly:open-editor-section";++export function openEditorSection(section: AnnouncementEditorSection): void {+ window.dispatchEvent(+ new CustomEvent<AnnouncementEditorSection>(OPEN_EDITOR_SECTION_EVENT, {+ detail: section,+ }),+ );+}++export async function runAnnouncementAction(+ action: AnnouncementAction,+): Promise<{ success: boolean; error?: string }> {+ if (action.section) {+ openEditorSection(action.section);+ return { success: true };+ }++ return window.electronAPI.openExternalUrl(action.url);+}diff --git a/src/lib/announcementState.ts b/src/lib/announcementState.tsnew file mode 100644index 00000000..13ab2719--- /dev/null+++ b/src/lib/announcementState.ts@@ -0,0 +1,46 @@+const DISMISSED_ANNOUNCEMENTS_KEY = "dismissedAnnouncementIds";+const ANNOUNCEMENT_IMPRESSIONS_KEY = "announcementImpressionCounts";+const MAX_DISMISSED_ANNOUNCEMENTS = 200;++export function readDismissedAnnouncementIds(): string[] {+ const value = window.electronAPI.getAppSetting(DISMISSED_ANNOUNCEMENTS_KEY);+ if (!Array.isArray(value)) {+ return [];+ }++ return value+ .filter((item): item is string => typeof item === "string")+ .slice(-MAX_DISMISSED_ANNOUNCEMENTS);+}++export function dismissAnnouncements(ids: Iterable<string>) {+ const dismissedIds = new Set(readDismissedAnnouncementIds());+ for (const id of ids) {+ dismissedIds.add(id);+ }+ window.electronAPI.setAppSetting(+ DISMISSED_ANNOUNCEMENTS_KEY,+ [...dismissedIds].slice(-MAX_DISMISSED_ANNOUNCEMENTS),+ );+}++export function readAnnouncementImpressionCounts(): Record<string, number> {+ const value = window.electronAPI.getAppSetting(ANNOUNCEMENT_IMPRESSIONS_KEY);+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ return {};+ }++ const counts: Record<string, number> = {};+ for (const [id, count] of Object.entries(value)) {+ if (typeof count === "number" && Number.isInteger(count) && count >= 0) {+ counts[id] = count;+ }+ }+ return counts;+}++export function recordAnnouncementImpression(id: string) {+ const counts = readAnnouncementImpressionCounts();+ counts[id] = (counts[id] ?? 0) + 1;+ window.electronAPI.setAppSetting(ANNOUNCEMENT_IMPRESSIONS_KEY, counts);+}diff --git a/src/lib/announcements.test.ts b/src/lib/announcements.test.tsnew file mode 100644index 00000000..a616c924--- /dev/null+++ b/src/lib/announcements.test.ts@@ -0,0 +1,257 @@+import { describe, expect, it } from "vitest";+import { compareVersions, parseAnnouncementFeed, selectAnnouncements } from "./announcements";++describe("parseAnnouncementFeed", () => {+ it("accepts safe text, media, and actions", () => {+ const feed = parseAnnouncementFeed({+ settings: { aspectRatio: "16:9" },+ announcements: [+ {+ id: "release-1",+ title: "New release",+ body: "See what changed.",+ audience: "editor",+ priority: 200,+ mediaMode: "cover",+ displayDurationSeconds: 15,+ maxImpressions: 3,+ controls: {+ close: false,+ dismiss: false,+ action: true,+ navigation: false,+ indicators: true,+ },+ media: {+ type: "video",+ url: "https://example.com/demo.mp4",+ posterUrl: "/announcement-poster.jpg",+ },+ action: { label: "Learn more", url: "https://example.com/release" },+ },+ ],+ });++ expect(feed.settings).toEqual({ aspectRatio: "16:9" });+ expect(feed.announcements).toEqual([+ {+ id: "release-1",+ title: "New release",+ body: "See what changed.",+ audience: "editor",+ priority: 100,+ mediaMode: "cover",+ displayDurationSeconds: 15,+ maxImpressions: 3,+ controls: {+ close: false,+ dismiss: false,+ action: true,+ navigation: false,+ indicators: true,+ },+ media: {+ type: "video",+ url: "https://example.com/demo.mp4",+ posterUrl: "/announcement-poster.jpg",+ },+ action: { label: "Learn more", url: "https://example.com/release" },+ },+ ]);+ });++ it("keeps notifications as text-only toasts", () => {+ const feed = parseAnnouncementFeed({+ announcements: [+ {+ id: "notice-1",+ title: "Service notice",+ body: "A short notification.",+ presentation: "notification",+ mediaMode: "cover",+ media: { type: "image", url: "https://example.com/banner.jpg" },+ action: { label: "Details", url: "https://example.com/details" },+ },+ ],+ });++ expect(feed.announcements).toEqual([+ {+ id: "notice-1",+ title: "Service notice",+ body: "A short notification.",+ presentation: "notification",+ audience: "all",+ priority: 0,+ action: { label: "Details", url: "https://example.com/details" },+ },+ ]);+ });++ it("keeps editor banners text-only", () => {+ const feed = parseAnnouncementFeed({+ announcements: [+ {+ id: "banner-1",+ title: "Editor notice",+ body: "A short banner.",+ presentation: "banner",+ mediaMode: "cover",+ media: { type: "video", url: "https://example.com/banner.mp4" },+ action: { label: "Details", url: "https://example.com/details" },+ },+ ],+ });++ expect(feed.announcements).toEqual([+ {+ id: "banner-1",+ title: "Editor notice",+ body: "A short banner.",+ presentation: "banner",+ audience: "all",+ priority: 0,+ action: { label: "Details", url: "https://example.com/details" },+ },+ ]);+ });++ it("accepts an action that opens a safe editor section", () => {+ const feed = parseAnnouncementFeed({+ announcements: [+ {+ id: "settings-link",+ title: "Try experimental updates",+ body: "Open settings to opt in.",+ action: { label: "Open settings", section: "settings" },+ },+ ],+ });++ expect(feed.announcements[0]?.action).toEqual({+ label: "Open settings",+ section: "settings",+ });+ });++ it("ignores ambiguous or unknown in-app actions", () => {+ const announcements = parseAnnouncementFeed({+ announcements: [+ {+ id: "ambiguous",+ title: "Ambiguous",+ body: "Two destinations are not allowed.",+ action: {+ label: "Open",+ url: "https://example.com",+ section: "settings",+ },+ },+ {+ id: "unknown",+ title: "Unknown",+ body: "Unknown destinations are ignored.",+ action: { label: "Open", section: "billing" },+ },+ ],+ }).announcements;++ expect(announcements.map((announcement) => announcement.action)).toEqual([+ undefined,+ undefined,+ ]);+ });++ it("drops malformed items and unsafe URLs", () => {+ const feed = parseAnnouncementFeed({+ announcements: [+ { id: "missing-body", title: "Incomplete" },+ {+ id: "safe-text",+ title: "Still valid",+ body: "Unsafe optional fields are ignored.",+ media: { type: "image", url: "javascript:alert(1)" },+ action: { label: "Bad", url: "http://example.com" },+ },+ ],+ });++ expect(feed.announcements).toEqual([+ {+ id: "safe-text",+ title: "Still valid",+ body: "Unsafe optional fields are ignored.",+ audience: "all",+ priority: 0,+ },+ ]);+ });+});++describe("selectAnnouncements", () => {+ it("filters by audience, date, version, and dismissal", () => {+ const parsed = parseAnnouncementFeed({+ announcements: [+ { id: "shown", title: "Shown", body: "Visible", priority: 2, minVersion: "1.2.0" },+ { id: "dismissed", title: "Dismissed", body: "Hidden" },+ { id: "future", title: "Future", body: "Hidden", startsAt: "2027-01-01T00:00:00Z" },+ { id: "expired", title: "Expired", body: "Hidden", endsAt: "2025-01-01T00:00:00Z" },+ { id: "newer", title: "Newer", body: "Hidden", minVersion: "2.0.0" },+ ],+ }).announcements;++ const selected = selectAnnouncements({+ bundled: [],+ remote: parsed,+ dismissedIds: new Set(["dismissed"]),+ appVersion: "1.3.5-beta.2",+ audience: "editor",+ now: new Date("2026-09-01T00:00:00Z"),+ });++ expect(selected.map((announcement) => announcement.id)).toEqual(["shown"]);+ });++ it("lets remote announcements replace bundled items with the same ID", () => {+ const common = { audience: "all" as const, priority: 0 };+ const selected = selectAnnouncements({+ bundled: [{ id: "same", title: "Bundled", body: "Old", ...common }],+ remote: [{ id: "same", title: "Remote", body: "New", ...common }],+ dismissedIds: new Set(),+ appVersion: "1.0.0",+ audience: "editor",+ });++ expect(selected[0]?.title).toBe("Remote");+ });++ it("stops selecting an announcement after its impression limit", () => {+ const common = { audience: "all" as const, priority: 0 };+ const selected = selectAnnouncements({+ bundled: [+ {+ id: "limited",+ title: "Limited",+ body: "Shown twice",+ maxImpressions: 2,+ ...common,+ },+ ],+ remote: [],+ dismissedIds: new Set(),+ impressionCounts: { limited: 2 },+ appVersion: "1.0.0",+ audience: "editor",+ });++ expect(selected).toEqual([]);+ });+});++describe("compareVersions", () => {+ it("compares numeric release segments", () => {+ expect(compareVersions("1.3.5-beta.2", "1.3.4")).toBe(1);+ expect(compareVersions("1.3", "1.3.0")).toBe(0);+ expect(compareVersions("v1.2.9", "1.3.0")).toBe(-1);+ });+});diff --git a/src/lib/announcements.ts b/src/lib/announcements.tsnew file mode 100644index 00000000..9a65c9f6--- /dev/null+++ b/src/lib/announcements.ts@@ -0,0 +1,355 @@+export type AnnouncementAudience = "all" | "editor";++export interface AnnouncementMedia {+ type: "image" | "video";+ url: string;+ alt?: string;+ posterUrl?: string;+}++export type AnnouncementEditorSection =+ | "scene"+ | "cursor"+ | "webcam"+ | "captions"+ | "settings"+ | "extensions";++export type AnnouncementAction =+ | { label: string; url: string; section?: never }+ | { label: string; section: AnnouncementEditorSection; url?: never };++export interface AnnouncementControls {+ close?: boolean;+ dismiss?: boolean;+ action?: boolean;+ navigation?: boolean;+ indicators?: boolean;+}++export interface Announcement {+ id: string;+ title: string;+ body: string;+ presentation?: "popup" | "notification" | "banner";+ audience: AnnouncementAudience;+ priority: number;+ mediaMode?: "banner" | "cover";+ displayDurationSeconds?: number;+ maxImpressions?: number;+ controls?: AnnouncementControls;+ media?: AnnouncementMedia;+ action?: AnnouncementAction;+ startsAt?: string;+ endsAt?: string;+ minVersion?: string;+ maxVersion?: string;+}++export interface AnnouncementFeed {+ settings: AnnouncementFeedSettings;+ announcements: Announcement[];+}++export interface AnnouncementFeedSettings {+ aspectRatio?: string;+}++const MAX_ANNOUNCEMENTS = 50;+const MAX_ID_LENGTH = 100;+const MAX_TITLE_LENGTH = 160;+const MAX_BODY_LENGTH = 2_000;+const MAX_LABEL_LENGTH = 80;+const MAX_URL_LENGTH = 2_048;++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function readTrimmedString(value: unknown, maxLength: number): string | undefined {+ if (typeof value !== "string") {+ return undefined;+ }++ const trimmed = value.trim();+ return trimmed && trimmed.length <= maxLength ? trimmed : undefined;+}++function readDate(value: unknown): string | undefined {+ const date = readTrimmedString(value, 64);+ return date && Number.isFinite(Date.parse(date)) ? date : undefined;+}++function readAspectRatio(value: unknown): string | undefined {+ const ratio = readTrimmedString(value, 16);+ const match = ratio?.match(/^(\d{1,3}):(\d{1,3})$/);+ if (!match) {+ return undefined;+ }++ const width = Number(match[1]);+ const height = Number(match[2]);+ const numericRatio = width / height;+ return width > 0 && height > 0 && numericRatio >= 0.4 && numericRatio <= 3+ ? `${width}:${height}`+ : undefined;+}++function readBoundedInteger(value: unknown, minimum: number, maximum: number): number | undefined {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ return undefined;+ }++ const rounded = Math.round(value);+ return rounded >= minimum && rounded <= maximum ? rounded : undefined;+}++function readSafeUrl(value: unknown, allowRelative: boolean): string | undefined {+ const url = readTrimmedString(value, MAX_URL_LENGTH);+ if (!url) {+ return undefined;+ }++ if (allowRelative && url.startsWith("/") && !url.startsWith("//")) {+ return url;+ }++ try {+ const parsed = new URL(url);+ return parsed.protocol === "https:" && !parsed.username && !parsed.password+ ? url+ : undefined;+ } catch {+ return undefined;+ }+}++function parseMedia(value: unknown): AnnouncementMedia | undefined {+ if (!isRecord(value) || (value.type !== "image" && value.type !== "video")) {+ return undefined;+ }++ const url = readSafeUrl(value.url, true);+ if (!url) {+ return undefined;+ }++ const alt = readTrimmedString(value.alt, 300);+ const posterUrl = value.type === "video" ? readSafeUrl(value.posterUrl, true) : undefined;+ return {+ type: value.type,+ url,+ ...(alt ? { alt } : {}),+ ...(posterUrl ? { posterUrl } : {}),+ };+}++function parseAction(value: unknown): AnnouncementAction | undefined {+ if (!isRecord(value)) {+ return undefined;+ }++ const label = readTrimmedString(value.label, MAX_LABEL_LENGTH);+ const url = readSafeUrl(value.url, false);+ const section = isAnnouncementEditorSection(value.section) ? value.section : undefined;+ if (!label || Boolean(url) === Boolean(section)) {+ return undefined;+ }++ if (url) {+ return { label, url };+ }++ return section ? { label, section } : undefined;+}++export function isAnnouncementEditorSection(value: unknown): value is AnnouncementEditorSection {+ return (+ value === "scene" ||+ value === "cursor" ||+ value === "webcam" ||+ value === "captions" ||+ value === "settings" ||+ value === "extensions"+ );+}++function parseControls(value: unknown): AnnouncementControls | undefined {+ if (!isRecord(value)) {+ return undefined;+ }++ const controls: AnnouncementControls = {};+ for (const key of ["close", "dismiss", "action", "navigation", "indicators"] as const) {+ if (typeof value[key] === "boolean") {+ controls[key] = value[key];+ }+ }++ return Object.keys(controls).length > 0 ? controls : undefined;+}++function parseAnnouncement(value: unknown): Announcement | undefined {+ if (!isRecord(value)) {+ return undefined;+ }++ const id = readTrimmedString(value.id, MAX_ID_LENGTH);+ const title = readTrimmedString(value.title, MAX_TITLE_LENGTH);+ const body = readTrimmedString(value.body, MAX_BODY_LENGTH);+ if (!id || !title || !body) {+ return undefined;+ }++ const audience = value.audience === "editor" ? "editor" : "all";+ const presentation =+ value.presentation === "notification" || value.presentation === "banner"+ ? value.presentation+ : undefined;+ const isTextOnlyPresentation = presentation === "notification" || presentation === "banner";+ const priority =+ typeof value.priority === "number" && Number.isFinite(value.priority)+ ? Math.max(-100, Math.min(100, value.priority))+ : 0;+ const media = isTextOnlyPresentation ? undefined : parseMedia(value.media);+ const action = parseAction(value.action);+ const controls = parseControls(value.controls);+ const mediaMode =+ !isTextOnlyPresentation && (value.mediaMode === "cover" || value.mediaMode === "banner")+ ? value.mediaMode+ : undefined;+ const displayDurationSeconds = readBoundedInteger(value.displayDurationSeconds, 3, 300);+ const maxImpressions = readBoundedInteger(value.maxImpressions, 1, 100);+ const startsAt = readDate(value.startsAt);+ const endsAt = readDate(value.endsAt);+ const minVersion = readTrimmedString(value.minVersion, 64);+ const maxVersion = readTrimmedString(value.maxVersion, 64);++ return {+ id,+ title,+ body,+ ...(presentation ? { presentation } : {}),+ audience,+ priority,+ ...(mediaMode ? { mediaMode } : {}),+ ...(displayDurationSeconds ? { displayDurationSeconds } : {}),+ ...(maxImpressions ? { maxImpressions } : {}),+ ...(controls ? { controls } : {}),+ ...(media ? { media } : {}),+ ...(action ? { action } : {}),+ ...(startsAt ? { startsAt } : {}),+ ...(endsAt ? { endsAt } : {}),+ ...(minVersion ? { minVersion } : {}),+ ...(maxVersion ? { maxVersion } : {}),+ };+}++export function parseAnnouncementFeed(value: unknown): AnnouncementFeed {+ if (!isRecord(value) || !Array.isArray(value.announcements)) {+ return { settings: {}, announcements: [] };+ }++ const settings = isRecord(value.settings)+ ? { aspectRatio: readAspectRatio(value.settings.aspectRatio) }+ : {};++ const announcements: Announcement[] = [];+ for (const item of value.announcements.slice(0, MAX_ANNOUNCEMENTS)) {+ const announcement = parseAnnouncement(item);+ if (announcement) {+ announcements.push(announcement);+ }+ }++ return {+ settings: settings.aspectRatio ? { aspectRatio: settings.aspectRatio } : {},+ announcements,+ };+}++function versionParts(version: string): number[] {+ const core = version.trim().replace(/^v/i, "").split("-")[0];+ return core.split(".").map((part) => {+ const parsed = Number.parseInt(part, 10);+ return Number.isFinite(parsed) ? parsed : 0;+ });+}++export function compareVersions(left: string, right: string): number {+ const leftParts = versionParts(left);+ const rightParts = versionParts(right);+ const length = Math.max(leftParts.length, rightParts.length);++ for (let index = 0; index < length; index += 1) {+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);+ if (difference !== 0) {+ return difference > 0 ? 1 : -1;+ }+ }++ return 0;+}++export function selectAnnouncements({+ bundled,+ remote,+ dismissedIds,+ impressionCounts = {},+ appVersion,+ audience,+ now = new Date(),+}: {+ bundled: Announcement[];+ remote: Announcement[];+ dismissedIds: ReadonlySet<string>;+ impressionCounts?: Readonly<Record<string, number>>;+ appVersion: string;+ audience: AnnouncementAudience;+ now?: Date;+}): Announcement[] {+ const byId = new Map<string, Announcement>();+ for (const announcement of bundled) {+ byId.set(announcement.id, announcement);+ }+ for (const announcement of remote) {+ byId.set(announcement.id, announcement);+ }++ const nowMs = now.getTime();+ return [...byId.values()]+ .filter((announcement) => {+ if (dismissedIds.has(announcement.id)) {+ return false;+ }+ if (+ announcement.maxImpressions &&+ (impressionCounts[announcement.id] ?? 0) >= announcement.maxImpressions+ ) {+ return false;+ }+ if (announcement.audience !== "all" && announcement.audience !== audience) {+ return false;+ }+ if (announcement.startsAt && Date.parse(announcement.startsAt) > nowMs) {+ return false;+ }+ if (announcement.endsAt && Date.parse(announcement.endsAt) < nowMs) {+ return false;+ }+ if (+ announcement.minVersion &&+ compareVersions(appVersion, announcement.minVersion) < 0+ ) {+ return false;+ }+ if (+ announcement.maxVersion &&+ compareVersions(appVersion, announcement.maxVersion) > 0+ ) {+ return false;+ }+ return true;+ })+ .sort((left, right) => right.priority - left.priority);+}