Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(announcements): one-time popups from the check feed
reviewe9623a4b6eeb
diff --git a/CLAUDE.md b/CLAUDE.mdindex e09bd3d29..72c5c3bb0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -10778,8 +10778,18 @@ Exposed split over two IPC handlers: `announcements.fetch()` → `messages`, `ap`update`. `components/AnnouncementBanner.tsx` (stacked above `UpdateCard` under the tab bar in a`.top-banners` column) shows the newest message the user hasn't dismissed (dismissed `id`s persistin `localStorage`); `update.mandatory`/`minSupported` flips `UpdateCard` into a blocking required--update state. The call no-ops under `DO_NOT_TRACK`/`NODETERM_TELEMETRY_DISABLED` or in unpackaged-builds (unless `NODETERM_API_BASE` targets a local server). Schema example:+update state. **One-time popups** ride the same reply under their own `popups` key (admin console:+Display → "popup (once)") — a separate key, so every build that reads only `messages` (older+desktops, mobile) never receives one as a banner that would come back every launch.+`components/AnnouncementPopup.tsx` (pure rules in `lib/announcementPopup.ts`) shows the newest one+not shown before and records it in localStorage (`nodeterm.seenPopups`) the moment it is SHOWN, not+when closed; it waits while another modal is on the dialog stack or a key was pressed in the last+4 s, takes no focus, answers no Enter, and shows at most one per feed read. Its button opens `url`,+or with `action: 'upgrade'` starts the Pro checkout — an upgrade popup is skipped for a Pro user and+closes when Pro arrives. Server Edition: the bridge answers `[]` (it does not read the feed). Mobile:+N/A for v1 (follow-up in the iOS repo). The call no-ops under+`DO_NOT_TRACK`/`NODETERM_TELEMETRY_DISABLED` or in unpackaged builds (unless `NODETERM_API_BASE`+targets a local server). Schema example:`docs/announcements.example.json`. **The request also states `plan=pro|free`** (offline`isPremium()`), because the admin console can aim a message at paid or free users and the feed isanonymous — the backend cannot look a device's plan up, and matches only on what we send (a builddiff --git a/src/core/check.test.ts b/src/core/check.test.tsindex 3d53c3200..cd7d2806b 100644--- a/src/core/check.test.ts+++ b/src/core/check.test.ts@@ -119,6 +119,46 @@ describe('/v1/check sanitize — update notes', () => {})})+// Popups ride their own key, so a build that reads only `messages` never gets one as a banner. The+// sanitizer is their whole contract: a closed action set, a clamped label, the banner's url rule.+describe('/v1/check sanitize — popups', () => {+ it('reads popups apart from the banners, with their button', () => {+ const r = sanitize({+ messages: [{ id: 'b', title: 'Banner' }],+ popups: [+ { id: 'p', title: 'Popup', body: 'a\nb', url: 'https://nodeterm.dev/pro', level: 'success', ctaLabel: ' See Pro ', action: 'upgrade' }+ ],+ update: {}+ })+ expect(r.messages.map((m) => m.id)).toEqual(['b'])+ expect(r.popups).toEqual([+ { id: 'p', title: 'Popup', body: 'a\nb', url: 'https://nodeterm.dev/pro', level: 'success', ctaLabel: 'See Pro', action: 'upgrade' }+ ])+ })++ it('drops what it cannot show and never guesses an action', () => {+ const r = sanitize({+ popups: [+ null,+ 'x',+ { title: 'no id' },+ { id: 'p1', title: 'P1', action: 'checkout', url: 'javascript:alert(1)', ctaLabel: ' ' },+ { id: 'p2', title: 'P2', ctaLabel: 'L'.repeat(200), level: 'danger' }+ ]+ })+ expect(r.popups.map((p) => p.id)).toEqual(['p1', 'p2'])+ expect(r.popups[0]).toEqual({ id: 'p1', title: 'P1', body: undefined, url: undefined, level: 'info' })+ expect(r.popups[1].ctaLabel).toHaveLength(40)+ expect(r.popups[1].level).toBe('info')+ })++ it('is an empty list when the feed sends none (every server before popups)', () => {+ expect(sanitize({ messages: [], update: {} }).popups).toEqual([])+ expect(sanitize({ popups: {} }).popups).toEqual([])+ expect(sanitize(null).popups).toEqual([])+ })+})+// The feed is anonymous, so the backend can aim a message at paid or free users only by the plan// the client states. Read per request and part of the cache key: an "upgrade to Pro" message// cached as a free user must not be served for five more minutes to the same user once they pay.@@ -189,7 +229,18 @@ describe('fetchCheck — reports the plan', () => {fetchMock.mockResolvedValueOnce(feed('Try Pro', '0.5.0')).mockRejectedValueOnce(new Error('offline'))await fetchCheck()premium.value = true- expect(await fetchCheck()).toEqual({ messages: [], update: { minSupported: '0.5.0', mandatory: false } })+ expect(await fetchCheck()).toEqual({ messages: [], popups: [], update: { minSupported: '0.5.0', mandatory: false } })+ })++ it('a failed read after a plan change drops the old plan’s popups too', async () => {+ const { fetchCheck } = await loadCheck()+ const body = { messages: [], popups: [{ id: 'p', title: 'Try Pro' }], update: { minSupported: null, mandatory: false } }+ fetchMock+ .mockResolvedValueOnce(new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }))+ .mockRejectedValueOnce(new Error('offline'))+ expect((await fetchCheck()).popups.map((p) => p.id)).toEqual(['p'])+ premium.value = true+ expect((await fetchCheck()).popups).toEqual([])})// The open-project count rides the same call, but — unlike the install count above — only while@@ -380,7 +431,11 @@ describe('fetchCheck — reports the plan', () => {const m = await loadCheck()const listener = vi.fn()m.onCheckAnswer(listener)- expect(await m.fetchCheck(), label).toEqual({ messages: [], update: { minSupported: null, mandatory: false } })+ expect(await m.fetchCheck(), label).toEqual({+ messages: [],+ popups: [],+ update: { minSupported: null, mandatory: false }+ })expect(fetchMock, label).toHaveBeenCalledTimes(1)expect(listener.mock.calls, label).toEqual(calls)}@@ -410,12 +465,12 @@ describe('fetchCheck — reports the plan', () => {expect(listener.mock.calls).toEqual([[{ kind: 'off' }]])})- it('a 2xx with limits answers on, and fetchCheck still returns only messages and update', async () => {+ it('a 2xx with limits answers on, and the limits never reach fetchCheck’s result', async () => {fetchMock.mockResolvedValue(limitsFeed(5, 3))const m = await loadCheck()const listener = vi.fn()m.onCheckAnswer(listener)- expect(await m.fetchCheck()).toEqual({ messages: [], update: { minSupported: null, mandatory: false } })+ expect(await m.fetchCheck()).toEqual({ messages: [], popups: [], update: { minSupported: null, mandatory: false } })expect(listener.mock.calls).toEqual([[{ kind: 'on', free: 5, epoch: 3 }]])})diff --git a/src/core/check.ts b/src/core/check.tsindex 85d26985b..c0d15e911 100644--- a/src/core/check.ts+++ b/src/core/check.ts@@ -1,6 +1,6 @@// Polls the backend /v1/check feed from the main process (so the renderer CSP stays 'self').// Successor to the static announcements.json: returns targeted messages for the announcement-// banner AND the mandatory-update policy for the Update Card. It also carries the anonymous+// banner, one-time popups (`popups`), AND the mandatory-update policy for the Update Card. It also carries the anonymous// install id (deviceId + os/arch/version), which the backend upserts into `devices` as a// passive active-install counter — so the version distribution reflects EVERY install, not only// the (few) that also opt into the telemetry ping. It also states the plan (`pro` | `free`) so a@@ -15,17 +15,20 @@import { platform } from './platform'import { getDeviceId } from './device-id'import { isPremium } from './license'-import type { Announcement, UpdatePolicy } from '../shared/types'+import type { Announcement, PopupAnnouncement, UpdatePolicy } from '../shared/types'const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'const CACHE_MS = 5 * 60 * 1000export interface CheckResult {messages: Announcement[]+ /** One-time popups. The server sends them under their own key so that a build reading only+ * `messages` (every one before this, and mobile) never receives one as a recurring banner. */+ popups: PopupAnnouncement[]update: UpdatePolicy}-const EMPTY: CheckResult = { messages: [], update: { minSupported: null, mandatory: false } }+const EMPTY: CheckResult = { messages: [], popups: [], update: { minSupported: null, mandatory: false } }// Same build + DO_NOT_TRACK gate as telemetry: dev never hits the prod API unless a local// server is targeted explicitly. Deliberately NOT gated on the in-app telemetry toggle: this@@ -41,17 +44,26 @@ function allowed(): boolean {function sanitize(data: unknown): CheckResult {if (!data || typeof data !== 'object') return EMPTYconst d = data as Record<string, unknown>- const rawMessages = Array.isArray(d.messages) ? d.messages : []- const messages: Announcement[] = rawMessages- .filter((m): m is Record<string, unknown> => !!m && typeof m === 'object')- .filter((m) => typeof m.id === 'string' && typeof m.title === 'string')- .map((m) => ({- id: m.id as string,- title: m.title as string,- body: typeof m.body === 'string' ? m.body : undefined,- url: typeof m.url === 'string' && /^https?:\/\//.test(m.url) ? m.url : undefined,- level: m.level === 'success' || m.level === 'warning' ? m.level : 'info'- }))+ const items = (raw: unknown): Record<string, unknown>[] =>+ (Array.isArray(raw) ? raw : [])+ .filter((m): m is Record<string, unknown> => !!m && typeof m === 'object')+ .filter((m) => typeof m.id === 'string' && typeof m.title === 'string')+ const toMessage = (m: Record<string, unknown>): Announcement => ({+ id: m.id as string,+ title: m.title as string,+ body: typeof m.body === 'string' ? m.body : undefined,+ url: typeof m.url === 'string' && /^https?:\/\//.test(m.url) ? m.url : undefined,+ level: m.level === 'success' || m.level === 'warning' ? m.level : 'info'+ })+ const messages = items(d.messages).map(toMessage)+ const popups = items(d.popups).map((m): PopupAnnouncement => {+ const p: PopupAnnouncement = toMessage(m)+ const label = typeof m.ctaLabel === 'string' ? m.ctaLabel.trim() : ''+ if (label) p.ctaLabel = label.slice(0, CTA_LABEL_MAX)+ // A closed set: an action this build does not know is no action, never a guess at one.+ if (m.action === 'upgrade') p.action = 'upgrade'+ return p+ })const u = (d.update ?? {}) as Record<string, unknown>const update: UpdatePolicy = {minSupported: typeof u.minSupported === 'string' ? u.minSupported : null,@@ -63,10 +75,11 @@ function sanitize(data: unknown): CheckResult {update.notes = u.notes.slice(0, NOTES_MAX)update.latestVersion = u.latestVersion.slice(0, 64)}- return { messages, update }+ return { messages, popups, update }}const NOTES_MAX = 16 * 1024+const CTA_LABEL_MAX = 40/** Test seam: the sanitizer is the whole contract with the feed's shape. */export const sanitizeCheckForTest = sanitize@@ -193,10 +206,10 @@ export async function fetchCheck(): Promise<CheckResult> {// or was fetched with the toggle off, is reused exactly as before.const countNowKnown = cache?.countOwed === true && Object.hasOwn(count.param, 'openProjects')if (cache && cache.plan === plan && now - cache.at < CACHE_MS && !countNowKnown) return cache.data- // A failed read keeps the last good answer, except the messages it fetched for another plan.- // The update policy does not depend on the plan, so it survives.+ // A failed read keeps the last good answer, except the messages and popups it fetched for another+ // plan. The update policy does not depend on the plan, so it survives.const fallback = (): CheckResult =>- !cache ? EMPTY : cache.plan === plan ? cache.data : { messages: [], update: cache.data.update }+ !cache ? EMPTY : cache.plan === plan ? cache.data : { messages: [], popups: [], update: cache.data.update }try {const q = new URLSearchParams({deviceId: getDeviceId(),diff --git a/src/main/index.ts b/src/main/index.tsindex e349dd0d5..b7ffacc54 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2063,6 +2063,7 @@ app.whenReady().then(async () => {telemetryEnabled: () => settingsStore.get().telemetryEnabled})ipcMain.handle(IPC.announcementsFetch, async () => (await fetchCheck()).messages)+ ipcMain.handle(IPC.announcementsPopups, async () => (await fetchCheck()).popups)ipcMain.handle(IPC.appUpdatePolicy, async () => (await fetchCheck()).update)// Writable base dir for app-managed files (e.g. default git worktree location). On the platform:diff --git a/src/preload/index.ts b/src/preload/index.tsindex e033eea97..fe633a3ef 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -565,7 +565,8 @@ const api: NodeTerminalApi = {}},announcements: {- fetch: () => ipcRenderer.invoke(IPC.announcementsFetch)+ fetch: () => ipcRenderer.invoke(IPC.announcementsFetch),+ popups: () => ipcRenderer.invoke(IPC.announcementsPopups)},usage: {fetch: (accountId?: string) => ipcRenderer.invoke(IPC.usageFetch, accountId),diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.tsindex 7c71792af..6706fe4ac 100644--- a/src/renderer/bridge/stubs.test.ts+++ b/src/renderer/bridge/stubs.test.ts@@ -83,6 +83,7 @@ describe('bridge stubs', () => {it('boot-path promise members resolve benignly', async () => {const s = buildStubApi()await expect(s.announcements.fetch()).resolves.toEqual([])+ await expect(s.announcements.popups()).resolves.toEqual([])// UpdateCard reads `p.mandatory` with no null guard, so the stub must return a real// UpdatePolicy — a `null` here was a TypeError on every Server Edition page load.await expect(s.updates.getPolicy()).resolves.toEqual({ minSupported: null, mandatory: false })diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex b9550ae89..2f40e965d 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -270,7 +270,9 @@ export function buildStubApi(): Omit<prepareQuit: noop},announcements: {- fetch: () => Promise.resolve([])+ fetch: () => Promise.resolve([]),+ // The Server Edition does not read the check feed, so there is never a popup to show.+ popups: () => Promise.resolve([])},license: {upgrade: U('license.upgrade'),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 7fdd15d28..e9e645247 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -287,6 +287,7 @@ import { admitPendingPeer } from '../lib/pendingPeerAdmission'import { SAS_COMPARE_HINT } from '@shared/remote/sas'import { promptDialog } from '../components/promptDialog'import { UpgradeDialog } from '../components/UpgradeDialog'+import { AnnouncementPopup } from '../components/AnnouncementPopup'import { ProjectLimitDialog } from '../components/ProjectLimitDialog'import {checkAgentProjectOpen,@@ -20735,6 +20736,7 @@ export function Canvas() {)}<UpgradeDialog />+ <AnnouncementPopup />{/* The free-tier limit moment (docs/project-limit.md). Close is the ordinary non-destructive close — never`endSessions`: the limit only ever blocks a NEW open, it never ends anything. */}<ProjectLimitDialog onCloseProject={(id) => performCloseProject(id)} />diff --git a/src/renderer/components/AnnouncementPopup.test.tsx b/src/renderer/components/AnnouncementPopup.test.tsxnew file mode 100644index 000000000..ad14dd28f--- /dev/null+++ b/src/renderer/components/AnnouncementPopup.test.tsx@@ -0,0 +1,192 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import type { PopupAnnouncement } from '@shared/types'+import { AnnouncementPopup } from './AnnouncementPopup'+import { popDialog, pushDialog, resetDialogStack } from './dialog-stack'+import { useEntitlement } from '../state/entitlement'+import { KEY_QUIET_MS, loadSeenPopups } from '../lib/announcementPopup'++// The real store subscribes to the license bridge when it is created; the popup reads the bit and+// calls the checkout.+vi.mock('../state/entitlement', async () => {+ const { create } = await import('zustand')+ return { useEntitlement: create(() => ({ isPremium: false, upgrade: async () => {} })) }+})++const pop = (id: string, extra: Partial<PopupAnnouncement> = {}): PopupAnnouncement => ({+ id,+ title: `Title ${id}`,+ body: `Body ${id}`,+ level: 'info',+ ...extra+})++let root: Root | null = null+let popups: ReturnType<typeof vi.fn>++function setFeed(...reads: PopupAnnouncement[][]): void {+ popups = vi.fn()+ for (const r of reads) popups.mockResolvedValueOnce(r)+ popups.mockResolvedValue(reads[reads.length - 1] ?? [])+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { announcements: { popups } }+}++async function mount(): Promise<void> {+ const el = document.createElement('div')+ root = createRoot(el)+ await act(async () => root!.render(<AnnouncementPopup />))+}++async function unmount(): Promise<void> {+ if (root) await act(async () => root!.unmount())+ root = null+}++const dialog = () => document.body.querySelector('.announce-popup')+const button = (label: string) =>+ [...document.body.querySelectorAll('button')].find((b) => b.textContent === label) as HTMLButtonElement | undefined++beforeEach(() => {+ vi.useFakeTimers()+ resetDialogStack()+})++afterEach(async () => {+ await unmount()+ vi.useRealTimers()+ useEntitlement.setState({ isPremium: false, upgrade: async () => {} })+ localStorage.clear()+ vi.restoreAllMocks()+})++it('shows the newest popup once, and records it the moment it is shown', async () => {+ setFeed([pop('new'), pop('old')])+ await mount()+ expect(dialog()?.textContent).toContain('Title new')+ expect(dialog()?.textContent).toContain('Body new')+ expect(loadSeenPopups().has('new')).toBe(true)++ // A relaunch with it still on screen (never closed) does not bring it back.+ await unmount()+ setFeed([pop('new')])+ await mount()+ expect(dialog()).toBeNull()+})++it('closing one does not bring up the next until the next read of the feed', async () => {+ const SIX_HOURS = 6 * 60 * 60 * 1000+ setFeed([pop('a'), pop('b')])+ await mount()+ expect(dialog()?.textContent).toContain('Title a')+ // A read while `a` is still up (the user is away) already knows `b` is next.+ await act(async () => vi.advanceTimersByTime(SIX_HOURS))+ expect(dialog()?.textContent).toContain('Title a')+ await act(async () => button('Close')!.click())+ expect(dialog()).toBeNull()+ await act(async () => vi.advanceTimersByTime(10_000))+ expect(dialog()).toBeNull()++ // The next read.+ await act(async () => vi.advanceTimersByTime(SIX_HOURS))+ expect(dialog()?.textContent).toContain('Title b')+})++it('waits for another modal to close before taking the screen', async () => {+ pushDialog('someone-else')+ setFeed([pop('a')])+ await mount()+ await act(async () => vi.advanceTimersByTime(10_000))+ expect(dialog()).toBeNull()+ expect(loadSeenPopups().has('a')).toBe(false)++ popDialog('someone-else')+ await act(async () => vi.advanceTimersByTime(1000))+ expect(dialog()?.textContent).toContain('Title a')+})++it('waits for the keyboard to go quiet', async () => {+ setFeed([])+ await mount()+ // The user is typing when the popup arrives (a plan change re-reads the feed).+ popups.mockResolvedValue([pop('a')])+ await act(async () => {+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'x' }))+ useEntitlement.setState({ isPremium: true })+ })+ await act(async () => useEntitlement.setState({ isPremium: false }))+ expect(dialog()).toBeNull()+ await act(async () => vi.advanceTimersByTime(KEY_QUIET_MS - 1000))+ expect(dialog()).toBeNull()+ await act(async () => vi.advanceTimersByTime(1000))+ expect(dialog()?.textContent).toContain('Title a')+})++it('closes on Escape and takes no focus from the user', async () => {+ const input = document.createElement('input')+ document.body.appendChild(input)+ input.focus()+ setFeed([pop('a')])+ await mount()+ expect(dialog()).not.toBeNull()+ expect(document.activeElement).toBe(input)+ // Enter answers nothing.+ await act(async () => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' })))+ expect(dialog()).not.toBeNull()+ await act(async () => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))+ expect(dialog()).toBeNull()+ input.remove()+})++it('opens its link and closes', async () => {+ const open = vi.spyOn(window, 'open').mockReturnValue(null)+ setFeed([pop('a', { url: 'https://nodeterm.dev/news', ctaLabel: 'Read it' })])+ await mount()+ await act(async () => button('Read it')!.click())+ expect(open).toHaveBeenCalledWith('https://nodeterm.dev/news', '_blank', 'noopener')+ expect(dialog()).toBeNull()+})++it('has only Close without a link or an action', async () => {+ setFeed([pop('a', { ctaLabel: 'Orphan' })])+ await mount()+ expect([...dialog()!.querySelectorAll('button')].map((b) => b.textContent)).toEqual(['Close'])+})++it('starts the checkout from an upgrade popup, and closes once Pro arrives', async () => {+ const upgrade = vi.fn(async () => {})+ useEntitlement.setState({ upgrade })+ setFeed([pop('a', { action: 'upgrade' })])+ await mount()+ await act(async () => button('Upgrade to Pro')!.click())+ expect(upgrade).toHaveBeenCalledTimes(1)+ expect(dialog()).toBeNull()++ // Left open, it is closed by the purchase itself.+ await unmount()+ localStorage.clear()+ setFeed([pop('b', { action: 'upgrade' })])+ await mount()+ expect(dialog()).not.toBeNull()+ await act(async () => useEntitlement.setState({ isPremium: true }))+ expect(dialog()).toBeNull()+})++it('never shows a Pro user an upgrade popup, and keeps it for a lapse', async () => {+ useEntitlement.setState({ isPremium: true })+ setFeed([pop('upsell', { action: 'upgrade' })])+ await mount()+ await act(async () => vi.advanceTimersByTime(10_000))+ expect(dialog()).toBeNull()+ expect(loadSeenPopups().has('upsell')).toBe(false)+})++it('shows nothing when the feed cannot be read', async () => {+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ announcements: { popups: vi.fn().mockRejectedValue(new Error('offline')) }+ }+ await mount()+ await act(async () => vi.advanceTimersByTime(10_000))+ expect(dialog()).toBeNull()+})diff --git a/src/renderer/components/AnnouncementPopup.tsx b/src/renderer/components/AnnouncementPopup.tsxnew file mode 100644index 000000000..df03bf784--- /dev/null+++ b/src/renderer/components/AnnouncementPopup.tsx@@ -0,0 +1,156 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import { createPortal } from 'react-dom'+import type { PopupAnnouncement } from '@shared/types'+import { useEntitlement } from '../state/entitlement'+import { loadSeenPopups, markPopupSeen, pickPopup, popupCta, popupMayShow } from '../lib/announcementPopup'+import { confirmKeyAction } from './confirm-key'+import { openDialogCount, useDialogStack } from './dialog-stack'++const SIX_HOURS = 6 * 60 * 60 * 1000+const RETRY_MS = 1000++/**+ * A one-time popup from the check feed (lib/announcementPopup.ts): the admin console's "popup+ * (once)" messages, aimed like banners (plan, OS, channel, version). Mounted once, in Canvas.+ *+ * At most one per feed read: closing a popup does not bring up the next one — that waits for the+ * next read (launch, the six-hour tick, a plan change). And it waits its turn on screen: never over+ * another modal, never while the user is typing (`popupMayShow`).+ */+export function AnnouncementPopup(): React.JSX.Element | null {+ const isPremium = useEntitlement((s) => s.isPremium)+ const [pending, setPending] = useState<PopupAnnouncement | null>(null)+ const [shown, setShown] = useState<PopupAnnouncement | null>(null)+ const lastKeyAt = useRef(0)++ // Main asks the feed with the current plan, so a plan change re-asks — a "try Pro" popup aimed at+ // free users must not come up for someone who has just paid.+ useEffect(() => {+ let cancelled = false+ const check = async (): Promise<void> => {+ let items: PopupAnnouncement[]+ try {+ items = await window.nodeTerminal.announcements.popups()+ } catch {+ return+ }+ if (cancelled) return+ setPending(pickPopup(items, loadSeenPopups(), isPremium))+ }+ void check()+ const timer = setInterval(() => void check(), SIX_HOURS)+ return () => {+ cancelled = true+ clearInterval(timer)+ }+ }, [isPremium])++ // Capture phase, and nothing else: only WHEN the user last typed matters, never what.+ useEffect(() => {+ const onKey = (): void => {+ lastKeyAt.current = Date.now()+ }+ window.addEventListener('keydown', onKey, true)+ return () => window.removeEventListener('keydown', onKey, true)+ }, [])++ useEffect(() => {+ if (!pending || shown) return+ const tryShow = (): boolean => {+ if (!popupMayShow(Date.now(), lastKeyAt.current, openDialogCount())) return false+ markPopupSeen(pending.id)+ setShown(pending)+ setPending(null)+ return true+ }+ if (tryShow()) return+ const timer = setInterval(tryShow, RETRY_MS)+ return () => clearInterval(timer)+ }, [pending, shown])++ const close = useCallback(() => {+ setShown(null)+ setPending(null)+ }, [])++ // An upgrade popup has done its job once Pro arrives (the checkout finishing in the browser).+ useEffect(() => {+ if (isPremium && shown?.action === 'upgrade') close()+ }, [isPremium, shown, close])++ if (!shown) return null+ return <PopupDialog key={shown.id} popup={shown} onClose={close} />+}++function PopupDialog({ popup, onClose }: { popup: PopupAnnouncement; onClose(): void }): React.JSX.Element {+ const isTop = useDialogStack()+ const boxRef = useRef<HTMLDivElement>(null)+ const shownAtRef = useRef(Date.now())++ // Escape closes. Enter answers nothing, and no button takes focus: the app raised this, so the+ // keyboard stays wherever the user left it (components/confirm-key).+ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => {+ const action = confirmKeyAction({+ key: e.key,+ repeat: e.repeat,+ top: isTop(),+ inDialog: !!(e.target instanceof Node && boxRef.current?.contains(e.target)),+ sinceMount: Date.now() - shownAtRef.current,+ enterConfirms: false+ })+ if (action !== 'cancel') return+ e.preventDefault()+ onClose()+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [isTop, onClose])++ const cta = popupCta(popup)+ const onCta = (): void => {+ if (!cta) return+ if (cta.kind === 'url') window.open(cta.url, '_blank', 'noopener')+ else void startUpgrade()+ onClose()+ }++ const titleId = `announce-popup-title-${popup.id}`+ return createPortal(+ <div className="confirm-overlay" onClick={onClose}>+ <div+ className={`confirm announce-popup announce-popup--${popup.level ?? 'info'}`}+ ref={boxRef}+ role="dialog"+ aria-modal="true"+ aria-labelledby={titleId}+ onClick={(e) => e.stopPropagation()}+ >+ <h2 className="announce-popup__title" id={titleId}>+ {popup.title}+ </h2>+ {/* Plain text, never markup; `.confirm__msg` keeps the console's line breaks. */}+ {popup.body && <p className="confirm__msg">{popup.body}</p>}+ <div className="confirm__actions">+ <button className="confirm__btn" onClick={onClose}>+ Close+ </button>+ {cta && (+ <button className="confirm__btn primary" onClick={onCta}>+ {cta.label}+ </button>+ )}+ </div>+ </div>+ </div>,+ document.body+ )+}++async function startUpgrade(): Promise<void> {+ try {+ await useEntitlement.getState().upgrade()+ } catch (err) {+ console.warn('[announcement-popup] upgrade failed', err instanceof Error ? err.message : String(err))+ }+}diff --git a/src/renderer/lib/announcementPopup.test.ts b/src/renderer/lib/announcementPopup.test.tsnew file mode 100644index 000000000..ac252065b--- /dev/null+++ b/src/renderer/lib/announcementPopup.test.ts@@ -0,0 +1,76 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it } from 'vitest'+import type { PopupAnnouncement } from '@shared/types'+import {+ KEY_QUIET_MS,+ SEEN_POPUPS_KEY,+ loadSeenPopups,+ markPopupSeen,+ pickPopup,+ popupCta,+ popupMayShow+} from './announcementPopup'++const pop = (id: string, extra: Partial<PopupAnnouncement> = {}): PopupAnnouncement => ({ id, title: id, ...extra })++afterEach(() => localStorage.clear())++describe('pickPopup', () => {+ it('takes the newest popup not shown before', () => {+ expect(pickPopup([pop('new'), pop('old')], new Set(), false)?.id).toBe('new')+ expect(pickPopup([pop('new'), pop('old')], new Set(['new']), false)?.id).toBe('old')+ expect(pickPopup([pop('new'), pop('old')], new Set(['new', 'old']), false)).toBeNull()+ expect(pickPopup([], new Set(), false)).toBeNull()+ })++ // Its button would be a checkout for what a Pro user already has. Skipped, not recorded: it is+ // still there for them if Pro lapses.+ it('skips an upgrade popup for a Pro user and takes the next one', () => {+ const items = [pop('upsell', { action: 'upgrade' }), pop('news')]+ expect(pickPopup(items, new Set(), true)?.id).toBe('news')+ expect(pickPopup(items, new Set(), false)?.id).toBe('upsell')+ })+})++describe('popupMayShow', () => {+ it('waits for a quiet keyboard and for no other modal', () => {+ expect(popupMayShow(10_000, 0, 0)).toBe(true)+ expect(popupMayShow(10_000, 10_000 - KEY_QUIET_MS, 0)).toBe(true)+ expect(popupMayShow(10_000, 10_000 - KEY_QUIET_MS + 1, 0)).toBe(false)+ expect(popupMayShow(10_000, 0, 1)).toBe(false)+ })+})++describe('popupCta', () => {+ it('is the checkout for an upgrade popup, whatever its link', () => {+ expect(popupCta(pop('a', { action: 'upgrade', url: 'https://x.dev' }))).toEqual({+ kind: 'upgrade',+ label: 'Upgrade to Pro'+ })+ expect(popupCta(pop('a', { action: 'upgrade', ctaLabel: 'Go Pro' }))?.label).toBe('Go Pro')+ })++ it('is the link otherwise, and nothing without one', () => {+ expect(popupCta(pop('a', { url: 'https://x.dev' }))).toEqual({ kind: 'url', label: 'Learn more', url: 'https://x.dev' })+ expect(popupCta(pop('a', { url: 'https://x.dev', ctaLabel: 'Read' }))?.label).toBe('Read')+ expect(popupCta(pop('a', { ctaLabel: 'Orphan label' }))).toBeNull()+ })+})++describe('seen record', () => {+ it('remembers every popup it was told about', () => {+ markPopupSeen('a')+ markPopupSeen('b')+ markPopupSeen('a')+ expect([...loadSeenPopups()].sort()).toEqual(['a', 'b'])+ })++ it('reads a damaged record as empty, never as a throw', () => {+ localStorage.setItem(SEEN_POPUPS_KEY, '{not json')+ expect(loadSeenPopups().size).toBe(0)+ localStorage.setItem(SEEN_POPUPS_KEY, JSON.stringify({ a: 1 }))+ expect(loadSeenPopups().size).toBe(0)+ localStorage.setItem(SEEN_POPUPS_KEY, JSON.stringify(['a', 3, null]))+ expect([...loadSeenPopups()]).toEqual(['a'])+ })+})diff --git a/src/renderer/lib/announcementPopup.ts b/src/renderer/lib/announcementPopup.tsnew file mode 100644index 000000000..cedaee6e7--- /dev/null+++ b/src/renderer/lib/announcementPopup.ts@@ -0,0 +1,64 @@+import type { PopupAnnouncement } from '@shared/types'++/**+ * One-time popups from the check feed (`popups` in the reply; components/AnnouncementPopup.tsx).+ *+ * "Once" is this install's record, kept in localStorage like the banner's dismissed ids — but a+ * popup is recorded the moment it is SHOWN, not when it is closed: a reload, a crash or a quit with+ * it on screen must not bring it back, and the feed keeps listing it for as long as it is active.+ */+export const SEEN_POPUPS_KEY = 'nodeterm.seenPopups'++/** No keystroke for this long before a popup may take the screen (see `popupMayShow`). */+export const KEY_QUIET_MS = 4000++export function loadSeenPopups(): Set<string> {+ try {+ const raw = localStorage.getItem(SEEN_POPUPS_KEY)+ const parsed: unknown = raw ? JSON.parse(raw) : []+ return new Set(Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === 'string') : [])+ } catch {+ return new Set()+ }+}++export function markPopupSeen(id: string): void {+ try {+ const seen = loadSeenPopups()+ seen.add(id)+ localStorage.setItem(SEEN_POPUPS_KEY, JSON.stringify([...seen]))+ } catch {+ // ignore quota / serialization errors — at worst the popup shows once more+ }+}++/**+ * The popup to show from one feed read: the newest (the feed is newest-first) not shown before. An+ * upgrade popup is skipped for a Pro user — its button would be a checkout for what they already+ * have — and is NOT recorded, so it is still there if they lapse.+ */+export function pickPopup(+ items: readonly PopupAnnouncement[],+ seen: ReadonlySet<string>,+ isPremium: boolean+): PopupAnnouncement | null {+ return items.find((p) => !seen.has(p.id) && !(isPremium && p.action === 'upgrade')) ?? null+}++/**+ * May a popup take the screen now? Not over another modal (it would bury the question the user is+ * answering), and not under typing hands: a modal that appears mid-keystroke catches the next+ * Enter or Space, and the user never reads what they just dismissed.+ */+export function popupMayShow(now: number, lastKeyAt: number, openDialogs: number): boolean {+ return openDialogs === 0 && now - lastKeyAt >= KEY_QUIET_MS+}++export type PopupCta = { kind: 'url'; label: string; url: string } | { kind: 'upgrade'; label: string }++/** The popup's one button besides Close, or null for none (no link and no action). */+export function popupCta(p: PopupAnnouncement): PopupCta | null {+ if (p.action === 'upgrade') return { kind: 'upgrade', label: p.ctaLabel ?? 'Upgrade to Pro' }+ if (p.url) return { kind: 'url', label: p.ctaLabel ?? 'Learn more', url: p.url }+ return null+}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 4a4af0704..25f71036c 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -7177,6 +7177,27 @@ body,white-space: nowrap;}+/* One-time popup from the check feed (components/AnnouncementPopup.tsx), in the `.confirm` shell.+ The level shows as the top edge, the banner's left edge turned on its side. */+.confirm.announce-popup {+ border-top: 3px solid var(--accent);+}++.confirm.announce-popup--success {+ border-top-color: var(--success);+}++.confirm.announce-popup--warning {+ border-top-color: var(--warn);+}++.announce-popup__title {+ margin: 0 0 10px;+ font-size: 15px;+ font-weight: 600;+ color: var(--text);+}+.confirm.project-limit__checking {width: auto;}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 214dc6244..e5a4c1df8 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -381,6 +381,7 @@ export const IPC = {projectLimitChanged: 'projectLimit:changed',appRestartToUpdate: 'app:restart-to-update',announcementsFetch: 'announcements:fetch',+ announcementsPopups: 'announcements:popups',usageFetch: 'usage:fetch',usageRefresh: 'usage:refresh',usageUpdate: 'usage:update',diff --git a/src/shared/types.ts b/src/shared/types.tsindex bf845851a..e371d8601 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3081,9 +3081,20 @@ export interface Announcement {level?: 'info' | 'success' | 'warning'}+/** A one-time popup from the same feed (`popups` in the check reply): shown once per install. */+export interface PopupAnnouncement extends Announcement {+ /** The button's label; absent = "Learn more" for a link, "Upgrade to Pro" for the checkout. */+ ctaLabel?: string+ /** 'upgrade' = the button starts the app's own Pro checkout instead of opening `url`. */+ action?: 'upgrade'+}+export interface AnnouncementsApi {/** Fetch the announcements feed from the website (returns [] on any failure). */fetch(): Promise<Announcement[]>+ /** The feed's one-time popups ([] on any failure, and on the Server Edition, which does not read+ * the feed). Which of them were already shown is the renderer's record, not the feed's. */+ popups(): Promise<PopupAnnouncement[]>}export interface NotifyPayload {